VIM reference manual By Bram Moolenaar version 1.13 1. Introduction 2. Notation 3. Starting VIM 4. Modes 5. Editing files 6. Cursor motions 7. Scrolling 8. Inserting text 9. Deleting text 10. Changing text 11. Copying and moving text 12. Various commands 13. Repeating commands 14. Undo and redo 15. Key mapping 16. Recovery after a crash 17. Options 18. Differences from Vi and Ex 19. Credits 1. Introduction VIM stands for Vi Imitation. VIM is a text editor which includes almost all the commands from the Unix program "Vi". It is very useful for editing programs and other ASCII text. A large number of the "Ex" commands (the commands that start with a colon) are included. However, there is no Ex mode. Throughout this manual the differences are mentioned in curly braces. Read the chapter "Differences from Vi and Ex" for a summary of the differences. This manual refers to VIM on the Commodore Amiga computer. On other computers and on terminals there may be small differences. This manual is a reference for all the VIM commands and options. A basic knowledge of "Vi" is assumed. A summary of this manual can be found in the file vim:vim.hlp. It can be accessed from within VIM with the key and with the command ":help". 2. Notation [] Characters in square brackets are optional. [cnt] An optional number that may precede the command to multiply or iterate the command. If no number is given a count of one is used, unless otherwise noted. Note that in this manual the [cnt] is not mentioned in the description of the command, but only in the explanation. This was done to make the commands more easy to lookup. The (partially) entered count is shown at the bottom of the window. You can use to erase the last digit. ["x] An optional named register designation to put deleted text into. The x is a single character between and or and . The uppercase and lower case letter designate the same register, but the lower case letter is used to overwrite the previous register contents, while the uppercase letter is used to append to the previous register contents. Without the ["x] the deleted text is put into the unnamed register. The ["x] must precede the [cnt]. {} Curly braces denote parts of the command which must appear, but can take a number of different values. The differences between VIM and Vi are also given in curly braces. {motion} A command that moves the cursor. They are listed in chapter 6. This is used after an "operator" command to move over the text that is to be operated upon. If the motion includes a count and the operator also had a count, the two counts are multiplied. For example: "2d3w" deletes six words. A special character from the table below or a single ASCII character. A single character from the range to . For example: is a lower case letter. Multiple ranges may be concatenated. For example: is any alphanumeric character. CTRL- typed as a control character, that is, typing while holding the CTRL key down. The case of does not matter, thus CTRL-A and CTRL-a are equivalent. notation meaning equivalent hex value ----------------------------------------------------------------------- bell CTRL-G 0x07 backspace CTRL-H 0x08 tab CTRL-I 0x09 linefeed CTRL-J 0x0a newline CTRL-J 0x0a (same as linefeed) formfeed CTRL-L 0x0c carriage return CTRL-M 0x0d escape CTRL-[ 0x1b space 0x20 delete 0x7f help key 0x80 cursor-up 0x84 cursor-down 0x85 cursor-left 0x86 cursor-right 0x87 shift-cursor-up 0x88 shift-cursor-down 0x89 shift-cursor-left 0x8a shift-cursor-right 0x8b - function keys 1 to 10 0x8c - 0x95 - shift-function keys 1 to 10 0x96 - 0x9f ----------------------------------------------------------------------- 3. Starting VIM 3.1 Command line Most often VIM is started to edit a single file with the command vim file More generally VIM is started with: vim [options] [filelist] If the filelist is missing, the editor will start with an empty buffer. Otherwise exactly one out of the following four may be used to choose one or more files to be edited. file .. A list of file names. The first one (alphabetically) will be the current file and read into the buffer. The cursor will be positioned on the first line of the buffer. +[num] file .. Same as the above, but the cursor will be positioned on line "num". If "num" is missing, the cursor will be positioned on the last line. +/pat file .. Same as the above, but the cursor will be positioned on the first occurrence of "pat" in the current file (see the section "pattern searches" for the available search patterns). -t {tag} A tag. {tag} is looked up in the tags file, the associated file becomes the current file and the associated command is executed. Mostly this is used for C programs. {tag} then should be a function name. The effect is that the file containing that function becomes the current file and the cursor is positioned on the start of the function (see the section "tag searches"). -e QuickFix mode. The error file "AztecC.Err" is read and the first error is displayed. See 5.6. The options, if present, must precede the filelist. The options may be given in any order. -r Recovery mode. The autoscript file is read to recover a crashed editing session. It has almost the same effect as "-s file.vim". See the chapter "Recovery after a crash". -v View mode. The readonly option will be set. You can still edit the buffer, but will be prevented from accidental overwriting a file. If you do want to overwrite a file, add an exclamation mark to the Ex command, as in ":w!". The readonly option can be reset with ":set noro" (see the options chapter). -n No autoscript file will be written. Recovery after a crash will be impossible. Handy if you want to edit a file on a very slow medium (e.g. floppy). Can also be done with ":set uc=0". -s {scriptin} The script file {scriptin} is read. The characters in the file are interpreted as if you had typed them. The same can be done with the command ":source! {scriptin}". If the end of the file is reached before the editor exits, further characters are read from the keyboard. -w {scriptout} All the characters that you type are recorded in the file {scriptout}, until you exit VIM. This is useful if you want to create a script file to be used with "vim -s" or ":source!". Example use of script file usage to change a name in several files: Create a file "sub.vi" containing substitute commands and a :wq command: :%s/Jones/Smith/g :%s/Allen/Peter/g :wq Execute VIM on all files you want to change: foreach i ( *.let ) vim -s sub.vi $i 3.2 Workbench (Amiga only) Vim can be started from the workbench by clicking on its icon twice. It will then start with an empty buffer. Vim can be started to edit one or more files by using a "Project" icon. The "Default Tool" of the icon must be the full pathname of the Vim executable. The name of the ".info" file must be the same as the name of the text file. By clicking on this icon twice, Vim will be started with the filename as current filename, which will be read into the buffer (if it exists). You can edit multiple files by pressing the shift key while clicking on icons, and clicking twice on the last one. The "Default Tool" for all these icons must be the same. It is not possible to give arguments to Vim, other than filenames, from the workbench. 3.3 Vim window VIM will run in the CLI window where it is started. If VIM is started with the "run" or "runback" command, or if VIM is started from the workbench, it will open a window of its own. To open the new window a little trick is used. As soon as VIM recognizes that it does not run in a normal CLI window, it will create a script file in t:. This script file contains the same command as how VIM was started, and an "endcli" command. This script file is then executed with a "newcli" command. The script file will hang around until reboot, or until you delete it. The "c:run" and "c:newcli" commands are required for this to work. This method is required to get the ":sh" and ":!" commands to work correctly. It is not done if Vim was started with the -e option (the ":sh" and ":!" commands are not available then). VIM will automatically recognize the window size and react to window resizing. It is advised to use the fastfonts program "FF", included in DOS 1.3, to speed up the display. 3.4 Initialization When VIM starts running it does initializations in this order: 1. The environment variable EXINIT, if it exists, is executed as an Ex command. 2. If the EXINIT environment variable does not exist, the file "s:.exrc", if it exists, is read and each line is executed as an Ex command. 3. The file ".exrc" in the current directory, if it exists, is read and each line is executed as an Ex command. 4. The environment variable SHELL, if it exists, is used to set the shell option. This can be used to set your default settings and mappings for all edit sessions or for sessions in a certain directory. See the section "Saving settings" for how to create a file with commands to recreate the current settings. On the Amiga two types of environment variables exist. The ones set with the DOS 1.3 setenv command are recognized. See the AmigaDos 1.3 manual. The environment variables set with the old Manx Set command are not recognized. 4. Modes 4.1 Introduction VIM has four basic modes: command mode In command mode you can enter all the editor commands. If you start the editor you get into this mode. insert mode In insert mode the text you type is inserted into the buffer. If the showmode option is set (which is default), the string "-- INSERT --" is shown at the bottom of the window. replace mode Replace mode is a special case of insert mode. You can do the same things as in insert mode, but for each character you enter (except some special characters) one character of the existing text is deleted. If the showmode option is set (which is default), the string "-- REPLACE --" is shown at the bottom of the window. command line mode In command line mode you can enter one line of text at the bottom of the window. This is for the Ex commands, the pattern search commands and the filter command. More explanation on the insert, replace and command line mode is further on in this chapter. 4.2 Switching from mode to mode If for any reason you do not know in which mode you are, you can always get back to command mode by typing twice. You will know you are back in command mode when you see the screen flash or hear the bell after you type . - go from command mode to insert mode by giving one of the commands "iIaAoOcCsS". - go from command mode to replace mode with the "R" command (not the "r" command!). - go from command mode to command line mode with the one of the commands ":/?!". - go from insert or replace mode to command mode with (twice in some rare cases). - go from command line mode to command mode with (which causes the entered command to be executed), by deleting the complete line (e.g. with "@") and giving a final , or by hitting twice. In the last case the first will also be used to start filename completion, but you can ignore that. 4.3 Insert and replace mode In insert and replace mode the following characters have a special meaning, other characters are inserted directly. To insert one of these special characters into the buffer, precede it with CTRL-V. char action ----------------------------------------------------------------------- CTRL-@ Insert previously inserted text and stop insert. {Vi: only when typed as first char, only upto 128 chars} CTRL-D Delete one shiftwidth after auto-indent, delete the character before the cursor otherwise. {Vi: only after auto-indent; also accepts preceding <^> and <0>} CTRL-E Insert the character which is below the cursor. {not in Vi} CTRL-H Delete the character before the cursor (the newline character if the cursor is in column 1 and the backspace option is set). {Vi: does not cross lines, does not delete autoindents} CTRL-J Begin new line. CTRL-M Begin new line. CTRL-R Insert the character which is above the cursor. {not in Vi} CTRL-T Insert one shiftwidth after auto-indent, TAB otherwise. {Vi: no TAB} CTRL-U Delete all entered characters in the current line. CTRL-V Insert next character literally. CTRL-W Delete word before the cursor (see the section "word motions" for the definition of a word). CTRL-[ End insert or replace mode, back to command mode. ----------------------------------------------------------------------- The textwidth option can be used to automatically break a line before it is getting too long. Set the textwidth option to the maximum line length. If you then type more characters (not being spaces or tabs), the last word will be put on a new line (unless it is the only word on the line). {Vi has the wrapmargin option, but it does not do what you want}. If you want to format a few lines do the following. First join them together into a single line. Set the textwidth option to the desired maximum width. Then append one character to the end of the line with "Ax". The text will be separated into several lines, each less than the maximum width. The extra character can be deleted with "". 4.4 Command line mode Command line mode is used to enter Ex commands, search patterns and commands. 4.4.1 Command line editing Normal characters are inserted in front of the cursor position. You can move around in the command line with the cursor keys. {Vi: can only alter the last character in the line} The command lines that you enter are remembered in a history table. You can recall them with the up and down cursor keys. Use the history option to set the number of lines that are remembered (default 20). CTRL-V insert next character literally {Vi: type the CTRL-V twice to get one} cursor left cursor right cursor one word left cursor one word right delete the character in front of the cursor delete the character under the cursor @ remove all characters recall older command line from history recall more recent command line from history CTRL-D list filenames that match the pattern in front of the cursor do filename completion on the pattern in front of the cursor For the last two you need arp.library in the libs: directory. Standard Amiga wildcards are accepted, plus the <*> and characters. For filename completion you can use the suffixes option to set a priority between files with almost the same name. If there are multiple matches, those files with a file extension that is in the suffixes option are ignored. The default is ".bak.o.h.info", which means that files with the extensions ".bak", ".o", ".h" and ".info" are sometimes ignored. It is impossible to ignore suffixes with two dots. Examples: pattern: files: match: test* test.c test.h test.o test.c test* test.h test.o (two matches) test* test.i test.h test.c (two matches) 4.4.2 Ex command lines The Ex commands have a few specialities: <"> or <#> at the start of a line cause the whole line to be ignored. <"> after a command causes the rest of the line to be ignored. This can be used to add comments. <|> can be used to separate commands, so you can give multiple commands in one line. The commands ":global", ":vglobal" and ":!" see the <|> as their argument, and can therefore not be followed by another command. When the characters <%> and <#> are used where a filename is expected, they are expanded to the current and alternate filename (see the chapter "editing files"). Embedded and trailing spaces in filenames are allowed if one filename is expected as argument (":next {file..}" uses the space to separate filenames). When you want to use the special characters <"> or <|> in a command, or want to use <%> or <#> in a filename, precede them with a backslash. The backslash is not required in a range and in the ":substitute" command. 4.4.3 Ex command line ranges Some Ex commands accept a line range in front of them. This is noted as [range]. It consists of one or more line specifiers, separated with ',' or ';'. When separated with ';' the cursor position will be set to that line before interpreting the next line specifier. The default line specifier for most commands is the Cursor position, but the commands ":write" and ":global" have the whole file (1,$) as default. If more line specifiers are given than required for the command, the first one(s) will be ignored. Line numbers may be specified with: {number} an absolute line number . the current line $ the last line in the file % equal to 1,$ (the entire file) 't position of mark t /{pattern} the next line where {pattern} matches ?{pattern} the previous line where {pattern} matches Each may be followed (several times) by '+' or '-' and an optional number. This number is added or subtracted from the preceding line number. If the number is omitted, 1 is used. Examples: .+3 three lines below the cursor /that+1 the line below the next line containing "that" .,$ from current line until end of file Some commands allow for a count after the command. This count is used as the number of lines to be used, starting with the line given in the last line specifier (the default is the cursor line). Examples: :s/x/X/g 5 substitute by in the current line and four more :23d 4 delete lines 23, 24, 25 and 26 4.5 The window contents In command and insert/replace mode the screen window will show the current contents of the buffer: What You See Is What You Get. {Vi: when changing text a <$> is placed on the last changed character; The window is not always updated on slow terminals} Lines longer than the window width will wrap. The bottom lines in the window may start with one of these two characters: <@> The next line is too long to fit in the window. <~> Below the last line of the buffer. All normal ASCII characters are displayed directly on the screen. The is replaced by the number of spaces that it represents. Other non-printing characters are replaced by "^", where is the non-printing character with 64 added. Thus character 7 (bell) will be shown as "^G". Characters between 127 and 160 are replaced by "~", where is the character with 64 subtracted. These characters occupy more than one position on the screen. The cursor can only be positioned on the last one. If you set the number option, all lines will be preceded with their number. If you set the list option, characters will not be shown as several spaces, but as "^I". A <$> will be placed at the end of the line, so you can find trailing blanks. In command line mode only the command line itself is shown correctly. The display of the buffer contents is updated as soon as you go back to command mode. Some commands hand over the window to external commands (e.g. ":shell" and "="). After these commands are finished the window may be clobbered with output from the external command, so it needs to be redrawn. If you are expected to have a look at the output of the external command, you are requested to hit when you want to continue. In fact and will also have the same effect. If you hit <:> instead, you are returned into command line mode. The last line of the window is used for messages, showing the current mode and displaying the command characters that you typed but were not used yet. {Vi: does not show the characters you typed} If there is an error, an error message will be shown for at least one second (in reverse video). {Vi: error messages may be overwritten with other messages before you have a chance to read them} Some commands show how many lines were affected. Above which threshold this happens can be controlled with the report option (default 5). On the Amiga VIM will run in a CLI window. The name VIM and the full name of the current filename will be shown in the title bar. When the window is resized, VIM will automatically redraw the window. You may make the window as small as you like, but if it gets too small not a single line will fit in it. Make it at least 40 characters wide to be able to read most messages on the last line. 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. Older alternate filenames are remembered in a list. When you start editing a new file, the filenames shift one down in this list. {Vi: no list of alternate filenames} In Ex commands (the ones that start with a colon) you can refer to the current filename with <%> and refer to the alternate filename with <#> or "#0". The older alternate filenames are "#1", "#2", etc. CTRL-G or :f[ile] Prints the current filename and the cursor position. :f[ile] {name} Sets the current filename to {name}. :files Lists the alternate filenames. 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 the original file to end in ".bak" before it will be overwritten. You can use this file if you discover that you need the original file. VIM remembers whether you have changed the buffer. You are protected from loosing 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 [+pat] Edit the current file, unless changes have been made. :e! [+pat] Edit the current file always. Discard any changes to the buffer. :e[dit] [+pat] {file} Edit {file}, unless changes have been made. :e[dit]! [+pat] {file} Edit {file} always. Discard any changes to the buffer. :ex [+pat] [file] Same as :edit. :vi[sual] [+pat] [file] Same as :edit. {Vi: go from Ex to visual mode} CTRL-^ Edit [cnt]th (default 0) alternate file (equivalent to ":e #[cnt]"). If the autowrite option is set and the buffer was changed, write it. :cd Print the current directory name. {Vi: not} :cd {path} Change the current directory to {path}. :chd[ir] [path] Same as :cd. 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 if you want to get to another directory, so you will not have to type that directory name in front of the filenames. 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. The [+pat] 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} must not contain spaces. {Vi: accepts an Ex command instead} 5.3 Tag searches :ta[g] {ident} Jump to the definition of {ident}, using the information in the tags file. Won't work if changes have been made and the autowrite option is off. :ta[g]! {ident} Jump to the definition of {ident}, using the information in the tags file. Discard any changes to the buffer. CTRL-] ":ta" to the identifier under cursor. {Vi: identifier after the cursor} A tag is an identifier that appears in the "tags" file. It is a sort of label that can be jumped to. For example: In C programs each function can get a tag with the name of the function. With the ":tag" command the cursor will be positioned on the tag. If the tag is in the current file this will always work. Otherwise the performed actions depend on whether the current file was changed and on the autowrite option: tag in file autowrite current file changed option action ----------------------------------------------------------------------------- yes x x goto tag no no x read other file, goto tag no yes on write current file, read other file, goto tag no yes off fail ----------------------------------------------------------------------------- - If the tag is in the current file, the command will always work. - If the tag is in another file and the current file was not changed, the other file will be made the current file and read into the buffer. - If the tag is in another file, the current file was changed and the autowrite option is set, the current file will be written, the other file will be made the current file and read into the buffer. - If the tag is in another file, the current file was changed and the autowrite option is not set, the command will fail. If you want to save the changes, use the ":w" command and then try again. If you want loose the changes you can use the ":tag!" command. The ":tag" command works very well for C programs. If you see a call to a function and wonder what that function does, position the cursor inside of the function name and hit CTRL-]. This will bring you to the function definition. An easy way back is with the "''" command, or, if the definition is in another file, with the CTRL-^ command. A tags file can be created with the external command 'ctags'. It will contain a tag for each function. Some versions of 'ctags' will also make a tag for each "#defined" macro. The lines in the tags file should have this format: {tag}{separator}{filename}{separator}{command} {tag} the identifier {separator} a single or space character {filename} the file that contains the definition of {tag} {command} the VIM command that positions the cursor on the tag (it can be any command, but normally it is a search command like "/^tag"). The tags option is a list of file names separated by spaces. Each of these files is searched for the tag. This can be used to use a different file than the default file "tags". It can also be used to access a common tags file. For example: :set tags=tags\ s:commontags The tag will first be searched for in the file "tags" in the current directory. If it is not found there the file "s:commontags" will be searched for the tag. The backslash is required for the space to be include in the string option. 5.4 The file list If you give more than one filename when starting VIM, this list is remembered as the file list. You can use this list with the following commands: :ar[gs] Print the file list, with the current file in "[]". :n[ext] Edit next file, unless changes have been made and the autowrite option is off. :n[ext]! Edit next file, discard any changes to the buffer. :n[ext] [+pat] {filelist} Define {filelist} as the new list of files and edit the first one, unless changes have been made and the autowrite option is off. :n[ext]! [+pat] {filelist} Define {filelist} as the new list of files and edit the first one. Discard any changes to the buffer. :N[ext] Edit previous file in file list, unless changes have been made and the autowrite option is off. :N[ext]! Edit previous file in file list. Discard any changes to the buffer. :pre[vious] Same as :Next. :rew[ind] Start editing the first file in the file list, unless changes have been made and the autowrite option is off. :rew[ind]! Start editing the first file in the file list. Discard any changes to the buffer. The wildcards in the file 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. You are protected from leaving VIM if you are not editing the last file in the file list. This prevents you from accidental forgetting that you were editing several files. You can exit anyway, and save any changes, with the ":wq!" command. To loose any changes use the ":q!" command. 5.5 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}. :[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,$). :q[uit] Quit, unless changes have been made or not editing the last file in the file list. :q[uit]! Quit always, without writing. :cq Quit always, without writing, and return an error code. Used for Manx's QuickFix option (see 5.6). :wq Write the current file. Exit if not editing the last file in the file list. :wq! Write the current file and exit. :wq {file} Write to {file}. Exit if not editing the last file in the file list. :wq! {file} Write to {file} and exit. :x[it][!] [file] Like ":wq", but write only when changes have been made. ZZ Store current file, if modified, and exit (same as ":x"). 5.6 using Manx's QuickFix option Manx's Aztec C compiler on the Amiga has a speciality to speedup the edit-compile-edit cycle. This is called the QuickFix option. VIM includes support for this handy feature which is almost identical to Manx's editor "Z". What you should do is: - 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. 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. :cn Display the next error in the list. :cp Display the previous error in the list. :cq Quit Vim with an error code, so that the compiler will not compile the same file again. :cf Read the error file. This is done automatically when Vim is started with the -e option. :cl List all errors. The name of the file can be set with the errorfile option. The default is "AztecC.Err". The format of the file 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' errornumber number of the error errormessage description of the error There are some restrictions to the Quickfix option. Only the first 25 errors are recognized (Manx's documentation does not say how to get the others). If Vim was started with the -e option 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 edit another file the marks are lost and the error locations may not be correct anymore. 6. Cursor motions These commands move the cursor position. If the new position is off of the screen, the screen is scrolled to show the cursor. The motion commands can be used after other commands, called operators, to have the command operate on the text that was moved over. That is the text between the cursor position before and after the motion. If the motion includes a count and the operator also had a count, the two counts are multiplied. For example: "2d3w" deletes six words. The operator either affects whole lines, or the characters between the cursor positions. Generally, motions that move between lines affect lines, and motions that move within a line affect characters. However, there are some exceptions. The motion is either inclusive or exclusive. When inclusive, the start and end positions of the motion are included in the operation. When exclusive, the last character towards the end of the buffer is not included. Line wise motions are always inclusive. Which motions are linewise, inclusive or exclusive is mentioned below. NOTE: Experienced users prefer the hjkl keys because they are always right under their fingers. Beginners often prefer the arrow keys, since they do not require memorization of which hjkl key is which. The mnemonic value of hjkl is clear from looking at the keyboard. Think of j as an arrow pointing downwards. 6.1 Left-right motions h or or CTRL-H or [cnt] characters to the left (exclusive). l or or [cnt] characters to the right (exclusive). 0 To the first character of the line (inclusive). ^ To the first non-blank character of the line (inclusive). $ To the end of line [cnt] from the cursor (inclusive). | To column [cnt] (inclusive). f To [cnt]'th occurrence of to the right. The cursor is placed on (inclusive). F To the [cnt]'th occurrence of to the left. The cursor is placed on (inclusive). t Till before [cnt]'th occurrence of to the right. The cursor is placed on the character left of (inclusive). T Till after [cnt]'th occurrence of to the left. The cursor is placed on the character right of (inclusive). ; Repeat latest f, t, F or T [cnt] times. , Repeat latest f, t, F or T in opposite direction [cnt] times. These commands move the cursor to the specified column in the current line. They stop at the first column and at the end of the line, except '$', which may move to one of the next lines. 6.2 Up-down motions k or or CTRL-P [cnt] lines upward (linewise). j or or CTRL-J or or CTRL-N [cnt] lines downward (linewise). - [cnt] lines upward, on the first non-blank character (linewise). + or CTRL-M or [cnt] lines downward, on the first non-blank character (linewise). _ [cnt] - 1 lines downward, on the first non-blank character (linewise). G Goto line [cnt], default last line, on the first non-blank character (linewise). :[range] Set the cursor on the (last) specified line number (cannot be used with an operator). These commands move to the specified line. They stop when reaching the first or the last line. The first two commands put the cursor in the same column (if possible) as it was after the last command that changed the column, except after the '$' command, then the cursor will be put on the last character of the line. 6.3 Word motions w [cnt] words forward (exclusive). W [cnt] WORDS forward (exclusive). e Forward to the end of word [cnt] (inclusive). E Forward to the end of WORD [cnt] (inclusive). b [cnt] words backward (exclusive). B [cnt] WORDS backward (exclusive). These commands move over words or WORDS. A word consists of a sequence of letters, digits and underscores, or a sequence of other non-blank characters, separated with blank space. A WORD consists of a sequence of non-blank characters, separated with blank space. The end of a line is also considered to be blank space. An empty line is also considered to be a word and a WORD. Special case: "cw" and "cW" are treated like "ce" and "cE" if the cursor is on a non-blank. This is because "cw" is interpreted as change-word, and a word does not include the following blank space. 6.4 Text object motions ( [cnt] sentences backward (exclusive). ) [cnt] sentences forward (exclusive). { [cnt] paragraphs backward (exclusive). } [cnt] paragraphs forward (exclusive). ]] [cnt] sections forward, except when used after an operator, then [cnt] SECTIONS forward (linewise). ][ [cnt] SECTIONS forward (linewise). [[ [cnt] sections backward (linewise). [] [cnt] SECTIONS backward (linewise). These commands move over three kinds of text objects. A sentence is defined as ending at a '.', '!' or '?' followed by either the end of a line, or by a space. {Vi: two spaces} Any number of closing ')', ']', '"' and ''' characters my appear after the '.', '!' or '?' before the spaces or end of line. A paragraph and section boundary is also a sentence boundary. A paragraph begins after each empty line, and also at each of a set of paragraph macros, specified by the pairs of characters in the paragraphs option. The default is "IPLPPPQPP LIpplpipbp", which corresponds to the macros ".IP", ".LP", etc.. A section boundary is also a paragraph boundary. A section begins after a form-feed in the first column, a '{' in the first column, and also at each of a set of section macros, specified by the pairs of characters in the sections option. The default is "SHNHH HUnhsh". A SECTION is the same as a section, except that a '}' replaces the '{'. This is useful to find the end of C-language functions. 6.5 Pattern searches /{pattern}[/] Search forward for the [cnt]'th occurrence of {pattern} (exclusive). /{pattern}/{offset} Search forward for the [cnt]'th occurrence of {pattern} and go {offset} lines up or down (see below). (linewise). / Search forward for the [cnt]'th latest used pattern. * Search forward for the [cnt]'th occurrence of the ident under the cursor (exclusive). {not in Vi} # Search backward for the [cnt]'th occurrence of the ident under the cursor (exclusive). {not in Vi} ?{pattern}[?] Search backward for the [cnt]'th previous occurrence of {pattern} (exclusive). ?{pattern}?{offset} Search backward for the [cnt]'th previous occurrence of {pattern} and go {offset} lines up or down (see below) (linewise). ? Search backward for the [cnt]'th latest used pattern. n Repeat the latest '/' or '?' [cnt] times. {Vi: no count} N Repeat the latest '/' or '?' [cnt] times in opposite direction. {Vi: no count} CTRL-C Interrupt current (search) command. These commands search for the specified pattern. With "/" and "?" an additional offset may be given. There are two types of offsets: line offsets and character offsets. {the character offsets are not in Vi} The offset gives the cursor positition relative to the found match: +[num] [num] lines downwards, in column 1 -[num] [num] lines upwards, in column 1 e[+num] [num] characters to the right of the end of the match e[-num] [num] characters to the left of the end of the match s[+num] [num] characters to the right of the start of the match s[-num] [num] characters to the left of the start of the match If [num] is omitted it is assumed to be zero. Examples: pattern cursor position /test/+1 one line below "test", in column 1 /test/e on the last t of "test" /test/s+2 on the "s" of "test" If one of these commands is used after an operator, the characters between the cursor position before and after the search is affected. However, if a line offset is given, the whole lines between the two cursor positions are affected. The last used and are remembered. They can be used to repeat the search, possibly in another direction or with another count. If the option wrapscan is set (which is the default), searches wrap around the end of the buffer. If wrapscan is not set, the backward search stops at the beginning and the forward search stops at the end of the buffer. If the pattern was not found the error message "pattern not found" is given, and the cursor will not be moved. Patterns may contain special characters, depending on the setting of the 'magic' option. The '*' and '#' commands search for the pattern currently under the cursor. This pattern may only contain letters, digits and underscores. Note that if you type with ten fingers, the characters are easy to remember: the '#' is under your left hand middle finger and the '*' is under your right hand middle finger. The definition of a pattern: 1. A pattern is one or more branches, separated by '\|'. It matches anything that matches one of the branches. 2. A branch is one or more pieces, concatenated. It matches a match for the first, followed by a match for the second, etc. 3. A piece is an atom, possibly followed by: magic nomagic * \* matches 0 or more of the preceding atom \+ \+ matches 1 or more of the preceding atom {not in Vi} \? \? matches 0 or 1 of the preceding atom {not in Vi} 4. An atom can be: - One of these five: magic nomagic . \. matches any single character \< \< matches the beginning of a word \> \> matches the end of a word ^ ^ at beginning of pattern, matches beginning of line $ $ at end of pattern, matches end of line - A pattern enclosed by escaped parentheses (e.g. "\(^a\)"). - A single character, with no special meaning, matches itself - A backslash followed by a single character, with no special meaning, matches the single character. - A range. This is a sequence of characters enclosed in '[]' with the magic option, or enclosed in '\[\]' with the nomagic option. It normally matches any single character from the sequence. If the sequence begins with '^', it matches any single character NOT in the sequence. If two characters in the sequence are separated by '-', this is shorthand for the full list of ASCII characters between them (e.g. '[0-9]' matches any decimal digit). To include a literal ']' in the sequence, make it the first character (following a possible '^'). To include a literal '\-', make it the first or last character. If the 'ignorecase' option is set, the case of letters is ignored. Examples: ^func( Probably the start of a C function. [a-zA-Z]$ Any alphabetic character at the end of a line. \(^\|[^a-zA-Z0-9_]\)[a-zA-Z_]\+[a-zA-Z0-9_]* A C identifier (will stop in front of it). [.!?][])"']*\($\|[ ]\) A search pattern that finds the end of a sentence, with almost the same definition as the <)> command. 6.6 Various motions m Set mark at cursor position (does not move the cursor, this is not a motion command). ' To the first non-blank character on the line with mark (linewise). ` To the mark (inclusive). A mark is not visible in any way. It is just a position in the file that is remembered. If you change a character in a line, or delete a line that contains a mark, that mark is erased. Do not confuse marks with named registers, they are totally unrelated. '' To the first non-blank character of the line where the cursor was before the latest jump (linewise). `` To the position before latest jump (inclusive). If you make the cursor "jump" with one of the following commands, the position of the cursor before the move is remembered. You can return to that position with the two commands above, unless the line containing that position was changed or deleted. The "jump" commands are: "'", "`", "G", "/", "?", "n", "N", "%", "(", ")", "[[", "]]", "{", "}", ":s" and the commands that start editing a new file. % Find the next parenthesis or (curly/square) bracket on this line and go to its match (inclusive). H To line [cnt] from top (Home) of screen (default: first line on the screen) on the first non-blank character (linewise). M To Middle line of screen, on the first non-blank character (linewise). L To line [cnt] from bottom of screen (default: Last line on the screen) on the first non-blank character (linewise). 7. Scrolling CTRL-E Window [cnt] lines downwards in the buffer ([cnt] lines Extra). CTRL-D Window [cnt] lines Downwards in the buffer (default: previous [cnt] or half a screen). CTRL-F Window [cnt] pages Forwards (downwards) in the buffer. CTRL-Y Window [cnt] lines upwards in the buffer. CTRL-U Window [cnt] lines Upwards in the buffer (default: previous [cnt] or half a screen). CTRL-B Window [cnt] pages Backwards (upwards) in the buffer. z Redraw, cursor line at top of window. {Vi: a number in front of the causes the window to be that tall} z. Redraw, cursor line at center of window. z- Redraw, cursor line at bottom of window. These commands move the contents of the window. If the cursor position is moved off of the window, the cursor is moved onto the window. A page is the number of lines in the window minus two. The mnemonics for these commands may be a bit confusing. Remember that the commands refer to moving the window upwards or downwards in the buffer. But when the window moves upwards in the buffer, the text in the window moves downwards on your screen. 8. Inserting text a Append text after the cursor [cnt] times. A Append text at the end of the line [cnt] times. i Insert text before the cursor [cnt] times. I Insert text before the first CHAR on the line [cnt] times. o Begin a new line below the cursor and insert text, repeat [cnt] times. {Vi: blank [cnt] screen lines} O Begin a new line above the cursor and insert text, repeat [cnt] times. {Vi: blank [cnt] screen lines} These commands are used to start inserting text. They can be undone and repeated. You can end insert mode with . See the section "Insert and replace mode" for the other special characters in insert mode. The effect of [cnt] takes place after insert mode is exited. :r[ead] {name} Insert the file {name} below the cursor. :r[ead]!{cmd} Execute {cmd} and insert its standard output below the cursor. These commands insert the contents of a file, or the output of a command, into the buffer. They can be undone. They cannot be repeated with the "." command. They work on a line basis, insertion starts below the line in which the cursor is. To insert text above the first line, you will first have to create a line with the "O" command, insert the text with the ":r" command, and then delete the first line again. 9. Deleting text ["x]x Delete [cnt] characters under and after the cursor [into register x] (not linewise). ["x]X Delete [cnt] characters before the cursor [into register x] (not linewise). ["x]d{motion} Delete text that is moved over [into register x]. ["x]dd Delete [cnt] lines [into register x] (linewise). ["x]D Delete the characters under the cursor until the end of the line and [cnt]-1 more lines [into register x]; synonym for d$ (not linewise). :[range]d[elete] ["x] Delete [range] lines (default: current line) [into register x]. :[range]d[elete] ["x] {count} Delete {count} lines, starting with [range] (default: current line, see 4.4.3) [into register x]. J Join [cnt] lines, with a minimum of two lines. One space is inserted in place of the . If the uppermost line had trailing blank space it is deleted first. {Vi: insert two spaces after a period} :[range]j[oin][!] Join [range] lines. Same as 'J', except when [!] is given, then no spaces will be inserted or deleted. :[range]j[oin][!] {count} Join {count} lines, starting with [range] (default: current line, see 4.4.3). Same as 'J', except when [!] is given, then no spaces will be inserted or deleted. These commands delete text. They can be repeated (except ":d" and ":j") and undone. See "copying" for an explanation of registers. 10. Changing text The following commands can be used to change text, that is delete some text and insert something else, with one command. They can all be undone. The non-Ex commands can be repeated with the "." command. 10.1 Delete and insert R Enter replace mode: each character you type replaces an existing character, starting with the character under the cursor. Repeat the entered text [cnt]-1 times. ["x]c{motion} Delete {motion} text [into register x] and start insert. ["x]cc Delete [cnt] lines [into register x] and start insert (linewise). ["x]C Delete from the cursor position to the end of the line and [cnt]-1 more lines [into register x], and start insert. Synonym for c$ (not linewise). ["x]s Delete [cnt] characters [into register x] and start insert (s stands for Substitute). Synonym for "cl" (not linewise). ["x]S Delete [cnt] lines [into register x] and start insert. Synonym for "^cc" or "0cc", depending on autoindent (not linewise). You can end insert and replace mode with . See the section "Insert and replace mode" for the other special characters in these modes. The effect of [cnt] takes place after insert or replace mode is exited. {Vi: does not directly delete the text, but puts a '$' at the last deleted character} See "copying" for an explanation of registers. Replace mode is just like insert mode, except that for every character you enter, one character is deleted. If the end of a line is reached is behaves the same as insert mode. In replace mode the backspace key only moves the cursor positition, no characters are deleted. Special case: "cw" and "cW" are translated into "ce" and "cE" if the cursor is on a word (you are expected to want to change the word, not any following blanks). 10.2 Simple changes r Replace [cnt] characters by . ~ Option notildeop: switch case of [cnt] characters under the cursor and move the cursor [cnt] characters to the right. {Vi: no count} ~{motion} Option tildeop: switch case of {motion} text. {Vi: no tildeop option} <{motion} Shift the {motion} lines one shiftwidth leftwards. << Shift [cnt] lines one shiftwidth leftwards. >{motion} Shift {motion} lines one shiftwidth rightwards. >> Shift [cnt] lines one shiftwidth rightwards. :[range]< Shift [range] lines left. :[range]< {count} Shift {count} lines left, starting with [range] (default current line, see 4.4.3). :[range]> Shift {count} [range] lines right. :[range]> {count} Shift {count} lines right, starting with [range] (default current line, see 4.4.3). The ">" and "<" commands are handy for changing the indent within programs. The size of the blank space which is inserted or deleted can be set with the option shiftwidth. Normally the shiftwidth option is set to 8, but you can set it to e.g. 3 to make smaller indents. The shift leftwards stops when there is no indent. The shift right does not do anything with empty lines. 10.3 Complex changes !{motion}{filter} Filter {motion} text through the external program {filter}. !!{filter} Filter [cnt] lines through the external program {filter}. :{range}![!]{filter} [!][arg] Filter {range} lines through the external program {filter}. The optional bangs are replaced with the latest given command. The optional [arg] is appended. ={motion} Filter {motion} lines through "indent". {Vi: when option 'lisp' is set autoindent {motion} lines} == Filter [cnt] lines through "indent". A filter is a program that accepts text at standard input, changes it in some way, and sends it to standard output. The commands above can be used to send some text through a filter. An example of a filter is "sort", which sorts lines alphabetically. The "indent" program is used to pretty indent C programs (you need a version of indent that works like a filter, not all versions do that). :[range]s[ubstitute]/{pattern}/{string}/[g][c] [count] For each line in [range] replace the first occurrence of {pattern} by {string}. With option [g] all occurrences in the line are replaced. With option [c] each replace has to be confirmed ( to replace, to quit replacing, anything else to skip). With [count] that many lines are are searched, starting with the last line number in [range] (default current line, see 4.4.3). :[range]s[ubstitute] [g][c] [count] Repeat last :substitute with new options and possibly on other lines. :[range]&[/{pattern}/{string}/][g][c] [count] Same as for :substitute. & Synonym for ":s". 11. Copying and moving text " Use register for next delete, yank or put (uppercase to append). :di[splay] Display the contents of numbered and named registers. {Vi: no such command} ["x]y{motion} Yank {motion} text [into register x]. ["x]yy Yank [cnt] lines [into register x] (linewise). ["x]Y With option noyankendofline: yank [cnt] lines [into register x] (synonym for yy, linewise); with option yankendofline: yank until end of line (synonym for y$, not linewise). :[range]y[ank] ["x] Yank [range] lines [into register x]. :[range]y[ank] ["x] {count} Yank {count} lines, starting with [range] (default: current line, see 4.4.3), [into register x]. ["x]p Put the text [from register x] after the cursor [cnt] times. ["x]P Put the text [from register x] before the cursor [cnt] times. :[line]pu[t] ["x] Put the text [from register x] after [line] (default current line). These commands can be used to copy text from one place to another. This is done by first getting the text into a register with a yank, delete or change command. The register can than be inserted with a put command. The put commands can be repeated (except for :put) and undone. If the command that was used to get the text into the register was linewise, the text will be inserted below or above the line where the cursor is. Otherwise the text will be inserted before or after the cursor. With the ":put" command the text will always be inserted in the next line. You can exchange single characters with the command sequence "xp". You can exchange single lines with the command sequence "ddp". There are three types of registers: one unnamed, nine numbered and 26 named registers. The unnamed register is filled with the text of each yank, delete or change command. It can be put by using the "p" or "P" command without a ["x]. Numbered register "1" is filled with the text of each delete or change (not yank) command, unless a ["x] is used. The contents of register "1" is put in "2", "2" in "3", and so forth. The contents of register "9" is lost. The named registers are only filled when you say so. They are named 'a' to 'z' normally. If you use the uppercase letter, the same registers as with the lower case letter is used, but the text is appended to the previous register contents. With a lower case letter the previous contents is lost. {Vi: unnamed register contents is lost when changing files} 12. Various commands CTRL-L Clear and redraw the screen. CTRL-Z Error. {Vi: suspend program} & Repeat last :s. : Ex command (see below). Show the file vim:vim.hlp page by page. {Vi: no help} :h[elp] Show the file vim:vim.hlp page by page. {Vi: no help} When entering a number: remove the last digit. :[range]p[rint] Print [range] lines (default current line). :[range]p[rint] {count} Print {count} lines, starting with [range] (default current line, see 4.4.3). := Print the line number. :sh[ell] Escape to a shell (name from option 'shell'). :![!]{cmd} [!][arg] Execute {cmd} with the shell. The optional bangs are replaced with the previously given command. The optional [arg] is appended. :ve[rsion] Print the version number of the editor. 13. Repeating commands 13.1 Single repeats . Repeat last change with count replaced by [cnt]. Simple changes can be repeated with the '.' command. Without a count, the count of the last change is used. If you enter a count, it will replace the last one. If the last change included a specification of a numbered register, the register number will be incremented. See the section on undo and redo for an example how to use this. 13.2 Multiple repeats :[range]g[lobal]/{pattern}/[cmd] Execute the Ex command [cmd] (default ":p") on the lines within [range] where {pattern} matches. :[range]g[lobal]!/{pattern}/[cmd] Execute the Ex command [cmd] (default ":p") on the lines within [range] where {pattern} does NOT match. :[range]v[global]/{pattern}/[cmd] Same as :g!. The global commands work by first scanning through the [range] lines and marking each line where a match occurs. In a second scan the [cmd] is executed for each marked line with its line number prepended. If a line is changed or deleted its mark disappears. The default for [range] is the whole buffer (1,$). Use "CTRL-C" to interrupt the command. To repeat non-Ex commands, you will have to put the commands in a file and use the Ex command ":source!". The undo/redo command will undo/redo the whole global command at once. 13.3 Complex repeats v Record typed characters into named register (uppercase to append). v Stops recording. {Vi: no recording} @ Execute the contents of named register [cnt] times. @@ Repeat the previous @ [cnt] times. :so[urce] {file} Read Ex commands from {file}. :so[urce]! {file} Read VIM commands from {file}. {Vi: not} All commands and command sequences can be repeated by putting them in a named register and then executing it. There are two ways to get the commands in the register: - Use the record command. You type the commands once, and while they are being executed they are stored in a register. Easy, because you can see what you are doing. If you make a mistake, 'put' the register into the file, edit the command sequence, and then delete it into the register again. You can continue recording by appending to the register (use an uppercase letter). - Delete or yank the command sequence into the register. Often used command sequences can be put under a function key with the ':map' command. An alternative is to put the commands in a file, and execute them with the ':source!' command. Useful for long command sequences. Can be combined with the ':map' command to put complicated commands under a funcion key. The ':source' command reads Ex commands from a file line by line. You will have to type any needed keyboard input. The ':source!' command reads from a script file character by character, interpreting each character as if you typed it. Example: When you give the ":!ls" command you are asked to "hit return to continue". If you ':source' a file with the line "!ls" in it, you will have to type the return yourself. But if you ':source!' a file with the line ":!ls" in it, the next characters from that file are read until a is found. You will not have to type yourself, unless ":!ls" was the last line in the file. It is possible to put ':source[!]' commands in the script file, so you can make a top-down hierachy of script files. The ':source' command can be nested as deep as the number of files that can be opened at one time (about 15). The ':source!' command can be nested up to 15 levels deep. 14. Undo and redo u or :u[ndo] Undo changes. {Vi: only one level} CTRL-R Redo changes which were undone with 'u'. {Vi: redraw screen} U Undo all latest changes on one line. {Vi: while not moved off of it} The last changes are remembered. You can go back in time with the 'u' command. You can then go forward again with the 'CTRL-R' command. If you make a new change after the 'u' command, the 'CTRL-R' will not be possible anymore. The number of changes that are remembered is set with the "undolevels" option. If it is zero, the old fashioned Vi undo is present: one level of undo and undo undoes itself. The 'U' command is treated by undo/redo just like any other command. Thus a 'u' command undos a 'U' command and a 'CTRL-R' command redoes it again. When mixing 'U', 'u' and 'CTRL-R' you will notice that the 'U' command will restore the situation of a line to before the previous 'U' command. This may be confusing. Try it out to get used to it. The numbered registers can also be used for undoing deletes. Each time you delete text, it is put into register "1. The contents of register "1 is shifted to "2, etc. The contents of register "9 is lost. You can now get back the most recent deleted text with the put command: '"1P'. You can get back the text of three deletes ago with '"3P'. If you want to get back more than one part of deleted text, you can use a special feature of the repeat command '.'. It will increase the number of the register used. So if you first do '"1P', the following '.' will result in a '"2P'. Repeating this will result in all numbered registers to be inserted. Example: If you deleted text with 'dd....' it can be restored with '"1P....'. If you don't know in which register the deleted text is, you can use the :display command. An alternative is to try the first register with '"1P', and if it is not what you want do 'u.'. This will result in the contents of the first put to be removed, and a repeat of the put command for the second register. Repeat the 'u.' until you got what you want. 15. Key mapping :ma[p] {lhs} {rhs} Map the key sequence {lhs} to {rhs} in normal mode. :ma[p]! {lhs} {rhs} Map the key sequence {lhs} to {rhs} in insert and command line mode. :unm[ap] {lhs} Remove the mapping of {lhs} for normal mode. :unm[ap]! {lhs} Remove the mapping of {lhs} for insert and command line mode. :map List all key mappings for normal mode. :map! List all key mappings for insert and command line mode. :map {lhs} List the key mappings for the key sequences starting with {lhs} in normal mode. :map! {lhs} List the key mappings for the key sequences starting with {lhs} in insert and command line mode. These commands are used to map a key or key sequence to a string of characters. You can use this to put command sequences under function keys, translate one key into another, etc. See the "Options" chapter below for how to save and restore the current mapping. Important: Everything from the first non-blank after {lhs} upto the end of the line (or <|>) is considered to be part of {rhs}. This allows the {rhs} to end with a space. It is currently not possible to have a {lhs} that contains a space or a {rhs} that starts with a space. It is not possible to put a comment after this command, because the <"> character is considered to be part of the {rhs}. To put a <|> in {rhs} escape it with a backslash or a ^V. Note that the second character (argument) of the commands @zZtTfF[]rm'`"v is not mapped. This was probably done to be able to use all the named registers and marks, even when the command with the same name has been mapped. Some examples (given as you type them; e.g. the "^V" is CTRL-V which you type, but will not show up on the screen): :map g /foo^V^Mcwbar^V^[ :map! qq quadrillion questions See the file "index" for keys that are not used and thus can be mapped without loosing any builtin function. 16. Recovery after a crash. You have spent several hours typing in that text that has to be finished next morning, and then disaster strikes: Your computer crashes. DON'T PANIC! 16.1 The autoscript file Vim keeps track of everything you type. Using the original file you started from and the autoscript file you can recover (almost) all of your work. The name of the autoscript file is the same as the file you are editing, but with the extension ".vim". If this file already exists (e.g. when you are recovering from a crash) a warning is given and another extension is used, ".vil" or something like that. An existing file will never be overwritten. The file is deleted as soon as the edited text is successfully written to disk. The autoscript file is updated after typing 100 characters or when you have not typed anything for two seconds. The reason why it is not kept up to date all the time is that this would slow down normal work too much. You can change the 100 character count with the "updatecount" parameter. You can set the time with the "updatetime" parameter. The time is given in milliseconds. If the writing to the autoscript file is not wanted, it can be switched off by setting the "updatecount" parameter to 0. It can be switched back on later. If you have changed the buffer when switching on, the autoscript file will be incomplete and recovery will probably fail. To avoid this write out the buffer with ":w" before switching on the autoscript file. 16.2 Recovery In most cases recovery is quite easy: start Vim on the same file you were editing when the crash happened, with the "-r" option added. Vim will start editing the file using the key strokes in the autoscript file. Be sure that the recovery was successful before overwriting the original file or deleting the autoscript file. Example: vim -r reference.doc Important: The .exrc file must be the same as with the original edit session, because some options have effect on the editing. Also the window size must be exactly the same, because the cursor movement resulting from some commands depends on the window size (e.g. CTRL-F). To help you with that the window resizing events are written into the script file with ":winsize" commands. The result of this command is that Vim will resize the used part of the window, but the window itself will remain the same size. The commands will be executed correctly, but the window contents may look disturbed. During normal editing you should not use the ":winsize" command. Use the window resizing gadget in the lower right corner of the window. Do not resize the window during recovery! In some cases the "-r" option does not result in successful recovery. This happens when you executed a command that cannot be reproduced anymore. For example: reading a file which does not exist anymore. In such a case the succeeding commands probably only make things worse. To solve this you will have to edit the autoscript file and remove the commands that cause errors. If this becomes difficult try splitting up the autoscript file in small pieces. {Vi: recovers in another way that has a larger change to succeed but causes more overhead} If the autoscript file is not ending in ".vim" but in something else, you can use the script reading option "-s {filename}". This will have (almost) the same effect as the "-r" option. You can give the "-r" option in combination with the "-s scriptin" option. The scriptin file will be read first, then the autoscript file for recovery. The difference between using the "-r" option and the "-s" option is that with the "-r" option the name of the script file is made from the file name, and the last modification date is checked to see if the autoscript file is newer. This prevents the wrong autoscript file to be used for a recovery. 17. Options Vi has a number of internal variables and switches which can be set to achieve special effects. These options come in three forms, those that are switches, which toggle from off to on and back, those that require a numeric value, and those that require an alphanumeric string value. 17.1 Setting options :se[t] Show all modified options. {Vi: non-default options} :se[t] all Show all options. :se[t] {option} Set toggle option on, show value of string or number option. :se[t] no{option} Set toggle option off. :se[t] {option}={value} Set string or number option to {value}. :se[t] {option}? Show value of {option}. The arguments to set may be repeated. For example: ":set ai nosi sw=3 ts=3". Besides changing options with the ":set" command, there are four alternatives to set options automatically for one or more files. The first and second ones are used for all files. The third is used to set options for the files in one directory. The last is used to set options for a single file. The first three are done when you start VIM, in the given order. The last is done whenever you start editing a new file. 1. The environment variable EXINIT is read for an Ex command. You can set EXINIT to something like "set noai sw=3" to set options. 2. Only if there is no EXINIT environment variable, the file "s:.exrc" is read for Ex commands. You can include set commands in this file (see below for how to automatically create a ".exrc" file). 3. The file ".exrc" in the current directory is read for Ex commands. You can include set commands in this file. 4. If you start editing a new file, a number of lines at the beginning and end of the file are checked for the string "vi:" or "ex:". The text after it is considered to be the arguments for a ":set" command, separated with colons. For example: "vi:noai:sw=3". How many lines are checked depends on the modelines option. 17.2 Saving settings :mkexrc [file] Write current key mappings and options to [file] (default ".exrc"), unless it already exists. {not in Vi} :mkexrc! [file] Always write current key mappings and options to [file] (default ".exrc"). {not in Vi} The ":mkexrc" command will write ":map" and ":set" commands to a file, in such a way that when these commands are executed, the current key mappings and options will be set again. A common method is to use a default ".exrc" file by first reading one in with ":source s:.exrc.Cprogs", change the settings and then save them in the current directory with ":mkexrc!". 17.3 Options summary In the list below all the options are mentioned with their full name and some with an abbreviation between brackets. Both forms may be used. autoindent (ai) toggle (default off) Copy indent from previous line when inserting text. autowrite (aw) toggle (default off) Write the contents of the file, if it has been modified, on each :next, :rewind, :previous, :stop, :tag, :!, CTRL-] and CTRL-^ command. backspace (bs) toggle (default off) Allow backspacing over newlines in insert mode. {not in Vi} backup (bk) toggle (default on) Make a backup before overwriting a file. errorbells (eb) toggle (default off) Ring the bell for error messages. errorfile (ef) string (default "AztecC.Err") Name of the error file for the QuickFix option (see 5.6). {not in Vi} history (hi) number (default 20) Number of command lines that are remembered. {not in Vi} ignorecase (ic) toggle (default off) Ignore case in search patterns. lines number (default 25) Number of lines in the display. list toggle (default off) List mode: show tabs as CTRL-I, end lines with $, etc.. magic toggle (default on) Allow for pattern matching characters besides ^ and $. modelines (ml) number (default 5) The number of lines that is checked for set commands. See 17.1. {not in Vi} number (nu) toggle (default off) Print the line number in front of the line. paragraphs (para) string (default "IPLPPPQPP LIpplpipbp") Specifies the nroff macros that separate paragraphs. These are pairs of two letters. readonly (ro) toggle (default off) If set, writes fail unless you use an !. Affects anything that writes to protect you from accidental overwriting a file. Default on when vim is started in view mode ("vim -v"). remap toggle (default on) Allows for :map command to work recursively. report number (default 5) Threshold for reporting number of lines changed. scroll number (default 12) Number of lines to scroll with CTRL-U and CTRL-D commands. sections string (default "SHNHH HUnhsh") Specifies the nroff macros that separate sections. These are pairs of two letters. shell (sh) string (default "sh") Name of the shell to use for ! and :! commands. The shell should be able to accept a command with the "-c" option for the ":!" command to work. shiftwidth (sw) number (default 8) Number of spaces to use for (auto)indent. showmatch (sm) toggle (default off) When a bracket is inserted, briefly jump to the matching one. showmode (mo) toggle (default on) If in insert or replace mode, print a message on the last line. smartindent (si) toggle (default off) Do smart autoindenting in insert mode for C programs. Insert or delete indents at appropriate places. {not in Vi} suffixes (su) string (default ".bak.o.h.info") Files with these suffixes are ignored when multiple files match a wildcard. tabstop (ts) number (default 8) Number of spaces that a TAB in the file counts for. taglength (tl) number (default 0) If non-zero, tags are significant upto this number of characters. tags string (default "tags") Filenames for the tag command, separated by spaces. {Vi: default is "tags /usr/lib/tags"} terse toggle (default on) Ignored. {Vi: shorten the error messages} tildeop (to) toggle (default off) The tilde behaves like an operator. textwidth number (default 9999) Maximum width of text that is being inserted. A longer line will be broken after white space to get this width. undolevels (ul) number (default 100) Maximum number of changes that can be undone (0 for Vi compatibility). updatecount (uc) number (default 100) After this many characters typed the auto script file will be written to disk. When zero the auto script will not be written to at all (see chapter on recovery). updatetime (ut) number (default 2000) If this many milliseconds nothing is typed the auto script file will be written to disk (see chapter on recovery). wrapmargin (wm) number (default 0) Number of characters from the right window border where wrapping starts. In Vim this is implemented by setting textwidth to the window width minus the wrapmargin. {Vi: works differently and less useful} wrapscan (ws) toggle (default on) Searches wrap around the end of the file. writeany (wa) toggle (default off) Do not check for allowance when writing files. yankendofline (ye) toggle (default off) The Y command yanks from the cursor until the end of the line instead of whole lines. 18. Differences from Vi and Ex 18.1 Missing commands These commands are in the unix Vi, but not in VIM. Q {Vi: go to Ex mode} z{cnt} {Vi: reset current window size to {cnt} lines and redraw} :a[ppend] {Vi: append text} :c[hange] {Vi: replace lines} :co[py] {Vi: copy lines} :i[nsert] {Vi: insert text} :k {Vi: synonym for mark without a space} :l[ist] {Vi: list lines} :mar[k] {Vi: mark line} :m[ove] {Vi: move lines} :nu[mber] {Vi: print specified lines with their line number} :o[pen] {Vi: start editing in open mode} :pres[erve] {Vi: emergency exit} :rec[over] {Vi: recover a file after a crash or :preserve} :st[op] {Vi: suspend the editor} :t {Vi: synonym for copy} :una[bbreviate] {Vi: remove from abbreviation list} :vi[sual] {Vi: switch from Ex or open to visual mode} :z {Vi: print some lines} :~ {Vi: do a substitute on the previous regular expression} 18.2 Missing options These options are in the unix Vi, but not in VIM. autoprint (ap) toggle (default on) beautify (bf) toggle (default off) directory (dir) string (default "t:") edcompatible toggle (default off) hardtabs (ht) number (default 8) number of spaces that a TAB moves on the display lisp toggle (default off) mesg toggle (default on) open toggle (default on) optimize (op) toggle (default on) prompt toggle (default on) redraw toggle (default off) slowopen (slow) toggle (default off) term string (default "") timeout toggle (default on) warn toggle (default on) warn when the file has changed before a ! command window number (default 24) w300 number (default 24) w1200 number (default 24) w9600 number (default 24) 19. Credits Parts of this manual comes from several Vi manuals, written by: W.N. Joy Alan P.W. Hewett Mark Horton The editor VIM is based on Stevie and includes (ideas from) other software, worked on by: Tim Thompson (Stevie) Tony Andrews (Stevie) G. R. (Fred) Walter (Stevie) Henry Spencer (regular expressions) Steve Kirkendall (Elvis) vi:tw=78