Change
Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.
This file describes commands that delete or change text. In this context,changing text means deleting the text and replacing it with other text usingone command. You can undo all of these commands. You can repeat the non-Excommands with the "." command.
["x]<Del>or
<Del>xdl["x]xDelete [count] characters under and after the cursor[into register x] (not
linewise). Does the same as"dl".The
<Del> key does not take a [count]. Instead, itdeletes the last character of the count.See
'whichwrap' for deleting a line break (joinlines).
Xdh["x]XDelete [count] characters before the cursor [intoregister x] (not
linewise). Does the same as "dh".Also see
'whichwrap'.
d["x]d{motion}Delete text that
{motion} moves over [into registerx]. See below for exceptions.
dd["x]ddDelete [count] lines [into register x]
linewise.
D["x]DDelete the characters under the cursor until the endof the line and [count]-1 more lines [into registerx]; synonym for "d$".(not
linewise)
{Visual}["x]xor
v_xv_dv_<Del>{Visual}["x]d or
{Visual}["x]<Del>Delete the highlighted text [into register x] (for
{Visual} see
Visual-mode).
{Visual}["x]CTRL-H or
v_CTRL-Hv_<BS>{Visual}["x]<BS>When in Select mode: Delete the highlighted text [intoregister x].
{Visual}["x]Xor
v_Xv_Dv_b_D{Visual}["x]DDelete the highlighted lines [into register x] (for
{Visual} see
Visual-mode). In Visual block mode,"D" deletes the highlighted text plus all text untilthe end of the line.
:d:de:del:delete:dl:dp:[range]d[elete] [x]Delete [range] lines (default: current line) [intoregister x].Note these weird abbreviations: :dldelete and list :dellidem :delelidem :deletlidem :deletelidem :dpdelete and print :depidem :delpidem :delepidem :deletpidem :deletepidem
:[range]d[elete] [x]
{count}Delete
{count} lines, starting with [range](default: current line
cmdline-ranges) [intoregister 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.
d-specialAn exception for the d{motion} command: If the motion is not linewise, thestart and end of the motion are not in the same line, and there are onlyblanks before the start and there are no non-blanks after the end of themotion, the delete becomes linewise. This means that the delete also removesthe line of blanks that you might expect to remain. Use the
o_v operator toforce the motion to be charwise.
Trying to delete an empty region of text (e.g., "d0" in the first column)is an error when
'cpoptions' includes the 'E' flag.
JJJoin [count] lines, with a minimum of two lines.Remove the indent and insert up to two spaces (seebelow). Fails when on the last line of the buffer.If [count] is too big it is reduced to the number oflines available.
v_J{Visual}JJoin the highlighted lines, with a minimum of twolines. Remove the indent and insert up to two spaces(see below).
gJgJJoin [count] lines, with a minimum of two lines.Don't insert or remove any spaces.
v_gJ{Visual}gJJoin the highlighted lines, with a minimum of twolines. Don't insert or remove any spaces.
:j:join:[range]j[oin][!] [flags]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, thiscommand does nothing. The default behavior is tojoin the current line with the line below it.See
ex-flags for [flags].
:[range]j[oin][!]
{count} [flags]Join
{count} lines, starting with [range] (default:current line
cmdline-ranges). Same as "J", exceptwith [!] the join does not insert or delete anyspaces.See
ex-flags for [flags].
These commands delete the<EOL> between lines. This has the effect of joiningmultiple lines into one line. You can repeat these commands (except:j) andundo them.
These commands, except "gJ", insert one space in place of the
<EOL> unlessthere is trailing white space or the next line starts with a ')'. Thesecommands, except "gJ", delete any leading white space on the next line. Ifthe
'joinspaces' option is on, these commands insert two spaces after a '.','!' or '?'.The 'B' and 'M' flags in
'formatoptions' change the behavior for insertingspaces before and after a multibyte character
fo-table.
The
'[ mark is set at the end of the first line that was joined,
'] at theend of the resulting line.
RREnter Replace mode: Each character you type replacesan existing character, starting with the characterunder the cursor. Repeat the entered text [count]-1times. See
Replace-mode for more details.
gRgREnter Virtual Replace mode: Each character you typereplaces existing characters in screen space. So a
<Tab> 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 startinsert. When
'cpoptions' includes the 'E' flag andthere is no text to delete (e.g., with "cTx" when thecursor is just after an 'x'), an error occurs andinsert 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 thereis no text to delete.
cc["x]ccDelete [count] lines [into register x] and startinsert
linewise. If
'autoindent' is on, preservethe indent of the first line.
C["x]CDelete from the cursor position to the end of theline and [count]-1 more lines [into register x], andstart insert. Synonym for c$ (not
linewise).
s["x]sDelete [count] characters [into register x] and startinsert (s stands for Substitute). Synonym for "cl"(not
linewise).
S["x]SDelete [count] lines [into register x] and startinsert. Synonym for "cc"
linewise.
{Visual}["x]cor
v_cv_s{Visual}["x]sDelete the highlighted text [into register x] andstart insert (for
{Visual} see
Visual-mode).
v_r{Visual}r{char}Replace all selected characters by
{char}.
CTRL-C will be inserted literally.
v_C{Visual}["x]CDelete the highlighted lines [into register x] andstart insert. In Visual block mode it worksdifferently
v_b_C.
v_S{Visual}["x]SDelete the highlighted lines [into register x] andstart insert (for
{Visual} see
Visual-mode).
v_R{Visual}["x]RCurrently just like
{Visual}["x]S. In a next versionit might work differently.
Notes: You can end Insert and Replace mode with<Esc>.
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 enterdeletes one character. If you reach the end of a line, Vim appends anyfurther characters (just like Insert mode). In Replace mode, the backspacekey restores the original text (if there was any). (See section "Insert andReplace mode"
mode-ins-repl).
cwcWSpecial case: When the cursor is in a word, "cw" and "cW" do not include thewhite space after a word, they only change up to the end of the word. This isbecause Vim interprets "cw" as change-word, and a word does not include thefollowing white space.
If you prefer "cw" to include the space after a word, see
cpo-_ to changethe behavior. Alternatively, use "caw" (see
aw).
: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 currentline.Adding [!] toggles
'autoindent' for the time thiscommand is executed.
rr{char}Replace the character under the cursor with
{char}.If
{char} is a
<CR> or
<NL>, a line break replaces thecharacter. To replace with a real
<CR>, use
CTRL-V<CR>.
CTRL-V<NL> replaces with a
<Nul>.
If
{char} is
CTRL-E or
CTRL-Y the character from theline below or above is used, just like with
i_CTRL-Eand
i_CTRL-Y. This also works with a count, thus
10r<C-E> copies 10 characters from the line below.
If you give a [count], Vim replaces [count] characterswith [count]
{char}s. When
{char} is a
<CR> or
<NL>,however, Vim inserts only one
<CR>: "5r<CR>" replacesfive characters with a single line break.When
{char} is a
<CR> or
<NL>, Vim performsautoindenting. This works just like deleting thecharacters that are replaced and then doing"i<CR><Esc>".
{char} can be entered as a digraph
digraph-arg.
:lmap mappings apply to
{char}. The
CTRL-^ commandin Insert mode can be used to switch this on/off
i_CTRL-^. See
utf-8-char-arg about usingcomposing characters when
'encoding' is Unicode.
grgr{char}Replace the virtual characters under the cursor with
{char}. This replaces in screen space, not filespace. See
gR and
Virtual-Replace-mode for moredetails. As with
r a count may be given.
{char} can be entered like with
r, but charactersthat have a special meaning in Insert mode, such asmost
CTRL-keys, cannot be used.
gr-defaultNvim creates
lsp-defaults mappings which may inhibitthe builtin behavior of
gr. Use this to restore thebuiltin behavior:
nnoremap <nowait> gr gr
digraph-argThe argument for Normal mode commands like
r and
t is a single character.When
'cpo' doesn't contain the 'D' flag, this character can also be enteredlike
digraphs. First type
CTRL-K and then the two digraph characters.
caseThe following commands change the case of letters. The currently active
locale is used. See
:language. The LC_CTYPE value matters here.
~~
'notildeop' option: Switch case of the characterunder the cursor and move the cursor to the right.If a [count] is given, do that many characters.
~
{motion}'tildeop' option: switch case of
{motion} text.
g~g~{motion}Switch case of
{motion} text.
g~g~
g~g~g~~g~~Switch case of current line.
v_~{Visual}~Switch case of highlighted text (for
{Visual} see
Visual-mode).
v_U{Visual}UMake highlighted text uppercase (for
{Visual} see
Visual-mode).
gUuppercasegU{motion}Make
{motion} text uppercase.Example:
:map! <C-F> <Esc>gUiw`]a
This works in Insert mode: pressCTRL-F to make theword before the cursor uppercase. Handy to typewords in lowercase and then make them uppercase.
gUgU
gUgUgUUgUUMake current line uppercase.
v_u{Visual}uMake highlighted text lowercase (for
{Visual} see
Visual-mode).
gugu
guguguuguuMake current line lowercase.
g?rot13g?{motion}Rot13 encode
{motion} text.
v_g?{Visual}g?Rot13 encode the highlighted text (for
{Visual} see
Visual-mode).
g?g?
g?g?g??g??Rot13 encode current line.
To turn one line into title caps, make every first letter of a worduppercase:
:s/\v<(.)(\w*)/\u\1\L\2/g
Adding and subtracting
CTRL-ACTRL-AAdd [count] to the number or alphabetic character ator after the cursor.
v_CTRL-A{Visual}CTRL-AAdd [count] to the number or alphabetic character inthe highlighted text.
v_g_CTRL-A{Visual}g
CTRL-AAdd [count] to the number or alphabetic character inthe highlighted text. If several lines arehighlighted, each one will be incremented by anadditional [count] (so effectively creating a[count] incrementing sequence).For Example, if you have this list of numbers:
1.
1.
1.
1.
Move to the second "1." and Visually select threelines, pressing g
CTRL-A results in:
1.
2.
3.
4.
CTRL-XCTRL-XSubtract [count] from the number or alphabeticcharacter at or after the cursor.
v_CTRL-X{Visual}CTRL-XSubtract [count] from the number or alphabeticcharacter in the highlighted text.
v_g_CTRL-X{Visual}g
CTRL-XSubtract [count] from the number or alphabeticcharacter in the highlighted text. If several linesare highlighted, each value will be decremented by anadditional [count] (so effectively creating a [count]decrementing sequence).
TheCTRL-A andCTRL-X commands work for (signed) decimal numbers, unsignedbinary/octal/hexadecimal numbers and alphabetic characters.
This depends on the
'nrformats' option:
When
'nrformats' includes "bin", Vim assumes numbers starting with '0b' or '0B' are binary.
When
'nrformats' includes "octal", Vim considers numbers starting with a '0' to be octal, unless the number includes a '8' or '9'. 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.
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 "alpha", Vim will change the alphabetic character under or after the cursor. This is useful to make lists with an alphabetic index.
For decimals a leading negative sign is considered for incrementing ordecrementing, for binary, octal and hex values, it won't be considered. Toignore the sign Visually select the number before usingCTRL-A orCTRL-X.
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".There is one exception: When a number that starts with a zero is found not tobe octal (it contains a '8' or '9'), but
'nrformats' does include "octal",leading zeros are removed to avoid that the result may be recognized as anoctal number.
Note that when
'nrformats' includes "octal", decimal numbers with leadingzeros cause mistakes, because they can be confused with octal numbers.
Note similarly, when
'nrformats' includes both "bin" and "hex", binary numberswith a leading '0x' or '0X' can be interpreted as hexadecimal rather thanbinary since '0b' are valid hexadecimal digits.
CTRL-A on "0x0b11" results in"0x0b12", not "0x0b100".When
'nrformats' includes "bin" and doesn't include "hex",
CTRL-A on "0b11" in"0x0b11" results in "0x0b100".
When the number under the cursor is too big to fit into 64 bits, it will berounded off to the nearest number that can be represented, and theaddition/subtraction is skipped. E.g.CTRL-X on 18446744073709551616 resultsin 18446744073709551615. Same for larger numbers, such as 18446744073709551618.
TheCTRL-A command is very useful in a macro. Example: Use the followingsteps to make a numbered list.
1. Create the first list entry, make sure it starts with a number.2. qa - start recording into register 'a'3. Y - yank the entry4. p - put a copy of the entry below the first one5.CTRL-A - increment the number6. q - stop recording7.<count>@a - repeat the yank, put and increment<count> times
If the
'shiftwidth' option is set to zero, the amountof indent is calculated at the first non-blankcharacter in the line.
<< <<Shift [count] lines one
'shiftwidth' leftwards.
If the
'shiftwidth' option is set to zero, the amountof indent is calculated at the first non-blankcharacter in the line.
>> >>Shift [count] lines one
'shiftwidth' rightwards.
:[range]le[ft] [indent]left align lines in [range]. Sets the indent in thelines to [indent] (default 0).
The ">" and "<" commands are handy for changing the indentation withinprograms. Use the
'shiftwidth' option to set the size of the white spacewhich 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 leftwardsstops when there is no indent. The shift right does not affect empty lines.
If the
'smartindent' option is on, or
'cindent' is on and
'cinkeys' contains'#' with a zero value, shift right does not affect lines starting with '#'(these are supposed to be C preprocessor lines that must stay in column 1).This can be changed with the
'cino' option, see
cino-#.
When the
'expandtab' option is off (this is the default) Vim uses
<Tab>s asmuch as possible to make the indent. You can use ">><<" to replace an indentmade out of spaces with the same indent made out of
<Tab>s (and a few spacesif necessary). If the
'expandtab' option is on, Vim uses only spaces. Thenyou can use ">><<" to replace
<Tab>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:>> 5move 5 lines 2 indents to the right:5>>move line 5 2 indents to the right
A filter is a program that accepts text at standard input, changes it in someway, and sends it to standard output. You can use the commands below to sendsome text through a filter, so that it is replaced by the filter output.Examples of filters are "sort", which sorts lines alphabetically, and"indent", which formats C program files (you need a version of indent thatworks like a filter; not all versions do). The
'shell' option specifies theshell Vim uses to execute the filter command. You can repeat filter commandswith ".". Vim does not recognize a comment (starting with '"') after the
:! command.
!!{motion}{filter}Filter
{motion} text lines through the externalprogram
{filter}.
!!!!{filter}Filter [count] lines through the external program
{filter}.
v_!{Visual}!{filter}Filter the highlighted lines through the externalprogram
{filter} (for
{Visual} see
Visual-mode).
:{range}![!]{filter} [!][arg]
:range!For executing external commands see
:!Filter
{range} lines through the external program
{filter}. Vim replaces the optional bangs with thelatest given command and appends the optional [arg].Vim saves the output of the filter command in atemporary file and then reads the file into the buffer
tempfile. Vim uses the
'shellredir' option toredirect the filter output to the temporary file.However, if the
'shelltemp' option is off then pipesare used when possible (on Unix).When the 'R' flag is included in
'cpoptions' marks inthe filtered lines are deleted, unless the
:keepmarks command is used. Example:
:keepmarks '<,'>!sort
When the number of lines after filtering is less thanbefore, marks in the missing lines are deleted anyway.
====Filter [count] lines like with ={motion}.
v_={Visual}=Filter the highlighted lines like with ={motion}.
tempdirtempfilesetuidNvim uses temporary files for filtering and generating diffs. Plugins alsocommonly use
tempname() for their own purposes. On the first request fora temporary file, Nvim creates a common directory (the "Nvim tempdir"), toserve as storage for all temporary files (including
stdpath("run") files
$XDG_RUNTIME_DIR) in the current session.
The Nvim tempdir is created in the first available system tempdir:Unix: $TMPDIR, /tmp, current-dir, $HOME.Windows: $TMPDIR, $TMP, $TEMP, $USERPROFILE, current-dir.
On unix the tempdir is created with permissions 0700 (only accessible by thecurrent user) to avoid security problems (e.g. symlink attacks). On exit,Nvim deletes the tempdir and its contents.
E5431If you see an error or
log message like:
E5431: tempdir disappeared (2 times)
this means an external process on your system deleted the Nvim tempdir.Typically this is caused by "antivirus" or a misconfigured cleanup service.
If Nvim has the setuid bit set this may cause problems: the temp fileis owned by the setuid user but the filter command probably runs as theoriginal user.
4.2 Substitute
:substitute:s:su:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]For each line in [range] replace a match of
{pattern}with
{string}.For the
{pattern} see
pattern.
{string} can be a literal string, or somethingspecial; see
sub-replace-special.When [range] and [count] are omitted, replace in thecurrent line only. When [count] is given, replace in[count] lines, starting with the last line in [range].When [range] is omitted start in the current line.
E939E1510[count] must be a positive number (max 2147483647)Also see
cmdline-ranges.
:[range]s[ubstitute] [flags] [count]:[range]&[&][flags] [count]
:&Repeat last :substitute with same search pattern andsubstitute string, but without the same flags. Youmay add [flags], see
:s_flags.Note that after
:substitute the '&' and '#' flagscan't be used, they're recognized as a patternseparator.The space between
:substitute and the 'c', 'g','i', 'I' and 'r' flags isn't required, but in scriptsit's a good idea to keep it to avoid confusion.Also see the two and three letter commands to repeat:substitute below
:substitute-repeat.
:[range]~[&][flags] [count]
:~Repeat last substitute with same substitute stringbut with last used search pattern. This is like
:&r. See
:s_flags for [flags].
&&Synonym for
:s (repeat last substitute). Notethat the flags are not remembered, thus it mightactually work differently. You can use
:&& to keepthe flags.
g&g&Synonym for
:%s//~/& (repeat last substitute withlast search pattern on all lines with the same flags).For example, when you first do a substitution with
:s/pattern/repl/flags and then
/search forsomething else,
g& will do
:%s/search/repl/flags.Mnemonic: global substitute.
:s_flagsThe flags that you can use for the substitute commands:
:&&[&]Must be the first one: Keep the flags from the previous substitutecommand. Examples:
:&&:s/this/that/&
Note that:s and:& don't keep the flags.
[c]Confirm each substitution. Vim highlights the matching string (with
hl-IncSearch). You can type:
:s_c 'y' to substitute this match 'l' to substitute this match and then quit ("last") 'n' to skip this match
<Esc> to quit substituting 'a' to substitute this and all remaining matches 'q' to quit substituting
CTRL-E to scroll the screen up
CTRL-Y to scroll the screen down
:s_e[e] When the search pattern fails, do not issue an error message and, inparticular, continue in maps as if no error occurred. This is mostuseful to prevent the "No match" error from breaking a mapping. Vimdoes not suppress the following error messages, however:Regular expressions can't be delimited by letters\ should be followed by /, ? or &No previous substitute regular expressionTrailing charactersInterrupted
:s_g[g]Replace all occurrences in the line. Without this argument,replacement occurs only for the first occurrence in each line. If the
'gdefault' option is on, this flag is on by default and the [g]argument switches it off.
[p]Print the line containing the last substitute.
:s_p[#]Like [p] and prepend the line number.
:s_#[l]Like [p] but print the text like
:list.
:s_l:s_r[r]Only useful in combination with
:& or
:s without arguments.
:&rworks the same way as
:~: When the search pattern is empty, use thepreviously used search pattern instead of the search pattern from thelast substitute or
:global. If the last command that did a searchwas a substitute or
:global, there is no effect. If the lastcommand was a search command such as "/", use the pattern from thatcommand.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. Adifferent command is used instead, or you can use
/\v and friends. Thereason is that the flags can only be found by skipping the pattern, and inorder to skip the pattern the "magicness" must be known. Catch 22!
If the{pattern} for the substitute command is empty, the command uses thepattern from the last substitute or:global command. If there is none, butthere is a previous search pattern, that one is used. With the [r] flag, thecommand uses the pattern from the last substitute,:global, or searchcommand.
If the
{string} is omitted the substitute is done as if it's empty. Thus thematched pattern is deleted. The separator after
{pattern} can also be leftout then. Example:
:%s/TESTING
This deletes "TESTING" from all lines, but only one per line.
For compatibility with Vi these two exceptions are allowed:"\/{string}/" and "\?{string}?" do the same as "//{string}/r"."\&{string}&" does the same as "//{string}/".
pattern-delimiterE146Instead of the '/' which surrounds the pattern and replacement string, you canuse another single-byte character. This is useful if you want to include a'/' in the search pattern or replacement string. Example:
:s+/+//+
You can use most characters, but not an alphanumeric character, '\', '"' or'|'.
For the definition of a pattern, see
pattern. In Visual block mode, use
/\%V in the pattern to have the substitute work in the block only.Otherwise it works on whole lines anyway.
The substitution is limited in recursion to 4 levels.
E1290Otherwise these characters in{string} have a special meaning:
magicnomagic action
& \& replaced with the whole matched pattern
s/\& \& & replaced with & \0 replaced with the whole matched pattern
\0s/\0 \1 replaced with the matched pattern in the first pair of ()
s/\1 \2 replaced with the matched pattern in the second pair of ()
s/\2 .. ..
s/\3 \9 replaced with the matched pattern in the ninth pair of ()
s/\9 ~ \~ replaced with the
{string} of the previous substitute
s~ \~ ~ replaced with ~
s/\~ \u next character made uppercase
s/\u \U following characters made uppercase, until \E
s/\U \l next character made lowercase
s/\l \L following characters made lowercase, until \E
s/\L \e end of \u, \U, \l and \L (
NOTE: not
<Esc>!)
s/\e \E end of \u, \U, \l and \L
s/\E<CR> split line in two at this point (Type the
<CR> as
CTRL-V<Enter>)
s<CR> \r idem
s/\r \<CR> insert a carriage-return (
CTRL-M) (Type the
<CR> as
CTRL-V<Enter>)
s/\<CR> \n insert a
<NL> (
<NUL> in the file) (does NOT break the line)
s/\n \b insert a
<BS>s/\b \t insert a
<Tab>s/\t \\ insert a single backslash
s/\\ \x where x is any character not mentioned above: Reserved for future expansion
The special meaning is also used inside the third argument
{sub} ofthe
substitute() function with the following exceptions:
A % inserts a percent literally without regard to
'cpoptions'.
magic is always set without regard to
'magic'.
A ~ inserts a tilde literally.
<CR> and \r inserts a carriage-return (CTRL-M).
\<CR> does not have a special meaning. It's just one of \x.
Examples:
:s/a\|b/xxx\0xxx/g modifies "a b" to "xxxaxxx xxxbxxx":s/\([abc]\)\([efg]\)/\2\1/g modifies "af fa bg" to "fa fa gb":s/abcde/abc^Mde/ modifies "abcde" to "abc", "de" (two lines):s/$/\^M/ modifies "abcde" to "abcde^M":s/\w\+/\u\0/g modifies "bla bla" to "Bla Bla":s/\w\+/\L\u\0/g modifies "BLA bla" to "Bla Bla"
Note: "\L\u" can be used to capitalize the first letter of a word. This isnot compatible with Vi and older versions of Vim, where the "\u" would cancelout the "\L". Same for "\U\l".
Note: In previous versionsCTRL-V was handled in a special way. Since this isnot Vi compatible, this was removed. Use a backslash instead.
commandtextresult
:s/aa/a^Ma/aaa<line-break>a:s/aa/a\^Ma/aaa^Ma:s/aa/a\\^Ma/aaa\<line-break>a
(you need to typeCTRL-V<CR> to get a ^M here)
The numbering of "\1", "\2" etc. is done based on which "\(" comes first inthe pattern (going left to right). When a parentheses group matches severaltimes, the last one will be used for "\1", "\2", etc. Example:
:s/\(\(a[a-d] \)*\)/\2/ modifies "aa ab x" to "ab x"
The "\2" is for "\(a[a-d] \)". At first it matches "aa ", secondly "ab ".
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" to "ax bx x x"
These commands repeat the previous:substitute command with the given flags.The first letter is always "s", followed by one or two of the possible flagcharacters. For example:sce works like:s///ce. The table lists thepossible combinations, not all flags are possible, because the command isshort for another command.
List of :substitute commands | c e g i I n p l r | c :sc :sce :scg :sci :scI :scn :scp :scl | e | g :sgc :sge :sg :sgi :sgI :sgn :sgp :sgl :sgr | i :sic :sie :si :siI :sin :sip :sir | I :sIc :sIe :sIg :sIi :sI :sIn :sIp :sIl :sIr | n | p | l | r :src :srg :sri :srI :srn :srp :srl :sr
Exceptions: :scr is:scriptnames :se is:set :sig is:sign :sil is:silent :sn is:snext :sp is:split :sl is:sleep :sre is:srewind
The special meaning for characters as mentioned at
sub-replace-special doesnot apply except for "<CR>". A
<NL> character is used as a line break, youcan get one with a double-quote string: "\n". Prepend a backslash to get areal
<NL> character (which will be a NUL in the file).
The "\=" notation can also be used inside the third argument
{sub} of
substitute() function. In this case, the special meaning for characters asmentioned at
sub-replace-special does not apply at all. Especially,
<CR> and
<NL> are interpreted not as a line break but as a carriage-return and anew-line respectively.
When the result is a
List then the items are joined with separating linebreaks. Thus each item becomes a line, except that they can contain linebreaks themselves.
The
submatch() function can be used to obtain matched text. The wholematched text can be accessed with "submatch(0)". The text matched with thefirst pair of () with "submatch(1)". Likewise for further sub-matches in ().
Be careful: The separation character must not appear in the expression!Consider using a character like "@" or ":". There is no problem if the resultof the expression contains the separation character.
Examples:
:s@\n@\="\r" .. expand("$HOME") .. "\r"@This replaces an end-of-line with a new line containing the value of $HOME.
s/E/\="\<Char-0x20ac>"/g
This replaces each 'E' character with a euro sign. Read more in
<Char->.
4.3 Changing tabs
change-tabs:ret:retab:retab!:[range]ret[ab][!] [-indentonly] [
{new-tabstop}]Replace all sequences of white-space containing a
<Tab> with new strings of white-space using
{new-tabstop}. If you do not specify
{new-tabstop} orit is zero, Vim uses the current value of
'tabstop'.The current value of
'tabstop' is always used tocompute the width of existing tabs.With !, Vim also replaces strings of only normalspaces with tabs where appropriate.With
'expandtab' on, Vim replaces all tabs with theappropriate number of spaces.This command sets
'tabstop' to
{new-tabstop} and ifperformed on the whole file, which is default, shouldnot make any visible change.
When [-indentonly] is specified, only the leadingwhite-space will be targeted. Any other consecutivewhite-space will not be changed.
Warning: This command modifies any<Tab> charactersinside of strings in a C program. Use "\t" to avoidthis (that's a good habit anyway).:retab! may also change a sequence of spaces by<Tab> characters, which can mess up a printf().A list of tab widths separated by commas may be usedin place of a single tabstop. Each value in the listrepresents the width of one tabstop, except the finalvalue which applies to all following tabstops.
retab-exampleExample for using autocommands and ":retab" to edit a file which is storedwith tabstops at 8 but edited with tabstops set at 4.
Warning: white spaceinside of strings can change! Also see
'softtabstop' option.
:auto BufReadPost*.xxretab! 4:auto BufWritePre*.xxretab! 8:auto BufWritePost*.xxretab! 4:auto BufNewFile*.xxset ts=4
5. Copying and moving textcopy-move
quote"{register}Use
{register} for next delete, yank or put. Usean uppercase character to append with delete and yank.Registers ".", "%", "#" and ":" only work with put.
:reg[isters]
{arg}Display the contents of the numbered and namedregisters that are mentioned in
{arg}. For example:
:reg 1a
to display registers '1' and 'a'. Spaces are allowedin{arg}.
yyank["x]y{motion}Yank
{motion} text [into register x]. When nocharacters are to be yanked (e.g., "y0" in column 1),this is an error when
'cpoptions' includes the 'E'flag.
yy["x]yyYank [count] lines [into register x]
linewise.
zy["x]zy{motion}Yank
{motion} text [into register x]. Only differsfrom
y when selecting a block of text, see
v_zy.
v_y{Visual}["x]yYank the highlighted text [into register x] (for
{Visual} see
Visual-mode).
v_Y{Visual}["x]YYank the highlighted lines [into register x] (for
{Visual} see
Visual-mode).
v_zy{Visual}["x]zyYank the highlighted text [into register x]. Trailingwhitespace at the end of each line of a selected blockwon't be yanked. Especially useful in combinationwith
zp. (for
{Visual} see
Visual-mode)
:y:yankE850:[range]y[ank] [x]Yank [range] lines [into register x].
:[range]y[ank] [x]
{count}Yank
{count} lines, starting with last line numberin [range] (default: current line
cmdline-ranges),[into register x].
pputE353E1240["x]pPut the text [from register x] after the cursor[count] times.
P["x]PPut the text [from register x] before the cursor[count] times.
<MiddleMouse>["x]<MiddleMouse>Put the text from a register before the cursor [count]times. Uses the "* register, unless another isspecified.Leaves the cursor at the end of the new text.Using the mouse only works when
'mouse' contains 'n'or 'a'.If you have a scrollwheel and often accidentally pastetext, you can use these mappings to disable thepasting with the middle mouse button:
:map <MiddleMouse> <Nop>:imap <MiddleMouse> <Nop>
You might want to disable the multi-click versionstoo, see
double-click.
gp["x]gpJust like "p", but leave the cursor just after the newtext.
gP["x]gPJust like "P", but leave the cursor just after the newtext.
:pu:put:[line]pu[t] [x]Put the text [from register x] after [line] (defaultcurrent line). This always works
linewise, thusthis command can be used to put a yanked block as newlines.If no register is specified, it depends on the
'clipboard' option: If
'clipboard' contains"unnamedplus", paste from the + register
quoteplus.Otherwise, if
'clipboard' contains "unnamed", pastefrom the * register
quotestar. Otherwise, paste fromthe unnamed register
quote_quote.The register can also be '=' followed by an optionalexpression. The expression continues until the end ofthe command. You need to escape the '|' and '"'characters to prevent them from terminating thecommand. Example:
:put ='path' .. \",/test\"
If there is no expression after '=', Vim uses theprevious expression. You can see it with ":dis =".
:[line]pu[t]! [x]Put the text [from register x] before [line] (defaultcurrent line).
:ip:iput:[line]ip[ut] [x]like
:put, but adjust indent to the current line
:[line]ip[ut]! [x]like
:put!, but adjust indent to the current line
["x]]p or
]p]<MiddleMouse>["x]]<MiddleMouse>Like "p", but adjust the indent to the current line.Using the mouse only works when
'mouse' contains 'n'or 'a'.
["x][P or
[P["x]]P or
]P["x][p or
[p[<MiddleMouse>["x][
<MiddleMouse>Like "P", but adjust the indent to the current line.Using the mouse only works when
'mouse' contains 'n'or 'a'.
["x]zp or
zpzP["x]zPLike "p" and "P", except without adding trailingspaces when pasting a block. Thus the inserted textwill not always be a rectangle. Especially useful incombination with
v_zy.
You can use these commands to copy text from one place to another. Do thisby first getting the text into a register with a yank, delete or changecommand, then inserting the register contents with a put command. You canalso use these commands to move text from one file to another, because Vimpreserves all registers when changing buffers (theCTRL-^ command is a quickway to toggle between two files).
linewise-registercharwise-registerYou can repeat the put commands with "." (except for :put) and undo them. Ifthe 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. Withthe ":put" command, Vim always inserts the text in the next line. You canexchange two characters with the command sequence "xp". You can exchange twolines with the command sequence "ddp". You can exchange two words with thecommand sequence "deep" (start with the cursor in the blank space before thefirst word). You can use the
'] or
`] command after the put command tomove the cursor to the end of the inserted text, or use
'[ or
`[ to movethe cursor to the start.
put-Visual-modeWhen using a put command like
p or
P in Visual mode, Vim will try toreplace the selected text with the contents of the register. How thisworks depends on the type of selection and the text. With blockwise selectionit also depends on the size of the block and whether the corners are on anexisting character. (Implementation detail: it actually works by firstputting the register after the selection and then deleting the selection.)
v_pp in Visual mode puts text and sets the default register (unnamed,selection, or clipboard) to the previously-selected text. Useful if you wantto put that text somewhere else. But you cannot repeat the same change.
v_PP in Visual mode puts text without setting the default register. You canrepeat the change, but the deleted text cannot be used. If you do need it youcan use
p with another register. E.g., yank the text to copy, Visuallyselect the text to replace and use "0p . You can repeat this as many times asyou like, and the unnamed register will be changed each time.
blockwise-putWhen a register contains text from one line (characterwise), using ablockwise Visual selection, putting that register will paste that textrepeatedly in each of the selected lines, thus replacing the blockwiseselected region by multiple copies of the register text. For example:
yank the word "TEXT" into a register withyw
select a visual block, marked with "v" in this text: aaavvaaa bbbvvbbb cccvvccc
pressp, results in: aaaTEXTaaa bbbTEXTbbb cccTEXTccc
blockwise-registerIf 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 cursorcolumn in the current and next lines. Vim makes the whole block of text startin the same column. Thus the inserted text looks the same as when it wasyanked or deleted. Vim may replace some
<Tab> characters with spaces to makethis happen. However, if the width of the block is not a multiple of a
<Tab>width and the text after the inserted block contains
<Tab>s, that text may bemisaligned.
Use
zP/|zp| to paste a blockwise yanked register without appending trailingspaces.
Note that after a charwise yank command, Vim leaves the cursor on the firstyanked 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 wouldsometimes not move the cursor to the first yanked character,because redisplaying was skipped. In Vim it always moves tothe first character, as specified by Posix.With a linewise yank command the cursor is put in the first line, but thecolumn is unmodified, thus it may not be on the first yanked character.
There are ten types of registers:
registers{register}E3541. The unnamed register ""2. 10 numbered registers "0 to "93. The small delete register "-4. 26 named registers "a to "z or "A to "Z5. Three read-only registers ":, "., "%6. Alternate buffer register "#7. The expression register "=8. The selection registers "* and "+9. The black hole register "_10. Last search pattern register "/
1. Unnamed register ""
quote_quotequotequoteVim fills this register with text deleted with the "d", "c", "s", "x" commandsor copied with the yank "y" command, regardless of whether or not a specificregister was used (e.g. "xdd). This is like the unnamed register is pointingto the last used register. Thus when appending using an uppercase registername, the unnamed register contains the same text as the named register.An exception is the '_' register: "_dd does not store the deleted text in anyregister.Vim uses the contents of the unnamed register for any put command (p or P)which does not specify a register. Additionally you can access it with thename '"'. This means you have to type two double quotes. Writing to the ""register writes to register "0.
2. Numbered registers "0 to "9
quote_numberquote0quote1quote2quote3quote4quote9Vim 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 orchange command (even when the command specified another register), unless thetext is less than one line (the small delete register is used then). Anexception is made for the delete operator with these movement commands:
%,
(,
),
`,
/,
?,
n,
N,
{ and
}.Register "1 is always used then (this is Vi compatible). The "- register isused as well if the delete is within a line. Note that these characters maybe mapped. E.g.
% is mapped by the matchit plugin. With each successive deletion or change, Vim shifts the previous contentsof register 1 into register 2, 2 into 3, and so forth, losing the previouscontents of register 9.
yankringTo also store yanks (not only deletions) in registers 1-9, try this:
-- Yank-ring: store yanked text in registers 1-9.vim.api.nvim_create_autocmd('TextYankPost', { callback = function() if vim.v.event.operator == 'y' then for i = 9, 1, -1 do -- Shift all numbered registers. vim.fn.setreg(tostring(i), vim.fn.getreg(tostring(i - 1))) end end end,})
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].
4. Named registers "a to "z or "A to "Z
quote_alphaquoteaVim fills these registers only when you say so. Specify them as lowercaseletters to replace their previous contents or as uppercase letters to appendto their previous contents. When the '>' flag is present in
'cpoptions' thena line break is inserted before the appended text.
5. Read-only registers ":, ". and "%These are '%', ':' and '.'. You can use them only with the "p", "P",and ":put" commands and with
CTRL-R.
quote_.quote.E29".Contains the last inserted text (the same as what is insertedwith the insert mode commands
CTRL-A and
CTRL-@).
Note: thisdoesn't work with
CTRL-R on the command-line. It works a bitdifferently, 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:E30":Contains the most recent executed command-line. Example: Use"@:" to repeat the previous command-line command.The command-line is only stored in this register when at leastone character of it was typed. Thus it remains unchanged ifthe command was executed completely from a mapping.
quote_#quote#6. Alternate file register "#Contains the name of the alternate file for the current window. It willchange how the
CTRL-^ command works.This register is writable, mainly to allow for restoring it after a plugin haschanged it. It accepts buffer number:
let altbuf = bufnr(@#)...let @# = altbuf
It will give error
E86 if you pass buffer number and this buffer does notexist.It can also accept a match with an existing buffer name:
let @# = 'buffer_name'
Error
E93 if there is more than one buffer matching the given name or
E94if none of buffers matches the given name.
7. Expression register "=
quote_=quote=@=This is not really a register that stores text, but is a way to use anexpression in commands which use a register. The expression register isread-write.
When typing the '=' after " or
CTRL-R the cursor moves to the command-line,where you can enter any expression (see
expression). All normalcommand-line editing commands are available, including a special history forexpressions. When you end the command-line by typing
<CR>, Vim computes theresult of the expression. If you end it with
<Esc>, Vim abandons theexpression. If you do not enter an expression, Vim uses the previousexpression (like with the "/" command).
The expression must evaluate to a String. A Number is always automaticallyconverted to a String. For the "p" and ":put" command, if the result is aFloat it's converted into a String. If the result is a List each element isturned into a String and used as a line. A Dictionary is converted into aString. A Funcref results in an error message (use string() to convert).
If the "= register is used for the "p" command, the String is split up at<NL>characters. If the String ends in a<NL>, it is regarded as a linewiseregister.
8. Selection registers "* and "+Use these registers for storing and retrieving the selected text for the GUI.See
quotestar and
quoteplus. When the clipboard is not available or notworking, the unnamed register is used instead. For Unix systems and Mac OS X,see
primary-selection.
9. Black hole register "_
quote_When writing to this register, nothing happens. This can be used to deletetext without affecting the normal registers. When reading from this register,nothing is returned.
10. Last search pattern register"/
quote_/quote/Contains the most recent search-pattern. This is used for "n" and
'hlsearch'.It is writable with
:let, you can change it to have
'hlsearch' highlightother matches without actually searching. You can't yank or delete into thisregister. The search direction is available in
v:searchforward.Note that the value is restored when returning from a function
function-search-undo.
@/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 registerthat was last filled (this is also the contents of the unnamed register). Ifyou are confused, use the
:dis command to find out what Vim will put (thiscommand displays all named and numbered registers; the unnamed register islabelled '"').
The next three commands always work on whole lines.
:[range]co[py]
{address}:co:copyCopy the lines given by [range] to below the linegiven by
{address}.
:[range]m[ove]
{address}:m:mo:moveE134Move the lines given by [range] to below the linegiven by
{address}.
:le:left:[range]le[ft] [indent]Left-align lines in [range]. Sets the indent in thelines to [indent] (default 0).
gqgq{motion}Format the lines that
{motion} moves over.Formatting is done with one of three methods:1. If
'formatexpr' is not empty the expression is evaluated. This can differ for each buffer.2. If
'formatprg' is not empty an external program is used.3. Otherwise formatting is done internally.
In the third case the
'textwidth' option controls thelength of each formatted line (see below).If the
'textwidth' option is 0, the formatted linelength is the screen width (with a maximum width of79).The
'formatoptions' option controls the type offormatting
fo-table.The cursor is left on the first non-blank of the lastformatted line.
NOTE: The "Q" command formerly performed thisfunction. If you still want to use "Q" forformatting, use this mapping:
:nnoremap Q gq
gqgq
gqgqgqqgqqFormat the current line. With a count format thatmany lines.
gwgw{motion}Format the lines that
{motion} moves over. Similar to
gq but puts the cursor back at the same position inthe text. However,
'formatprg' and
'formatexpr' arenot used.
gwgw
gwgwgwwgwwFormat the current line as with "gw".
v_gw{Visual}gwFormat the highlighted text as with "gw". (for
{Visual} see
Visual-mode).
Example: To format the current paragraph use:
gqapgqap
The "gq" command leaves the cursor in the line where the motion command takesthe cursor. This allows you to repeat formatting repeated with ".". Thisworks well with "gqj" (format current and next line) and "gq}" (format untilend of paragraph).
Note: When
'formatprg' is set, "gq" leaves the cursor onthe first formatted line (as with using a filter command).
If you want to format the current paragraph and continue where you were, use:
gwap
If you always want to keep paragraphs formatted you may want to add the 'a'flag to
'formatoptions'. See
auto-format.
If the
'autoindent' option is on, Vim uses the indent of the first line forthe following lines.
Formatting does not change empty lines (but it does change lines with onlywhite space!).
The
'joinspaces' option is used when lines are joined together.
You can set the
'formatexpr' option to an expression or the
'formatprg' optionto 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 externalprogram.
format-formatexprThe
'formatexpr' option can be set to a Vim script function that performsreformatting of the buffer. This should usually happen in an
ftplugin,since formatting is highly dependent on the type of file. It makessense to use an
autoload script, so the corresponding script is only loadedwhen actually needed and the script should be called
<filetype>format.vim.
For example, the XML filetype plugin distributed with Vim in the$VIMRUNTIME/ftplugin directory, sets the
'formatexpr' option to:
setlocal formatexpr=xmlformat#Format()
That means, you will find the corresponding script, defining thexmlformat#Format() function, in the file
$VIMRUNTIME/autoload/xmlformat.vimHere is an example script that removes trailing whitespace from the selectedtext. Put it in your autoload directory, e.g. ~/.vim/autoload/format.vim:
func! format#Format() " only reformat on explicit gq command if mode() != 'n' " fall back to Vim's internal reformatting return 1 endif let lines = getline(v:lnum, v:lnum + v:count - 1) call map(lines, {key, val -> substitute(val, '\s\+$', '', 'g')}) call setline('.', lines) " do not run internal formatter! return 0endfunc
You can then enable the formatting by executing:
setlocal formatexpr=format#Format()
Note: this function explicitly returns non-zero when called from insert mode(which basically means, text is inserted beyond the
'textwidth' limit). Thiscauses Vim to fall back to reformat the text by using the internal formatter.
However, if the
gq command is used to reformat the text, the functionwill receive the selected lines, trim trailing whitespace from those lines andput them back in place. If you are going to split single lines into multiplelines, be careful not to overwrite anything.
If you want to allow reformatting of text from insert or replace mode, one hasto be very careful, because the function might be called recursively. Fordebugging it helps to set the
'debug' option.
right-justifyThere is no command in Vim to right justify text. You can do it withan external command, like "par" (e.g.:
:.,}!par to format until the end of theparagraph) or set
'formatprg' to "par".
Vim can automatically insert and format comments in a special way. Vimrecognizes a comment by a specific string at the start of the line (ignoringwhite 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 atype of comment string. A part consists of:
{flags}:{string}
{string} is the literal text that must appear.
{flags}: nNested comment. Nesting with mixed parts is allowed. If
'comments'is "n:),n:>" a line starting with "> ) >" is a comment.
bBlank (<Space>,<Tab> or<EOL>) required after{string}.
fOnly the first line has the comment string. Do not repeat comment onthe next line, but preserve indentation (e.g., a bullet-list).
sStart of three-piece comment
mMiddle of a three-piece comment
eEnd of a three-piece comment
lLeft align. Used together with 's' or 'e', the leftmost character ofstart or end will line up with the leftmost character from the middle.This is the default and can be omitted. See below for more details.
rRight align. Same as above but rightmost instead of leftmost. Seebelow for more details.
ODon't consider this comment for the "O" command.
xAllows three-piece comments to be ended by just typing the lastcharacter of the end-comment string as the first action on a newline when the middle-comment string has been inserted automatically.See below for more details.
{digits}When together with 's' or 'e': add{digit} amount of offset to anautomatically inserted middle or end comment leader. The offsetbegins from a left alignment. See below for more details.
-{digits}Like{digits} but reduce the indent. This only works when there issome 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 thecomment string repeats at the start of each line. The{flags} field may beempty.
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 arequired 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 otherparts 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 stringincludes the 'b' flag. For three-piece comments, Vim checks the text afterthe 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 musthave 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 leaderfor the new line: " * ". To close this comment you just have to type "/"before typing anything else on the new line. This will replace themiddle-comment leader with the end-comment leader and apply any specifiedalignment, leaving just" */". There is no need to hit Backspace first.
When there is a match with a middle part, but there also is a matching endpart which is longer, the end part is used. This makes a C style comment workwithout requiring the middle part to end with a space.
Here is an example of alignment flags at work to make a comment stand out(kind of looks like a 1 too). Consider comment string:
:set comments=sr:/***,m:**,ex-2:******/
/*** **<--right aligned from "r" flag **offset 2 spaces for the "-2" flag-->** ******/
In this case, the first comment was typed, then return was pressed 4 times,then "/" was pressed to end the comment.
Here are some finer points of three part comments. There are three times whenalignment and offset flags are taken into consideration: opening a new lineafter a start-comment, opening a new line before an end-comment, andautomatically ending a three-piece comment. The end alignment flag has abackwards perspective; the result is that the same alignment flag used with"s" and "e" will result in the same indent for the starting and ending pieces.Only one alignment per comment part is meant to be used, but an offset numberwill override the "r" and "l" flag.
Enabling
'cindent' will override the alignment flags in many cases.Reindenting using a different method like
gq or
= will not consultalignment flags either. The same behaviour can be defined in those otherformatting options. One consideration is that
'cindent' has additionaloptions for context based indenting of comments but cannot replicate manythree piece indent alignments. However,
'indentexpr' has the ability to workbetter with three piece comments.
Other 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.
fo-tableYou can use the
'formatoptions' option to influence how Vim formats text.
'formatoptions' is a string that can contain any of the letters below. Youcan separate the option letters with commas for readability.
fo-ttAuto-wrap text using
'textwidth'fo-ccAuto-wrap comments using
'textwidth', inserting the current commentleader automatically.
fo-rrAutomatically insert the current comment leader after hitting
<Enter> in Insert mode.
fo-ooAutomatically insert the current comment leader after hitting 'o' or'O' in Normal mode. In case comment is unwanted in a specific placeuse
CTRL-U to quickly delete it.
i_CTRL-Ufo-//When 'o' is included: do not insert the comment leader for a //comment after a statement, only when // is at the start of the line.
fo-qqAllow formatting of comments with "gq".Note that formatting will not change blank lines or lines containingonly the comment leader. A new paragraph starts after such a line,or when the comment leader changes.
fo-wwTrailing white space indicates a paragraph continues in the next line.A line that ends in a non-white character ends a paragraph.
fo-aaAutomatic formatting of paragraphs. Every time text is inserted ordeleted the paragraph will be reformatted. See
auto-format.When the 'c' flag is present this only happens for recognizedcomments.
fo-nnWhen formatting text, recognize numbered lists. This actually usesthe
'formatlistpat' option, thus any kind of list can be used. Theindent of the text after the number is used for the next line. Thedefault is to find a number, optionally followed by '.', ':', ')',']' or '}'. Note that
'autoindent' must be set too. Doesn't workwell together with "2".Example:
1. the first item wraps2. the second item
fo-22When formatting text, use the indent of the second line of a paragraphfor the rest of the paragraph, instead of the indent of the firstline. This supports paragraphs in which the first line has adifferent indent than the rest. Note that
'autoindent' must be settoo. Example:
first line of a paragraphsecond line of the same paragraphthird line.
This also works inside comments, ignoring the comment leader.
fo-vvVi-compatible auto-wrapping in insert mode: Only break a line at ablank that you have entered during the current insert command. (
Note:this is not 100% Vi compatible. Vi has some "unexpected features" orbugs in this area. It uses the screen column instead of the linecolumn.)
fo-bbLike 'v', but only auto-wrap if you enter a blank at or beforethe wrap margin. If the line was longer than
'textwidth' when youstarted the insert, or you do not enter a blank in the insert beforereaching
'textwidth', Vim does not perform auto-wrapping.
fo-llLong lines are not broken in insert mode: When a line was longer than
'textwidth' when the insert command started, Vim does notautomatically format it.
fo-mmAlso break at a multibyte character above 255. This is useful forAsian text where every character is a word on its own.
fo-MMWhen joining lines, don't insert a space before or after a multibytecharacter. Overrules the 'B' flag.
fo-BBWhen joining lines, don't insert a space between two multibytecharacters. Overruled by the 'M' flag.
fo-11Don't break a line after a one-letter word. It's broken before itinstead (if possible).
fo-]]Respect
'textwidth' rigorously. With this flag set, no line can belonger than
'textwidth', unless line-break-prohibition rules make thisimpossible. Mainly for CJK scripts and works only if
'encoding' is"utf-8".
fo-jjWhere it makes sense, remove a comment leader when joining lines. Forexample, joining:
int i; // the index
// in the list
Becomes:
int i; // the index in the list
fo-ppDon't break lines at single spaces that follow periods. This isintended to complement
'joinspaces' and
cpo-J, for prose withsentences separated by two spaces. For example, with
'textwidth' setto 28:
Surely you're joking, Mr. Feynman!
Becomes:
Surely you're joking,Mr. Feynman!
Instead of:
Surely you're joking, Mr.Feynman!
With 't' and 'c' you can specify when Vim performs auto-wrapping:
valueaction
""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 automatic formatting anyway (butdoes insert comment leaders according to the
'comments' option). An exceptionis when the 'a' flag is present.
auto-formatNote that
'textwidth' can be non-zero even if Vim never performsauto-wrapping;
'textwidth' is still useful for formatting with "gq".
If the
'comments' option includes "/*", "*" and/or "*/", then Vim has somebuilt 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 samehappens with formatting and auto-wrapping. Opening a line after a linestarting with "/*" or "*" and containing "*/", will cause no comment leader tobe inserted, and the indent of the new line is taken from the line containingthe start of the comment.E.g.:
/* * Your typical comment. */The indent on this line is the same as the start of the abovecomment.
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):
:set fo=croq
for Mail/news(format all, don't start comment with "o" command):
:set fo=tcrq
When the 'a' flag is present in
'formatoptions' text is formattedautomatically when inserting text or deleting text. This works nicely forediting text paragraphs. A few hints on how to use this:
You need to properly define paragraphs. The simplest is paragraphs that are separated by a blank line. When there is no separating blank line, consider using the 'w' flag and adding a space at the end of each line in the paragraphs except the last one.
bla bla foobar blabla foobar bla foobar bla bla bla foobar blabla foobar bla bla foobar
Add the 'c' flag to only auto-format comments. Useful in source code.
Set
'textwidth' to the desired width. If it is zero then 79 is used, or the width of the screen if this is smaller.
And a few warnings:
When part of the text is not properly separated in paragraphs, making changes in this text will cause it to be formatted anyway. Consider doing
:set fo-=a
When using the 'w' flag (trailing space means paragraph continues) and deleting the last line of a paragraph with
dd, the paragraph will be joined with the next one.
Changed text is saved for undo. Formatting is also a change. Thus each format action saves text for undo. This may consume quite a lot of memory.
Formatting a long paragraph and/or with complicated indenting may be slow.
Vim has a sorting function and a sorting command. The sorting function can befound here:
sort(),
uniq().Also see
:uniq.
:sor:sort:[range]sor[t][!] [b][f][i][l][n][o][r][u][x] [/{pattern}/]Sort lines in [range]. When no range is given alllines are sorted.
With [!] the order is reversed.
With [i] case is ignored.
:sort-lWith [l] sort uses the current collation locale.Implementation details: strcoll() is used to comparestrings. See
:language to check or set the collationlocale. Example:
:language collate en_US.UTF-8:%sort l
v:collate can also used to check the current locale.Sorting using the locale typically ignores case.This does not work properly on Mac.
Options [n][f][x][o][b] are mutually exclusive.
With [n] sorting is done on the first decimal numberin the line (after or inside a{pattern} match).One leading '-' is included in the number.
With [f] sorting is done on the Float in the line.The value of Float is determined similar to passingthe text (after or inside a{pattern} match) tostr2float() function.
With [x] sorting is done on the first hexadecimalnumber in the line (after or inside a{pattern}match). A leading "0x" or "0X" is ignored.One leading '-' is included in the number.
With [o] sorting is done on the first octal number inthe line (after or inside a{pattern} match).
With [b] sorting is done on the first binary number inthe line (after or inside a
{pattern} match).
:sort-u:sort-uniqWith [u] (u stands for unique) only keep the first ofa sequence of identical lines (ignoring case when [i]is used). Without this flag, a sequence of identicallines will be kept in their original order.Note that leading and trailing white space may causelines to be different.When you just want to make things unique, use
:uniq.
When /{pattern}/ is specified and there is no [r] flagthe text matched with
{pattern} is skipped, so thatyou sort on what comes after the match.
'ignorecase' applies to the pattern, but
'smartcase'is not used.Instead of the slash any non-letter can be used.For example, to sort on the second comma-separatedfield:
:sort /[^,]*,/
To sort on the text at virtual column 10 (thusignoring the difference between tabs and spaces):
:sort /.*\%10v/
To sort on the first number in the line, no matterwhat is in front of it:
:sort /.\{-}\ze\d/(Explanation: ".\{-}" matches any text, "\ze" sets theend of the match and \d matches a digit.)With [r] sorting is done on the matching
{pattern}instead of skipping past it as described above.For example, to sort on only the first three lettersof each line:
:sort /\a\a\a/ r
If a{pattern} is used, any lines which don't have amatch for{pattern} are kept in their current order,but separate from the lines which do match{pattern}.If you sorted in reverse, they will be in reverseorder after the sorted lines, otherwise they will bein their original order, right before the sortedlines.
If{pattern} is empty (e.g. // is specified), thelast search pattern is used. This allows trying outa pattern first.
Note that using:sort with:global doesn't sort the matching lines, it'squite useless.
:sort does not use the current locale unless the l flag is used.Vim does do a "stable" sort.
The sorting can be interrupted, but if you interrupt it too late in theprocess you may end up with duplicated lines. This also depends on the systemlibrary function used.
Vim has a deduplicating function and a deduplicating command. Thededuplicating function can be found here:
uniq().Also see
:sort-uniq.
:uni:uniq:[range]uni[q][!] [i][l][r][u] [/{pattern}/]Remove duplicate lines that are adjacent to each otherin [range]. When no range is given, all lines areprocessed.
With [i] case is ignored when comparing lines.
With [l] comparison uses the current collation locale.See
:sort-l for more details.
With [r] comparison is done on the text that matches/{pattern}/ instead of the full line.
With [u] only keep lines that do not repeat (i.e., arenot immediately followed by the same line).
With [!] only keep lines that are immediately followedby a duplicate.
If both [!] and [u] are given, [u] is ignored and [!]takes effect.
When /{pattern}/ is specified and [r] is not used, thetext matched with
{pattern} is skipped and comparisonis done on what comes after the match.
'ignorecase' applies to the pattern, but
'smartcase'is not used.Instead of the slash any non-letter can be used.
For example, to remove adjacent duplicate lines basedon the second comma-separated field:
:uniq /[^,]*,/
Or to keep only unique lines ignoring the first 5characters:
:uniq u /.\{5}/If{pattern} is empty (e.g. // is used), the lastsearch pattern is used.
Note that leading and trailing white space may causelines to be considered different.To remove all duplicates regardless of position, use
:sort-u or external tools.