VIM REFERENCE MANUAL - Part 3

By Bram Moolenaar

CONTENTS

[Note: The commands for multiple windows and buffers are explained in a different file, see vim_win.html]

  1. Introduction
  2. Notation
  3. Starting Vim
    1. Command line
    2. Workbench (Amiga only)
    3. Vim window (Amiga only)
    4. Initialization
    5. Suspending
    6. The viminfo file
  4. Modes
    1. Introduction
    2. Switching from mode to mode
    3. Insert and Replace mode
      1. special keys
      2. special special keys
      3. 'textwidth' option
      4. 'expandtab' option
      5. Replace mode
      6. Insert mode completion
    4. Command_line mode
      1. Command line editing
      2. Command line completion
      3. Ex command lines
      4. Ex command line ranges
      5. Ex special characters
    5. The window contents
    6. Abbreviations
    7. Digraphs
    8. Using the mouse
    9. On-line help
  5. Editing files
    1. Introduction
    2. Editing a file
    3. The argument list
    4. Writing and quitting
    5. Using the QuickFix mode
    6. Editing binary files
    7. Automatic commands
  6. Cursor motions
    1. Left-right motions
    2. Up-down motions
    3. Word motions
    4. Text object motions
    5. Text object selection
    6. Pattern searches
    7. Various motions
  7. Scrolling
  8. Tags and special searches
    1. Tags
    2. Identifier searches
  9. Inserting text
  10. Deleting text
  11. Changing text
    1. Delete and insert
    2. Simple changes
    3. Complex changes
    4. Formatting text
    5. Formatting C programs
  12. Copying and moving text
  13. Visual mode
  14. Various commands
  15. Repeating commands
    1. Single repeats
    2. Multiple repeats
    3. Complex repeats
  16. Undo and redo
  17. Key mapping
  18. Recovery after a crash
    1. The swap file
    2. Recovery
  19. Options
    1. Setting options
    2. Automatically setting options
    3. Saving settings
    4. Options summary
  20. Terminal information
    1. Startup
    2. Terminal options
    3. Window size
    4. Slow and fast terminals
  21. Differences from Vi and Ex
    1. Missing commands
    2. Missing options
    3. Limits

5. Editing files

5.1 Introduction
Editing a file with Vim means:
  1. reading the file into the internal buffer
  2. changing the buffer with editor commands
  3. writing the buffer into a file
As long as you don't write the buffer, the original file remains unchanged. If you start editing a file (read a file into the buffer), the file name is remembered as the "current filename".

