PDA

View Full Version : [TUTORIAL] Programming With Vim


kmj
06-19-2002, 02:11 PM
Introduction to Programming in C/C++ with Vim

Vi has been one of the most popular editing tools for programmers since Bill Joy first created it. Over the years it has evolved, and the current version of vim has many capabilities which make a programmer's life easy. Listed below is a brief description of some tools which have made so many programmers loyal to vi and vim. The purpose of this document is to inform propspective Vim users of, and introduce them to some of these tools, but not necessarily to be the definitive source of information on them. In most cases, interested readers should check the noted "extra information" sources.

Note: Throughout this paper, I may use the name vi when referring to vim. Some options may only be compatible with vim, and not vi.

On with the features:


Ctags
Ctags is a program that comes with vim. Basically, it's purpose is to help a programmer get to various parts of his program with relative ease. The typical method of running ctags is by simply typing the following in your source directory:

[/home/someuser/src]$ ctags *

This will create a 'tags' file in your current directory with the following information for all C or C++ files in you
directory. This file contains a listing of the following objects:
- macros defined by #define
- enumerated values
- function definitions, prototypes, and declarations
- class, enum, struct, and union names
- variables (definitions and declarations)
- class, struct, and union members

Vim then uses this file to help you locate these tagged items. This can be done in a few ways. First, one can open vim to the location of a tagged object. To do this, run vim with the '-t'
flag and the tag-name as an rgument. For example:

[/home/someuser/src]$ vi -t foo_bar

would open to the file containing the definition of foo_bar at that line. If you are already in vi, you can enter the command by the tag-name:

:ta foo_bar

This may take you out of the file you are currently in, unless the 'autowrite' option is enabled. (It is off by default.)
For more information on autowrite, type ':h autowrite' from with vi command-mode. The final way to jump to a tagged location is by typing Ctrl-] in command mode while the cursor is on a specific word. For example, if you are looking at my program, and you come across a point where I call foo_bar(), you can type 'Ctrl-]' while the cursor is somewhere on that word and it will jump to that definition. Note that 'Ctrl-]' is the escape character for telnet, so this may cause some issues if your editing files remotely. Type ':h ^]' for more information. Togo back to the point you were at before jumping to a ctag, simply type Ctr-t.

Ctags can also be used with other languages (java, fortran, ...and more) and editors (emacs, NEdit, ...and more). When set up properly, this tool can make your job tremendously easier, especially when you have to jump into a large ongoing project head-first.

For more information: View the man page, man ctags, or view the vim help, :h ctags.

Auto-Indenting
Vi has various methods of implementing auto-indenting. The best for C and C++ programmers is, obviously, cindent mode.
This is a very versatile tool which gives the programmer much control over
the look and feel of his source code, without any effort (except the effort
of initial setup, of course). To enable c-indenting, just type :set cindent' from the command mode. The most important thing to note is that cindenting makes use of shiftwidth, not tabstops. The default shiftwidth is 8. In order to change this, enter :set shiftwidth=x where x is the desired number of spaces to shift. The default cindent options tend to be nice, but if you find your program indenting in some way that is nnoying, you can modify the behaviour. To set the cindent options, type :set cino=<string>, where <string> is a list defining exactly how you want your cindent options to behave. There are quite a few different types of indenting which can be done, and vim's help does a good job explaining them, so I won't go over them here. To view the help for the possible values of cinoptions, type :h cinoptions-values. To view the current values, simply type ':set cino'. Most likely there will be none, since everything starts at a default value.
For more information, check out the following: ':h shiftwidth', :h cindent', ':h cinoptions', ':h cinoptions-values', ':h cinkeys', and ':h cinwords'.



Programmers who are used to integrated development environments know the beauty of syntax highlighting. It doesn't just make your code more readable; it also helps prevent annoying commenting
and string errors. Vim has syntax highlighting for a number of languages. To enable it, type ':syntax
on'. Using it is as simple as that if you're happy with the default values. Vim's syntax highlighting tools can be quite complex, with a number of different things to play around with. To view information on syntax hilighting, type ':h syntax', which will
lead you to vim's extensive help system. Syntax hilighting with color
terminals and with gvim is nice, but if you don't have color, vim uses
underlining, boldface, etc. To me, this is pretty ugly. For more info: ':h syntax', ':h syn-qstart', ':h syntax-printing'

