Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
:map <F2> a<C-R>=strftime("%c")<CR><Esc>This appends the current date and time after the cursor (in <> notation <>).
{lhs}
{rhs}
mapmode-nvo :map {lhs}
{rhs}
mapmode-n :nm :nmap
:vm[ap] {lhs}
{rhs}
mapmode-v :vm :vmap
:xm[ap] {lhs}
{rhs}
mapmode-x :xm :xmap
:smap {lhs}
{rhs}
mapmode-s :smap {lhs}
{rhs}
mapmode-o :om :omap
:map! {lhs}
{rhs}
mapmode-ic :map! {lhs}
{rhs}
mapmode-i :im :imap
:lm[ap] {lhs}
{rhs}
mapmode-l :lm :lma :lmap
:cm[ap] {lhs}
{rhs}
mapmode-c :cm :cmap
:tma[p] {lhs}
{rhs}
mapmode-t :tma :tmap
Map the key sequence {lhs}
to {rhs}
for the modes
where the map command applies. The result, including
{rhs}
, is then further scanned for mappings. This
allows for nested and recursive use of mappings.
Note: Trailing spaces are included in the {rhs}
,
because space is a valid Normal mode command.
See map-trailing-white.{lhs}
{rhs}
mapmode-nvo :no :noremap :nor
:nn[oremap] {lhs}
{rhs}
mapmode-n :nn :nnoremap
:vn[oremap] {lhs}
{rhs}
mapmode-v :vn :vnoremap
:xn[oremap] {lhs}
{rhs}
mapmode-x :xn :xnoremap
:snor[emap] {lhs}
{rhs}
mapmode-s :snor :snore :snoremap
:ono[remap] {lhs}
{rhs}
mapmode-o :ono :onoremap
:no[remap]! {lhs}
{rhs}
mapmode-ic :no! :noremap!
:ino[remap] {lhs}
{rhs}
mapmode-i :ino :inor :inoremap
:ln[oremap] {lhs}
{rhs}
mapmode-l :ln :lnoremap
:cno[remap] {lhs}
{rhs}
mapmode-c :cno :cnor :cnoremap
:tno[remap] {lhs}
{rhs}
mapmode-t :tno :tnoremap
Map the key sequence {lhs}
to {rhs}
for the modes
where the map command applies. Disallow mapping of
{rhs}
, to avoid nested and recursive mappings. Often
used to redefine a command.
Note: Keys in {rhs}
also won't trigger abbreviation,
with the exception of i_CTRL-] and c_CTRL-].
Note: When <Plug>
appears in the {rhs}
this part is
always applied even if remapping is disallowed.{lhs}
mapmode-nvo :unm :unmap
:nun[map] {lhs}
mapmode-n :nun :nunmap
:vu[nmap] {lhs}
mapmode-v :vu :vunmap
:xu[nmap] {lhs}
mapmode-x :xu :xunmap
:sunm[ap] {lhs}
mapmode-s :sunm :sunmap
:ou[nmap] {lhs}
mapmode-o :ou :ounmap
:unm[ap]! {lhs}
mapmode-ic :unm! :unmap!
:iu[nmap] {lhs}
mapmode-i :iu :iunmap
:lu[nmap] {lhs}
mapmode-l :lu :lunmap
:cu[nmap] {lhs}
mapmode-c :cu :cun :cunmap
:tunma[p] {lhs}
mapmode-t :tunma :tunmap
Remove the mapping of {lhs}
for the modes where the
map command applies. The mapping may remain defined
for other modes where it applies.
It also works when {lhs}
matches the {rhs}
of a
mapping. This is for when an abbreviation applied.
Note: Trailing spaces are included in the {lhs}
.
See map-trailing-white.<buffer>
argument to remove buffer-local
mappings :map-<buffer>
Warning: This also removes the default-mappings.{lhs}
mapmode-nvo :map_l {lhs}
mapmode-n :nmap_l {lhs}
mapmode-v :vmap_l {lhs}
mapmode-x :xmap_l {lhs}
mapmode-s :smap_l {lhs}
mapmode-o :omap_l {lhs}
mapmode-ic :map_l! {lhs}
mapmode-i :imap_l {lhs}
mapmode-l :lmap_l {lhs}
mapmode-c :cmap_l {lhs}
mapmode-t :tmap_l {lhs}
in the modes where the map command applies.:imap aa foo :imap aaa barWhen Vim has read "aa", it will need to get another character to be able to decide if "aa" or "aaa" should be mapped. This means that after typing "aa" that mapping won't get expanded yet, Vim is waiting for another character. If you type a space, then "foo" will get inserted, plus the space. If you type "a", then "bar" will get inserted.
:map @@ foo :unmap @@ | printBecause it tries to unmap "@@ ", including the white space before the command separator "|". Other examples with trailing white space:
unmap @@ unmap @@ " commentAn error will be issued, which is very hard to identify, because the ending whitespace character in
unmap @@
is not visible.unmap @@| " comment
:map <buffer> ,w /[.,;]<CR>Then you can map ",w" to something else in another buffer:
:map <buffer> ,w /[#&!]<CR>The local buffer mappings are used before the global ones. See
<nowait>
below
to make a short local mapping not taking effect when a longer global one
exists.
The "<buffer>" argument can also be used to clear mappings::unmap <buffer> ,w :mapclear <buffer>Local mappings are also cleared when a buffer is deleted, but not when it is unloaded. Just like local option values. Also see map-precedence.
<nowait>
argument. Then the mapping will be used when it matches, Vim does
not wait for more characters to be typed. However, if the characters were
already typed they are used.
Note that this works when the <nowait>
mapping fully matches and is found
before any partial matches. This works when:
:map <silent> ,h /Header<CR>The search string will not be echoed when using this mapping. Messages from the executed command are still given though. To shut them up too, add a ":silent" in the executed command:
:map <silent> ,h :exe ":silent normal /Header\r"<CR>Note that the effect of a command might also be silenced, e.g., when the mapping selects another entry for command line completion it won't be displayed. Prompts will still be given, e.g., for inputdialog(). Using "<silent>" for an abbreviation is possible, but will cause redrawing of the command line to fail.
{rhs}
using mappings that were defined local to a script, starting with
"<SID>". This can be used to avoid that mappings from outside a script
interfere (e.g., when CTRL-V
is remapped in mswin.vim), but do use other
mappings defined in the script.
Note: ":map <script>
" and ":noremap <script>
" do the same thing. The
"<script>" overrules the command name. Using ":noremap <script>
" is
preferred, because it's clearer that remapping is (mostly) disabled.:map <unique> ,w /[#&!]<CR>When defining a local mapping, there will also be a check if a global map already exists which is equal. Example of what will fail:
:map ,w /[#&!]<CR> :map <buffer> <unique> ,w /[.,;]<CR>If you want to map a key and then have it do what it was originally mapped to, have a look at maparg().
{rhs}
that is used. Example::inoremap <expr> . <SID>InsertDot()The result of the s:InsertDot() function will be inserted. It could check the text before the cursor and start omni completion when some condition is met. Using a script-local function is preferred, to avoid polluting the global namespace. Use
<SID>
in the RHS so that the script that the mapping was
defined in can be found.{lhs}
. You
should not either insert or change the v:char.func StoreColumn() let g:column = col('.') return 'x' endfunc nnoremap <expr> x StoreColumn() nmap ! f!xYou will notice that g:column has the value from before executing "f!", because "x" is evaluated before "f!" is executed. This can be solved by inserting
<Ignore>
before the character that is
expression-mapped:nmap ! f!<Ignore>xBe very careful about side effects! The expression is evaluated while obtaining characters, you may very well make the command dysfunctional. Therefore the following is blocked for
<expr>
mappings:
inoremap <expr> <C-L> nr2char(getchar()) inoremap <expr> <C-L>x "foo"If you now type
CTRL-L
nothing happens yet, Vim needs the next character to
decide what mapping to use. If you type 'x' the second mapping is used and
"foo" is inserted. If you type any other key the first mapping is used,
getchar() gets the typed key and returns it.let counter = 0 inoremap <expr> <C-L> ListItem() inoremap <expr> <C-R> ListReset() func ListItem() let g:counter += 1 return g:counter .. '. ' endfunc func ListReset() let g:counter = 0 return '' endfuncCTRL-L inserts the next number,
CTRL-R
resets the count. CTRL-R
returns an
empty string, so that nothing is inserted.<Cmd>
pseudokey begins a "command mapping", which executes the command
directly without changing modes. Where you might use ":...<CR>" in the
{rhs}
of a mapping, you can instead use "<Cmd>...<CR>".
Example:noremap x <Cmd>echo mode(1)<CR>
:<C-U>
in Visual and Operator-pending mode, or
<C-O>:
in Insert mode, because the commands are executed directly in the
current mode, instead of always going to Normal mode. Visual mode is
preserved, so tricks with gv are not needed. Commands can be invoked
directly in Command-line mode (which would otherwise require timer hacks).
Example of using <Cmd>
halfway Insert mode:nnoremap <F3> aText <Cmd>echo mode(1)<CR> Added<Esc>Unlike
<expr>
mappings, there are no special restrictions on the <Cmd>
command: it is executed as if an (unrestricted) autocommand was invoked
or an async event was processed.<Cmd>
avoids mode-changes (unlike ":") it does not trigger
CmdlineEnter and CmdlineLeave events. This helps performance.
<silent>
.
{rhs}
is not subject to abbreviations nor to other mappings, even if the
mapping is recursive.
line('v')
and col('v')
to get one end of the
Visual area, the cursor is at the other end.
<Cmd>
commands must terminate, that is, they must be followed by <CR>
in the
{rhs}
of the mapping definition. Command-line mode is never entered. To use
a literal <CR>
in the {rhs}
, use <lt>.:omap { wmakes "y{" work like "yw" and "d{" like "dw".
onoremap <silent> F :<C-U>normal! 0f(hviw<CR>The
CTRL-U
(<C-U>
) is used to remove the range that Vim may insert. The
Normal mode commands find the first '(' character and select the first word
before it. That usually is the function name.:map xx something-difficult :ounmap xxLikewise for a mapping for Visual and Operator-pending mode or Normal and Operator-pending mode.
CTRL-^
command i_CTRL-^ c_CTRL-^. These commands change the value of
the 'iminsert' option. When starting to enter a normal command line (not a
search pattern) the mappings are disabled until a CTRL-^
is typed. The state
last used is remembered for Insert mode and Search patterns separately. The
state for Insert mode is also used when typing a character as an argument to
command like "f" or "t".
Language mappings will never be applied to already mapped characters. They
are only used for typed characters. This assumes that the language mapping
was already done when typing the mapping. Correspondingly, language mappings
are applied when recording macros, rather than when applying them.
<Space>
Normal, Visual, Select and Operator-pending
n Normal
v Visual and Select
s Select
x Visual
o Operator-pending
! Insert and Command-line
i Insert
l ":lmap" mappings for Insert, Command-line and Lang-Arg
c Command-line
t Terminal-Job{rhs}
a special character can appear:
* indicates that it is not remappable
& indicates that only script-local mappings are remappable
@ indicates a buffer-local mapping{lhs}
up to the end of the line
(or '|') is considered to be part of {rhs}
. This allows the {rhs}
to end
with a space.{lhs}
and {rhs}
in the raw form. If a
description was added using nvim_set_keymap() or nvim_buf_set_keymap()
then the pattern is also matched against it.:verbose map <C-W>* n <C-W>* * <C-W><C-S>* Last set from ~/.config/nvim/init.vimSee :verbose-cmd for more information.
CTRL-K
and then hit the function key, or use the form "<F2>", "<F10>",
"<Up>", "<S-Down>", "<S-F7>", etc. (see table of keys key-notation, all keys
from <Up>
can be used).CTRL-V
is mentioned here as a special character for mappings
and abbreviations. When 'cpoptions' does not contain 'B', a backslash can
also be used like CTRL-V
. The <> notation can be fully used then <>. But
you cannot use "<C-V>" like CTRL-V
to escape the special meaning of what
follows.{rhs}
, the special
sequence "<Bslash>" can be used. This avoids the need to double backslashes
when using nested mappings.CTRL-C
in the {lhs}
is possible, but it will only work when Vim is
waiting for a key, not when Vim is busy with something. When Vim is busy
CTRL-C interrupts/breaks the command.
When using the GUI version on MS-Windows CTRL-C
can be mapped to allow a Copy
command to the clipboard. Use CTRL-Break
to interrupt Vim.{lhs}
precede it with a CTRL-V
(type two CTRL-V
s for
each space).
map_space_in_rhs map-space_in_rhs
If you want a {rhs}
that starts with a space, use "<Space>". To be fully Vi
compatible (but unreadable) don't use the <> notation, precede {rhs}
with a
single CTRL-V
(you have to type CTRL-V
two times).
map_empty_rhs map-empty-rhs
You can create an empty {rhs}
by typing nothing after a single CTRL-V
(you
have to type CTRL-V
two times). Unfortunately, you cannot do this in a vimrc
file.
<Nop>
An easier way to get a mapping that doesn't produce anything, is to use
"<Nop>" for the {rhs}
. For example, to disable function key 8::map <F8> <Nop> :map! <F8> <Nop>
:set encoding=latin1 :imap <M-C> foo :set encoding=utf-8The mapping for
<M-C>
is defined with the latin1 encoding, resulting in a 0xc3
byte. If you type the character á (0xe1 <M-a>
) in UTF-8 encoding this is the
two bytes 0xc3 0xa1. You don't want the 0xc3 byte to be mapped then or
otherwise it would be impossible to type the á character.map <Leader>A oanother line<Esc>Works like:
map \A oanother line<Esc>But after:
let mapleader = ","It works like:
map ,A oanother line<Esc>Note that the value of "g:mapleader" is used at the moment the mapping is defined. Changing "g:mapleader" after that has no effect for already defined mappings.
<LocalLeader>
is just like <Leader>
, except that it uses "maplocalleader"
instead of "mapleader". <LocalLeader>
is to be used for mappings which are
local to a buffer. Example::map <buffer> <LocalLeader>A oanother line<Esc>
<Leader>
should be used and in a filetype plugin
<LocalLeader>
. "mapleader" and "maplocalleader" can be equal. Although, if
you make them different, there is a smaller chance of mappings from global
plugins to clash with mappings for filetype plugins. For example, you could
keep "mapleader" at the default backslash, and set "maplocalleader" to an
underscore.<Char>
construct can be used:
<Char-123>
character 123
<Char-033>
character 27
<Char-0x7f>
character 127
<S-Char-114>
character 114 ('r') shifted ('R')
This is useful to specify a (multibyte) character in a 'keymap' file.
Upper and lowercase differences are ignored."
character is considered to be part of the {lhs}
or {rhs}
. However, one can
use |"
, since this starts a new, empty command with a comment.{rhs}
.
There are three methods:
<Bar>
always :map _l :!ls <Bar>
more^M
\| 'b' is not in 'cpoptions' :map _l :!ls \| more^M
^V| always :map _l :!ls ^V| more^MCTRL-V
; to get one CTRL-V
you have to type it twice; you
cannot use the <> notation "<C-V>" here).<CR>
is recommended for
this (see <>). Example::map _ls :!ls -l %:S<CR>:echo "the end"<CR>To avoid mapping of the characters you type in insert or Command-line mode, type a
CTRL-V
first.
map-error CTRL-X
is not mapped. This was done to be able to use all the named
registers and marks, even when the command with the same name has been
mapped.{lhs}
. You will have to avoid keys that are used for Vim commands,
otherwise you would not be able to use those commands anymore. Here are a few
suggestions:
<F2>
, <F3>
, etc.. Also the shifted function keys <S-F1>
,
<S-F2>
, etc. Note that <F1>
is already used for the help command.
CTRL-P
and
CTRL-N
. Use an extra character to allow more mappings.
<Leader>
and one or more other keys. This is especially
useful in scripts. mapleader
{key}
^D" to find out if
a key is used for some command. ({key}
is the specific key you want to find
out about, ^D is CTRL-D
).:map <F3> o#include :map <M-g> /foo<CR>cwbar<Esc> :map _x d/END/e<CR> :map! qq quadrillion questionsMultiplying a count
{lhs}
. For example, with this mapping::map <F4> 3wTyping 2<F4> will result in "23w". Thus not moving 2 * 3 words but 23 words. If you want to multiply counts use the expression register:
:map <F4> @='3w'<CR>The part between quotes is the expression being executed. @=
<nowait>
, even if a longer mapping
has the same prefix. For example, given the following two mappings::map <buffer> <nowait> \a :echo "Local \a"<CR> :map \abc :echo "Global \abc"<CR>When typing \a the buffer-local mapping will be used immediately. Vim will not wait for more characters to see if the user might be typing \abc.
<F1>
to <F4>
the actual key code generated may correspond to
<xF1>
to <xF4>
. There are mappings from <xF1>
to <F1>
, <xF2>
to <F2>
, etc.,
but these are not recognized after another half a mapping. Make sure the
key codes for <F1>
to <F4>
are correct::set <F1>=<type CTRL-V><type F1>
<F1>
as four characters. The part after the "=" must be done with
the actual keys, not the literal text.
Another solution is to use the actual key code in the mapping for the second
special key::map <F1><Esc>OP :echo "yes"<CR>Don't type a real
<Esc>
, Vim will recognize the key code and replace it with
<F1>
anyway.{lhs}
in the {rhs}
you have a recursive mapping. When
{lhs}
is typed, it will be replaced with {rhs}
. When the {lhs}
which is
included in {rhs}
is encountered it will be replaced with {rhs}
, and so on.
This makes it possible to repeat a command an infinite number of times. The
only problem is that the only way to stop this is by causing an error. The
macros to solve a maze uses this, look there for an example. There is one
exception: If the {rhs}
starts with {lhs}
, the first character is not mapped
again (this is Vi compatible).
For example::map ab abcdwill execute the "a" command and insert "bcd" in the text. The "ab" in the
{rhs}
will not be mapped again.:noremap k j :noremap j kThis will exchange the cursor up and down commands.
{lhs}
. For example, if you use::map x y :map y xVim will replace x with y, and then y with x, etc. When this has happened 'maxmapdepth' times (default 1000), Vim will give the error message "recursive mapping".
<A-k>
form can be used. Note that <A-k>
and <A-K>
are different, the latter will use an upper case letter. Actually,
<A-K>
and <A-S-K>
are the same. Instead of "A" you can use "M". If you have
an actual Meta modifier key, please see :map-meta-keys.{key}
within 'ttimeoutlen'
milliseconds, the ESC is interpreted as:
<ALT-{key}>
otherwise it is interpreted as two key presses:
<ESC>
{key}
<M-a>
actually is for using the Alt key. That can be
confusing! It cannot be changed, it would not be backwards compatible.:imap <T-b> terrible1.12 MAPPING SUPER-KEYS or COMMAND-KEYS :map-super-keys :map-cmd-key
:imap <D-b> barritone
{motion}
command. To define your own operator
you must create a mapping that first sets the 'operatorfunc' option and then
invoke the g@ operator. After the user types the {motion}
command the
specified function will be called.{motion}
, the '] mark on the last
character of the text.
The function is called with one String argument:
"line" {motion}
was linewise
"char" {motion}
was charwise
"block" {motion}
was blockwise-visual
The type can be forced, see forced-motion.<F4>
:nnoremap <expr> <F4> CountSpaces() xnoremap <expr> <F4> CountSpaces() " doubling <F4> works on a line nnoremap <expr> <F4><F4> CountSpaces() .. '_' function CountSpaces(context = {}, type = '') abort if a:type == '' let context = #{ \ dot_command: v:false, \ extend_block: '', \ virtualedit: [&l:virtualedit, &g:virtualedit], \ } let &operatorfunc = function('CountSpaces', [context]) set virtualedit=block return 'g@' endif let save = #{ \ clipboard: &clipboard, \ selection: &selection, \ virtualedit: [&l:virtualedit, &g:virtualedit], \ register: getreginfo('"'), \ visual_marks: [getpos("'<"), getpos("'>")], \ } try set clipboard= selection=inclusive virtualedit= let commands = #{ \ line: "'[V']", \ char: "`[v`]", \ block: "`[\<C-V>`]", \ }[a:type] let [_, _, col, off] = getpos("']") if off != 0 let vcol = getline("'[")->strpart(0, col + off)->strdisplaywidth() if vcol >= [line("'["), '$']->virtcol() - 1 let a:context.extend_block = '$' else let a:context.extend_block = vcol .. '|' endif endif if a:context.extend_block != '' let commands ..= 'oO' .. a:context.extend_block endif let commands ..= 'y' execute 'silent noautocmd keepjumps normal! ' .. commands echomsg getreg('"')->count(' ') finally call setreg('"', save.register) call setpos("'<", save.visual_marks[0]) call setpos("'>", save.visual_marks[1]) let &clipboard = save.clipboard let &selection = save.selection let [&l:virtualedit, &g:virtualedit] = get(a:context.dot_command ? save : a:context, 'virtualedit') let a:context.dot_command = v:true endtry endfunctionAn
<expr>
mapping is used to be able to fetch any prefixed count and register.
This also avoids using a command line, which would trigger CmdlineEnter and
CmdlineLeave autocommands."*
or "+
registers, if its value contains the item unnamed
or unnamedplus
.mode()
function will return the state as it will be after applying the
operator.nnoremap <F4> <Cmd>let &opfunc='{t -> \ getline(".") \ ->split("\\zs") \ ->insert("\"", col("'']")) \ ->insert("\"", col("''[") - 1) \ ->join("") \ ->setline(".")}'<CR>g@
<Esc>
that ends Insert mode or the <CR>
that ends a
command. The non-keyword character which ends the abbreviation is inserted
after the expanded abbreviation. An exception to this is the character <C-]>
,
which is used to expand an abbreviation without inserting any extra
characters.:ab hh hello
{CURSOR}
is where you type a non-keyword character):ab foo four old otters
:ab #i #include
:ab ;; <endofline>
<endofline>
"CTRL-V
before the character
that would trigger the abbreviation. E.g. CTRL-V
<Space>
. Or type part of
the abbreviation, exit insert mode with <Esc>
, re-enter insert mode with "a"
and type the rest.CTRL-V
twice somewhere in
the abbreviation to avoid it to be replaced. A CTRL-V
in front of a normal
character is mostly ignored otherwise.:iab if if ()<Left>You can even do more complicated things. For example, to consume the space typed after an abbreviation:
func Eatchar(pat) let c = nr2char(getchar(0)) return (c =~ a:pat) ? '' : c endfunc iabbr <silent> if if ()<Left><C-R>=Eatchar('\s')<CR>There are no default abbreviations.
:abb <buffer> FF for (i = 0; i < ; ++i)
:verbose abbreviate ! teh the Last set from /home/abcd/vim/abbr.vimSee :verbose-cmd for more information.
{lhs}
list the abbreviations that start with {lhs}
You may need to insert a CTRL-V
(type it twice) to
avoid that a typed {lhs}
is expanded, since
command-line abbreviations apply here.<expr>
] [<buffer>
] {lhs}
{rhs}
add abbreviation for {lhs}
to {rhs}
. If {lhs}
already
existed it is replaced with the new {rhs}
. {rhs}
may
contain spaces.
See :map-<expr> for the optional <expr>
argument.
See :map-<buffer> for the optional <buffer>
argument.<buffer>
] {lhs}
Remove abbreviation for {lhs}
from the list. If none
is found, remove abbreviations in which {lhs}
matches
with the {rhs}
. This is done so that you can even
remove abbreviations after expansion. To avoid
expansion insert a CTRL-V
(type it twice).<expr>
] [<buffer>
] [lhs] [rhs]
same as ":ab", but no remapping for this {rhs}
<expr>
] [<buffer>
] [lhs] [rhs]
same as ":ab", but for Command-line mode only.<expr>
] [<buffer>
] [lhs] [rhs]
same as ":ab", but for Command-line mode only and no
remapping for this {rhs}
<expr>
] [<buffer>
] [lhs] [rhs]
same as ":ab", but for Insert mode only and no
remapping for this {rhs}
CTRL-V
s need to be typed depends on how you enter the
abbreviation. This also applies to mappings. Let's use an example here.<Esc>
character. When you
type the ":ab" command in Vim, you have to enter this: (here ^V is a CTRL-V
and ^[ is <Esc>
)<SNR>
, followed by a number that's unique for the script, and an
underscore. Example::map <SID>Addwould define a mapping "<SNR>23_Add".
<SID>
cannot be correctly
expanded, use the expand() function:let &includexpr = expand('<SID>') .. 'My_includeexpr()'Otherwise, using "<SID>" outside of a script context is an error.
func s:ScriptNumber() return matchstr(expand('<SID>'), '<SNR>\zs\d\+\ze_') endfuncThe "<SNR>" will be shown when listing functions and mappings. This is useful to find out what they are defined to.
<SNR>
number is.:command Rename ... :command Renumber ... :Rena " Means "Rename" :Renu " Means "Renumber" :Ren " Error - ambiguous :command Paste ...It is recommended that full names for user-defined commands are used in scripts.
filter Pyth command:com[mand]
{cmd}
List the user-defined commands that start with {cmd}
:verbose command TOhtml
<line1>
, <line2>
){attr}
...] {cmd}
{repl}
Define a user command. The name of the command is
{cmd}
and its replacement text is {repl}
. The
command's attributes (see below) are {attr}
. If the
command already exists, an error is reported, unless a
! is specified, in which case the command is
redefined. There is one exception: When sourcing a
script again, a command that was previously defined in
that script will be silently replaced.{cmd}
E1237 {cmd}
that was defined
for the current buffer.:let s:error = "None" :command -nargs=1 Error echoerr <args>
:source script1.vim :let s:error = "Wrong!" :Error s:errorExecuting script2.vim will result in "None" being echoed. Not what you intended! Calling a function may be an alternative.
CTRL-D
is hit
-complete=user user names
-complete=var user variables
-complete=custom,{func} custom completion, defined via {func}
-complete=customlist,{func} custom completion, defined via {func}
{func}
"
or the "customlist,{func}
" completion argument. The {func}
part should be a
function with the following signature::function {func}(ArgLead, CmdLine, CursorPos)The function need not use all these arguments. The function should provide the completion candidates as the return value.
:com -complete=custom,ListUsers -nargs=1 Finger !finger <args> :fun ListUsers(A,L,P) : return system("cut -d: -f1 /etc/passwd") :endfunThe following example completes filenames from the directories specified in the 'path' option:
:com -nargs=1 -bang -complete=customlist,EditFileComplete \ EditFile edit<bang> <args> :fun EditFileComplete(A,L,P) : return split(globpath(&path, a:A), "\n") :endfun
.
, $
or %
which by default correspond to the current line, last line and the whole
buffer, relate to arguments, (loaded) buffers, windows or tab pages.{nvim-api}
Commands can show an 'inccommand' (as-you-type) preview by defining a preview
handler (only from Lua, see nvim_create_user_command()).function cmdpreview(opts, ns, buf)
-- If invoked as a preview callback, performs 'inccommand' preview by -- highlighting trailing whitespace in the current buffer. local function trim_space_preview(opts, preview_ns, preview_buf) vim.cmd('hi clear Whitespace') local line1 = opts.line1 local line2 = opts.line2 local buf = vim.api.nvim_get_current_buf() local lines = vim.api.nvim_buf_get_lines(buf, line1 - 1, line2, false) local preview_buf_line = 0 for i, line in ipairs(lines) do local start_idx, end_idx = string.find(line, '%s+$') if start_idx then -- Highlight the match vim.api.nvim_buf_add_highlight( buf, preview_ns, 'Substitute', line1 + i - 2, start_idx - 1, end_idx ) -- Add lines and set highlights in the preview buffer -- if inccommand=split if preview_buf then local prefix = string.format('|%d| ', line1 + i - 1) vim.api.nvim_buf_set_lines( preview_buf, preview_buf_line, preview_buf_line, false, { prefix .. line } ) vim.api.nvim_buf_add_highlight( preview_buf, preview_ns, 'Substitute', preview_buf_line, #prefix + start_idx - 1, #prefix + end_idx ) preview_buf_line = preview_buf_line + 1 end end end -- Return the value of the preview type return 2 end -- Trims all trailing whitespace in the current buffer. local function trim_space(opts) local line1 = opts.line1 local line2 = opts.line2 local buf = vim.api.nvim_get_current_buf() local lines = vim.api.nvim_buf_get_lines(buf, line1 - 1, line2, false) local new_lines = {} for i, line in ipairs(lines) do new_lines[i] = string.gsub(line, '%s+$', '') end vim.api.nvim_buf_set_lines(buf, line1 - 1, line2, false, new_lines) end -- Create the user command vim.api.nvim_create_user_command( 'TrimTrailingWhitespace', trim_space, { nargs = '?', range = '%', addr = 'lines', preview = trim_space_preview } )
{repl}
for a user defined command is scanned for special
escape sequences, using <...> notation. Escape sequences are replaced with
values from the entered command line, and all other text is copied unchanged.
The resulting string is executed as an Ex command. To avoid the replacement
use <lt>
in place of the initial <. Thus to include "<bang>" literally use
"<lt>bang>".<line1>
The starting line of the command range.
<line2> <line2>
The final line of the command range.
<range> <range>
The number of items in the command range: 0, 1 or 2
<count> <count>
Any count supplied (as described for the '-range'
and '-count' attributes).
<bang> <bang>
(See the '-bang' attribute) Expands to a ! if the
command was executed with a ! modifier, otherwise
expands to nothing.
<mods> <q-mods> :command-modifiers
<mods>
The command modifiers, if specified. Otherwise, expands to
nothing. Supported modifiers are :aboveleft, :belowright,
:botright, :browse, :confirm, :hide, :horizontal,
:keepalt, :keepjumps, :keepmarks, :keeppatterns,
:leftabove, :lockmarks, :noautocmd, :noswapfile,
:rightbelow, :sandbox, :silent, :tab, :topleft,
:unsilent, :verbose, and :vertical.
Note that :filter is not supported.
Examples:command! -nargs=+ -complete=file MyEdit \ for f in expand(<q-args>, 0, 1) | \ exe '<mods> split ' .. f | \ endfor function! SpecialEdit(files, mods) for f in expand(a:files, 0, 1) exe a:mods .. ' split ' .. f endfor endfunction command! -nargs=+ -complete=file Sedit \ call SpecialEdit(<q-args>, <q-mods>)
<reg>
(See the '-register' attribute) The optional register,
if specified. Otherwise, expands to nothing. <register>
is a synonym for this.
<args> <args>
The command arguments, exactly as supplied (but as
noted above, any count or register can consume some
of the arguments, which are then not part of <args>
).
<lt>
A single '<' (Less-Than) character. This is needed if you
want to get a literal copy of one of these escape sequences
into the expansion - for example, to get <bang>
, use
<lt>
bang>.<q-args>
) then the value is quoted in such a way as to make it a valid value
for use in an expression. This uses the argument as one single value.
When there is no argument <q-args>
is an empty string. See the
q-args-example below.
<f-args> <f-args>
("function args"). This splits the command
arguments at spaces and tabs, quotes each argument individually, and the
<f-args>
sequence is replaced by the comma-separated list of quoted arguments.
See the Mycmd example below. If no arguments are given <f-args>
is removed.
To embed whitespace into an argument of <f-args>
, prepend a backslash.
<f-args>
replaces every pair of backslashes (\\) with one backslash. A
backslash followed by a character other than white space or a backslash
remains unmodified. Also see f-args-example below. Overview:<f-args>
" Delete everything after here to the end :com Ddel +,$d " Rename the current buffer :com -nargs=1 -bang -complete=file Ren f <args>|w<bang> " Replace a range with the contents of a file " (Enter this all as one line) :com -range -nargs=1 -complete=file Replace <line1>-pu_|<line1>,<line2>d|r <args>|<line1>d " Count the number of lines in the range :com! -range -nargs=0 Lines echo <line2> - <line1> + 1 "lines"
<f-args>
):com -nargs=* Mycmd call Myfunc(<f-args>)When executed as:
:Mycmd arg1 arg2This will invoke:
:call Myfunc("arg1","arg2")
:function Allargs(command) : let i = 0 : while i < argc() : if filereadable(argv(i)) : execute "e " .. argv(i) : execute a:command : endif : let i = i + 1 : endwhile :endfunction :command -nargs=+ -complete=command Allargs call Allargs(<q-args>)The command Allargs takes any Vim command(s) as argument and executes it on all files in the argument list. Usage example (note use of the "e" flag to ignore errors and the "update" command to write modified buffers):
:Allargs %s/foo/bar/ge|updateThis will invoke:
:call Allargs("%s/foo/bar/ge|update")