If there already was a current filename, then that one becomes the alternate file name. All filenames are remembered in the file list. When you enter a filename, for editing (e.g. with ":e filename") or writing (e.g. with (:w filename"), the filename is added to the list. You can use this list to remember which files you edited and to quickly switch from one file to another with the CTRL-^ command (e.g. to copy text). First type the number of the file and then hit CTRL-^. {Vi: only one alternate filename}

CTRL-G or
:f[ile]
Prints the current filename (as typed) and the cursor position (unless the 'ruler' option is set). See also 'shortmess' option. {Vi does not include column number}

{count}CTRL-G
Prints the current filename with full path and the cursor position. If the count is higher than 1 the current buffer number is also given. {not in Vi}

g CTRL-G
Prints the current position of the cursor in three ways: Column, Line and Character. If there are characters in the line that take more than one position on the screen (<Tab> or special character), both the "real" column and the screen column are shown, separated with a dash. See also 'ruler' option. {not in Vi}

:f[ile] {name}
Sets the current filename to {name}.

:buffers
:files
:ls
List all the currently known file names. See 'vim_win.html' :files :buffers :ls. {not in Vi}
Vim will remember the full path name of a file name that you enter. In most cases when the file name is displayed only the name you typed is shown, but the full path name is being used if you used the ":cd" command.

If the environment variable 'HOME' is set, and the file name starts with that string, it is often displayed with HOME replaced with "~". This was done to keep file names short. When reading or writing files the full name is still used, the "~" is only used when displaying file names. When replacing the file name would result in just "~", "~/" is used instead (to avoid confusion with 'backupext' set to "~").

When writing the buffer, the default is to use the current filename. Thus when you give the "ZZ" or ":wq" command, the original file will be overwritten. If you do not want this, the buffer can be written into another file by giving a filename argument to the ":write" command. For example:

vim testfile
[change the buffer with editor commands]
:w newfile
:q

This will create a file "newfile", that is a modified copy of "testfile". The file "testfile" will remain unchanged. Anyway, if the 'backup' option is set, Vim renames or copies the original file before it will be overwritten. You can use this file if you discover that you need the original file. See also the 'patchmode' option. The name of the backup file is normally the same as the original file with 'backupext' appended. The default "~" is a bit strange to avoid accidently overwriting existing files. If you prefer ".bak" change the 'backupext' option. Extra dots are replaced with '_' on MS-DOS machines, when Vim has detected that an MS-DOS-like filesystem is being used (e.g. messydos or crossdos) or when the 'shortname' option is set. The backup file can be placed in another directory by setting 'backupdir'.

Technical:
On the Amiga you can use 30 characters for a file name. But on an MS-DOS-compatible filesystem only 8 plus 3 characters are available. Vim tries to detect the type of filesystem when it is creating the .swp file. If an MS-DOS-like filesystem is suspected, a flag is set that has the same effect as setting the 'shortname' option. This flag will be reset as soon as you start editing a new file. The flag will be used when making the filename for the ".swp" and ".~" files for the current file. But when you are editing a file in a normal filesystem and write to an MS-DOS-like filesystem the flag will not have been set. In that case the creation of the ".~" file may fail and you will get an error message. Use the 'shortname' option in this case.
When you started editing without giving a file name, "No File" is displayed in messages. If a ":write file" or ":read file" command is used, the file name for the current file is set to the file name in that command. This is useful when starting Vim without an argument and then doing ":read file" to start editing a file. Or when entering text in an empty buffer and then writing it to a file. Because the file name was set without really starting to edit that file, you are protected from overwriting that file. This is done by setting the "notedited" flag. You can see if this flag is set with the CTRL-G or ":file" command. It will include "[Not edited]" when the "notedited" flag is set. When writing the buffer to the current file name (with ":w!"), the "notedited" flag is reset.

Vim remembers whether you have changed the buffer. You are protected from losing the changes you made. If you try to quit without writing, or want to start editing another file, this will be refused. In order to overrule this protection add a '!' to the command. The changes will then be lost. For example: ":q" will not work if the buffer was changed, but ":q!" will. To see whether the buffer was changed use the "CTRL-G" command. The message includes the string "[Modified]" if the buffer has been changed.

5.2 Editing a file
:e[dit] [+cmd]
Edit the current file, unless changes have been made.

:e[dit]! [+cmd]
Edit the current file always. Discard any changes to the buffer.

:e[dit] [+cmd] {file}
Edit {file}, unless changes have been made.

:e[dit]! [+cmd] {file}
Edit {file} always. Discard any changes to the buffer.

:e[dit] #[count]
Edit the [count]th alternate filename (as shown by :files). This command does the same as [count] CTRL-^.

:ex [+cmd] [file]
Same as :edit. {Vi: go from visual to Ex mode}

:vi[sual] [+cmd] [file]
Same as :edit. {Vi: go from Ex to visual mode}

:vie[w] [+cmd] file
Same as :edit, but set 'readonly' option for this buffer. {not in Vi}

[count]CTRL-^
Edit [count]th alternate file (equivalent to ":e #[count]"). Without count this gets you to the previously edited file. This is a quick way to toggle between two (or more) files. If the 'autowrite' option is set and the buffer was changed, write it.

]f
[f
gf
Edit the file whose name is under or after the cursor. Mnemonic: "goto file". Uses the 'path' variable as a list of directory names to look for the file. Also looks for the file relative to the current file. This command fails if the current file cannot be abandoned. If the name is a hypertext link, that looks like "type://machine/path", only "/path" is used. For Unix the '~' character is expanded, like in "~user/file". {not in Vi}

:cd
On non-Unix systems: Print the current directory name. On Unix systems: Change the current directory to the home directory.

:cd {path}
Change the current directory to {path}. Does not change the meaning of an already entered file name, because its full path name is remembered. On MS-DOS this also changes the active drive.

:chd[ir] [path]
Same as :cd.

:pw[d]
Print the current directory name. {Vi: no pwd}
These commands are used to start editing a single file. This means that the file is read into the buffer and the current filename is set. You may use the ":cd" command to get to another directory, so you will not have to type that directory name in front of the filenames. One warning: After using ":cd" the full path name will be used for reading and writing files. On some networked file systems this may cause problems. The result of using the full path name is that the file names currently in use will remain referring to the same file. Example: If you have a file a:test and a directory a:vim the commands ":e test" ":cd vim" ":w" will overwrite the file a:test and not write a:vim/test. But if you do ":w test" the file a:vim/test will be written, because you gave a new file name and did not refer to a file name before the ":cd".

Note for systems other than Unix and MS-DOS: When using a command that accepts a single file name (like ":edit file") spaces in the file name are allowed, but trailing spaces are ignored. This is useful on systems that allow file names with embedded spaces (like the Amiga). Example: The command ":e Long File Name " will edit the file "Long File Name". When using a command that accepts more than one file name (like ":next file1 file2") embedded spaces must be escaped with a backslash.

On Unix you can also use backticks in the file name, for example:

:e `find . -name ver\\*.c -print`
The backslashes before the star are required to prevent "ver*.c" to be expanded by the shell before executing the find program.

You can use the ":e!" command if you messed up the buffer and want to start all over again. The ":e" command is only useful if you have changed the current filename.

Note that ":e file" will fail if there are changes in the current buffer, also when the 'autowrite' option is set. This is unlogical, because with other commands (e.g. ":next") the current buffer would be written and abandoned, but this behaviour is compatible with Vi. If you encounter this problem, you can use CTRL-^ to jump to the file, because the alternate file name is set to the argument of the ":e" command.

The [+cmd] can be used to position the cursor in the newly opened file:
+ Start at the last line.
+{num} Start at line {num}.
+/{pat} Start at first line containing {pat}. {pat} must not contain any spaces.
+{command} Execute {command} after opening the new file. {command} is an Ex command. It must not contain spaces.

When reading a file when the 'textmode' option is off (default for non-MS-DOS) the <NL> character is interpreted as end-of-line. If 'textmode' is on (default for MS-DOS), <CR><NL> is also interpreted as end-of-line.

When writing a file when the 'textmode' option is off a <NL> character is used to separate lines. When the 'textmode' option is on <CR><NL> is used.

You can read a file with 'textmode' set and write it with 'textmode' reset. This will replace all <CR><NL> pairs by <NL>. If you read a file with 'textmode' reset and write with 'textmode' set, all <NL> characters will be replaced with <CR><NL>.

If you start editing a new file and the 'textauto' option is set, Vim will try to detect whether the lines in the file are separated by a single <NL> (as used on Unix and Amiga) or by a <CR><NL> pair (MS-DOS). It reads up to the first <NL> and checks if there is a <CR> in front of it. If there is the 'textmode' option is set, otherwise it is reset. If the 'textmode' option is set on non-MS-DOS systems the message "[textmode]" is shown to remind you that something unusual is happening. On MS-DOS systems you get the message "[notextmode]" if the 'textmode' option is not set.

Before editing binary, executable or Vim script files you should set the 'textmode' and 'textauto' options off. With 'textmode' on you risk that single <NL> characters are unexpectedly replaced with <CR><NL>. A simple way to do this is by starting Vim with the "-b" option.

5.3 The argument list
If you give more than one filename when starting Vim, this list is remembered as the argument list. Do not confuse this with the file list, which you can see with the ":files" command. The argument list was already present in Vi, the file list is new in Vim. The file names in the argument list will also be present in the file list (unless they were deleted with ":bdel").

You can use the argument list with the following commands:

:ar[gs]
Print the argument list, with the current file in square brackets.

:[count]argu[ment] [count] [+cmd]
Edit file [count] in the argument list, unless changes have been made and the 'autowrite' option is off. {Vi: no such command}

:[count]argu[ment]! [count] [+cmd]
Edit file [count] in the argument list, discard any changes to the current buffer. {Vi: no such command}

:[count]n[ext] [+cmd]
Edit [count] next file, unless changes have been made and the 'autowrite' option is off {Vi: no count}.

:[count]n[ext]! [+cmd]
Edit [count] next file, discard any changes to the buffer {Vi: no count}.

:ar[gs] [+cmd] {filelist}
:n[ext] [+cmd] {filelist}
Define {filelist} as the new argument list and edit the first one, unless changes have been made and the 'autowrite' option is off.

:ar[gs]! [+cmd] {filelist}
:n[ext]! [+cmd] {filelist}
Define {filelist} as the new argument list and edit the first one. Discard any changes to the buffer.

:[count]N[ext] [count] [+cmd]
Edit [count] previous file in argument list, unless changes have been made and the 'autowrite' option is off {Vi: no count}.

:[count]N[ext]! [count] [+cmd]
Edit [count] previous file in argument list. Discard any changes to the buffer {Vi: no count}.

:[count]pre[vious] [count] [+cmd]
Same as :Next {Vi: only in some versions}

:rew[ind] [+cmd]
Start editing the first file in the argument list, unless changes have been made and the 'autowrite' option is off.

:rew[ind]! [+cmd]
Start editing the first file in the argument list. Discard any changes to the buffer.

:la[st] [+cmd]
Start editing the last file in the argument list, unless changes have been made and the 'autowrite' option is off. {not in Vi}

:la[st]! [+cmd]
Start editing the last file in the argument list. Discard any changes to the buffer. {not in Vi}

:[count]wn[ext] [+cmd]
Write current file and start editing the [count] next file. {not in Vi}

:[count]wn[ext] [+cmd] {file}
Write current file to {file} and start editing the [count] next file, unless {file} already exists and the 'writeany' option is off. {not in Vi}

:[count]wn[ext]! [+cmd] {file}
Write current file to {file} and start editing the [count] next file. {not in Vi}

:[count]wN[ext][!] [+cmd] [file]
:[count]wp[revous][!] [+cmd] [file]
Same as :wnext, but go to previous file instead of next. {not in Vi}
The [count] in the commands above defaults to one. For some commands it is possible to use two counts. The last one (rightmost one) is used.

For [+cmd] see 5.2 edit_a_file.

The wildcards in the argument list are expanded and the filenames are sorted. Thus you can use the command "vim *.c" to edit all the C files. From within Vim the command ":n *.c" does the same. On Unix you can also use backticks, for example:

:n `find . -name \\*.c -print`
The backslashes before the star are required to prevent "*.c" to be expanded by the shell before executing the find program.

You are protected from leaving Vim if you have not been editing the last file in the argument list. This prevents you from forgetting that you were editing one out of several files. To exit anyway try to exit twice. If there are changes in the current buffer this will fail. You can exit anyway, and save any changes, with the ":wq!" command. To lose any changes use the ":q!" command.

When there is an argument list you can see which file you are editing in the title of the window (if there is one and 'title' is on) and with the file message you get with the "CTRL-G" command. You will see something like

(file 4 of 11)
If 'shortmess' contains 'f' it will be
(4 of 11)
If you are not really editing the file at the current position in the argument list it will be
(file (4) of 11)
This means that you are position 4 in the argument list, but not editing the fourth file in the argument list. This happens when you do ":e file".
5.4 Writing and quitting
:[range]w[rite][!]
Write the specified lines to the current file.

:[range]w[rite] {file}
Write the specified lines to {file}, unless it already exists and the 'writeany' option is off.

:[range]w[rite]! {file}
Write the specified lines to {file}. Overwrite an existing file.

:[range]w[rite][!] >>
Append the specified lines to the current file.

:[range]w[rite][!] >> {file}
Append the specified lines to {file}. '!' forces the write even if file does not exist.

:[range]w[rite] !{cmd}
Execute {cmd} with [range] lines as standard input (note the space in front of the '!').
The default [range] for the ":w" command is the whole buffer (1,$). If a file name is give with ":w" it becomes the alternate file. This can be used when the write fails and you want to try again later with ":w #".
:q[uit]
Quit, unless changes have been made or not editing the last file in the argument list.

:q[uit]!
Quit always, without writing.

:cq
Quit always, without writing, and return an error code. Used for Manx's QuickFix mode (see 5.5 quickfix).

:wq
Write the current file and exit (unless editing the last file in the argument list or the file is read-only).

:wq!
Write the current file and exit.

:wq {file}
Write to {file}. Exit if not editing the last file in the argument list.

:wq! {file}
Write to {file} and exit.

:[range]wq[!] [file]
Same as above, but only write the lines in [range].

:[range]x[it][!] [file]
Like ":wq", but write only when changes have been made.

:[range]exi[t][!] [file]
Same as :xit.

ZZ
Write current file, if modified, and exit (same as ":x"). (Note: If there are several windows for the current file, the file is written if it was modified and the window is closed).
Vim remembers the timestamp of the file when you start editing it. When you write a file the timestamp is checked. If the file has been changed since you started editing it, Vim will ask you if you really want to overwrite the file:

WARNING: The file has been changed since reading it!!!
Do you really want to write to it (y/n)?

If you hit 'y' Vim will continue writing the file. If you hit 'n' the write is aborted. If you used ":wq" or "ZZ" Vim will not exit, you will get another chance to write the file. The message would normally mean that somebody has written to the file after the edit session started. This could be another person, in which case you probably want to check if your changes to the file and the changes from the other person should be merged. Write the file under another name and check for differences (the "diff" program can be used for this). It is also possible that you modified the file yourself, from another edit session or with another command (e.g. a filter command). Then you will know which version of the file you want to keep.

If you write to an existing file (but do not append) while the 'backup', 'writebackup' or 'patchmode' option is on, a backup of the original file is made. On Unix systems the file is copied, on other systems the file is renamed. After the file has been successfully written and when the 'writebackup' option is on and the 'backup' option is off, the backup file is deleted. When the 'patchmode' option is set the backup file may be renamed.

'backup' 'writebackup' action
off off no backup made
off on backup current file, deleted afterwards (default)
on off delete old backup, backup current file
on on delete old backup, backup current file

When the 'backup' option is set, an old backup file (with the same name as the new backup file) will be deleted. If 'backup' is not set, but 'writebackup' is set, an existing backup file will not be deleted. The backup file that is made while the file is being written will have a different name.

The directories given with the 'backupdir' option is used to put the backup file in. (default: same directory as the written file).

On Unix systems: When you write to an existing file, that file is truncated and then filled with the new text. This means that protection bits, owner and symbolic links are unmodified. The backup file however, is a new file, owned by the user who edited the file. The group of the backup is set to the group of the original file. If this fails, the protection bits for the group are made the same as for others.

If the creation of a backup file fails, the write is not done. If you want to write anyway add a '!' to the command.

If the writing of the new file fails, you have to be careful not to lose your changes AND the original file. If there is no backup file and writing the new file failed, you have already lost the original file! DON'T EXIT VIM UNTIL YOU WRITE OUT THE FILE! If a backup was made, it is put back in place of the original file (if possible). If you exit Vim, and lose the changes you made, the original file will mostly still be there. If putting back the original file fails, there will be an error message telling you that you lost the original file.

If the 'textmode' option is set <CR><NL> is used for end-of-line. This is default for MS-DOS. On other systems the message "[textmode]" is shown to remind you that an usual end-of-line marker was used. If the 'textmode' is not set NL is used for end-of-line. On MS-DOS the message "[notextmode]" is shown. See also the 'textmode' and 'textauto' options.

5.5 Using the QuickFix mode
Vim has a special mode to speedup the edit-compile-edit cycle. This is inspired by the quickfix option of the Manx's Aztec C compiler on the Amiga. The idea is to save the error messages from the compiler in a file and use Vim to jump to the errors one by one. You can then examine each problem and fix it, without having to remember all the error messages.

If you are using Manx's Aztec C compiler on the Amiga you should do the following:

  • Set the CCEDIT environment variable with the command mset "CCEDIT=vim -e"
  • Compile with the -qf option. If the compiler finds any errors, Vim is started and the cursor is positioned on the first error. The error message will be displayed on the last line. You can go to other errors with the commands mentioned below. You can fix the errors and write the file(s).
  • If you exit Vim normally the compiler will re-compile the same file. If you exit with the :cq command, the compiler will terminate. Do this if you cannot fix the error, or if another file needs to be compiled first.
If you are using another compiler you should save the error messages in a file and start Vim with "vim -e filename". An easy way to do this is with the ":make" command (see below). The 'errorformat' option should be set to match the error messages from your compiler (see below).

The following commands can be used if you are in QuickFix mode:

:cc [nr]
Display error [nr]. If [nr] is omitted, the same error is displayed again. {not in Vi}

:[count]cn[ext]
Display the [count] next error in the list that includes a file name. If there are no file names at all, go the the [count] next error. {not in Vi}

:[count]cN[ext]
:[count]cp[revious]
Display the [count] previous error in the list that includes a file name. If there are no file names at all, go the the [count] previous error. {not in Vi}

:cq[uit]
Quit Vim with an error code, so that the compiler will not compile the same file again. {not in Vi}

:cf[ile] [errorfile]
Read the error file and jump to the first error. This is done automatically when Vim is started with the -e option. You can use this command when you keep Vim running while compiling. If you give the name of the errorfile, the 'errorfile' option will be set to [errorfile] {not in Vi}

:cl[ist]
List all errors that inlcude a file name. {not in Vi}

:cl[ist]!
List all errors. {not in Vi}

:mak[e] [arguments]
  1. If the 'autowrite' option is set write any changed buffers
  2. Any existing 'errorfile' is deleted.
  3. The program given with the 'makeprg' option is started (default "make") with the optional [arguments] and the output is saved in 'errorfile' (for Unix it is also echoed on the screen).
  4. The 'errorfile' is then read and the first error is jumped to.
  5. The 'errorfile' is deleted.
{not in Vi}
The name of the file can be set with the 'errorfile' option. The default is "AztecC.Err" for the Amiga and "errors.vim" for other systems. The format of the file from the Aztec compiler is:

filename>linenumber:columnnumber:errortype:errornumber:errormessage

filename name of the file in which the error was detected
linenumber line number where the error was detected
columnnumber column number where the error was detected
errortype type of the error, normally a single 'E' or 'W'
errornumber number of the error (for lookup in the manual)
errormessage description of the error

Another compiler is likely to use a different format. You should set the 'errorformat' option to a scanf-like string that describes the format. First you need to know how scanf works. Look in the documentation of your C compiler. Vim will understand eight conversion characters. Others are invalid.
%f file name (finds a string)
%l line number (finds a number)
%c column number (finds a number)
%t error type (finds a single character)
%n error number (finds a number)
%m error message (finds a string)
%*<conv> any scanf non-assignable conversion
%% the single '%' character

Examples:
%f>%l:%c:%t:%n:%m" for the AztecC.Err file
%f:%l:\ %t%*[^0123456789]%n:\ %m for Manx/Aztec C error messages (scanf() doesn't understand [0-9])
%f\ %l\ %t%*[^0-9]%n:\ %m for SAS C
\"%f\"\\,%*[^0-9]%l:\ %m for generic C compilers
%f:%l:\ %m for GCC
%f(%l)\ :\ %*[^:]:\ %m old SCO C compiler (pre-OS5)
%f(%l)\ :\ %t%*[^0-9]%n:\ %m idem, with error type and number
%f:%l:\ %m,In\ file\ included\ from\ %f:%l:,\^I\^Ifrom\ %f:%l%m for GCC, with some extras

Note the backslash in front of a space and double quote. It is required for the :set command. There are two backslashes in front of a comma, one for the :set command and one to avoid recognizing the comma as a separator of error formats.

The "%f" and "%m" conversions have to detect the end of the string. They should be followed by a character that cannot be in the string. Everything up to that character is included in the string. Be careful: "%f%l" will include everything up to the first '%' in the file name. If the "%f" or "%m" is at the end, everything up to the end of the line is included.

To be able to detect output from several compilers, several format patterns may be put in 'errorformat', separated by commas (note: blanks after the comma are ignored). The first pattern that has a complete match is used. If no match is found, matching parts from the last one will be used, although the file name is removed and the error message is set to the whole message. If there is a pattern that may match output from several compilers (but not in a right way), put it after one that is more restrictive. To include a comma in a pattern precede it with a backslash (you have to type two in a set command). To include a backslash itself give two backslashes (you have to type four in a set command).

If a line is detected that does not completely match the 'errorformat', the whole line is put in the error message and the entry is marked "not valid" These lines are skipped with the ":cn" and ":cp" commands (unless there is no valid line at all). You can use ":cl!" to display all the error messages.

If the error format does not contain a file name Vim cannot switch to the correct file. You will have to do this by hand.

If you have a compiler that produces error messages that do not fit in the format string, you could write a program that translates the error messages into this format. You can use this program with the ":make" command by changing the 'makeprg' option. For example:

":set mp=make\ \\\|&\ error_filter".
The backslashes before the pipe character are required to avoid it to be recognized as a command separator. The backslash before each space is required for the set command.

The ":make" command executes the command given with the 'makeprg' option. This is done by passing the command to the shell given with the 'shell' option. This works almost like typing

":!{makeprg} [arguments] {shellpipe} {errorfile}".

{makeprg} is the string given with the 'makeprg' option. Any command can be used, not just "make". Characters '%' and '#' are expanded as usual on a command line. You can use "#<" to insert the current filename without extension, for example ":set makeprg=make\ #<.o".

[arguments] is anything that is typed after ":make".
{shellpipe} is the 'shellpipe' option.
{errorfile} is the 'errorfile' option.

The 'shellpipe' option defaults to ">" for the Amiga and MS-DOS. This means that the output of the compiler is saved in a file and not shown on the screen directly. For Unix "| tee" is used. The compiler output is shown on the screen and saved in a file the same time. Depending on the shell used "|& tee" or "2>&1| tee" is the default, so stderr output will be included.

There are some restrictions to the Quickfix mode on the Amiga. The compiler only writes the first 25 errors to the errorfile (Manx's documentation does not say how to get more). If you want to find the others, you will have to fix a few errors and exit the editor. After recompiling, up to 25 remaining errors will be found.

On the Amiga, if Vim was started from the compiler, the :sh and :! commands will not work, because Vim is then running in the same process as the compiler and these two commands may guru the machine then.

If you insert or delete lines, mostly the correct error location is still found because hidden marks are used (Manx's Z editor does not do this). Sometimes, when the mark has been deleted for some reason, the message "line changed" is shown to warn you that the error location may not be correct. If you quit Vim and start again the marks are lost and the error locations may not be correct anymore.

5.6 Editing binary files
Although Vim was made to edit text files, it is possible to edit binary files. The "-b" command line option (b for binary) sets some options for editing binary files ('binary' on, 'textwidth' to 0, 'textmode' and 'textauto' off, 'modeline' off, 'expandtab' off). Setting the 'binary' option has the same effect. Don't forget to do this before reading the file.

There are a few things to remember when editing binary files:

  • When editing executable files the number of characters must not change. Use only the "R" or "r" command to change text. Do not delete characters with "x" or by backspacing.
  • Set the 'textwidth' option to 0. Otherwise lines will unexpectedly be split in two.
  • When there are not many end-of-line characters, the lines will become very long. If you want to edit a line that does not fit on the screen reset the 'wrap' option. Horizontal scrolling is used then. If a line becomes too long (more than about 32767 characters on the Amiga, much more on 32-bit systems, see limits) you cannot edit that line. The line will be split when reading the file. It is also possible that you get an "out of memory" error when reading the file.
  • Make sure the 'textmode' and 'textauto' options are off before loading the file. In 'textmode' both <CR><NL> and <NL> are considered to end a line and when the file is written the <NL> will be replaced with <CR><NL>. The 'modelines' option should also be off, because there may be a string like ":vi:" in the file that would give unpredictable results.
  • <Nul> characters are shown on the screen as ^@. You can enter them with "CTRL-V CTRL-@" or "CTRL-V 000" {Vi cannot handle <Nul> characters in the file}
  • To insert a <NL> character in the file split up a line. When writing the buffer to a file a <NL> will be written for the end of line.
  • Vim normally appends an end-of-line character at the end of the file if there is none. Setting the 'binary' option prevents this. If you want to add the final end-of-line, set the 'endofline' option. You can also read the value of this option to see if there was an end-of-line character for the last line (you cannot see this in the text).
5.7 Automatic commands
You can specify commands to be executed automatically for when reading or writing a file, when entering or leaving a buffer or window, and when exiting Vim. For example, 'cindent' can be set for files matching *.c, and unset otherwise. Autocommands can be used to edit compressed files. These commands are normally put in your .vimrc or .exrc file. {All this is not in Vi}

WARNING: Using autocommands is very powerful, but may lead to unexpected side effects. Be careful not to destroy your text.

  • It's a good idea to first do some testing on a copy of a file first. For example: If you use autocommands to decompress a file when starting to edit it, make sure that the autocommands for compressing when writing work correctly.
  • Be prepared for an error halfway through (e.g. disk full). Vim will mostly be able to undo the changes to the buffer, but you may have to clean up the changes to other files by hand (e.g. compress a file that has been decompressed).
  • If the BufRead* events allow you to edit a compressed file, the FileRead* events should do the same (to be able to do recovery in some rare cases). It's a good idea to use the same autocommands for the File* and Buf* events when possible.
The autocommand feature is only included if Vim has been compiled with AUTOCMD defined. If the output of ":version" contains "+autocmd" it is included (this is the default), if it contains "-autocmd" then the autocommand feature doesn't work.

Note: This command cannot be followed by another command, since any '|' is considered part of the command.

:au[tocmd] {event} {pat} {cmd}
Add {cmd} to the list of commands that will be automatically executed on {event} for a file matching {pat}. It is not added if it is already there (as may happen when .vimrc is sourced again). The order of entering {cmd} and {pat} is important.

:au[tocmd] {event} {pat}
Show the auto-commands associated with {event} and {pat}.

:au[tocmd] * {pat}
Show the auto-commands associated with pat} for all events.

:au[tocmd] {event}
Show all auto-commands for {event}.

:au[tocmd]
Show all auto-commands.

:au[tocmd]! {event} {pat} {cmd}
Remove all auto-commands associated with {event} and {pat}, and add the command {cmd}.

:au[tocmd]! {event} {pat}
Remove all auto-commands associated with {event} and {pat}.

:au[tocmd]! * {pat}
Remove all auto-commands associated with {pat} for all events.

:au[tocmd]! {event} Remove ALL auto-commands for {event}.

:au[tocmd]! Remove ALL auto-commands.

:do[autocmd] {event} [fname]
Apply the autocommands matching [fname] (default: current file name) for {event} to the current buffer. This can be used when the current file name does not match the right pattern, after changing settings, or to execute autocommands for a certain event.

These events are recognized. Case is ignored, for example "BUFread" and "bufread" can be used instead of "BufRead".

BufNewFile
When starting to edit a file that doesn't exist. Can be used to read in a skeleton file.
BufReadPre
When starting to edit a new buffer, before reading the file into the buffer. Not used when starting to edit a new file.
BufRead or BufReadPost
When starting to edit a new buffer, after reading the file into the buffer, before executing the modelines. This does NOT work for ":r file". Not used when starting to edit a new file.
FileReadPre
Before reading a file with a ":read" command.
FileReadPost
After reading a file with a ":read" command. Note that the '[ and '] marks are set to the first and last line of the read, this can be used to operate on the just read lines.
FilterReadPre
Before reading a file from a filter command. The file name of the current buffer is used to match with the pattern, not the name of the temporary file that is the output of the filter command.
FilterReadPost
After reading a file from a filter command. Like FilterReadPre, the file name of the current buffer is used.
BufWrite or BufWritePre
Before writing the whole buffer to a file.
BufWritePost
After writing the whole buffer to a file (should undo the commands for BufWritePre).
FileWritePre
Before writing to a file, when not writing the whole buffer.
FileWritePost
After writing to a file, when not writing the whole buffer.
FileAppendPre
Before appending to a file.
FileAppendPost
After appending to a file.
FilterWritePre
Before writing a file for a filter command. The file name of the current buffer is used to match with the pattern, not the name of the temporary file that is the input for the filter command.
FilterWritePost
After writing a file for a filter command. Like FilterWritePre, the file name of the current buffer is used.
BufEnter
After entering a buffer. Useful for setting options for a file type. Also executed when starting to edit a buffer, after the BufReadPost autocommands.
BufLeave
Before leaving to another buffer. Also when leaving or closing the current window and the new current window is not for the same buffer.
WinEnter
After entering another window. Not done for the first window, when Vim is just started. Useful for setting the window height. If the window is for another buffer, the BufEnter autocommands are executed after the WinEnter autocommands.
WinLeave
Before leaving to another window. If the window to be entered is for a different buffer, the BufLeave autocommands are executed before the WinLeave autocommands.
VimLeave
Before exiting Vim, just before writing the .viminfo file. There is no VimEnter event, because you can use the .vimrc for that.
For READING FILES there are three possible pairs of events, only one pair is used at a time:
BufNewFile starting to edit a non-existant file
BufReadPre BufReadPost starting to edit an existing file
FilterReadPre FilterReadPost read the temp file with filter output
FileReadPre FileReadPost any other file read

Before the *ReadPre event the '[ mark is set to the line just above where the new lines will be inserted. Before the *ReadPost event the '[ mark is set to the first line that was just read, the '] mark to the last line. Careful: '[ and '] will change when using commands that change the buffer. "CTRL-V f" can be used for the file name that is being read, in commands where a file name is expected (where you can also use "%" for the current file name).

Examples for reading compressed files:

:autocmd! BufReadPre,FileReadPre *.gz set bin
:autocmd BufReadPost,FileReadPost *.gz '[,']!gunzip
:autocmd BufReadPost,FileReadPost *.gz set nobin

NOTE: When using the examples given, any existing autocommands for the same event/pattern combination will be removed, because of the '!'.

For WRITING FILES there are four possible pairs of events, only one pair is used at a time:
BufWritePre BufWritePost writing the whole buffer
FilterWritePre FilterWritePost writing to the temp file with filter input
FileAppendPre FileAppendPost appending to a file
FileWritePre FileWritePost any other file write

Note that the *WritePost commands should undo any changes to the buffer that were caused by the *WritePre commands, otherwise writing the file will have the side effect of changing the buffer.

Before the *WritePre event the '[ mark is set to the first line that will be written, the '] mark to the last line. Careful: '[ and '] will change when using commands that change the buffer. "CTRL-V f" can be used for the file name that is being written, in commands where a file name is expected (where you can also use "%" for the current file name).

Examples for writing compressed files:

:autocmd! BufWritePost,FileWritePost *.gz !mv ^Vf ^Vf:r
:autocmd BufWritePost,FileWritePost *.gz !gzip ^Vf:r

:autocmd! FileAppendPre *.gz !gunzip ^Vf
:autocmd FileAppendPre *.gz !mv ^Vf:r ^Vf
:autocmd! FileAppendPost *.gz !mv ^Vf ^Vf:r
:autocmd FileAppendPost *.gz !gzip ^Vf:r

("^Vf" stands for "CTRL-V f", "^Vf:r" is the file name without the extension, see :_%:)

The commands executed for the BufNewFile, BufRead/BufReadPost, BufWritePost, FileAppendPost and VimLeave events do not set or reset the changed flag of the buffer. When you decompress the buffer with the BufReadPost autocommands, you can still exit with ":q". When you use ":undo" in BufWritePost to undo the changes made by BufWritePre commands, you can still do ":q" (this also makes "ZZ" work).

To execute Normal mode commands from an autocommand, use the ":normal" command. Use with care! If the Normal mode command is not finished, the user needs to type characters (e.g. after ":normal m" you need to type a mark name).

If you want the buffer not to be modified after changing it, reset the 'modified' option. This makes it possible to exit the buffer with ":q" instead of ":q!".

Autocommands do not nest. If you use ":r" or ":w" in an autocommand, the BufRead and BufWrite autocommands are not executed for those commands. It's also not possible to use the ":au" command in an autocommand (that could be a self-modifying command!).

There is currently no way to disable the autocommands. If you want to write a file without executing the autocommands for that type of file, write it under another name and rename it with a shell command.

Note: When doing a ":read file" command and the last line in the file does not have an end-of-line character, this is remembered. When executing the FileReadPost autocommands and the same line is written again as the last line in a file, no end-of-line character is written if 'binary' is set. This makes a filter command on the just read lines write the same file as was read.

Multiple patterns may be given separated by commas. Here are some examples:

:autocmd BufRead * set tw=79 nocin ic infercase fo=2croq
:autocmd BufRead .letter set tw=72 fo=2tcrq
:autocmd BufEnter .letter set dict=/usr/lib/dict/words
:autocmd BufLeave .letter set dict=
:autocmd BufRead,BufNewFile *.c,*.h set tw=0 cin noic
:autocmd BufEnter *.c,*.h abbr FOR for(i = 0; i < 3; i++)^M{^M}^[O
:autocmd BufLeave *.c,*.h unabbr FOR

For makefiles (makefile, Makefile, imakefile, makefile.unix, etc):

:autocmd BufEnter *akefile* set include=^s\=include
:autocmd BufLeave *akefile* set include&

To always start editing C files at the first function:

:autocmd BufRead *.c,*.h 1;/^{

Without the "1;" above, the search would start from wherever the file was entered, rather than from the start of the file.

To read a skeleton file for new C files:

:autocmd BufNewFile *.c 0r ~/.skeleton.c
:autocmd BufNewFile *.h 0r ~/.skeleton.h

To insert the current date and time in a *.html file when writing it:

:autocmd BufWritePre,FileWritePre *.html normal msgg/Last modification: /e D
:autocmd BufWritePre,FileWritePre *.html read !date
:autocmd BufWritePre,FileWritePre *.html normal kJ's

You need to have a line "Last modification: " in the file for this to work. The (and anything after it) will be replaced with the current date and time.

When entering :autocmd on the command line, completion of events and command names may be done (with <Tab>, CTRL-D, etc) where appropriate.

All matching auto-commands will be executed in the order that they were specified. It is recommended that your first auto-command be used for all files by using "*" as the file pattern. This means that you can define defaults you like here for any settings, and if there is another matching auto-command it will override these. But if there is no other matching auto-command, then at least your default settings are recovered (if entering this file from another for which auto-commands did match). Note that "*" will also match files starting with ".", unlike Unix shells.

Normally the file pattern is tested for a match against just the tail part of the file name (without its leading directory path), but if a path separator character (eg '/' on Unix) appears in the pattern, then it will be tested against the full file name. For example:

:autocmd BufRead */vim/src/* set wrap
Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part 9
Send feedback on this page to Rajesh Kallingal
For Vim version 3.24. Last modification: 1996 Apr 25