You are on page 1of 14


Command line options

vim +n file vim + file vim +/pattern file
Open file and place cursor at line n Open file and place cursor at last line of file Open file and place cursor at first occurrence of pattern Hint: When you want to close a file and continue working on it later, place a pattern such as ZZZ where you stopped editing to easily return there when you reopen the file. Open file in read-only mode (can use :w! to override)

view file or vim -R file

-b -d old_file new_file -E -g -o, -O

The file should be opened as binary. Start in diff mode (same as calling vimdiff). Start in improved ex mode (extended regular expressions). Start in GUI mode (gvim). Open all files in new horizontal (o) or vertical (O) windows. One can also optionally specify the exact number of windows to open.

Save / Load / Quit / Run cmd

:w range >>newfile
Save the current file. If range is present, then only that particular range of lines is saved (see section ex mode for how a range of lines is specified). If newfile is present then the current buffer (or specified range) is saved in a file named thus (newfile may include a whole path). If >> is present then the buffer (or range) is appended to newfile. Note that including newfile does not change the current file name. That is, if you subsequently type :w then the buffer will be saved under the old file name. reload the current file (add ! to discard changes) (or load another file if specified) quit (add a to quit all buffers, add ! to discard changes). Run <cmd> from linux. Use <cmd>=bash for access to the shell. Save and exit (like :wq), but save only if there are changes since the last save. (This is important e.g. in the context of make which checks timestamps).

:e[!] newfile :q[a][!] :!<cmd> :x

:nr filename :nr !<shell cmd> :<range> !<shell cmd>

Read the contents of file filename and place them after the current cursor line (n absent) or after line n if n present. Execute <shell_cmd> under the shell and write the output after line n or after the current line if n absent.

Pass the lines of <range> (or the current line if !! is used instead of <range>!) as standard input to <shell_cmd>, and replace them with the standard output of <shell_cmd>.

