*change.txt* For Vim version 5.6. Last change: 1999 Dec 21 VIM REFERENCE MANUAL by Bram Moolenaar This file describes commands that delete or change text. In this context, changing text means deleting the text and replacing it with other text using one command. You can undo all of these commands. You can repeat the non-Ex commands with the "." command. 1. Deleting text |deleting| 2. Delete and insert |delete-insert| 3. Simple changes |simple-change| *changing* 4. Complex changes |complex-change| 5. Copying and moving text |copy-move| 6. Formatting text |formatting| 7. Indenting C programs |C-indenting| For inserting text see |insert.txt|. ============================================================================== 1. Deleting text *deleting* ["x] or ** *x* *dl* ["x]x Delete [count] characters under and after the cursor [into register x] (not linewise). Does the same as "dl". See |:fixdel| if the key does not do what you want. See |'whichwrap'| for deleting the (join lines). {Vi does not support } *X* *dh* ["x]X Delete [count] characters before the cursor [into register x] (not linewise). Does the same as "dh". Also see |'whichwrap'|. *d* ["x]d{motion} Delete text that {motion} moves over [into register x]. See below for exceptions. *dd* ["x]dd Delete [count] lines [into register x] (linewise). *D* ["x]D Delete the characters under the cursor until the end of the line and [count]-1 more lines [into register x]; synonym for d$ (not linewise). {Visual}["x]x or *v_x* *v_d* {Visual}["x]d Delete the highlighted text [into register x] (for {Visual} see |Visual-mode|). {not in Vi} {Visual}["x]CTRL-H or *v_CTRL-H* *v_* {Visual}["x] When in Select mode: Delete the highlighted text [into register x]. {Visual}["x]X or *v_X* *v_D* *v_b_D* {Visual}["x]D Delete the highlighted lines [into register x] (for {Visual} see |Visual-mode|). In Visual block mode, "D" deletes the highlighted text plus all text until the end of the line. {not in Vi} *:d* *:de* *:del* *:delete* :[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 |cmdline-ranges|) [into register x]. These commands delete text. You can repeat them with the "." command (except ":d") and undo them. Use Visual mode to delete blocks of text. See |registers| for an explanation of registers. An exception for the d{motion} command: If the motion is not linewise, the start and end of the motion are not in the same line, and there are only blanks before the start and after the end of the motion, the delete becomes linewise. This means that the delete also removes the line of blanks that you might expect to remain. Trying to delete an empty region of text (e.g., "d0" in the first column) is an error when 'cpoptions' includes the 'E' flag. *J* J Join [count] lines, with a minimum of two lines. Remove the indent and insert up to two spaces (see below). *v_J* {Visual}J Join the highlighted lines, with a minimum of two lines. Remove the indent and insert up to two spaces (see below). {not in Vi} *gJ* gJ Join [count] lines, with a minimum of two lines. Don't insert or remove any spaces. {not in Vi} *v_gJ* {Visual}gJ Join the highlighted lines, with a minimum of two lines. Don't insert or remove any spaces. {not in Vi} *:j* *:join* :[range]j[oin][!] Join [range] lines. Same as "J", except with [!] the join does not insert or delete any spaces. If a [range] has equal start and end values, this command does nothing. The default behavior is to join the current line with the line below it. :[range]j[oin][!] {count} Join {count} lines, starting with [range] (default: current line |cmdline-ranges|). Same as "J", except with [!] the join does not insert or delete any spaces. These commands delete the between lines. This has the effect of joining multiple lines into one line. You can repeat these commands (except ":j") and undo them. These commands, except "gJ", insert one space in place of the unless there is trailing white space or the next line starts with a ')'. These commands, except "gJ", delete any leading white space on the next line. If the 'joinspaces' option is on, these commands insert two spaces after a '.', '!' or '?' (but if 'cpoptions' includes the 'j' flag, they insert two spaces only after a '.'). ============================================================================== 2. Delete and insert *delete-insert* *replacing* *R* R Enter Replace mode: Each character you type replaces an existing character, starting with the character under the cursor. Repeat the entered text [count]-1 times. See |Replace-mode| for more details. *gR* gR Enter Virtual replace mode: Each character you type replaces existing characters in screen space. So a may replace several characters at once. Repeat the entered text [count]-1 times. See |Virtual-replace-mode| for more details. *c* ["x]c{motion} Delete {motion} text [into register x] and start insert. When 'cpoptions' includes the 'E' flag and there is no text to delete (e.g., with "cTx" when the cursor is just after an 'x'), an error occurs and insert mode does not start (this is Vi compatible). When 'cpoptions' does not include the 'E' flag, the "c" command always starts insert mode, even if there is no text to delete. *cc* ["x]cc Delete [count] lines [into register x] and start insert (linewise). If 'autoindent' is on, preserve the indent of the first line. *C* ["x]C Delete from the cursor position to the end of the line and [count]-1 more lines [into register x], and start insert. Synonym for c$ (not linewise). *s* ["x]s Delete [count] characters [into register x] and start insert (s stands for Substitute). Synonym for "cl" (not linewise). *S* ["x]S Delete [count] lines [into register x] and start insert. Synonym for "cc" (linewise). {Visual}["x]c or {Visual}["x]s or *v_c* *v_r* *v_s* {Visual}["x]r Delete the highlighted text [into register x] and start insert (for {Visual} see |Visual-mode|). {not in Vi} {Visual}["x]C or {Visual}["x]S or *v_C* *v_R* *v_S* {Visual}["x]R Delete the highlighted lines [into register x] and start insert (for {Visual} see |Visual-mode|). {not in Vi} Notes: - You can end Insert and Replace mode with . - See the section "Insert and Replace mode" |mode-ins-repl| for the other special characters in these modes. - The effect of [count] takes place after Vim exits Insert or Replace mode. - When the 'cpoptions' option contains '$' and the change is within one line, Vim continues to show the text to be deleted and puts a '$' at the last deleted character. See |registers| for an explanation of registers. Replace mode is just like Insert mode, except that every character you enter deletes one character. If you reach the end of a line, Vim appends any further characters (just like Insert mode). In Replace mode, the backspace key restores the original text (if there was any). (See section "Insert and Replace mode" |mode-ins-repl|). *cw* *cW* Special case: "cw" and "cW" work the same as "ce" and "cE" if the cursor is on a non-blank. This is because Vim interprets "cw" as change-word, and a word does not include the following white space. {Vi: "cw" when on a blank followed by other blanks changes only the first blank; this is probably a bug, because "dw" deletes all the blanks} *:c* *:ch* *:change* :{range}c[hange] Replace lines of text with some different text. Type a line containing only "." to stop replacing. Without {range}, this command changes only the current line. ============================================================================== 3. Simple changes *simple-change* *r* r{char} Replace the character under the cursor with {char}. If {char} is a or , a line break replaces the character. To replace with a real , use CTRL-V . CTRL-V replaces with a . {Vi: CTRL-V still replaces with a line break, cannot replace something with a } If you give a [count], Vim replaces [count] characters with [count] {char}s. When {char} is a or , however, Vim inserts only one : "5r" replaces five characters with a single line break. When {char} is a or , Vim performs autoindenting. This works just like deleting the characters that are replaced and then doing "i". *gr* gr{char} Replace the virtual characters under the cursor with {char}. This replaces in screen space, not file space. See |gR| and |Virtual-replace-mode| for more details. As with |r| a count may be given. *case* *locale* *$LANG* The following commands change the case of letters. The currently active locale is used. This depends on your system On Unix, setting the $LANG environment variable can make a difference. For example, to enable changing the case of letters with umlauts: > setenv LANG de *~* ~ 'notildeop' option: Switch case of the character under the cursor and move the cursor to the right. If a [count] is given, do that many characters. {Vi: no count} ~{motion} 'tildeop' option: switch case of {motion} text. {Vi: tilde cannot be used as an operator} *g~* g~{motion} Switch case of {motion} text. {not in Vi} g~g~ *g~g~* *g~~* g~~ Switch case of current line. {not in Vi}. *v_~* {Visual}~ Switch case of highlighted text (for {Visual} see |Visual-mode|). {not in Vi} *v_U* {Visual}U Make highlighted text uppercase (for {Visual} see |Visual-mode|). {not in Vi} *gU* *uppercase* gU{motion} Make {motion} text uppercase. {not in Vi} gUgU *gUgU* *gUU* gUU Make current line uppercase. {not in Vi}. *v_u* {Visual}u Make highlighted text lowercase (for {Visual} see |Visual-mode|). {not in Vi} *gu* *lowercase* gu{motion} Make {motion} text lowercase. {not in Vi} gugu *gugu* *guu* guu Make current line lowercase. {not in Vi}. *g?* g?{motion} Rot13 encode {motion} text. {not in Vi} *v_g?* {Visual}g? Rot13 encode the highlighted text (for {Visual} see |Visual-mode|). {not in Vi} g?g? *g?g?* *g??* g?? Rot13 encode current line. {not in Vi}. Adding and subtracting ~ *CTRL-A* CTRL-A Add [count] to the number at or after the cursor. {not in Vi} *CTRL-X* CTRL-X Subtract [count] from the number at or after the cursor. {not in Vi} The CTRL-A and CTRL-X commands work for (signed) decimal numbers and unsigned octal and hexadecimal numbers. This depends on the 'nrformats' option. - When 'nrformats' includes "hex", Vim assumes numbers starting with '0x' or '0X' are hexadecimal. The case of the rightmost letter in the number determines the case of the resulting hexadecimal number. If there is no letter in the current number, Vim uses the previously detected case. - When 'nrformats' includes "octal", Vim considers numbers starting with a '0' to be octal. Other numbers are decimal and may have a preceding minus sign. If the cursor is on a number, the commands apply to that number; otherwise Vim uses the number to the right of the cursor. For numbers with leading zeros (including all octal and hexadecimal numbers), Vim preserves the number of characters in the number when possible. CTRL-A on "0077" results in "0100", CTRL-X on "0x100" results in "0x0ff". Note that when 'nrformats' includes "octal", decimal numbers with leading zeros are impossible because they are indistinguishable from octal numbers. The CTRL-A command is very useful in a macro. Example: Use the following steps to make a numbered list. 1. Create the first list entry, make sure it starts with a number. 2. qa - start recording into buffer 'a' 3. Y - yank the entry 4. p - put a copy of the entry below the first one 5. CTRL-A - increment the number 6. q - stop recording 7. @a - repeat the yank, put and increment times SHIFTING LINES LEFT OR RIGHT *shift-left-right* *<* <{motion} Shift {motion} lines one 'shiftwidth' leftwards. *<<* << Shift [count] lines one 'shiftwidth' leftwards. *v_<* {Visual}[count]< Shift the highlighted lines [count] 'shiftwidth' leftwards (for {Visual} see |Visual-mode|). {not in Vi} *>* >{motion} Shift {motion} lines one 'shiftwidth' rightwards. *>>* >> Shift [count] lines one 'shiftwidth' rightwards. *v_>* {Visual}[count]> Shift the highlighted lines [count] 'shiftwidth' rightwards (for {Visual} see |Visual-mode|). {not in Vi} *:<* :[range]< Shift [range] lines one 'shiftwidth' left. Repeat '<' for shifting multiple 'shiftwidth's. :[range]< {count} Shift {count} lines one 'shiftwidth' left, starting with [range] (default current line |cmdline-ranges|). Repeat '<' for shifting multiple 'shiftwidth's. :[range]le[ft] [indent] left align lines in [range]. Sets the indent in the lines to [indent] (default 0). {not in Vi} *:>* :[range]> Shift {count} [range] lines one 'shiftwidth' right. Repeat '>' for shifting multiple 'shiftwidth's. :[range]> {count} Shift {count} lines one 'shiftwidth' right, starting with [range] (default current line |cmdline-ranges|). Repeat '>' for shifting multiple 'shiftwidth's. The ">" and "<" commands are handy for changing the indentation within programs. Use the 'shiftwidth' option to set the size of the white space which these commands insert or delete. Normally the 'shiftwidth' option is 8, but you can set it to, say, 3 to make smaller indents. The shift leftwards stops when there is no indent. The shift right does not affect empty lines. If the 'shiftround' option is on, the indent is rounded to a multiple of 'shiftwidth'. If the 'smartindent' option is on, or 'cindent' is on and 'cinkeys' contains '#', shift right does not affect lines starting with '#' (these are supposed to be C preprocessor lines that must stay in column 1). When the 'expandtab' option is off (this is the default) Vim uses s as much as possible to make the indent. You can use ">><<" to replace an indent made out of spaces with the same indent made out of s (and a few spaces if necessary). If the 'expandtab' option is on, Vim uses only spaces. Then you can use ">><<" to replace s in the indent by spaces (or use ":retab!"). To move a line several 'shiftwidth's, use Visual mode or the ":" commands. For example: > Vjj4> move three lines 4 indents to the right > :<<< move current line 3 indents to the left > :>> 5 move 5 lines 2 indents to the right > :5>> move line 5 2 indents to the right ============================================================================== 4. Complex changes *complex-change* *!* *filter* !{motion}{filter} Filter {motion} text through the external program {filter}. *!!* !!{filter} Filter [count] lines through the external program {filter}. *v_!* {Visual}!{filter} Filter the highlighted lines through the external program {filter} (for {Visual} see |Visual-mode|). {not in Vi} :{range}![!]{filter} [!][arg] *:range!* Filter {range} lines through the external program {filter}. Vim replaces the optional bangs with the latest given command and appends the optional [arg]. Vim saves the output of the filter command in a temporary file and then reads the file into the buffer. Vim uses the 'shellredir' option to redirect the filter output to the temporary file. *=* ={motion} Filter {motion} lines through the external program given with the 'equalprg' option. When the 'equalprg' option is empty (this is the default), use the internal formatting function to set the indent of each line |C-indenting|. *==* == Filter [count] lines through the external program given with the 'equalprg' option. When the 'equalprg' option is empty (this is the default), use the internal formatting function |C-indenting|. *v_=* {Visual}= Filter the highlighted lines through the external program given with the 'equalprg' option. When the 'equalprg' option is empty (this is the default), use the internal formatting function |C-indenting|. (for {Visual} see |Visual-mode|). {not in Vi} A filter is a program that accepts text at standard input, changes it in some way, and sends it to standard output. You can use the commands above to send some text through a filter. Examples of filters are "sort", which sorts lines alphabetically, and "indent", which formats C program files (you need a version of indent that works like a filter; not all versions do). The 'shell' option specifies the shell Vim uses to execute the filter command (See also the 'shelltype' option). You can repeat filter commands with ".". Vim does not recognize a comment (starting with '"') after the ":!" command. *:s* *:su* *:substitute* :[range]s[ubstitute]/{pattern}/{string}/[c][e][g][p][r][i][I] [count] For each line in [range] replace a match of {pattern} with {string}. See |:s_flags| for the flags. :[range]s[ubstitute] [c][e][g][r][i][I] [count] :[range]&[c][e][g][r][i][I] [count] *:&* Repeat last :substitute with same search pattern and substitute string, but without the same flags. You may add extra flags (see |:s_flags|). :[range]~[c][e][g][r][i][I] [count] *:~* Repeat last substitute with same substitute string but with last used search pattern. This is like "&r". See |:s_flags| for the flags. *&* & Synonym for ":s//~/" (repeat last substitute). *:snomagic* :[range]sno[magic] ... Same as ":substitute", but always use 'nomagic'. *:smagic* :[range]sm[agic] ... Same as ":substitute", but always use 'magic'. *:s_flags* The arguments that you can use for the substitute commands: [c] Confirm each substitution. Vim positions the cursor on the matching string. You can type: *:s_c* 'y' to substitute this match 'n' to skip this match to skip this match 'a' to substitute this and all remaining matches {not in Vi} 'q' to quit substituting {not in Vi} CTRL-E to scroll the screen up {not in Vi} CTRL-Y to scroll the screen down {not in Vi}. If the 'edcompatible' option is on, Vim remembers the [c] flag and toggles it each time you use it, but resets it when you give a new search pattern. [e] When the search pattern fails, do not issue an error message and, in particular, continue in maps as if no error occurred. This is most useful to prevent the "No match" error from breaking a mapping. Vim does not suppress the following error messages, however: Regular expressions can't be delimited by letters \ should be followed by /, ? or & No previous substitute regular expression Trailing characters Interrupted [g] Replace all occurrences in the line. Without this argument, replacement occurs only for the first occurrence in each line. If the 'edcompatible' option is on, Vim remembers this flag and toggles it each time you use it, but resets it when you give a new search pattern. If the 'gdefault' option is on, this flag is on by default and the [g] argument switches it off. [i] Ignore case for the pattern. The 'ignorecase' and 'smartcase' options are not used. [I] Don't ignore case for the pattern. The 'ignorecase' and 'smartcase' options are not used. [p] Print the line containing the last substitute. [r] Only useful in combination with ":&" or ":s" without arguments. ":&r" works the same way as ":~": When the search pattern is empty, use the previously used search pattern instead of the search pattern from the last substitute or ":global". If the last command that did a search was a substitute or ":global", there is no effect. If the last command was a search command such as "/", use the pattern from that command. For ":s" with an argument this already happens: > :s/blue/red/ > /green > :s//red/ or :~ or :&r The last commands will replace "green" with "red". > :s/blue/red/ > /green > :& The last command will replace "blue" with "red". Note that there is no flag to change the "magicness" of the pattern. A different command is used instead. The reason is that the flags can only be found by skipping the pattern, and in order to skip the pattern the "magicness" must be known. Catch 22! [count] Search [count] lines, starting with the last line number in [range] (default is to search only the current line |cmdline-ranges|). If the {pattern} for the substitute command is empty, the command uses the pattern from the last substitute or ":global" command. With the [r] flag, the command uses the pattern from the last substitute, ":global", or search command. For compatibility with Vi these two exceptions are allowed: "\/{string}/" and "\?{string}?" do the same as "//{string}/r". "\&{string}&" does the same as "//{string}/". Instead of the '/' which surrounds the pattern and replacement string, you can use any other character, but not an alphanumeric character, '\', '"' or '|'. This is useful if you want to include a '/' in the search pattern or replacement string. Example: > :s+/+//+ For the definition of a pattern, see |pattern|. *sub-replace-special* Some characters in {string} have a special meaning: magic nomagic action ~ & \& replaced with the whole matched pattern \& & replaced with & \0 replaced with the whole matched pattern \1 replaced with the matched pattern in the first pair of () \2 replaced with the matched pattern in the second pair of () .. .. \9 replaced with the matched pattern in the ninth pair of () ~ \~ replaced with the {string} of the previous substitute \~ ~ replaced with ~ \u next character made uppercase \U following characters made uppercase \l next character made lowercase \L following characters made lowercase \e end of \u, \U, \l and \L (NOTE: not !) \E end of \u, \U, \l and \L split line in two at this point \r idem CTRL-V insert a carriage-return (CTRL-M) \n (does NOT break the line) \b \t Examples: > :s/a\|b/xxx\0xxx/g modifies "a b" in "xxxaxxx xxxbxxx" > :s/\([abc]\)\([efg]\)/\2\1/g modifies "af fa bg" in "fa fa gb" > :s/abcde/abc^Mde/ modifies "abcde" in "abc", "de" (two lines) > :s/$/^V^M/ modifies "abcde" in "abcde^M" Note: To insert a ^M you have to type CTRL-V . To insert a ^V you have to type CTRL-V CTRL-V. So to insert the ^V^M in the last example you have to type CTRL-V CTRL-V CTRL-V . Because CTRL-V inserts a , it is impossible to insert a CTRL-V just in front of a line break. You will have to perform the substitution in two steps: > :s/foo/^Vxxxx/ > :s/xxxx/^M/ When using parentheses in combination with '|', like in \([ab]\)\|\([cd]\), either the first or second pattern in parentheses did not match, so either \1 or \2 is empty. Example: > :s/\([ab]\)\|\([cd]\)/\1x/g modifies "a b c d" in "ax bx x x" *:pro* *:promptfind* :promptf[ind] [string] Win32 GUI only: Put up a Search dialog. When [string] is given, it is used as the initial search string. *:promptr* *:promptrepl* :promptr[epl] [string] Win32 GUI only: Put up a Search/Replace dialog. When [string] is given, it is used as the initial search string. *:ret* *:retab* :[range]ret[ab][!] [new_tabstop] Replace all sequences of white-space containing a with new strings of white-space using the new tabstop value given. If you do not specify a new tabstop size, Vim uses the current value of 'tabstop'. The current value of 'tabstop' is always used to compute the width of existing tabs. With !, Vim also replaces strings of normal spaces with tabs where appropriate. With 'expandtab' on, Vim replaces all tabs with the appropriate number of spaces. This command sets 'tabstop' to the new value given, and if performed on the whole file, which is default, should not make any visible change. Careful: This command modifies any characters inside of strings in a C program. Use "\t" to avoid this (that's a good habit anyway). ":retab!" may also change a sequence of spaces by characters, which can mess up a printf(). {not in Vi} Not available when |+ex_extra| feature was disabled at compile time. *retab-example* Example for using autocommands and ":retab" to edit a file which is stored with tabstops at 8 but edited with tabstops set at 4. Warning: white space inside of strings can change! Also see 'softtabstop' option. > auto BufReadPost *.xx retab! 4 > auto BufWritePre *.xx retab! 8 > auto BufWritePost *.xx retab! 4 > auto BufNewFile *.xx set ts=4 ============================================================================== 5. Copying and moving text *copy-move* *quote* "{a-zA-Z0-9.%#:-"} Use register {a-zA-Z0-9.%#:-"} for next delete, yank or put (use uppercase character to append with delete and yank) ({.%#:} only work with put). *:reg* *:registers* :reg[isters] Display the contents of all numbered and named registers. {not in Vi} :reg[isters] {arg} Display the contents of the numbered and named registers that are mentioned in {arg}. For example: > :dis 1a to display registers '1' and 'a'. Spaces are allowed in {arg}. {not in Vi} *:di* *:display* :di[splay] [arg] Same as :registers. {not in Vi} *y* *yank* ["x]y{motion} Yank {motion} text [into register x]. When no characters are to be yanked (e.g., "y0" in column 1), this is an error when 'cpoptions' includes the 'E' flag. *yy* ["x]yy Yank [count] lines [into register x] (linewise). *Y* ["x]Y yank [count] lines [into register x] (synonym for yy, linewise). If you like "Y" to work from the cursor to the end of line (which is more logical, but not Vi-compatible) use ":map Y y$". *v_y* {Visual}["x]y Yank the highlighted text [into register x] (for {Visual} see |Visual-mode|). {not in Vi} *v_Y* {Visual}["x]Y Yank the highlighted lines [into register x] (for {Visual} see |Visual-mode|). {not in Vi} *:y* *:yank* :[range]y[ank] [x] Yank [range] lines [into register x]. :[range]y[ank] [x] {count} Yank {count} lines, starting with last line number in [range] (default: current line |cmdline-ranges|), [into register x]. *p* *put* ["x]p Put the text [from register x] after the cursor [count] times. {Vi: no count} ["x]P or *P* ** ["x] Put the text [from register x] before the cursor [count] times. Using the mouse only works when 'mouse' contains 'n' or 'a'. {Vi: no count} *gp* ["x]gp Just like "p", but leave the cursor just after the new text. {not in Vi} *gP* ["x]gP Just like "P", but leave the cursor just after the new text. {not in Vi} *:pu* *:put* :[line]pu[t] [x] Put the text [from register x] after [line] (default current line). The register can also be '=' followed by an optional expression. The expression continues until the end of the command. You need to escape the '|' and '"' characters to prevent them from terminating the command. Example: > :put ='path' . \",/test\" If there is no expression after '=', Vim uses the previous expression. You can see it with ":dis =". :[line]pu[t]! [x] Put the text [from register x] before [line] (default current line). ["x]]p or *]p* *]* ["x]] Like "p", but adjust the indent to the current line. Using the mouse only works when 'mouse' contains 'n' or 'a'. {not in Vi} ["x][P or *[P* ["x]]P or *]P* ["x][p or *[p* *[* ["x][ Like "P", but adjust the indent to the current line. Using the mouse only works when 'mouse' contains 'n' or 'a'. {not in Vi} You can use these commands to copy text from one place to another. Do this by first getting the text into a register with a yank, delete or change command, then inserting the register contents with a put command. You can also use these commands to move text from one file to another, because Vim preserves all registers when changing buffers (the CTRL-^ command is a quick way to toggle between two files). *linewise-register* *characterwise-register* You can repeat the put commands with "." (except for :put) and undo them. If the command that was used to get the text into the register was linewise, Vim inserts the text below ("p") or above ("P") the line where the cursor is. Otherwise Vim inserts the text after ("p") or before ("P") the cursor. With the ":put" command, Vim always inserts the text in the next line. You can exchange two characters with the command sequence "xp". You can exchange two lines with the command sequence "ddp". You can exchange two words with the command sequence "deep" (start with the cursor in the blank space before the first word). You can use the "']" or "`]" command after the put command to move the cursor to the end of the inserted text, or use "'[" or "`[" to move the cursor to the start. *blockwise-register* If you use a blockwise Visual mode command to get the text into the register, the block of text will be inserted before ("P") or after ("p") the cursor column in the current and next lines. Vim makes the whole block of text start in the same column. Thus the inserted text looks the same as when it was yanked or deleted. Vim may replace some characters with spaces to make this happen. However, if the width of the block is not a multiple of a width and the text after the inserted block contains s, that text may be misaligned. Note that after a yank command, Vim leaves the cursor on the first yanked character that is closest to the start of the buffer. This means that "yl" doesn't move the cursor, but "yh" moves the cursor one character left. Rationale: In Vi the "y" command followed by a backwards motion would sometimes not move the cursor to the first yanked character, because redisplaying was skipped. In Vim it always moves to the first character, as specified by Posix. There are nine types of registers: *registers* 1. The unnamed register "" 2. 10 numbered registers "0 to "9 3. The small delete register "- 4. 26 named registers "a to "z or "A to "Z 5. four read-only registers ":, "., "% and "# 6. the expression register "= 7. The selection register "* 8. The black hole register "_ 9. Last search pattern register "/ 1. Unnamed register "" *quote_quote* *quotequote* Vim fills this register with text deleted with the "d", "c", "s", "x" commands or copied with the yank "y" command, regardless of whether or not a specific register was used (e.g. "xdd). An exception is the '_' register: "_dd does not store the deleted text in any register. Vim uses the contents of this register for any put command (p or P) which does not specify a register. Additionally you can access it with the name '"'. This means you have to type two double quotes. {Vi: register contents are lost when changing files, no '"'} 2. Numbered registers "0 to "9 *quote_number* *quote0* *quote1* *quote2* *quote3* *quote4* *quote9* Vim fills these registers with text from yank and delete commands. Numbered register 0 contains the text from the most recent yank command, unless the command specified another register with ["x]. Numbered register 1 contains the text deleted by the most recent delete or change command, unless the command specified another register or the text is less than one line (Vim puts text deleted with "x" or "dw" in the small delete register). With each successive deletion or change, Vim shifts the previous contents of register 1 into register 2, 2 into 3, and so forth, losing the previous contents of register 9. {Vi: numbered register contents are lost when changing files; register 0 does not exist} 3. Small delete register "- *quote_-* *quote-* This register contains text from commands that delete less than one line, except when the command specifies a register with ["x]. {not in Vi} 4. Named registers "a to "z or "A to "Z *quote_alpha* *quotea* Vim fills these registers only when you say so. Specify them as lowercase letters to replace their previous contents or as uppercase letters to append to their previous contents. 5. Read-only registers ":, "., "% and "# These are '%', '#', ':' and '.'. You can use them only with the "p", "P", and ":put" commands and with CTRL-R. {not in Vi} *quote_.* *quote.* ". Contains the last inserted text (the same as what is inserted with the insert mode commands CTRL-A and CTRL-@). Note: this doesn't work with CTRL-R on the command-line. It works a bit differently, like inserting the text instead of putting it ('textwidth' and other options affect what is inserted). *quote_%* *quote%* "% Contains the name of the current file. *quote_#* *quote#* "# Contains the name of the alternate file. *quote_:* *quote:* ": Contains the most recent command-line. Example: Use "@:" to repeat the most recent command-line. 6. Expression register "= *quote_=* *quote=* This is not really a register that stores text, but is a way to use an expression in commands which use a register. The expression register is read-only; you cannot put text into it. After the '=', the cursor moves to the command-line, where you can enter any expression (see |expression|). All normal command-line editing commands are available, including a special history for expressions. When you end the command-line by typing , Vim computes the result of the expression. If you end it with , Vim abandons the expression. If you do not enter an expression, Vim uses the previous expression (like with the "/" command). If the "= register is used for the "p" command, the string is split up at characters. If the string ends in a , it is regarded as a linewise register. {not in Vi} 7. Selection register "* Use this register for storing and retrieving the selected text for the GUI. See |quotestar|. When the clipboard is not available or not working, the unnamed register is used instead. {not in Vi} 8. Black hole register "_ *quote_* When writing to this register, nothing happens. This can be used to delete text without affecting the normal registers. When reading from this register, nothing is returned. {not in Vi} 9. Last search pattern register "/ *quote_/* *quote/* Contains the most recent search-pattern. This is used for "n" and 'hlsearch'. {not in Vi} *@/* You can write to a register with a ":let" command |:let-@|. Example: > :let @/ = "the" If you use a put command without specifying a register, Vim uses the register that was last filled (this is also the contents of the unnamed register). If you are confused, use the ":dis" command to find out what Vim will put (this command displays all named and numbered registers; the unnamed register is labelled '"'). The next three commands always work on whole lines. :[range]co[py] {address} *:co* *:copy* Copy the lines given by [range] to below the line given by {address}. *:t* :t Synonym for copy. :[range]m[ove] {address} *:m* *:mo* *:move* Move the lines given by [range] to below the line given by {address}. ============================================================================== 6. Formatting text *formatting* :[range]ce[nter] [width] *:ce* *:center* Center lines in [range] between [width] columns (default 'textwidth' or 80 when 'textwidth' is 0). {not in Vi} Not available when |+ex_extra| feature was disabled at compile time. :[range]ri[ght] [width] *:ri* *:right* Right-align lines in [range] at [width] columns (default 'textwidth' or 80 when 'textwidth' is 0). {not in Vi} Not available when |+ex_extra| feature was disabled at compile time. *:le* *:left* :[range]le[ft] [indent] Left-align lines in [range]. Sets the indent in the lines to [indent] (default 0). {not in Vi} Not available when |+ex_extra| feature was disabled at compile time. *gq* gq{motion} Format the lines that {motion} moves over. The 'textwidth' option controls the length of each formatted line (see below). If the 'textwidth' option is 0, the formatted line length is the screen width (with a maximum width of 79). {not in Vi} The 'formatoptions' option controls the type of formatting |fo-table|. NOTE: The "Q" command formerly performed this function. If you still want to use "Q" for formatting, use this mapping: > :nnoremap Q gq gqgq *gqgq* *gqq* gqq Format the current line. {not in Vi} *v_gq* {Visual}gq Format the highlighted text. (for {Visual} see |Visual-mode|). {not in Vi} Example: To format the current paragraph use > gqap The "gq" command leaves the cursor in the line where the motion command takes the cursor. This allows you to repeat formatting repeated with ".". This works well with "gqj" (format current and next line) and "gq}" (format until end of paragraph). Note: When 'formatprg' is set, "gq" leaves the cursor on the first formatted line (as with using a filter command). If the 'autoindent' option is on, Vim uses the indent of the first line for the following lines. Formatting does not change empty lines (but it does change lines with only white space!). The 'joinspaces' option is used when lines are joined together. You can set the 'formatprg' option to the name of an external program for Vim to use for text formatting. The 'textwidth' and other options have no effect on formatting by an external program. *right-justify* There is no command in Vim to right justify text. You can do it with an external command, like "par" (e.g.: "!}par" to format until the end of the paragraph) or set 'formatprg' to "par". *format-comments* Vim can format comments in a special way. Vim recognizes a comment by a specific string at the start of the line (ignoring white space). Three types of comments can be used: - A comment string that repeats at the start of each line. An example is the type of comment used in shell scripts, starting with "#". - A comment string that occurs only in the first line, not in the following lines. An example is this list with dashes. - Three-piece comments that have a start string, an end string, and optional lines in between. The strings for the start, middle and end are different. An example is the C-style comment: /* * this is a C comment */ The 'comments' option is a comma-separated list of parts. Each part defines a type of comment string. A part consists of: {flags}:{string} {string} is the literal text that must appear. {flags}: n Nested comment. Nesting with mixed parts is allowed. If 'comments' is "n:),n:>" a line starting with "> ) >" is a comment. b Blank (, or ) required after {string}. f Only the first line has the comment string. Do not repeat comment on the next line, but preserve indentation (e.g., a bullet-list). s Start of three-piece comment m Middle of a three-piece comment e End of a three-piece comment l Left adjust middle with start or end (default). Only recognized when used together with 's' or 'e'. r Right adjust middle with start or end. Only recognized when used together with 's' or 'e'. x Allows three-piece comments to be ended by just typing the last character of the end-comment string as the first character on a new line, when the middle-comment string has already been inserted automatically. See below for more details. {digits} When together with 's' or 'e': add extra indent for the middle part. This can be used to left-align the middle part with the start or end and then add an offset. -{digits} Like {digits} but reduce the indent. This only works when there is some indent for the start or end part that can be removed. When a string has none of the 'f', 's', 'm' or 'e' flags, Vim assumes the comment string repeats at the start of each line. The flags field may be empty. Any blank space in the text before and after the {string} is part of the {string}, so do not include leading or trailing blanks unless the blanks are a required part of the comment string. When one comment leader is part of another, specify the part after the whole. For example, to include both "-" and "->", use > :set comments=f:->,f:- A three-piece comment must always be given as start,middle,end, with no other parts in between. An example of a three-piece comment is > sr:/*,mb:*,ex:*/ for C-comments. To avoid recognizing "*ptr" as a comment, the middle string includes the 'b' flag. For three-piece comments, Vim checks the text after the start and middle strings for the end string. If Vim finds the end string, the comment does not continue on the next line. Three-piece comments must have a middle string because otherwise Vim can't recognize the middle lines. Notice the use of the "x" flag in the above three-piece comment definition. When you hit Return in a C-comment, Vim will insert the middle comment leader for the new line, eg " * ". To close this comment you just have to type "/" before typing anything else on the new line. This will replace the middle-comment leader with the end-comment leader, leaving just " */". There is no need to hit BackSpace first. Examples: > "b:*" Includes lines starting with "*", but not if the "*" is > followed by a non-blank. This avoids a pointer dereference > like "*str" to be recognized as a comment. > "n:>" Includes a line starting with ">", ">>", ">>>", etc. > "fb:-" Format a list that starts with "- ". By default, "b:#" is included. This means that a line that starts with "#include" is not recognized as a comment line. But a line that starts with "# define" is recognized. This is a compromise. Often the alignment can be changed from right alignment to a left alignment with an additional space. For example, for Javadoc comments, this can be used (insert a backslash before the space when using ":set"): > s1:/*,mb:*,ex:*/ Note that an offset is included with start, so that the middle part is left aligned with the start and then an offset of one character added. This makes it possible to left align the start and middle for this construction: > /** > * comment > */ {not available when compiled without the |+comments| feature} *fo-table* You can use the 'formatoptions' option to influence how Vim formats text. 'formatoptions' is a string that can contain any of the letters below. The default setting is "tcq". You can separate the option letters with commas for readability. letter meaning when present in 'formatoptions' ~ t Auto-wrap text using textwidth c Auto-wrap comments using textwidth, inserting the current comment leader automatically. r Automatically insert the current comment leader after hitting in insert mode. o Automatically insert the current comment leader after hitting 'o' or 'O' in Normal mode. q Allow formatting of comments with "gq". Note that formatting will not change blank lines or lines containing only the comment leader. A new paragraph starts after such a line, or when the comment leader changes. 2 When formatting text, use the indent of the second line of a paragraph for the rest of the paragraph, instead of the indent of the first line. This supports paragraphs in which the first line has a different indent than the rest. Note that 'autoindent' must be set too. v Vi-compatible auto-wrapping in insert mode: Only break a line at a blank that you have entered during the current insert command. (Note: this is not 100% Vi compatible. Vi has some "unexpected features" or bugs in this area. It uses the screen column instead of the line column.) b Like 'v', but only auto-wrap if you enter a blank at or before the wrap margin. If the line was longer than 'textwidth' when you started the insert, or you do not enter a blank in the insert before reaching 'textwidth', Vim does not perform auto-wrapping. l Long lines are not broken in insert mode: When a line was longer than 'textwidth' when the insert command started, Vim does not automatically format it. With 't' and 'c' you can specify when Vim performs auto-wrapping: value action ~ "" no automatic formatting (you can use "gq" for manual formatting) "t" automatic formatting of text, but not comments "c" automatic formatting for comments, but not text (good for C code) "tc" automatic formatting for text and comments Note that when 'textwidth' is 0, Vim does no formatting anyway (but does insert comment leaders according to the 'comments' option). Note that when 'paste' is on, Vim does no formatting at all. Note that 'textwidth' can be non-zero even if Vim never performs auto-wrapping; 'textwidth' is still useful for formatting with "gq". If the 'comments' option includes "/*", "*" and/or "*/", then Vim has some built in stuff to treat these types of comments a bit more cleverly. Opening a new line before or after "/*" or "*/" (with 'r' or 'o' present in 'formatoptions') gives the correct start of the line automatically. The same happens with formatting and auto-wrapping. Opening a line after a line starting with "/*" or "*" and containing "*/", will cause no comment leader to be inserted, and the indent of the new line is taken from the line containing the start of the comment. E.g.: /* * Your typical comment. */ The indent on this line is the same as the start of the above comment. All of this should be really cool, especially in conjunction with the new :autocmd command to prepare different settings for different types of file. Some examples: for C code (only format comments): > fo=croq for Mail/news (format all, don't start comment with "o" command): > fo=tcrq ============================================================================== 7. Indenting C programs *C-indenting* Vim has options for automatically indenting C program files. These options affect only the indent and do not perform other formatting. For comment formatting, see |format-comments|. Note that you can disable the |+smartindent| and |+cindent| features at compile time. There are in fact three methods available for indentation: 'autoindent' uses the indent from the previous line. 'smartindent' is like 'autoindent' but also recognizes some C syntax to increase/reduce the indent where appropriate. 'cindent' Works more cleverly than the other two and is configurable to different indenting styles. The rest of this section describes the 'cindent' option. Note that 'cindent' indenting does not work for every code scenario. Vim is not a C compiler: it does not recognize all syntax. These four options control C program indenting: 'cindent' Enables Vim to perform C program indenting automatically. 'cinkeys' Specifies which keys trigger reindenting in insert mode. 'cinoptions' Sets your preferred indent style. 'cinwords' Defines keywords that start an extra indent in the next line. If 'lisp' is not on and 'equalprg' is empty, the "=" operator indents using Vim's built-in algorithm rather than calling an external program. See |autocommand| for how to set the 'cindent' option automatically for C code files and reset it for others. *'cinkeys'* *'cink'* The 'cinkeys' option is a string that controls Vim's indenting in response to typing certain characters or commands in certain contexts. The default is "0{,0},:,0#,!^F,o,O,e" which specifies that indenting occurs as follows: "0{" if you type '{' as the first character in a line "0}" if you type '}' as the first character in a line ":" if you type ':' anywhere "0#" if you type '#' as the first character in a line "!^F" if you type CTRL-F (which is not inserted) "o" if you type a anywhere or use the "o" command (not in insert mode!) "O" if you use the "O" command (not in insert mode!) "e" if you type the second 'e' for an "else" at the start of a line Characters that can precede each key: '!' When a '!' precedes the key, Vim will not insert the key but will instead reindent the current line. This allows you to define a command key for reindenting the current line. CTRL-F is the default key for this. Be careful if you define CTRL-I for this because CTRL-I is the ASCII code for . '*' When a '*' precedes the key, Vim will reindent the line before inserting the key. If 'cinkeys' contains "*", Vim reindents the current line before opening a new line. '0' When a zero precedes the key (but appears after '!' or '*') Vim will reindent the line only if the key is the first character you type in the line. When neither '!' nor '*' precedes the key, Vim reindents the line after you type the key. So ';' sets the indentation of a line which includes the ';'. Special key names: <> Angle brackets mean spelled-out names of keys. For example: "", "" (see |key-notation|). '^' Letters preceded by a caret (^) are control characters. For example: "^F" is CTRL-F. 'o' Reindent a line when you use the "o" command or when Vim opens a new line below the current one (e.g., when you type in insert mode). 'O' Reindent a line when you use the "O" command. 'e' Reindent a line that starts with "else" when you type the second 'e'. If you really want to reindent when you type 'o', 'O', 'e', '0', '<', '>', '*' or '!', use "", "", "", "<0>", "<<>", "<>>", "<*>" or "", respectively, for those keys. For an emacs-style indent mode where lines aren't indented every time you press Return but only if you press Tab, I suggest: :set cinkeys=0{,0},:,0#,!,!^F You might also want to switch off 'autoindent' then. Note: If you change the current line's indentation manually, Vim ignores the cindent settings for that line. This prevents vim from reindenting after you have changed the indent by typing , , or in the indent or used CTRL-T or CTRL-D. *cinoptions-values* The 'cinoptions' option sets how Vim performs indentation. In the list below, "N" represents a number of your choice (the number can be negative). When there is an 's' after the number, Vim multiplies the number by 'shiftwidth': "1s" is 'shiftwidth', "2s" is two times 'shiftwidth', etc. You can use a decimal point, too: "-0.5s" is minus half a 'shiftwidth'. The examples below assume a 'shiftwidth' of 4. >N Amount added for "normal" indent. Used after a line that should increase the indent (lines starting with "if", an opening brace, etc.). (default 'shiftwidth'). cino= cino=>2 cino=>2s if (cond) if (cond) if (cond) { { { foo; foo; foo; } } } eN Add N to the prevailing indent inside a set of braces if the opening brace at the End of the line (more precise: is not the first character in a line). This is useful if you want a different indent when the '{' is at the start of the line from when '{' is at the end of the line. (default 0). cino= cino=e2 cino=e-2 if (cond) { if (cond) { if (cond) { foo; foo; foo; } } } else else else { { { bar; bar; bar; } } } nN Add N to the prevailing indent for a statement after an "if", "while", etc., if it is Not inside a set of braces. This is useful if you want a different indent when there is no '{' before the statement from when there is a '{' before it. (default 0). cino= cino=n2 cino=n-2 if (cond) if (cond) if (cond) foo; foo; foo; else else else { { { bar; bar; bar; } } } fN Place the first opening brace of a function or other block in column N. This applies only for an opening brace that is not inside other braces and is at the start of the line. What comes after the brace is put relative to this brace. (default 0). cino= cino=f.5s cino=f1s func() func() func() { { { int foo; int foo; int foo; {N Place opening braces N characters from the prevailing indent. This applies only for opening braces that are inside other braces. (default 0). cino= cino={.5s cino={1s if (cond) if (cond) if (cond) { { { foo; foo; foo; }N Place closing braces N characters from the matching opening brace. (default 0). cino= cino={2,}-0.5s cino=}2 if (cond) if (cond) if (cond) { { { foo; foo; foo; } } } ^N Add N to the prevailing indent inside a set of braces if the opening brace is in column 0. This can specify a different indent for whole of a function (some may like to set it to a negative number). (default 0). cino= cino=^-2 cino=^-s func() func() func() { { { if (cond) if (cond) if (cond) { { { a = b; a = b; a = b; } } } } } } :N Place case labels N characters from the indent of the switch(). (default 'shiftwidth'). cino= cino=:0 switch (x) switch(x) { { case 1: case 1: a = b; a = b; default: default: } } =N Place statements occurring after a case label N characters from the indent of the label. (default 'shiftwidth'). cino= cino==10 case 11: case 11: a = a + 1; a = a + 1; b = b + 1; gN Place C++ scope declarations N characters from the indent of the block they are in. (default 'shiftwidth'). A scope declaration can be "public:", "protected:" or "private:". cino= cino=g0 { { public: public: a = b; a = b; private: private: } } hN Place statements occurring after a C++ scope declaration N characters from the indent of the label. (default 'shiftwidth'). cino= cino=h10 public: public: a = a + 1; a = a + 1; b = b + 1; pN Parameter declarations for K&R-style function declarations will be indented N characters from the margin. (default 'shiftwidth'). cino= cino=p0 cino=p2s func(a, b) func(a, b) func(a, b) int a; int a; int a; char b; char b; char b; tN Indent a function return type declaration N characters from the margin. (default 'shiftwidth'). cino= cino=t0 cino=t7 int int int func() func() func() +N Indent a continuation line (a line that spills onto the next) N additional characters. (default 'shiftwidth'). cino= cino=+10 a = b + 9 * a = b + 9 * c; c; cN Indent comment lines after the comment opener, when there is no other text with which to align, N characters from the comment opener. (default 3). See also |format-comments|. cino= cino=c5 /* /* text. text. */ */ (N When in unclosed parentheses, indent N characters from the line with the unclosed parentheses. When N is 0 or the line starts with '(', line up with the unclosed parentheses. (default 'shiftwidth' * 2). cino= cino=(0 if (c1 && (c2 || if (c1 && (c2 || c3)) c3)) foo; foo; if (c1 && if (c1 && (c2 || c3)) (c2 || c3)) { { uN Same as (N, but for one level deeper. (default 'shiftwidth'). cino= cino=u2 if (c123456789 if (c123456789 && (c22345 && (c22345 || c3)) || c3)) )N Vim searches for unclosed parentheses at most N lines away. This limits the time needed to search for parentheses. (default 20 lines). *N Vim searches for unclosed comments at most N lines away. This limits the time needed to search for the start of a comment. (default 30 lines). The defaults, spelled out in full, are: cinoptions=>s,e0,n0,f0,{0,}0,^0,:s,=s,ps,ts,c3,+s,(2s,us,)20,*30,gs,hs Vim puts a line in column 1 if: - It starts with '#' (preprocessor directives), if 'cinkeys' contains '#'. - It starts with a label (a keyword followed by ':', other than "case" and "default"). - Any combination of indentations causes the line to have less than 0 indentation. vim:tw=78:ts=8:sw=8: