Vim is the most powerful and most popular of the vi clones currently in use. It is the default version of vi on most GNU/Linux systems.
-b
Start in binary mode.
-c
command
Execute command at startup (POSIX
version of the historical
+
command).
-C
Run in vi compatibility mode.
-f
For the GUI version, stay in the foreground.
-g
Start the GUI version of Vim, if Vim was compiled with support for the GUI.
-i
viminfo
Read the given viminfo file for initialization instead of the default viminfo file.
-o
[N
]Open N windows, if given; otherwise, open one window per file.
-O
[N
]Like -o
, but split the windows
vertically.
-n
Don’t create a swap file: recovery won’t be possible.
-p
Open a new tab for each file named on the command line.
-q
filename
Treat filename as the “quick fix” file.
-R
Start in read-only mode, setting the
readonly
option.
-s
Enter batch (script) mode. This is only for ex and intended for running editing scripts (POSIX version of the historical “–” argument).
-u
vimrc
Read the given .vimrc file for initialization and skip all other normal initialization steps.
-U
gvimrc
Read the given .gvimrc file for GUI initialization and skip all other normal GUI initialization steps.
-y
Enter “easy” mode, which provides more intuitive behavior for beginners.
-Z
Enter restricted mode (same as having a leading
r
in the name).
Vim lets you split the screen into multiple windows and control their size and placement.
Command | Function |
---|---|
| Close the current window; behavior affected by
the |
| Close the current window, if it’s not the last one on the screen |
[ | Create a new window, editing an empty buffer |
| Make this window the only one on the screen |
| Exit Vim |
| Quit the current window (exit if given in the last window) |
| Increase or decrease the current window height by n |
| Set the current window height to n if supplied; otherwise, set it to the largest size possible without hiding the other windows |
[ | Split the window and move to the next file in the argument list, or to the Nth file if a count is supplied |
[ | Split the current window in half |
| Split the window and run the
|
[ | Same as |
| Write all modified buffers that have filenames |
| Write all changed buffers and exit |
| Same as |
Similar to modern web browsers, Vim lets you create and manage multiple tabs. Within each tab, there can be multiple windows. You can then switch back and forth between tabs. This is an easy way to work on multiple unrelated editing tasks without cluttering up your screen. Tabs are supported in both the character and the GUI versions of Vim.
Tabs are numbered from one.
Command | Function |
---|---|
[count ]
tab
command | Run command, but open a new
tab when otherwise a new window would be opened, e.g., use
|
tabc [lose ][! ]
[count ] | Close the current tab page. With
count, close the page whose number is
indicated in count. Use
|
tabdo
command | Execute command for each tab. |
tabe [dit ]
[option ]
[command ]
[file ] | Open a new page with a window editing file. With no arguments, open an empty page. |
tabf [ind ]
[option ]
[command ]
file | Open a new page and search for
file in the value of the
|
tabf [irst ] | Move to the first tab. |
tabl [ast ] | Move to the last tab. |
tabm [ove ]
[N ] | Move the current tab page to after tab page N (change the ordering of the tab pages themselves, not which tab you’re working in). With no argument, make the current tab become the last one. |
tabnew
[option ]
[command ]
[file ] | Same as
|
tabn [ext ]
[count ] | Move to next tab, or to tab count. |
tabN [ext ]
[count ] | Same as
|
tabo [nly ][! ] | Close all other tab pages. |
tabp [revious ]
[count ] | Move to previous tab, or go back count tabs. This wraps around. |
tabr [ewind ] | Move to the first tab (same as
|
The control sequences work in both command mode and insert mode.
Command | Function |
---|---|
| Same as |
| Same as |
^W gf | Edit the filename under the cursor in a new tab page |
^W gF | Edit the filename under the cursor in a new tab page, starting at the line number following the filename |
{...}
Defines an interval expression. Interval expressions describe counted numbers of repetitions. In the following description, n and m represent integer constants:
{
n
}
Matches exactly n repetitions of the previous regular expression.
{
n
,}
Matches n or more repetitions of the previous regular expression, as many as possible.
{
n
,
m
}
Matches n to m repetitions.
For Vim, n and m
can range from 0 to 32,000. Vim requires the backslash only on the
{
and not on the }
. Vim
extends traditional interval expressions with additional matching
notations, as follows:
{,
m
}
Matches 0 to m of the preceding regular expression, as much as possible.
{}
Matches 0 or more of the preceding regular
expressions, as much as possible (same as
*
).
{-
n
,
m
}
Matches n to m of the preceding regular expression, as few as possible.
{-
n
}
Matches n of the preceding regular expression.
{-
n
,}
Matches at least n of the preceding regular expression, as few as possible.
{-,
m
}
Matches 0 to m of the preceding regular expression, as few as possible.
i
Matches any identifier character, as defined by the isident
option.
I
Like i
, excluding digits.
k
Matches any keyword character, as defined by the iskeyword
option.
K
Like k
, excluding digits.
f
Matches any filename character, as defined by the isfname
option.
F
Like f
, excluding digits.
p
Matches any printable character, as defined by the isprint
option.
P
Like p
, excluding digits.
s
Matches a whitespace character (exactly a space or tab).
S
Matches anything that isn’t a space or a tab.
Backspace.
e
Escape.
Carriage return.
Tab.
Matches the end of line.
~
Matches the last given substitute (i.e., replacement) string.
(...)
Provides grouping for *
,
+
, and =
, as well as
making matched subtexts available in the replacement part of a
substitute command (1
, 2
,
etc.).
1
Matches the same string that was matched by the first
subexpression in (
and )
.
2
, 3
, and so on, may be
used to represent the second, third, and so forth subexpressions.
The isident
, iskeyword
,
isfname
, and isprint
options
define the characters that appear in identifiers, keywords, and
filenames, and that are printable, respectively.
Vim keeps a history of ex commands that you have issued. You can recall and edit commands from that history and use the completion facilities to save typing when entering commands.
Key | Meaning |
---|---|
↑, ↓ | Move up (previous), down (more recent) in the history |
←, → | Move left, right on the recalled line |
INS | Toggle insert/overstrike mode; default is insert mode |
BACKSPACE | Delete characters |
SHIFT or CONTROL combined with ← or → | Move left or right one word at a time |
| Move to the beginning of the command line |
| Move to the end of the command line |
If Vim is in vi compatibility mode, ESC acts likes ENTER and executes the command. When vi compatibility is turned off, ESC exits the command line without executing anything.
The wildchar
option contains the character
you type when you want Vim to do a completion. The default value is
the tab character. You can use completion for the following:
Available at the start of the command line.
After you’ve typed :tag
.
When typing a command that takes a filename argument (see
:help suffixes
for details).
When entering a :set
command, for both
option names and their values.
Command | Function |
---|---|
Insert all names that match the pattern | |
| List the names that match the pattern; for filenames, directories are highlighted |
| If there is exactly one match, insert it; otherwise, expand to the longest common prefix of the multiple matches |
| Go to next of multiple
|
| Go to previous of multiple
|
Value of
| (Default: tab) Perform a match, inserting the generated text; pressing TAB successively cycles among all the matches |
Vim provides ex and vi commands for managing the tag stack.
Command | Function |
---|---|
[ | Pop a cursor position off the stack, restoring the cursor to its previous position |
| Like |
| Edit the file containing tagstring as defined in the tags file |
[ | Jump to the Nth newer entry in the tag stack |
| Display the contents of the tag stack |
| Jump to the last matching tag |
[ | Jump to the Nth next matching tag (default one) |
[ | Same as
|
[ | Jump to the Nth previous matching tag (default one) |
[ | Jump to the first matching tag; with N, jump to the Nth matching tag |
| List the tags that match tagstring, using the information in the tags file(s) |
Vim provides several commands to increase programmer productivity.
Command | Function |
---|---|
| Display error n if supplied; otherwise, redisplay the current error |
| Read the error file and jump to the first error |
| Display error n if supplied; otherwise, display the last error |
| List the errors that include a filename |
[ | Display the Nth next error that includes a filename |
[ | Display the Nth previous error that includes a filename |
| Display error n if supplied |
| Quit with an error code so that the compiler won’t compile the same file again; intended primarily for the Amiga compiler |
| Run make, based on the settings of several options as described in the next table, then go to the location of the first error |
Option | Value | Function |
---|---|---|
| | A description of what error messages from the compiler look like; this example value is for gcc, the C compiler from the GNU Compiler Collection |
| | The name of a file that will contain the compiler
output; the |
| | The program that handles the recompilation |
| | The shell to execute the command for rebuilding your program |
| | Whatever is needed to cause the shell to save both standard output and standard error from the compilation in the error file |
Vim provides multiple mechanisms for finding identifiers that are of interest.
Command | Function |
---|---|
| List all the included files that couldn’t be
found; with the |
[ | Like |
[
| Like |
[ | Like |
[ | Like |
[ | Like |
[ | Like |
[ | Like |
[ | Like |
Command | Function |
---|---|
| Display the first macro definition for the identifier under the cursor |
| Display the first macro definition for the identifier under the cursor, but start the search from the current position |
| Display all macro definitions for the identifier under the cursor; filenames and line numbers are displayed |
| Display all macro definitions for the identifier under the cursor, but start the search from the current position |
| Jump to the first macro definition for the identifier under the cursor |
| Jump to the first macro definition for the identifier under the cursor, but start the search from the current position |
| Open a new window showing the location of the first macro definition of the identifier under the cursor; with a preceding count, find the specified occurrence of the macro |
| Display the first line that contains the keyword under the cursor |
| Display the first line that contains the keyword under the cursor, but start the search at the current position in the file; this command is most effective when given a count |
| Display all lines that contain the keyword under the cursor; filenames and line numbers are displayed |
| Display all lines that contain the keyword under the cursor, but start from the current position in the file |
| Jump to the first occurrence of the keyword under the cursor |
| Jump to the first occurrence of the keyword under the cursor, but start the search from the current position |
| Open a new window showing the location of the first occurrence of the identifier under the cursor; with a preceding count, go to the specified occurrence |
Provide a preceding count to these commands to move forward or backward by more than one instance of the desired search text.
Command | Function |
---|---|
| Extended to match the |
| Move to the Nth previous
unmatched |
| Move to the Nth next
unmatched |
| Move to the Nth previous
unmatched |
| Move to the Nth next
unmatched |
| Move to the Nth previous
unmatched |
| Move to the Nth next
unmatched |
| Move to the Nth previous
unmatched start of a C comment,
|
| Move to the Nth next
unmatched end of a C comment,
|
Option | Function |
---|---|
| Simple-minded indentation; uses that of the previous line |
| Similar to |
| Enables automatic indenting for C programs and is quite smart; C formatting is affected by the rest of the options listed in this table |
| Input keys that trigger indentation options |
| Options that tailor your preferred indentation style |
| Keywords that start an extra indentation on the following line |
| A number of single-letter flags that control several behaviors, notably how comments are formatted as you type them |
Describes different formatting options for different kinds of comments, both those with starting and ending delimiters, as in C, and those that start with a single symbol and go to the end of the line, such as in a Makefile or shell program |
Folding is enabled with the foldenable
option.
There are six folding methods,
controlled by the foldmethod
option, as follows:
diff
Folds are used for unchanged text.
expr
Folds are defined by a regular expression.
indent
Folds are defined by the
indentation of the text being folded and the value of
shiftwidth
.
manual
Folds are defined using regular Vim commands (such as the search and motion commands).
marker
Folds are defined by predefined markers (which you can change) in the text.
syntax
Folds are defined by the syntax of the language being edited.
Command | Function |
---|---|
range
fo [ld ] | Create a fold for the lines in range. |
range
foldc [lose ][! ] | Close folds in range. With
|
[range ]
folddoc [losed ]
command | (Fold do closed.) Similar to the
|
[range ]
foldd [oopen ]
command | (Fold do open.) Similar to the
|
range
foldo [pen ][! ] | Open folds in range. With
|
Folding commands start with z
, since it looks
something like a folded piece of paper, viewed from the side.
Command | Function |
---|---|
za | Toggle folding. On an open fold, close one or
count folds. On a closed fold, open folds
and set |
zA | Like |
zc | Close one or count folds under the cursor. |
zC | Close all folds under the cursor. |
zd | Delete the fold under the cursor. Nested folds are moved up a level. Careful! This can delete more than you expect, and there is no undo. |
zD | Delete folds recursively starting under the cursor. |
zE | Eliminate all folds in the window. |
zf
motion | Create a fold. |
zF | Create a fold for count
lines (like |
zi | Toggle the value of
|
zj | Move down to start of next fold or down count folds. |
zk | Move up to start of previous fold or up count folds. |
zm | Fold more by subtracting one from
|
zM | Close all folds, set
|
zn | Fold “none”: reset |
zN | Fold “normal”: set |
zo | Open one or count folds. |
zO | Open all folds under the cursor. |
zr | Reduce folding. Adds one to
|
zR | Open all folds and set
|
zv | Open enough folds to make the line with the cursor visible (view the cursor). |
zx | Update folds by undoing manually opened and
closed folds, reapplying |
zX | Undo manually opened and closed folds, then
reapply |
[z | Move to start of current open fold. If already there, move to start of containing fold if there is one; otherwise, fail. With count, repeat the given number of times. |
]z | Like |
Option | Default |
---|---|
foldclose (fcl) | 0 |
foldcolumn (fdc) | 0 |
foldenable (fen) | |
foldexpr (fde) | 0 |
foldignore (fdi) | |
foldlevel (fdl) | 0 |
foldlevelstart (fdls) | –1 |
foldmarker (fmr) | |
foldmethod (fdm) | |
foldminlines (fml) | 1 |
foldnestmax (fdn) | |
foldopen (fdo) |
|
foldtext (fd) |
Vim provides completion facilities: the ability to enter only a part of the final text and have Vim provide you with a list of suggested completions based on the commands you use and the content of the current files.
The completion commands (except for completion with the
complete
option) are two-keystroke combinations that
start with CTRL-X. Most second keystrokes are not bound
to actions in input mode, so it is often useful to map the second
keystroke to the original combination, such as :inoremap ^F
^X^F
.
The completion commands present a list of choices that you can cycle through using CTRL-N and CTRL-P (for “next” and “previous,” respectively). Use CTRL-E to end the completion without making a choice, and use CTRL-Y or ENTER to select the current choice and insert it.
The completion facilities are not simple, but they bring considerable power and time savings to long editing sessions. It is worthwhile to invest time to learn to use them. See Chapter 14 of Learning the vi and Vim Editors for the details.
The order here is alphabetic by keystroke. Commands marked with a ✓ allow use of the second character to move to the next candidate, along with the regular CTRL-N.
Completion with the complete
option is the
most customizable and flexible method.
Command | Completion | Description |
---|---|---|
| Using | Do completion searching forward
( |
^X ^D ✓ | Macro names | Search the current and included files for macros
(defined with |
^X ^F ✓ | Filename | Look for filenames (not file contents) that match
the word under the cursor. The |
^X ^I | Keyword in file and included files | Similar to keyword completion ( |
^X ^K ✓ | Dictionary | Search the files in the comma-separated list that is the value
of the |
^X ^L ✓ | Whole line | Search backward in the file for a line matching
what you’ve typed so far. Typing |
| Keyword in file | Search forward ( |
^X ^O ✓ | Omni | Call the Vim function named by the
|
| Spelling | Offer possible spelling corrections for the word
under the cursor.
Spellchecking must be enabled with the
|
^X ^T ✓ | Thesaurus | Similar to dictionary completion; search files in
the |
^X ^U ✓ | User function | Call the Vim function named by the
|
^X ^V ✓ | ex command line | Provide completion for Vim commands. This is intended to simplify Vim script development. Repeating the command does additional completion. |
^X ^] ✓ | Tag | Search forward in the current and included files
for the first tag matching the word under the cursor. If
|
The next table describes possible completion sources for use
with the complete
option. Sources are listed
alphabetically. The default value for complete
is
".,w,b,u,t,i"
.
Name | Description |
---|---|
| The current buffer. |
| Other buffers, even those that are not loaded in a window (visible). |
| The current and included files; search for macro definitions. |
| The current and included files. |
| The dictionary files listed in the
|
| Scan file for dictionary
lines that match. May be given multiple times, e.g.,
|
| Use the current spellchecking scheme. |
| The thesaurus files listed in the
|
| Scan file for thesaurus
lines. May be given multiple times, e.g.,
|
| Tag completion. |
| The unloaded buffers in the buffer list. |
| The buffers that are not in the buffer list. |
| Buffers in other windows. |
Option | Default |
---|---|
complete
(cpt ) |
|
completefunc
(cfu ) |
|
completeopt
(cot ) |
|
|
|
dictionary
(dict ) |
|
|
|
infercase
(inf ) |
|
|
|
|
|
omnifunc
(ofu ) |
|
pumheight
(ph ) | 0 |
showfulltag
(sft ) |
|
spell |
|
thesaurus
(tsr ) |
When invoked as either vimdiff or gvimdiff, Vim provides diff mode, which lets you view a comparison of the differences between two files. vimdiff is for use on a standard terminal (or inside a terminal emulator), while gvimdiff uses the GUI facilities of your operating system.
When Vim is built from source, vimdiff and gvimdiff are usually installed as links to Vim. On a system using a package manager, you may have to install them separately.
Figure 1-1 shows an example screenshot of gvimdiff in action. The figure shows the salient points:
Lines that are identical are folded so that they are hidden (see Folding and Unfolding Text for information on folding text).
Lines that appear in one file but not in the other are highlighted (in light blue) in the file in which they are present and are shown as lines of dashes in the file from which they are absent.
Lines that are different between the files are highlighted (in pink), with the actual differences between the lines highlighted in red.
This mode makes it straightforward to move bits of text from one version of a file to another. For example, if you maintain a project using copies of library files from another source, when the source files are revised, it is easy to copy and paste the changes into your version of the file.
Scripting in Vim is a large topic, one deserving of a full book to itself. This section presents some of the barest essentials. For more information, see Chapter 12 of Learning the vi and Vim Editors and the online help.
Vim provides essentially a full-featured programming language with variables, operators, control flow constructs, and the ability to define your own functions. This section looks (briefly) at each of these in turn.
Following vi, comments start with a double-quote character and continue to the end of the line. Typically you put comments on lines by themselves to avoid problems with double-quoted strings, which are also part of Vim’s language.
Vim lets you define your own variables and includes a mechanism to indicate the scope, or lifetime, of a variable. You may also access the value of Vim options. Variable names consist of any number of letters, digits, or underscores, and may not start with a digit. Vim uses special markers in front of the variable or option name to indicate the type and scope. By default, variables are global:
Prefix | Meaning |
---|---|
& | Vim option |
$ | Environment variable |
@ | Register (single-character names) |
a: | Function argument |
b: | Local to the buffer |
g: | Global |
l: | Local to the function |
s: | Local to script read with
|
t: | Local to the tab page |
v: | Vim-defined global variable |
w: | Local to the window |
Two commands assign a value to a variable or remove a variable:
Command | Function |
---|---|
let | Assign a value |
unlet [! ] | Remove a variable; adding |
Numeric values in Vim are always integer values. Prefix a number with
0
(zero) to indicate it is octal (base 8), or with
either 0x
or 0X
to indicate that
it is hexadecimal (base 16). Otherwise, the number is taken as decimal
(base 10).
Vim provides regular arrays (termed lists) and associative arrays (termed dictionaries). As dictionaries may hold functions, you can even do object-oriented programming! See the online help for more information.
The control flow commands are conventional, as described in the following table.
Command | Function |
---|---|
| If-then-else statement. The
|
| Loop over a list of values, setting variable
var to a new value each time before
running commands. This is similar to the
shell |
| While condition is true, execute commands. |
| Catch exceptions (see the online help for details). |
break | Break out of the enclosing
|
continue | Go to the top of the enclosing
|
finish | Exit from a script read with the
|
throw
expr | Evaluate expr and throw the
result as an exception; the exception is caught with a
|
Expressions are built up by applying operators to values. Values are obtained from numeric or string constants and from variables, options, and list or dictionary elements. Most of the operators will be familiar to programmers, and their precedence is generally that of the C language (“The usual precedence is used,” says the online help).
Operators | Meaning |
---|---|
+ − | Addition and subtraction |
* / % | Multiplication, division, and modulus |
. (period) | String concatenation |
e1 ?
e2 :
e3 | The C ternary operator: if e1 is true, use e2, otherwise, use e3 |
== != | Equals and not equals |
< <= | Less than and less than or equals |
> >= | Greater than and greater than or equals |
=~ !~ | Matches and does not match (regular expression matching) |
= | Absolute assignment; use with
|
+= -= .= | Incremental assignment: add to, subtract from,
and concatenate onto the end; use with
|
By default, the comparison operators (==
, !=
, <
, <=
, >
, >=
, =~
, !~
) ignore case or respect it based on
the setting of the ignorecase
option. Suffixing the
operators with #
forces the test to match case,
whereas using ?
forces the test to ignore
case.
Vim lets you define your own functions. The following table outlines the commands related to defining and calling functions, with explanation following the table.
Command | Function |
---|---|
| Define a function |
| Define a function that operates upon a range of lines |
| Define a function, even if the function already exists |
| Define a function that takes a variable number of arguments |
| List all user-defined function names and their arguments |
| Display the body of function Name |
| Remove (undefine) function Name |
[ | Call a function upon a range of lines N through M |
User-defined function names must begin with an uppercase letter so that Vim can distinguish them from built-in functions.
Arguments (parameters) are optional. If they’re supplied, you
reference them within the function body using the
a:
prefix on their names. When the
“...
” syntax is used, you access the additional,
unnamed arguments as a:1
, a:2
,
and so on. a:0
is a count of the additional
parameters, and a:000
is a list of all the
additional arguments. Functions using “...
” may
have up to 20 additional arguments.
Functions defined with the range
syntax are
called once for the range of lines; the starting and ending line
numbers are available as a:firstline
and
a:lastline
, respectively. Functions defined without
range
are called once for each line in the
range.
Use the return
statement to return a value
from the function. Return values must be numeric;
return
without a value or “falling off the end” of
the function causes the function to return zero.
Variables used within a function body are automatically local to
the function; you must use the g:
prefix to access
global variables.
The function body is checked for validity when the function is called, not when it’s defined. You should therefore test your functions carefully before publishing them.
The call
command calls a function on a range
of lines. Otherwise, function calls may be used as elements in an
expression in any context that accepts an expression (such as with
if
).
Vim also provides function references, which are variables that “point” at functions and may be used to call them indirectly. Such variables must also have names that start with an uppercase letter. When combined with dictionaries, they provide a rudimentary object-oriented programming capability; see the online help for the details.
Of course, as is often the case in the Free Software and open source worlds, chances are good that someone else has already written a function that does what you need (or 90% of it). There are many Vim functions available at the Vim website. Check there first before diving in to write a function of your own!
There are multiple ways to run scripts. You can read a file
directly with the source
command. For example, your
~/.vimrc file might execute source
~/.exrc
. Doing this lets you keep commands that will only
work in vi in the .exrc file,
while still letting you execute them in Vim as well.
More commonly used, the auto-commands mechanism lets you read and execute scripts based on a file’s type, as determined by the file’s suffix. For example, the author has the following in his .vimrc file:
autocmd BufReadPre,FileReadPre *.xml source ~/.ex-sgml-rc
The aliases and input mappings specific to XML are kept in a separate file. This keeps them from getting in the way when you are working on other kinds of files, but makes them available when you are editing XML.
Option | Default |
---|---|
autoread
(ar ) | noautoread |
| |
| 0 |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
completeopt (cot ) | menu,preview |
| |
cursorcolumn
(cuc ) | nocursorcolumn |
cursorline
(cul ) | nocursorline |
|
|
| |
| |
| |
| (too long to print) |
| |
| |
| |
| Vim default: |
| |
| |
| |
| |
| Vim default: 20; vi default: 0 |
| |
| |
|
|
| |
|
|
| |
| |
| |
| /tmp/vim##.err |
| |
modifiable
(ma ) | modifiable |
| |
| |
| |
| |
| |
| |
| |
| Vim default: |
| 0 |
| |
spell | nospell |
| |
| 0 |
| Vim default: |
| |
| |
| |
| |
|
3.134.79.121