QuickFix
This is a really nifty feature. Basically,
by typing one command, you can cause vim to attempt to make the program
you're working on, then open to whatever file first compiler error is in
at the line of that error. The command to execute is ':mak' (or ':make'). Vim will run whatever program is denoted
by the value of 'makeprg'. The default value for 'makeprg' is 'make'. You can change this, if you wish, by typing ':set makprg=&lt;string>', where &lt;string> denotes the desired command. Vim uses the 'errorformat' value to figure out how to understand the output from the compiler. Since different compilers have different output format's, you'll probably have to enter the format string. The method used
is rather similar to C-style formatting with scanf. The most important format specifiers are %f, meaning filename, %l, meaing line-number, and %m, meaning message. %f:%l:\%m
This can become quite complex with different compilers, but fortunately, vim has a world of information in their help at ':h errorformat'. For more info, check: 'h: quickfix', ':h mak', ':h makeprg', ':h errorfile', ':h
errorformat'.

Useful Keystrokes
There are certain command-mode keystrokes that are especially useful for programmers. Below is a small subset of these:

[[ = Go to previous first-column '{'; equivilent to ?^{
]] = Go to next first-column '{';
equivilent to /^{
[] = Go to previous first-column '}'; equivilient to ?^}
][ = Go to next first-column '}';
equivilent to /^}
{ = Go to previous blank line.
} = Go to next blank line.
gd = Go to definition
of current local variable (current = cursor is on it)
* = Go to next instance of current word
# = Go to previous instance of current word
'' = Go to location where last search was started.

Parenthesis Matching
% takes you to the matching parenthesis, curly brace, or bracket, depending on what you are on. This always comes in handy as a quick double-check.

Pattern matching and substitution
Vim has powerful substition
capabilities, with a very simple interface. No annoying GUI to get in the way (though you may need to keep a cheat-sheet handy). To
search for and replace text, use the following command:


: [address] s/<pattern>/<string>/[g|c|N]

This finds one (or more) instance
of the grep-style regular expression represented by <pattern>, and substitutes it with <string>. 'address', 'g', and 'N' are modifiers which
determine which and how many occurances of <pattern> are replaced.

g Global: Replace all occurances of <pattern> on the line.

c Cond: Ask before making each replacement.

N N represents an integer value. Replace only the Nth occurance of <pattern> on the line.

No modifier: implies N=1, the first occurance on that line

The [address] field may be one specifier or two seperated by a comma. (Below, x represents
an integer.)

. The current line
$ The last line in the file
% Entire file
x The xth line of the file
+x x lines after the current line
-x x lines before the current line

The comma may seperate any of the above in order to specify a range. All
lines within the given range will undergo the substitution. The best reference I have found for subsituting can be found at the Vi Helpfile, linked
below.

kmj
06-19-2002, 02:13 PM
--- continiued ----


Miscellany
Vim has so many nifty little things, it would be impossible to list them
all. Here are a few more things that are worth taking a look at.

Include File Searching- ':h include-search'

Bookmarking- 'mx' to set, ' 'x' to return; (x can be any letter, must stay within file to remember)

"Clipboard" buffers- ' "xY ' to cut or copy to buffer x (Y represents any normal deletion or yank command),
' "xZ ' to paste contents of x (Z represents pasting... p
or P); (x can be any letter, can switch to another file(:e filename) and still maintain contents of buffers).

Comment Specifiers- ':h comments'

.vimrc-

Don't forget your .vimrc!!! (Located in your home directory). You'll
find it very handy to add many of the above things to your .vimrc file,
so that vim "remembers" everything you want it to. (You may find that some of them are already there.) Remember that you don't need to prepend a ':' to the command when adding them to the .vimrc.


Other Resources
X_Console has written a really nice Vi
Crash Course NHF (http://linuxnewbie.internet.com/nhf/intel/tools/vicc.html) , which should help you get over the learning curve,
if you're just starting out. There are many, many webpages around with information on Vi/Vim, some good, some not so good (depending on what level you're looking for). A search for Vi or Vim at Google or any other search engine will turn up plenty of results. In my opinion, these are two of the best:
- Many links, lots of info...