Cursor Movement
h, j, k, l , , , 0, $ ^, +, -, [Enter] b, B w, W e, E nG mx ``, ''
Move to beginning (0) or end ($) of the current line. Move to the first non-blank character of this line (^), the next (+), or the previous (-) line. [Enter] is the same as + Move to the beginning of the previous word (b counts symbols and punctuation as words, B does not). Move to the beginning of the next word (w counts symbols and punctuation as words, W does not). Move to the next end of word (e counts symbols and punctuation as words, E does not). Go to line n, or go to end of file if n absent. Mark current position as x (x can be any letter). Return to the last mark set, or to the position of last edit, or to the position from where the last G movement command was issued, or to position from where a search was started, whichever occurred last. `` moves to the exact position, while '' to the beginning of the line. Go to exact position marked as x (`) or to the beginning of the line containing the mark x ('). If n absent, move to top line of screen (H) or middle line (M) or last line (L). If n present, move to n lines below first line of the screen (nH) or n lines above the last line (nL). Move to column n of current line. Go to matching bracket (), [], {} Go to n percent of the file single character movement.

`x, 'x nH, M, nL

n| % n%

Movement by search
/<pattern>[Enter] ?<pattern>[Enter] n, N fx, Fx tx, Tx
Go to next occurrence of <pattern> (can be a regular expression). Go to previous occurrence of <pattern>. Go to next (n) or previous (N) occurrence of the most recently searched pattern. Go to the next (f) or previous (F) occurrence of character x (x may be any character) in the present line. Go to the character immediately before the next occurrence of character x (x may be any character) (t) or immediately after the previous occurrence of x (T) in the present line. Repeat most recent character search

These may be used after a command (e.g. diw deletes the inner word that is, without the spaces on either side where the cursor lies; the cursor does not have to be at the beginning of the word). They may be also used in visual mode to select the respective text.

aw, aW, iw, iW a[, i[

a w(W)ord, inner w(W)ord a [] block, inner [] block. If a repeat count n is used then this goes back to the n-th unclosed [ and selects up to (and including in case of a[) the matching ]. a () block, inner () block. a <> block, inner <> block. a {} block, inner {} block. Quoted string blocks (only work within single line).

a(, ab, i(, ib a<, i< a{, aB, i{, iB a', a, a`, i', i, i`

Visual mode
v, V
Press to enter / exit visual mode per character (v) or per line (V). In this mode any movement causes selection of the text from the original position to the new position. See also text-objects. Then the following may be performed on the selected text: Change case

~ d, c, y >, < ! = gq

Delete, Change, Yank Shift right (>), left (<) Filter through external command Filter through 'equalprg' option command Format lines to 'textwidth' length

Editing Text
In the following, <pos> is a cursor position determined by commands described in section Cursor Movement above.

i, I

Insert text at cursor position (i) or at the beginning of the current line (I) goes into insert state. Use a repeat count to repeat the text typed between pressing the i (or I, a, A) and the ESC key. Insert (append) text after the cursor (a) or after the end of the line (A) goes into insert state. Insert a blank line below (o) or above (O) the cursor, move cursor to the beginning of that line, and go into insert state Substitute single character (s) (use repeat count for many characters), or whole line (S) (use repeat count for many lines) (same as cc) goes into insert state.

a, A o, O s, S

x, X r R ~ g~~, J g~w

Delete single character below cursor (x) like the delete key, or single character before cursor (X) like backspace Replace single character below cursor Overwrite mode Change case of single character below cursor (use repeat count for more). Change case of entire line, or up to end of current word. Join the present line with the next one. Use a repeat count to join more lines that follow.

c<pos>, C, cc d<pos>, D, dd y<pos>, yy p, P

Change (replace) from cursor to <pos>, or from cursor to the end of line (C) equivalent to c$, or the whole line (cc) Delete from cursor to <pos>, or from cursor to the end of line (D) equivalent to d$ or delete whole line (dd)
Yank (copy) from cursor to <pos>, or yank whole line (yy) Paste deleted (d,D) or yanked (y,Y) text after (p) or before (P) the cursor position. If whole lines have been deleted (dd) or yanked (yy) then p puts them below the cursor and P puts them above the cursor. See also buffers.

np, nP
Vim remembers the last 9 lines that have been deleted (dd) and holds them in a corresponding buffer. np (or nP) pastes the contents of buffer number n (1=latest, 9=oldest deletion).

1pu.u.u etc. xd<pos>, xdd, xy<pos>, xyy Xd<pos>, Xdd, Xy<pos>, Xyy xp, xP

Search backwards through the numbered buffers. Each successive redo (.) causes the buffer number to increase. Delete (d) or yank (y) and store the text in named buffer x where x can be any lowercase character. Any previous contents of that buffer are overwritten. Delete (d) or yank (y) and append the text in named buffer x where x is the lowercase character corresponding to the uppercase character X. Put the contents of buffer x before (p) or after (P) cursor.

Other editing commands

u, U
[Ctrl]-r, :redo Undo last command (u), or undo all changes while cursor has been positioned on the current line (U) Redo last undone command ([Ctrl]-r can take a repeat count).

Repeat last command

Screen movement
[Ctrl] f, b [Ctrl] d, u [Ctrl] y, e Scroll one screen forward (C-f) or backward (C-b) Scroll half screen down (C-d) or up (C-u) Scroll one line forward (C-y) or backward (C-e)

nz[Enter] z. z-

Scroll screen such that the current line (if n absent) or line n appears at the top of the screen. Scroll screen such that the current line (if n absent) or line n appears at the middle of the screen. Scroll screen such that the current line (if n absent)or line n appears at the middle of the screen.

[Ctrl] l

Redraw the screen.

ex mode
To issue an ex command in vi press :. Pressing Q in vi goes into ex mode, and entering vi in ex goes to visual (vi) mode. More than one ex commands can be listed on the same line and executed in sequence by separating them with a vertical bar |.

ex operates on line numbers. A range of line numbers takes the form l1,l2 or l1;l2 or just l1 for a single line, or % for all lines in the file, where l1 and l2 can be either absolute line numbers or expressions. Expressions can be constructed using line numbers, the + and operators. The use of special symbols is permitted:

. $ %

current line last line of file

every line of file (this is a range by itself, not a line number)

An expression takes the form s+n or sn. If s is missing, it is assumed to be equal to . (the current line number but see below), and if n is missing it is assumed to equal 1. If a range is given by l1;l2 (ie. using a semicolon separator (;) rather than a comma separator (,)) and l2 itself is given by an expression where s is absent, then s is assumed to equal not the present line number . but the line number l1. Another way to identify a line number is the expression /pattern/ which means the number of the next line which contains pattern.

:<range> d :<range> m <dest> :<range> co <dest>

Delete the lines with numbers contained in <range> Move the lines with numbers contained in <range> after line number <dest>. Use <dest> = 0 to move the lines to the top of the file. Copy the lines with numbers contained in <range> after line number <dest>.Use <dest> = 0 to move the lines to the top of the file. t may be used instead of co. Yank the lines with numbers contained in <range> in buffer named after the character x. For each line in the whole text (or within <range> if present) that contains pattern (or that does not contain pattern if ! is present), execute command. In command, the current line may be denoted by .

:<range> ya x

:<range>g[!] /pattern/command


:/pattern/;+10 m 0

Move the next line containing the string pattern and the 10 lines immediately following it to the top of the file (the spaces before and after m are not necessary). Copy line 25 and all the following lines up to and including the line immediately following the present line to the end of the file. Delete all blank lines, plus any lines that contain only whitespace (tab denotes a tab).

:25,+ co $ :g/^[ tab]*$/d

Global replacements
:range s/pattern1/pattern2/g
Substitute all occurrences of pattern1 with pattern2 within the lines specified by range, or in the current line if range is absent. By removing g only the first occurrence in each line is substituted. You can add a c after g to ask for confirmation for each substitution. Instead of / One can use any other non-alphanumeric, now-whitespace character except \, and |. This is useful if / is part of a pattern, unless you use backslashes to escape the slashes of the pattern. pattern1 can be a regular expression, while some metacharacters can be used also for pattern2 see book p. 78.

This is similar to the substitution command described above, only that the substitution of pattern1 with pattern2 occurs only in those lines containing pattern0.

ex scripts
To automatically source ex script code, place it in ~/.vimrc. If you want to automatically source ex code depending on the current directory in which vim is launched, place this code in a file .exrc in that directory, and place the following line in ~/.vimrc:

set exrc

:so script

Sources script (which must be in the present directory). This signifies the beginning of a comment.

Abbreviations and mapping

:ab abbr phrase :map x sequence
Substitute abbr for phrase whenever it is typed as a whole word. Use unab to reset. Whenever x is pressed, act as if the sequence of keys has been pressed in that order. The sequence may include a colon : so that ex commands may be executed this way. To include special characters such as ENTER in the sequence press Ctrl-v, then the special character. Use unmap to reset. Use :map to list all mapped keys. Use #n instead of x to map to function key n. Use imap instead of map so that the sequence will apply to insert mode.

For programmers
:set list
Makes tabs show as ^I and end of lines as $. Use :set nolist to deactivate.

:set autoindent
When you press enter the cursor goes to the next line and indents by the same amount as before pressing enter. If writing comments, and you move past the textwidth limit (see options), the writing automatically continues at the next line, same indentation level, without needing to insert the comment symbol. Smarter than autoindent, it recognizes do loops, if constructs, etc. and indents accordingly. To recognize these constructs, it uses the keywords stored in option cinwords, whose default value is if,else,while,do,for,switch (case sensitive) as you can see by :set cinwords?. To add additional keywords appropriate to Fortran, add them to cinwords, e.g. :set cinwords+=IF. Reduce / increase indentation (in insert mode). Reduce / increase indentation (in command mode) may use repeat counts as well for multiple lines. Sets indentation to n spaces. Note that if n=8 then a tab will be used instead of 8 spaces. Uses spaces instead of tabs.

:set smartindent

[Ctrl]-D, [Ctrl]-T

<<, >> :set shiftwidth=n :set expandtab

:ta[g] [/]name
Opens the appropriate file containing the function name (or a function whose name matches the regular expression name if / is present before name) and moves the cursor to the beginning of this function. This can be performed in command mode by placing the cursor at the beginning of name in the text and pressing [Ctrl]-]. Like tag, but opens the file in a new window (splits the current window). List all tags matching name (or a function whose name matches the regular expression name if / is present before name), allowing to make a selection.

:stag [/]name :ts [/]name

:sts [/]name :set tags=tagsfile

Like :ts but splits the window for the selected tag.
Sets the path and filename of the file which contains the tag definitions. This is constructed using the command ctags from the shell (package ctags-exuberant).

:tags :nta[g]

Show the tags stack. Jump to the n-th newer entry in the tags stack. In command mode: Pop a cursor position off the stack, restoring the cursor to its previous position. Use a counter to specify how many elements to pop off the stack. Same as [Ctrl]-T, but for ex-mode. n is the optional counter.


:ntn, :ntp :tr, :tl

Jump to the n-th next (or previous) tag default is 1. Jump to the first (rewind) or last matching tag. Use a counter with :tr to jump immediately to the n-th matching tag.

Line commands applied to folded lines apply to the whole fold.

:set foldmethod=method :set foldcolumn=n :set foldenable zi

method can be any of manual, indent, expr, syntax, diff, marker.

Set the first n leftmost columns as a visual aid for folding. Enable folding Toggle foldenable option.

za, zA zc, zC zo, zO zd, zD zE zj, zk zf zm, zr zM, zR :mkview :loadview

Toggle fold of current cursor position, either just one fold (za) or all folds recursively (zA). Close folds. Open folds. Delete folds. Eliminate all folds.

Move to the start of the next fold (zj) or to the end of the previous fold (zk).
Manual folding: Create fold from current line up to the line of the next movement command. Indent folding: Decrement (zm) or increment (zr) the value of the foldlevel option by one. Indent folding: Close all folds (zM, set foldlevel=0) or open all folds (zR, set foldlevel=max).
Save folds for future session. Load folds saved from previous session.

Multiple windows
:nsplit filename ^Ws
Break current window into two horizontal windows, both containing the current buffer if filename is absent or the shortcut version ^Ws is used, or containing the specified file in the top window. If n is present then it determines the number of lines of the top window. Similar to split, but the window is split vertically. Similar to split, but a new empty file is created at the top window. Vertical version of new.

:nvsplit filename ^Wv :nnew :nvnew :set winheight= :set winwidth= :set equalalways ^Wn

These set the minimum size of the current window.

Set size of all windows equal when adding or removing windows. Can be combined with the set eadirection= option which can take the values hor, ver, or both to set a particular direction in which window sizes must be equal. Set the command line height (in number of lines). Quit current window, close current window. Make the current window the only window (close all others).

:set cmdheight=n ^Wq, ^Wc ^Wo

Moving between windows

^W h, j, k, l ^W , , , ^W t, ^W b ^W w ^W W ^W p
Move to the top leftmost or bottom rightmost window. Move to next window down or to the right (cycles through windows) Move to previous window up or to the left (cycles through windows) Move to the previous window accessed. Move cursor to the window in the respective direction.

Reposition the windows

^W r, ^W R, ^W x
Rotate the windows forward (r) or backward (R), or exchange the current with the next window (x) in the latter case, a repeat count n can be used to exchange with the n-th next window. Move the current window to occupy the left (H), bottom (J), top (K) or right (L) part of the screen. Move window to a new tab.

^W H, J, K, L ^W T

Resize the windows

Although there are commands to do that, it is easier to :set mouse=a and move the window borders with the mouse.

Lists buffers. Flags shown:

u=unlisted buffer (shown only by :ls!) %=current buffer #=next buffer a=active (visible) h=hidden (no windows assigned) -=readonly, but this can be overridden. ==readonly, but cannot be overridden. +=modified buffer x=buffer with read errors. :windo cmd :bufdo cmd :badd file :bdelete :[s]buffer n :[s]bnext :[s]bprevious :[s]bfirst, [s]blast :[s]bmod n
Execute ex command cmd at all open windows. Execute ex command cmd at all buffers. Add file to list of buffers. Unload buffer and remove from buffer list. Move to buffer n (sbuffer opens it in a new window). Move to next buffer (sbnext opens it in a new window). Move to the previous buffer. Move to the first or last buffer. Move to n-th modified buffer (or next modified if n absent).

:tabs :tabnew file :tabclose :tabonly ^W T :ngt :tabn n, tabp
Displays a list of open tabs. Open file in a new tab (or an empty tab if file absent). Close current tab. Close all other tabs. Move window to a new tab.

Go to next tab (n absent) or to tab n.

Navigate among tabs. If n present, go to tab n.

[Ctrl]-[PgDn], [Ctrl]-[PgUp] Navigate among tabs in gvim.

:tabf file :tabdo cmd :mksession filename

Open file in a new tab. Execute ex command cmd at all open tabs. Saves tabs and windows information, so that after closing the file and needing to reopen it you can revoke them with the command :source filename.

[Ctrl]-n, [Ctrl]-p Keyword completion: Search text forward (n) or backward (p). Each source of completion is denoted by a single character in a commaseparated list in the complete option (.=keywords in current buffer, b= in other loaded buffers, t=in tags etc). You can assign this task to the tab key thus: :imap <tab> <c-n> (use :iunmap <tab> to release the tab key to its original use).

All other completion commands start with [Ctrl]-x, followed by: [Ctrl]-n, [Ctrl]-p Keyword completion: Search text forward (n) or backward (p) to find a matching word (the iskeyword option contains the characters which define words the default options are for all alphanumeric characters and underscore). Line completion match whole line. Completion by dictionary, defined by the dictionary option. The dictionary contains one word per line. Completion by thesaurus, defined by the thesaurus option. The thesaurus file contains a list of words of similar meaning per line. Tag completion. Filename completion.

[Ctrl]-l [Ctrl]-k [Ctrl]-t [Ctrl]-] [Ctrl]-f

Also, after performing a particular completion, if the particular completion proposed first is not satisfactory, one can cycle through all possibilities thus: [Ctrl]-n [Ctrl]-p Next possibility. Previous possibility.

Various options
:set option+=x (-=x) :set incsearch :set wrap (nowrap) :set sidescroll = n
Adds (+=) or removes (-=) character x from option. Sets searches to be incremental. Sets long lines to wrap (or not) at the edge of the screen. Sets the number of positions to scroll when the cursor moves past the side of the screen. Set n = 0 so that each scroll puts the cursor in the middle of the screen. (n=1 recommended for modern PCs).

:set sidescrolloff=n Sets the number of positions to always exist between the cusror and the edge of the screen. E.g. if set to 10 then when only 10 characters appear between the cursor and the right edge of the screen, then moving the cursor further right will cause scrolling. :set laststatus=1
Set to 1 to always display status line at the bottom, or to zero to not display it.

:set mouse=a :set mouse= :set textwidth=n

Activate the mouse for all uses. Disable mouse. Text wraps when characters in a line exceed n characters.

Syntax highlighting
:syntax enable :syntax on :set syntax=fortran
Enable syntax highlighting. Turn on syntax highlighting. Explicitly set the syntax highlighting to a specific type (here fortran see syntax definition file $VIMRUNTIME/syntax for more possibilities) should not normally be necessary. Activate a particular color scheme (see directory $VIMRUNTIME/colors for available schemes).

:colorscheme name

:set background=dark Or light according to the background. :highlight

Display highlight definitions and their values (some groups have defined values, others link back to other groups).

:highlight group parameters Set the highlighting of the words belonging to group, according to the parameters. To see the available groups type :highlight without arguments. The groups depend on the loaded syntax of the present filetype (see :set syntax above). The parameters are as follows: term= cterm= gui= ctermfg= guifg=
appearance on terminals without color (NONE, bold, underline, italic, inverse,standout) appearance on terminals with colors (bold, italic etc.) appearance on gvim foreground color on terminals with color (8+8 DOS colors available). color on GUI (gvim), use codename (e.g. blue) or description (#rrggbb).

Custom highlighting: Insert appropriate highlight commands as described above in a file ~/.vim/after/syntax/fortran.vim. These will replace the respective commands from the $VIMRUNTIME/syntax/fortran.vim default file. The ~/.vim/after directory must be in the runtimepath option. If not, add it:

:set runtimepath+=~/.vim/after


:set makeprg=gcc :make arguments :cw
Set the external program which will be used as compiler (default = make). Call the external compiler followed by the arguments. Open a window showing the quickfix list, if there are any compiletime errors (see :help quickfix for more commands) Within the window each line describes an error: press ENTER or double-click on a line to go to the respective line of code in the main window. In order for vim to pass the output of the compiler as a list of errors, it needs to know the particular output format of the compiler. This is set through the errorformat option (see :help efm). For gfortran an appropriate option is (from

set efm=%E%f:%l.%c:,%E%f:%l:,%C,%C%p%*[0123456789^],%ZError:\ %m,%C%.%#

Other stuff
Convert the lines specified in <range> to html in a new window. If you want the whole text, just use the Convert to html option from gvim (Syntax menu).

When editing a fortran file, vim loads the plugin: /usr/share/vim/vim71/ftplugin/fortran.vim To see what this does type:

:help ft-fortran-plugin
Also useful:

:help ft-fortran-syntax :help ft-fortran-indent

According to the first of these two help files, to :set foldmethod=syntax you must first set one or more of the following, before turning syntax on:

:let fortran_fold=1

main programs, subroutines, functions, block data, interface blocks, modules. do loops, if blocks, select case constructs.

:let fortran_fold_conditionals=1

:let fortran_fold_multilinecomments=1 Comment regions more than 2 lines. :let fortran_more_precise=1

Make syntax highlighting better, but slower.