Various
Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.
Various commands
:redr:redraw:redr[aw][!]Redraws pending screen updates now, or the entirescreen if "!" is included. To CLEAR the screen use
:mode or
CTRL-L.It can be used to redraw the screen in a scriptor function (or a mapping if
'lazyredraw' is set).See also
nvim__redraw().
:redraws:redrawstatus:redraws[tatus][!]Redraws the status line and window bar of the currentwindow, or all status lines and window bars if "!" isincluded. Redraws the commandline instead if it containsthe
'ruler'. Useful if
'statusline' or
'winbar' includesan item that doesn't cause automatic updating.See also
nvim__redraw().
N<Del><Del>When entering a number: Remove the last digit.
Note: if you like to use
<BS> for this, add thismapping to your vimrc:
:map CTRL-V <BS> CTRL-V <Del>
:as[cii]or
ga:as:asciigaPrint the ascii value of the character under thecursor in decimal, hexadecimal and octal.Mnemonic: Get Ascii value.
For example, when the cursor is on a 'R':
<R> 82, Hex 52, Octal 122
When the character is a non-standard ASCII character,but printable according to the
'isprint' option, thenon-printable version is also given.
When the character is larger than 127, the
<M-x> formis also printed. For example:
<~A> <M-^A> 129, Hex 81, Octal 201
<p> <|~><M-~> 254, Hex fe, Octal 376
(where
<p> is a special character)
The
<Nul> character in a file is stored internally as
<NL>, but it will be shown as:
<^@> 0, Hex 00, Octal 000
If the character has composing characters these arealso shown. The value of
'maxcombine' doesn't matter.
If the character can be inserted as a digraph, alsooutput the two characters that can be used to createthe character:
<ö> 246, Hex 00f6, Oct 366, Digr o:
This shows you can type
CTRL-K o : to insert ö.
g8g8Print the hex values of the bytes used in thecharacter under the cursor, assuming it is in
UTF-8encoding. This also shows composing characters. Thevalue of
'maxcombine' doesn't matter.Example of a character with two composing characters:
e0 b8 81 + e0 b8 b9 + e0 b9 89
8g88g8Find an illegal UTF-8 byte sequence at or after thecursor.Can be used when editing a file that was supposed tobe UTF-8 but was read as if it is an 8-bit encodingbecause it contains illegal bytes.Does not wrap around the end of the file.Note that when the cursor is on an illegal byte or thecursor is halfway through a multibyte character thecommand won't move the cursor.
v_gx{Visual}gxOpens the selected text using the system defaulthandler. Mapped to
vim.ui.open().
:p:pr:printE749:[range]p[rint] [flags]Print [range] lines (default current line). Can alsobe spelled
:[range]| due to Vi compatibility (see
:bar). Gives an error in an empty buffer.In the GUI you can use the File.Print menu entry.See
ex-flags for [flags].The
:filter command can be used to only show linesmatching a pattern.
:[range]p[rint]
{count} [flags]Print
{count} lines, starting with [range] (defaultcurrent line
cmdline-ranges).See
ex-flags for [flags].
:l:list:[range]l[ist] [count] [flags]Same as :print, but show tabs as ">", trailing spacesas "-", and non-breakable space characters as "+" bydefault. Further changed by the
'listchars' option.See
ex-flags for [flags].
:#:[range]# [count] [flags]synonym for :number.
:#!vim-shebang:#!{anything}Ignored, so that you can start a Vim script with:
#!vim -Slet mylogbook='$HOME/logbook.md'exe $':e {mylogbook}'$put ='## ' .. strftime('%d. %b %Y')norm! o Make that script executable and run it to create anew diary entry.
:zE144:[range]z[+-^.=][count]Display several lines of text surrounding the linespecified with [range], or around the current lineif there is no [range].
If there is a [count], that's how many lines you'llsee; if there is no [count] and only one window thentwice the value of the
'scroll' option is used,otherwise the current window height minus 3 is used.This is the value of "scr" in the table below.
If there is a [count] the
'window' option is set toits value.
:z can be used either alone or followed by any ofseveral marks. These have the following effect:
mark first line last line new cursor line
---- ---------- --------- ------------+ current line 1 scr forward 1 scr forward
1 scr back current line current line^ 2 scr back 1 scr back 1 scr back. 1/2 scr back 1/2 scr fwd 1/2 scr fwd= 1/2 scr back 1/2 scr fwd current line
Specifying no mark at all is the same as "+".If the mark is "=", a line of dashes is printedaround the current line.
:z!:[range]z![+-^.=][count]Like ":z", but when [count] is not specified, itdefaults to the Vim window height minus one.
:[range]z[!]#[+-^.=][count]
:z#Like ":z" or ":z!", but number the lines.
:=:= [args]Without [args]: prints the last line number.With [args]: equivalent to
:lua ={expr}. see
:lua :{range}=Prints the last line number in
{range}. For example,this prints the current line number:
:.=
:norm[al][!]
{commands}:norm:normalExecute Normal mode commands
{commands}. This makesit possible to execute Normal mode commands typed onthe command-line.
{commands} are executed like theyare typed. For undo all commands are undone together.Execution stops when an error is encountered.
If the [!] is given, mappings will not be used.Without it, when this command is called from anon-remappable mapping (
:noremap), the argument canbe mapped anyway.
{commands} should be a complete command. If
{commands} does not finish a command, the last onewill be aborted as if
<Esc> or
<C-C> was typed.This implies that an insert command must be completed(to start Insert mode, see
:startinsert). A ":"command must be completed as well. And you can't use"gQ" to start Ex mode.
The display is not updated while ":normal" is busy.
{commands} cannot start with a space. Put a count of1 (one) before it, "1 " is one space.
This command cannot be followed by another command,since any '|' is considered part of the command.
This command can be used recursively, but the depth islimited by
'maxmapdepth'.
An alternative is to use
:execute, which uses anexpression as argument. This allows the use ofprintable characters to represent special characters.
Example:
:exe "normal \<c-w>\<c-w>"
:{range}norm[al][!]
{commands}:normal-rangeExecute Normal mode commands
{commands} for each linein the
{range}. Before executing the
{commands}, thecursor is positioned in the first column of the range,for each line. Otherwise it's the same as the":normal" command without a range.
By default the current window is used. To open ina split window, use
:horizontal or
:vertical:
:hor te:vert te
Fails if changes have been made to the current buffer,unless
'hidden' is set.
To enter
Terminal-mode automatically:
autocmd TermOpen * startinsert
The command runs in a non-interactive shell connectedto a pipe (not a terminal). Use
:terminal to run aninteractive shell connected to a terminal.
Backgrounded ("&") commands must not write to stdoutor stderr, the streams are closed immediately.
E5677Use
jobstart() instead.
:call jobstart('foo', {'detach':1})For powershell, chaining a stringed executable pathrequires using the call operator (&).
:!Write-Output "1`n2" | & "C:\Windows\System32\sort.exe" /r
Vim builds command line using options
'shell',
'shcf',
'sxq' and
'shq' in the following order:
&sh &shcf &sxq &shq {cmd} &shq &sxq So setting both
'sxq' and
'shq' is possible but rarelyuseful. Additional escaping inside
{cmd} may alsobe due to
'sxe' option.
Also, all
cmdline-special characters in
{cmd} arereplaced by Vim before passing them to shell.
E34Any "!" in
{cmd} is replaced with the previousexternal command (see also
'cpoptions'), unlessescaped by a backslash. Example: ":!ls" followed by":!echo ! \! \\!" executes "echo ls ! \!".
Any "|" in
{cmd} is passed to the shell, you cannotuse it to append a Vim command. See
:bar.
Any "%" in
{cmd} is expanded to the current file name.Any "#" in
{cmd} is expanded to the alternate file name.Special characters are not escaped, use quotes or
shellescape():
:!ls "%":exe "!ls " .. shellescape(expand("%"))Newline character ends
{cmd} unless a backslashprecedes the newline. What follows is interpreted asanother
: command.
After the command has been executed, the timestamp andsize of the current file is checked
timestamp.
If the command produces too much output some lines maybe skipped so the command can execute quickly. Nodata is lost, this only affects the display. The lastfew lines are always displayed (never skipped).
To avoid the hit-enter prompt use:
:silent !{cmd}:!!:!!Repeat last ":!{cmd}".
:redi:redir:redi[r][!] >
{file}Redirect messages to file
{file}. The messages whichare the output of commands are written to that file,until redirection ends. The messages are also stillshown on the screen. When [!] is included, anexisting file is overwritten. When [!] is omitted,and
{file} exists, this command fails.
Only one ":redir" can be active at a time. Calls to":redir" will close any active redirection beforestarting redirection to the new target. For recursiveuse check out
execute().
To stop the messages and commands from being echoed tothe screen, put the commands in a function and call itwith ":silent call Function()".Alternatives are the
'verbosefile' option or
execute() function, these can be used in combinationwith ":redir".
:redi[r] >>{file}Redirect messages to file{file}. Append if{file}already exists.
:redi[r] @{a-zA-Z}:redi[r] @{a-zA-Z}>Redirect messages to register{a-z}. Append to thecontents of the register if its name is givenuppercase{A-Z}. The ">" after the register name isoptional.:redi[r] @{a-z}>>Append messages to register{a-z}.
:redi[r] @*>:redi[r] @+>Redirect messages to the selection or clipboard. Forbackward compatibility, the ">" after the registername can be omitted. See
quotestar and
quoteplus.:redi[r] @*>>:redi[r] @+>>Append messages to the selection or clipboard.
:redi[r] @">Redirect messages to the unnamed register. Forbackward compatibility, the ">" after the registername can be omitted.:redi[r] @">>Append messages to the unnamed register.
:redi[r] =>
{var}Redirect messages to a variable. If the variabledoesn't exist, then it is created. If the variableexists, then it is initialized to an empty string.The variable will remain empty until redirection ends.Only string variables can be used. After theredirection starts, if the variable is removed orlocked or the variable type is changed, then furthercommand output messages will cause errors. When usinga local variable (l:var in a function or s:var in ascript) and another
:redir causes the current one toend, the scope might be different and the assignmentfails.To get the output of one command the
execute()function can be used instead of redirection.
:redi[r] =>>{var}Append messages to an existing variable. Only stringvariables can be used.
:redi[r] ENDEnd redirecting messages.
:filt:filter:filt[er][!]
{pattern}{command}:filt[er][!] /{pattern}/
{command}Restrict the output of
{command} to lines matchingwith
{pattern}. For example, to list only xml files:
:filter /\.xml$/ oldfiles
If the [!] is given, restrict the output of{command}to lines that do NOT match{pattern}.
{pattern} is a Vim search pattern. Instead ofenclosing it in / any non-ID character (see
'isident')can be used, so long as it does not appear in
{pattern}.Without the enclosing character the pattern cannotinclude the bar character.
'ignorecase' is not used.
The pattern is matched against the relevant part ofthe output, not necessarily the whole line. Only somecommands support filtering, try it out to check if itworks. Some of the commands that support filtering:
:# - filter whole line
:clist - filter by file name or module name
:command - filter by command name
:files - filter by file name
:highlight - filter by highlight group
:history - filter by history commands
:jumps - filter by file name
:let - filter by variable name
:list - filter whole line
:llist - filter by file name or module name
:marks - filter by text in the current file, or file name for other files
:oldfiles - filter by file name
:registers - filter by register contents (does not work multi-line)
:set - filter by option name
Only normal messages are filtered, error messages arenot.
:sil:silent:silent!:sil[ent][!]
{command}Execute
{command} silently. Normal messages will notbe given or added to the message history.When [!] is added, error messages will also beskipped, and commands and mappings will not be abortedwhen an error is detected.
v:errmsg is still set.When [!] is not used, an error message will causefurther messages to be displayed normally.Redirection, started with
:redir, will continue asusual, although there might be small differences.This will allow redirecting the output of a commandwithout seeing it on the screen. Example:
:redir >/tmp/foobar:silent g/Aap/p:redir END
To execute a Normal mode command silently, use the
:normal command. For example, to search for astring without messages:
:silent exe "normal /path\<CR>"
":silent!" is useful to execute a command that mayfail, but the failure is to be ignored. Example:
:let v:errmsg = "":silent! /^begin:if v:errmsg != "": ... pattern was not found
":silent" also skips the hit-enter prompt.Dialogs that prompt for user input (
confirm(),
'swapfile', …) are never silent.
:uns:unsilent:uns[ilent]
{command}Execute
{command} not silently. Only makes adifference when
:silent was used to get to thiscommand.Use this for giving a message even when
:silent wasused. In this example
:silent is used to avoid themessage about reading the file and
:unsilent to beable to list the first line of each file.
:silent argdo unsilent echo expand('%') .. ": " .. getline(1) :verb:verbose:[count]verb[ose]
{command}Execute
{command} with
'verbose' set to [count]. If[count] is omitted one is used. ":0verbose" can beused to set
'verbose' to zero.The additional use of ":silent" makes messagesgenerated but not displayed.The combination of ":silent" and ":verbose" can beused to generate messages and check them with
v:statusmsg and friends. For example:
:let v:statusmsg = "":silent verbose runtime foobar.vim:if v:statusmsg != "": " foobar.vim could not be found:endif
When concatenating another command, the ":verbose"only applies to the first one:
:4verbose set verbose | set verbose
verbose=4
verbose=0
For logging verbose messages in a file use the
'verbosefile' option.
:verbose-cmdWhen
'verbose' is non-zero, listing the value of a Vim option or a key map oran abbreviation or a user-defined function or a command or a highlight groupor an autocommand will also display where it was last defined. If they weredefined in Lua they will only be located if
'verbose' is set. So Startnvim with -V1 arg to see them. If it was defined manually then therewill be no "Last set" message. When it was defined while executing a function,user command or autocommand, the script in which it was defined is reported.
K[count]KRuns the program given by
'keywordprg' to lookup the
word (defined by
'iskeyword') under or right of thecursor. Default is "man". Works like this:
:tabnew | terminal {program} {keyword} Special cases:
If
'keywordprg' begins with ":" it is invoked as a Vim command with [count].
When
'keywordprg' is equal to "man", a [count] before "K" is inserted after the "man" command and before the keyword. For example, using "2K" while the cursor is on "mkdir", results in:
!man 2 mkdir
When
'keywordprg' is equal to "man -s", a [count] before "K" is inserted after the "-s". If there is no count, the "-s" is removed.
K-lsp-defaultv_K{Visual}KLike "K", but use the visually highlighted text forthe keyword. Only works when the highlighted text isnot more than one line.
gOgOShow a filetype-specific, navigable "outline" of thecurrent buffer. For example, in a
help buffer thisshows the table of contents.
[N]gs
gs:sl:sleep:[N]sl[eep] [N][m]Do nothing for [N] seconds, or [N] milliseconds if [m]was given. "gs" always uses seconds.Default is one second.
:sleep "sleep for one second:5sleep "sleep for five seconds:sleep 100m "sleep for 100 milliseconds10gs "sleep for ten seconds
Can be interrupted withCTRL-C."gs" stands for "goto sleep".While sleeping the cursor is positioned in the text,if at a visible position.Queued messages are processed during the sleep.
:sl!:sleep!:[N]sl[eep]! [N][m]Same as above, but hide the cursor.
g==g==Executes the current code block.
2. Using Vim like less or moreless
If you use the less or more program to view a file, you don't get syntaxhighlighting. Thus you would like to use Vim instead. You can do this byusing the shell script "$VIMRUNTIME/scripts/less.sh".
This shell script uses the Vim script "$VIMRUNTIME/scripts/less.vim". It setsup mappings to simulate the commands that less supports. Otherwise, you canstill use the Vim commands.
This isn't perfect. For example, when viewing a short file Vim will still usethe whole screen. But it works well enough for most uses, and you get syntaxhighlighting.
The "h" key will give you a short overview of the available commands.
If you want to set options differently when using less, define theLessInitFunc in your vimrc, for example:
func LessInitFunc() set nocursorcolumn nocursorlineendfunc
Nvim supports commenting and uncommenting of lines based on
'commentstring'.
Acting on a single line behaves as follows:
If the line matches
'commentstring', the comment markers are removed (e.g.
/*foo*/ is transformed to
foo).
Otherwise the comment markers are added to the current line (e.g.foo is transformed to/*foo*/). Blank lines are ignored.
Acting on multiple lines behaves as follows:
If each affected non-blank line matches
'commentstring', then all comment markers are removed.
Otherwise all affected lines are converted to comments; blank lines are transformed to empty comments (e.g./**/). Comment markers are aligned to the least indented line.
Matching
'commentstring' does not account for whitespace in comment markers.Removing comment markers is first attempted exactly, with fallback to usingmarkers trimmed from whitespace.
gcgc-defaultgc{motion}Comment or uncomment lines covered by
{motion}.
gccgcc-defaultgccComment or uncomment [count] lines starting at cursor.
o_gco_gc-defaultgcText object for the largest contiguous block ofnon-blank commented lines around the cursor (e.g.
gcgc uncomments a comment block;
dgc deletes it).Works only in Operator-pending mode.