The VI Helpfile (http://www.vmunix.com/~gabor/vi.html) - Very comlete, terse reference. Great for ex commands.
Unixworld
Vi Tutorial (http://www.networkcomputing.com/unixworld/tutorial/009/009.html) - Nine parts, from start to finish... Go through this and you'll understand why we love Vi.


This file was created by Keith Jones (kjones9 at rochester.rr.com). I'm no expert on vim, but I hope some of the above was helpful. Enjoy!!!



Oh.. and expect updates on this, if I'm not too lazy.

And.. Please feel free to add your favourite vim info here!

kbum
09-28-2003, 02:16 AM
Hey kmj, this is very nice, thank you for all this info. I've been using vim for a very short period of time but I really like it. I have one question though that I couldn't find the answer so I will ask it here. Consider the following lines: (I will use part of a song lol)


There's a lady who's sure all that glitters is gold
And she's buying a stairway to heaven
And when she gets there she knows if the stores are closed
With a word she can get what she came for



Woe oh oh oh oh oh
And she's buying a stairway to heaven


There's a sign on the wall but she wants to be sure
And you know sometimes words have two meanings
In the tree by the brook there's a songbird who sings
Sometimes all of our thoughts are misgiven


Now, let's say I want to delete those two lines standing by themselves. The text would look like this


There's a lady who's sure all that glitters is gold
And she's buying a stairway to heaven
And when she gets there she knows if the stores are closed
With a word she can get what she came for






There's a sign on the wall but she wants to be sure
And you know sometimes words have two meanings
In the tree by the brook there's a songbird who sings
Sometimes all of our thoughts are misgiven


Now here is my problem. How would I put those two paragraphs together using vim? Thank you

:D

Solean
12-07-2003, 01:00 PM
Make sure your in command mode, go to the space in the middle, and type "d".

JesusCyborg
12-10-2003, 11:29 AM
ah yes VIM, for the the elitist unix nerd inside all of us

freaknutnot9
01-18-2004, 06:49 PM
hey i wanna learn to hack and i need to learn proggraming can sum1 please help me with sum proggraming langunage thing please help me!!!

Strike
01-18-2004, 07:39 PM
Originally posted by freaknutnot9
hey i wanna learn to hack and i need to learn proggraming can sum1 please help me with sum proggraming langunage thing please help me!!!
No. "Hackers" aren't welcome here, unless you mean it like this (http://www.catb.org/~esr/jargon/html/H/hacker.html), which I strongly doubt.

Whiteknight
02-19-2004, 10:32 AM
man, i cant figure out vim at all. every time i push a button it beeps, and i cant use any of the commands.

I cant even figure out how to exit the friggen program--hows that for a n00b?

and how does one get into command mode?

i cant deal with this. i'm sticking to nano.

sicarius
02-19-2004, 05:21 PM
Well, the beeping usually comes from trying to do something in command mode that isn't a command.

When vi opens, it is automatically in command mode. There are several ways to enter insert mode (sometimes called edit mode). The most basic is to hit 'i'.

Once you are in insert mode you simply press escape to reenter command mode. if you press escape again you may hear a beep. This just lets you know you are in command mode. Most of the time, if you are unsure what mode you are in just hit escape a few times until you hear the beep.

To quit vi just use the following sequence of keystrokes while in command mode

:q

the above will quit vi, but in some cases (for example when you have changed something in a file and have not saved) it will not quit and issue a warning.

If you have made some change to a file and wish to exit without saving use the command

:q!

If you wish to save the file THEN quit vi use the command

:wq

More generally if you want to save the file under its current name you can use the command

:w

then you can use :q to quit normally.

vi is a great editor once you get the hang of it. I am certain that after a few hours of using it you will decide that nano is inferior.

Strike
02-19-2004, 08:13 PM
Whiteknight: vimtutor

Whiteknight
02-20-2004, 10:01 AM
awesome, I've had a shell locked up in vi for about 2 months now because i couldnt close the program, and didnt want to reset my server to get the shell back.

so, i just hit alt+F3 and continued my business like normal. I'm sure nano is inferior, and i'll probably migrate to vi eventually (i've been having a hell of a time acclimatizing to emacs lately)

kmj
03-03-2004, 07:54 PM
Originally posted by Whiteknight
awesome, I've had a shell locked up in vi for about 2 months now because i couldnt close the program, and didnt want to reset my server to get the shell back.


Lol! :D vi does have a steep learning curve, but vim eases it, and you can google for "vim tutorial" for a plethora of helpful web articles.

tjohnsson
04-01-2004, 01:50 AM
Just for fun...

....Microsoft report cites research indicating that vi users have 12% less hair than Word users....

http://humorix.org/articles/2004/03/vi-vs-word/

-- I'm vim user too --

hungry_dog
05-07-2004, 05:08 AM
ya i know that vi saves any unsaved file whenever there is any power cut or ur system gets restarted ....... but can anybody tell me something about numbered buffers ......

kmj
06-27-2004, 12:22 AM
Ah, but I'll bet Word users write significantly less than 78% less code than vi users. :p

kmj
06-27-2004, 12:24 AM
Originally posted by hungry_dog
ya i know that vi saves any unsaved file whenever there is any power cut or ur system gets restarted ....... but can anybody tell me something about numbered buffers ......

:help buffer should give you all the help you need