Movatterモバイル変換


[0]ホーム

URL:


Map

Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.


Key mapping, abbreviations and user-defined commands.
This subject is introduced in sections05.3,24.7 and40.1 of the usermanual.

1. Key mappingkey-mappingmapping

Key mapping is used to change the meaning of typed keys. The most common useis to define a sequence of commands for a function key. Example:
:map <F2> a<C-R>=strftime("%c")<CR><Esc>
This appends the current date and time after the cursor (in <> notation<>).

1.1 MAP COMMANDS:map-commands

There are commands to enter new mappings, remove mappings and list mappings.Seemap-overview for the various forms of "map" and their relationships withmodes.
{lhs}means left-hand-side{lhs}{rhs}means right-hand-side{rhs}
:map{lhs}{rhs}mapmode-nvo:map
:nm[ap]{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
:om[ap]{lhs}{rhs}mapmode-o:om:omap:map!{lhs}{rhs}mapmode-ic:map!
:im[ap]{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:tmapMap the key sequence{lhs} to{rhs} for the modeswhere the map command applies. The result, including{rhs}, is then further scanned for mappings. Thisallows for nested and recursive use of mappings.Note: Trailing spaces are included in the{rhs},because space is a valid Normal mode command.Seemap-trailing-white.
:nore:norem:no[remap]{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:tnoremapMap the key sequence{lhs} to{rhs} for the modeswhere the map command applies. Disallow mapping of{rhs}, to avoid nested and recursive mappings. Oftenused to redefine a command.Note: Keys in{rhs} also won't trigger abbreviation,with the exception ofi_CTRL-] andc_CTRL-].Note: When<Plug> appears in the{rhs} this part isalways applied even if remapping is disallowed.
:unm[ap]{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:tunmapRemove the mapping of{lhs} for the modes where themap command applies. The mapping may remain definedfor other modes where it applies.It also works when{lhs} matches the{rhs} of amapping. This is for when an abbreviation applied.Note: Trailing spaces are included in the{lhs}.Seemap-trailing-white.
:mapc[lear]mapmode-nvo:mapc:mapclear:nmapc[lear]mapmode-n:nmapc:nmapclear:vmapc[lear]mapmode-v:vmapc:vmapclear:xmapc[lear]mapmode-x:xmapc:xmapclear:smapc[lear]mapmode-s:smapc:smapclear:omapc[lear]mapmode-o:omapc:omapclear:mapc[lear]!mapmode-ic:mapc!:mapclear!:imapc[lear]mapmode-i:imapc:imapclear:lmapc[lear]mapmode-l:lmapc:lmapclear:cmapc[lear]mapmode-c:cmapc:cmapclear:tmapc[lear]mapmode-t:tmapc:tmapclearRemove ALL mappings for the modes where the mapcommand applies.Use the<buffer> argument to remove buffer-localmappings:map-<buffer>Warning: This also removes thedefault-mappings.
:mapmapmode-nvo :nm[ap]mapmode-n :vm[ap]mapmode-v :xm[ap]mapmode-x :sm[ap]mapmode-s :om[ap]mapmode-o :map!mapmode-ic :im[ap]mapmode-i :lm[ap]mapmode-l :cm[ap]mapmode-c :tma[p]mapmode-t List all key mappings for the modes where the mapcommand applies. Note that ":map" and ":map!" areused most often, because they include the other modes.
:map{lhs}mapmode-nvo:map_l
:nm[ap]{lhs}mapmode-n:nmap_l
:vm[ap]{lhs}mapmode-v:vmap_l
:xm[ap]{lhs}mapmode-x:xmap_l
:sm[ap]{lhs}mapmode-s:smap_l
:om[ap]{lhs}mapmode-o:omap_l
:map!{lhs}mapmode-ic:map_l!
:im[ap]{lhs}mapmode-i:imap_l
:lm[ap]{lhs}mapmode-l:lmap_l
:cm[ap]{lhs}mapmode-c:cmap_l
:tma[p]{lhs}mapmode-t:tmap_l
List the key mappings for the key sequences startingwith{lhs} in the modes where the map command applies.
These commands are used to map a key or key sequence to a string ofcharacters. You can use this to put command sequences under function keys,translate one key into another, etc. See:mkexrc for how to save andrestore the current mappings.
map-ambiguous
When two mappings start with the same sequence of characters, they areambiguous. Example:
:imap aa foo:imap aaa bar
When Vim has read "aa", it will need to get another character to be able todecide 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 youtype "a", then "bar" will get inserted.
Trailing white space
map-trailing-white
This unmap command does NOT work:
:map @@ foo:unmap @@ | print
Because it tries to unmap "@@ ", including the white space before the commandseparator "|". Other examples with trailing white space:
unmap @@ unmap @@     " comment
An error will be issued, which is very hard to identify, because the endingwhitespace character inunmap @@ is not visible.
A generic solution is to put the command separator "|" right after the mappedkeys. After that white space and a comment may follow:
unmap @@|    " comment

1.2 SPECIAL ARGUMENTS:map-arguments

"<buffer>", "<nowait>", "<silent>", "<script>", "<expr>" and"<unique>" can be used in any order. They must appear right after thecommand, before any other arguments.
:map-local:map-<buffer>:map-bufferE224E225If the first argument to one of these commands is "<buffer>" the mapping willbe effective in the current buffer only. Example:
: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> belowto make a short local mapping not taking effect when a longer global oneexists.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 isunloaded. Just like local option values.Also seemap-precedence.
:map-<nowait>:map-nowaitWhen defining a buffer-local mapping for "," there may be a global mappingthat starts with ",". Then you need to type another character for Vim to knowwhether to use the "," mapping or the longer one. To avoid this add the<nowait> argument. Then the mapping will be used when it matches, Vim doesnot wait for more characters to be typed. However, if the characters werealready typed they are used.Note that this works when the<nowait> mapping fully matches and is foundbefore any partial matches. This works when:
There is only one matching buffer-local mapping, since these are always found before global mappings.
There is another buffer-local mapping that partly matches, but it is defined earlier (last defined mapping is found first).
:map-<silent>:map-silentTo define a mapping which will not be echoed on the command line, add"<silent>" as the first argument. Example:
:map <silent> ,h /Header<CR>
The search string will not be echoed when using this mapping. Messages fromthe 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 themapping selects another entry for command line completion it won't bedisplayed.Prompts will still be given, e.g., for inputdialog().Using "<silent>" for an abbreviation is possible, but will cause redrawing ofthe command line to fail.
:map-<script>:map-scriptIf the first argument to one of these commands is "<script>" and it is used todefine a new mapping or abbreviation, the mapping will only remap charactersin the{rhs} using mappings that were defined local to a script, starting with"<SID>". This can be used to avoid that mappings from outside a scriptinterfere (e.g., whenCTRL-V is remapped in mswin.vim), but do use othermappings defined in the script.Note: ":map<script>" and ":noremap<script>" do the same thing. The"<script>" overrules the command name. Using ":noremap<script>" ispreferred, because it's clearer that remapping is (mostly) disabled.
:map-<unique>:map-uniqueE226E227If the first argument to one of these commands is "<unique>" and it is used todefine a new mapping or abbreviation, the command will fail if the mapping orabbreviation already exists. Example:
:map <unique> ,w  /[#&!]<CR>
When defining a local mapping, there will also be a check if a global mapalready 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 atmaparg().
:map-<expr>:map-expressionIf the first argument to one of these commands is "<expr>" and it is used todefine a new mapping or abbreviation, the argument is an expression. Theexpression is evaluated to obtain the{rhs} that is used. Example:
:inoremap <expr> . <SID>InsertDot()
The result of the s:InsertDot() function will be inserted. It could check thetext before the cursor and start omni completion when some condition is met.Using a script-local function is preferred, to avoid polluting the globalnamespace. Use<SID> in the RHS so that the script that the mapping wasdefined in can be found.
For abbreviationsv:char is set to the character that was typed to triggerthe abbreviation. You can use this to decide how to expand the{lhs}. Youshould not either insert or change the v:char.
In case you want the mapping to not do anything, you can have the expressionevaluate to an empty string. If something changed that requires Vim togo through the main loop (e.g. to update the display), return "\<Ignore>".This is similar to "nothing" but makes Vim return from the loop that waits forinput.
Keep in mind that the expression may be evaluated when looking fortypeahead, before the previous command has been executed. For example:
func StoreColumn()  let g:column = col('.')  return 'x'endfuncnnoremap <expr> x StoreColumn()nmap ! f!x
You 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 isexpression-mapped:
nmap ! f!<Ignore>x
Be very careful about side effects! The expression is evaluated whileobtaining characters, you may very well make the command dysfunctional.Therefore the following is blocked for<expr> mappings:
Changing the buffer texttextlock.
Editing another buffer.
The:normal command.
Moving the cursor is allowed, but it is restored afterwards.
If the cmdline is changed, the old text and cursor position are restored.If you want the mapping to do any of these let the returned characters dothat, or use a<Cmd> mapping instead.
You can use getchar(), it consumes typeahead if there is any. E.g., if youhave these mappings:
inoremap <expr> <C-L> nr2char(getchar())inoremap <expr> <C-L>x "foo"
If you now typeCTRL-L nothing happens yet, Vim needs the next character todecide 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.
Here is an example that inserts a list number that increases:
let counter = 0inoremap <expr> <C-L> ListItem()inoremap <expr> <C-R> ListReset()func ListItem()  let g:counter += 1  return g:counter .. '. 'endfuncfunc ListReset()  let g:counter = 0  return ''endfunc
CTRL-L inserts the next number,CTRL-R resets the count.CTRL-R returns anempty string, so that nothing is inserted.
Note that using 0x80 as a single byte before other text does not work, it willbe seen as a special key.
<Cmd>:map-cmdThe<Cmd> pseudokey begins a "command mapping", which executes the commanddirectly 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>
This is more flexible than:<C-U> in Visual and Operator-pending mode, or<C-O>: in Insert mode, because the commands are executed directly in thecurrent mode, instead of always going to Normal mode. Visual mode ispreserved, so tricks withgv are not needed. Commands can be invokeddirectly 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 invokedor an async event was processed.
Note:
Because<Cmd> avoids mode-changes (unlike ":") it does not triggerCmdlineEnter andCmdlineLeave events. This helps performance.
For the same reason,keycodes like<C-R><C-W> are interpreted as plain, unmapped keys.
The command is not echo'ed, no need for<silent>.
The{rhs} is not subject to abbreviations nor to other mappings, even if the mapping is recursive.
In Visual mode you can useline('v') andcol('v') to get one end of the Visual area, the cursor is at the other end.
E1255E1136<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 usea literal<CR> in the{rhs}, use<lt>.

1.3 MAPPING AND MODES:map-modes

mapmode-nvomapmode-nmapmode-vmapmode-omapmode-t
There are seven sets of mappings
For Normal mode: When typing commands.
For Visual mode: When typing commands while the Visual area is highlighted.
For Select mode: like Visual mode but typing text replaces the selection.
For Operator-pending mode: When an operator is pending (after "d", "y", "c", etc.). See below:omap-info.
For Insert mode. These are also used in Replace mode.
For Command-line mode: When entering a ":" or "/" command.
For Terminal mode: When typing in a:terminal buffer.
Special case: While typing a count for a command in Normal mode, mapping zerois disabled. This makes it possible to map zero without making it impossibleto type a count with a zero.
map-overviewmap-modesOverview of which map command works in which mode. More details below.
COMMANDS MODES
:map :noremap :unmap Normal, Visual, Select, Operator-pending:nmap :nnoremap :nunmap Normal:vmap :vnoremap :vunmap Visual and Select:smap :snoremap :sunmap Select:xmap :xnoremap :xunmap Visual:omap :onoremap :ounmap Operator-pending:map! :noremap! :unmap! Insert and Command-line:imap :inoremap :iunmap Insert:lmap :lnoremap :lunmap Insert, Command-line, Lang-Arg:cmap :cnoremap :cunmap Command-line:tmap :tnoremap :tunmap Terminal
Same information in a table:map-table
Mode | Norm | Ins | Cmd | Vis | Sel | Opr | Term | Lang |
Command +------+-----+-----+-----+-----+-----+------+------+
[nore]map | yes | - | - | yes | yes | yes | - | - |n[nore]map | yes | - | - | - | - | - | - | - |[nore]map! | - | yes | yes | - | - | - | - | - |i[nore]map | - | yes | - | - | - | - | - | - |c[nore]map | - | - | yes | - | - | - | - | - |v[nore]map | - | - | - | yes | yes | - | - | - |x[nore]map | - | - | - | yes | - | - | - | - |s[nore]map | - | - | - | - | yes | - | - | - |o[nore]map | - | - | - | - | - | yes | - | - |t[nore]map | - | - | - | - | - | - | yes | - |l[nore]map | - | yes | yes | - | - | - | - | yes |
COMMANDS MODES
Normal Visual+Select Operator-pending
:map :noremap :unmap :mapclear yes yes yes:nmap :nnoremap :nunmap :nmapclear yes - -:vmap :vnoremap :vunmap :vmapclear - yes -:omap :onoremap :ounmap :omapclear - - yes
:nunmap can also be used outside of a monastery.mapmode-xmapmode-sSome commands work both in Visual and Select mode, some in only one. Notethat quite often "Visual" is mentioned where both Visual and Select modeapply.Select-mode-mappingNOTE: Mapping a printable character in Select mode may confuse the user. It'sbetter to explicitly use :xmap and :smap for printable characters. Or use:sunmap after defining the mapping.
COMMANDS MODES
Visual Select
:vmap :vnoremap :vunmap :vmapclear yes yes:xmap :xnoremap :xunmap :xmapclear yes -:smap :snoremap :sunmap :smapclear - yes
mapmode-icmapmode-imapmode-cmapmode-lSome commands work both in Insert mode and Command-line mode, some not:
COMMANDS MODES
Insert Command-lineLang-Arg
:map! :noremap! :unmap! :mapclear! yes yes -:imap :inoremap :iunmap :imapclear yes- -:cmap :cnoremap :cunmap :cmapclear - yes -:lmap :lnoremap :lunmap :lmapclear yes* yes* yes*
* If'iminsert' is 1, seelanguage-mapping below.
The original Vi did not have separate mappings forNormal/Visual/Operator-pending mode and for Insert/Command-line mode.Therefore the ":map" and ":map!" commands enter and display mappings forseveral modes. In Vim you can use the ":nmap", ":vmap", ":omap", ":cmap" and":imap" commands to enter mappings for each mode separately.
omap-info
Operator-pending mappings can be used to define a movement command that can beused with any operator. Simple example:
:omap { w
makes "y{" work like "yw" and "d{" like "dw".
To ignore the starting cursor position and select different text, you can havethe omap start Visual mode to select the text to be operated upon. Examplethat operates on a function name in the current line:
onoremap <silent> F :<C-U>normal! 0f(hviw<CR>
TheCTRL-U (<C-U>) is used to remove the range that Vim may insert. TheNormal mode commands find the first '(' character and select the first wordbefore it. That usually is the function name.
To enter a mapping for Normal and Visual mode, but not Operator-pending mode,first define it for all three modes, then unmap it forOperator-pending mode:
:map    xx something-difficult:ounmap xx
Likewise for a mapping for Visual and Operator-pending mode or Normal andOperator-pending mode.
language-mapping
":lmap" defines a mapping that applies to:
Insert mode
Command-line mode
when entering a search pattern
the argument of the commands that accept a text character, such as "r" and "f"
for the input() lineGenerally: Whenever a character is to be typed that is part of the text in thebuffer, not a Vim command character. "Lang-Arg" isn't really another mode,it's just used here for this situation. The simplest way to load a set of related language mappings is by using the'keymap' option. See45.5. In Insert mode and in Command-line mode the mappings can be disabled withtheCTRL-^ commandi_CTRL-^c_CTRL-^. These commands change the value ofthe'iminsert' option. When starting to enter a normal command line (not asearch pattern) the mappings are disabled until aCTRL-^ is typed. The statelast used is remembered for Insert mode and Search patterns separately. Thestate for Insert mode is also used when typing a character as an argument tocommand like "f" or "t". Language mappings will never be applied to already mapped characters. Theyare only used for typed characters. This assumes that the language mappingwas already done when typing the mapping. Correspondingly, language mappingsare applied when recording macros, rather than when applying them.

1.4 LISTING MAPPINGSmap-listing

When listing mappings the characters in the first two columns are:
CHARMODE
<Space>Normal, Visual, Select and Operator-pendingnNormalvVisual and SelectsSelectxVisualoOperator-pending!Insert and Command-lineiInsertl":lmap" mappings for Insert, Command-line and Lang-ArgcCommand-linetTerminal-Job
Just before the{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
Everything from the first non-blank after{lhs} up to the end of the line(or '|') is considered to be part of{rhs}. This allows the{rhs} to endwith a space.
Note: When using mappings for Visual mode, you can use the "'<" mark, whichis the start of the last selected Visual area in the current buffer'<.
The:filter command can be used to select what mappings to list. Thepattern is matched against the{lhs} and{rhs} in the raw form. If adescription was added usingnvim_set_keymap() ornvim_buf_set_keymap()then the pattern is also matched against it.
:map-verbose
When'verbose' is non-zero, listing a key map will also display where it waslast defined. Example:
:verbose map <C-W>*n  <C-W>*      * <C-W><C-S>*        Last set from ~/.config/nvim/init.vim
See:verbose-cmd for more information.

1.5 MAPPING SPECIAL KEYS:map-special-keys

To map a function key, use the internal code for it. To enter such a mappingtypeCTRL-K and then hit the function key, or use the form "<F2>", "<F10>","<Up>", "<S-Down>", "<S-F7>", etc. (see table of keyskey-notation, all keysfrom<Up> can be used).

1.6 SPECIAL CHARACTERS:map-special-chars

map_backslashmap-backslashNote that onlyCTRL-V is mentioned here as a special character for mappingsand abbreviations. When'cpoptions' does not contain 'B', a backslash canalso be used likeCTRL-V. The <> notation can be fully used then<>. Butyou cannot use "<C-V>" likeCTRL-V to escape the special meaning of whatfollows.
To map a backslash, or use a backslash literally in the{rhs}, the specialsequence "<Bslash>" can be used. This avoids the need to double backslasheswhen using nested mappings.
map_CTRL-Cmap-CTRL-CUsingCTRL-C in the{lhs} is possible, but it will only work when Vim iswaiting for a key, not when Vim is busy with something. When Vim is busyCTRL-C interrupts/breaks the command.When using the GUI version on MS-WindowsCTRL-C can be mapped to allow a Copycommand to the clipboard. UseCTRL-Break to interrupt Vim.
map_space_in_lhsmap-space_in_lhsTo include a space in{lhs} precede it with aCTRL-V (type twoCTRL-Vs foreach space).map_space_in_rhsmap-space_in_rhsIf you want a{rhs} that starts with a space, use "<Space>". To be fully Vicompatible (but unreadable) don't use the<> notation, precede{rhs} with asingleCTRL-V (you have to typeCTRL-V two times).map_empty_rhsmap-empty-rhsYou can create an empty{rhs} by typing nothing after a singleCTRL-V (youhave to typeCTRL-V two times). Unfortunately, you cannot do this in a vimrcfile.<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>
map-multibyte
It is possible to map multibyte characters, but only the whole character. Youcannot map the first byte only. This was done to prevent problems in thisscenario:
:set encoding=latin1:imap <M-C> foo:set encoding=utf-8
The mapping for<M-C> is defined with the latin1 encoding, resulting in a 0xc3byte. If you type the character á (0xe1<M-a>) in UTF-8 encoding this is thetwo bytes 0xc3 0xa1. You don't want the 0xc3 byte to be mapped then orotherwise it would be impossible to type the á character.
<Leader>mapleaderTo define a mapping which uses the "g:mapleader" variable, the special string"<Leader>" can be used. It is replaced with the string value of"g:mapleader". If "g:mapleader" is not set or empty, a backslash is usedinstead. Example:
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 isdefined. Changing "g:mapleader" after that has no effect for already definedmappings.
<LocalLeader>maplocalleader<LocalLeader> is just like<Leader>, except that it uses "maplocalleader"instead of "mapleader".<LocalLeader> is to be used for mappings which arelocal to a buffer. Example:
:map <buffer> <LocalLeader>A  oanother line<Esc>
In a global plugin<Leader> should be used and in a filetype plugin<LocalLeader>. "mapleader" and "maplocalleader" can be equal. Although, ifyou make them different, there is a smaller chance of mappings from globalplugins to clash with mappings for filetype plugins. For example, you couldkeep "mapleader" at the default backslash, and set "maplocalleader" to anunderscore.
map-<SID>
In a script the special key name "<SID>" can be used to define a mappingthat's local to the script. See<SID> for details.
<Plug>
The special key name "<Plug>" can be used for an internal mapping, which isnot to be matched with any key sequence. This is useful in pluginsusing-<Plug>.
<MouseMove>
The special key name "<MouseMove>" can be used to handle mouse movement. Itneeds to be enabled with'mousemoveevent'.Thegetmousepos() function can be used to obtain the mouse position.
<Char><Char->To map a character by its decimal, octal or hexadecimal number the<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.
map-comments
It is not possible to put a comment after these commands, because the"character is considered to be part of the{lhs} or{rhs}. However, one canuse|", since this starts a new, empty command with a comment.
map_barmap-barSince the '|' character is used to separate a map command from the nextcommand, you will have to do something special to include a '|' in{rhs}.There are three methods:
use works when example
<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^M
(here ^V stands forCTRL-V; to get oneCTRL-V you have to type it twice; youcannot use the <> notation "<C-V>" here).
All three work when you use the default setting for'cpoptions'.
When 'b' is present in'cpoptions', "\|" will be recognized as a mappingending in a '\' and then another command. This is Vi compatible, butillogical when compared to other commands.
map_returnmap-returnWhen you have a mapping that contains an Ex command, you need to put a lineterminator after it to have it executed. The use of<CR> is recommended forthis (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 aCTRL-V first.map-error
Note that when an error is encountered (that causes an error message or mightcause a beep) the rest of the mapping is not executed. This is Vi-compatible.
Note that the second character (argument) of the commands @zZtTfF[]rm'`"vandCTRL-X is not mapped. This was done to be able to use all the namedregisters and marks, even when the command with the same name has beenmapped.

1.7 WHAT KEYS TO MAPmap-which-keys

If you are going to map something, you will need to choose which key(s) to usefor the{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 fewsuggestions:
Function keys<F2>,<F3>, etc.. Also the shifted function keys<S-F1>,<S-F2>, etc. Note that<F1> is already used for the help command.
Meta-keys (with the ALT key pressed). Depending on your keyboard accented characters may be used as well.:map-alt-keys
Use the '_' or ',' character and then any other character. The "_" and "," commands do exist in Vim (see_ and,), but you probably never use them.
Use a key that is a synonym for another command. For example:CTRL-P andCTRL-N. Use an extra character to allow more mappings.
The key defined by<Leader> and one or more other keys. This is especially useful in scripts.mapleader
See the file "index" for keys that are not used and thus can be mapped withoutlosing any builtin function. You can also use ":help{key}^D" to find out ifa key is used for some command. ({key} is the specific key you want to findout about, ^D isCTRL-D).

1.8 EXAMPLESmap-examples

A few examples (as you type them: for "<CR>" you type four characters).
:map <F3>  o#include:map <M-g> /foo<CR>cwbar<Esc>:map _x    d/END/e<CR>:map! qq   quadrillion questions
Multiplying a count
When you type a count before triggering a mapping, it's like the count wastyped before the{lhs}. For example, with this mapping:
:map <F4>  3w
Typing 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.@=

1.9 USING MAPPINGSmap-typing

Vim will compare what you type with the start of a mapped sequence. If thereis an incomplete match, it will get more characters until there either is acomplete match or until there is no match at all. Example: If you map! "qq",the first 'q' will not appear on the screen until you type anothercharacter. This is because Vim cannot know if the next character will be a'q' or not. If the'timeout' option is on (which is the default) Vim willonly wait for one second (or as long as specified with the'timeoutlen'option). After that it assumes that the 'q' is to be interpreted as such. Ifyou type slowly, or your system is slow, reset the'timeout' option. Then youmight want to set the'ttimeout' option.
map-precedence
Buffer-local mappings (defined using:map-<buffer>) take precedence overglobal mappings. When a buffer-local mapping is the same as a global mapping,Vim will use the buffer-local mapping. In addition, Vim will use a completemapping immediately if it was defined with<nowait>, even if a longer mappinghas 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 willnot wait for more characters to see if the user might be typing \abc.
map-keys-fails
There are situations where key codes might not be recognized:
Vim can only read part of the key code. Mostly this is only the first character. This happens on some Unix versions in an xterm.
The key code is after character(s) that are mapped. E.g., "<F1><F1>" or "g<F1>".
The result is that the key code is not recognized in this situation, and themapping fails. There are two actions needed to avoid this problem:
Remove the 'K' flag from'cpoptions'. This will make Vim wait for the rest of the characters of the function key.
When using<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>
Type the<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 secondspecial 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.
recursive_mapping
If you include the{lhs} in the{rhs} you have a recursive mapping. When{lhs} is typed, it will be replaced with{rhs}. When the{lhs} which isincluded 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. Theonly problem is that the only way to stop this is by causing an error. Themacros to solve a maze uses this, look there for an example. There is oneexception: If the{rhs} starts with{lhs}, the first character is not mappedagain (this is Vi compatible).For example:
:map ab abcd
will execute the "a" command and insert "bcd" in the text. The "ab" in the{rhs} will not be mapped again.
If you want to exchange the meaning of two keys you should use the :noremapcommand. For example:
:noremap k j:noremap j k
This will exchange the cursor up and down commands.
With the normal :map command mapping takes place until the text is found notto be a part of a{lhs}. For example, if you use:
:map x y:map y x
Vim 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".
:map-undo
If you include an undo command inside a mapped sequence, this will bring thetext back in the state before executing the macro. This is compatible withthe original Vi, as long as there is only one undo command in the mappedsequence (having two undo commands in a mapped sequence did not make sensein the original Vi, you would get back the text before the first undo).

1.10 MAPPING ALT-KEYS:map-alt-keys

For a readable mapping command the<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 havean actual Meta modifier key, please see:map-meta-keys.
In the GUI Nvim handles theALT key itself, thus mapping keys with ALTshould always work. But in a terminal Nvim gets a sequence of bytes and hasto figure out whether ALT was pressed. Terminals may use ESC to indicate thatALT was pressed. If ESC is followed by a{key} within'ttimeoutlen'milliseconds, the ESC is interpreted as: <ALT-{key}>otherwise it is interpreted as two key presses:<ESC>{key}

1.11 MAPPING META-KEYS:map-meta-keys

Mapping keys with the Meta modifier works very similar to using the Alt key.What key on your keyboard produces the Meta modifier depends on your keyboardand configuration.
Note that mapping<M-a> actually is for using the Alt key. That can beconfusing! It cannot be changed, it would not be backwards compatible.
For the Meta modifier the "T" character is used. For example, to map Meta-bin Insert mode:
:imap <T-b> terrible
1.12 MAPPING SUPER-KEYS or COMMAND-KEYS:map-super-keys:map-cmd-key
The Super / Command modifier is available if the terminal or GUI supports it.The character "D" is used for the Super / Command modifier.
For example, to map Command-b in Insert mode:
:imap <D-b> barritone

1.13 MAPPING AN OPERATOR:map-operator

An operator is used before a{motion} command. To define your own operatoryou must create a mapping that first sets the'operatorfunc' option and theninvoke theg@ operator. After the user types the{motion} command thespecified function will be called.
g@E774E775g@{motion}Call the function set by the'operatorfunc' option.The '[ mark is positioned at the start of the textmoved over by{motion}, the '] mark on the lastcharacter of the text.The function is called with one String argument: "line"{motion} waslinewise "char"{motion} wascharwise "block"{motion} wasblockwise-visualThe type can be forced, seeforced-motion.
Here is an example that counts the number of spaces with<F4>:
nnoremap <expr> <F4> CountSpaces()xnoremap <expr> <F4> CountSpaces()" doubling <F4> works on a linennoremap <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  endtryendfunction
An<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 andCmdlineLeave autocommands.
Note that the'selection' option is temporarily set to "inclusive" to be ableto yank exactly the right text by using Visual mode from the '[ to the ']mark.
Also note that the'clipboard' option is temporarily emptied to avoidclobbering the"* or"+ registers, if its value contains the itemunnamedorunnamedplus.
Themode() function will return the state as it will be after applying theoperator.
Here is an example for using a lambda function to create a normal-modeoperator to add quotes around text in the current line:
nnoremap <F4> <Cmd>let &opfunc='{t ->                        \ getline(".")                        \ ->split("\\zs")                        \ ->insert("\"", col("'']"))                        \ ->insert("\"", col("''[") - 1)                        \ ->join("")                        \ ->setline(".")}'<CR>g@

2. AbbreviationsabbreviationabbreviationsAbbreviations

Abbreviations are used in Insert mode, Replace mode and Command-line mode.If you enter a word that is an abbreviation, it is replaced with the word itstands for. This can be used to save typing for often used long words. Andyou can use it to automatically correct obvious spelling errors.Examples:
:iab ms Microsoft:iab tihs this
There are three types of abbreviations:
full-id The "full-id" type consists entirely of keyword characters (letters and characters from'iskeyword' option). This is the most common abbreviation.
Examples: "foo", "g3", "-1"
end-id The "end-id" type ends in a keyword character, but all the other characters are not keyword characters.
Examples: "#i", "..f", "$/7"
non-id The "non-id" type ends in a non-keyword character, the other characters may be of any type, excluding space and tab.
Examples: "def#", "4/7$"
Examples of strings that cannot be abbreviations: "a.b", "#def", "a b", "_$r"
An abbreviation is only recognized when you type a non-keyword character.This can also be the<Esc> that ends Insert mode or the<CR> that ends acommand. The non-keyword character which ends the abbreviation is insertedafter the expanded abbreviation. An exception to this is the character<C-]>,which is used to expand an abbreviation without inserting any extracharacters.
Example:
:ab hhhello
"hh<Space>" is expanded to "hello<Space>" "hh<C-]>" is expanded to "hello"
The characters before the cursor must match the abbreviation. Each type hasan additional rule:
full-id In front of the match is a non-keyword character, or this is where the line or insertion starts. Exception: When the abbreviation is only one character, it is not recognized if there is a non-keyword character in front of it, other than a space or a tab. However, for the command line "'<,'>" (or any other marks) is ignored, as if the command line starts after it.
end-id In front of the match is a keyword character, or a space or a tab, or this is where the line or insertion starts.
non-id In front of the match is a space, tab or the start of the line or the insertion.
Examples: ({CURSOR} is where you type a non-keyword character)
:ab foo   four old otters
" foo{CURSOR}" is expanded to " four old otters"" foobar{CURSOR}" is not expanded"barfoo{CURSOR}" is not expanded
:ab #i #include
"#i{CURSOR}" is expanded to "#include"">#i{CURSOR}" is not expanded
:ab ;; <endofline>
"test;;" is not expanded"test ;;" is expanded to "test<endofline>"
To avoid the abbreviation in Insert mode: TypeCTRL-V before the characterthat would trigger the abbreviation. E.g.CTRL-V<Space>. Or type part ofthe abbreviation, exit insert mode with<Esc>, re-enter insert mode with "a"and type the rest.
To avoid the abbreviation in Command-line mode: TypeCTRL-V twice somewhere inthe abbreviation to avoid it to be replaced. ACTRL-V in front of a normalcharacter is mostly ignored otherwise.
It is possible to move the cursor after an abbreviation:
:iab if if ()<Left>
You can even do more complicated things. For example, to consume the spacetyped after an abbreviation:
func Eatchar(pat)   let c = nr2char(getchar(0))   return (c =~ a:pat) ? '' : cendfunciabbr <silent> if if ()<Left><C-R>=Eatchar('\s')<CR>
There are no default abbreviations.
Abbreviations are never recursive. You can use ":ab f f-o-o" without anyproblem. But abbreviations can be mapped.
:abbreviate-local:abbreviate-<buffer>Just like mappings, abbreviations can be local to a buffer. This is mostlyused in afiletype-plugin file. Example for a C plugin file:
:abb <buffer> FF  for (i = 0; i < ; ++i)
:ab:abbreviate:ab[breviate]list all abbreviations. The character in the firstcolumn indicates the mode where the abbreviation isused: 'i' for insert mode, 'c' for Command-linemode, '!' for both. These are the same as formappings, seemap-listing.
:abbreviate-verbose
When'verbose' is non-zero, listing an abbreviation will also display where itwas last defined. Example:
:verbose abbreviate!  teh the        Last set from /home/abcd/vim/abbr.vim
See:verbose-cmd for more information.
:ab[breviate]{lhs}list the abbreviations that start with{lhs}You may need to insert aCTRL-V (type it twice) toavoid that a typed{lhs} is expanded, sincecommand-line abbreviations apply here.
:ab[breviate] [<expr>] [<buffer>]{lhs}{rhs}add abbreviation for{lhs} to{rhs}. If{lhs} alreadyexisted it is replaced with the new{rhs}.{rhs} maycontain spaces.See:map-<expr> for the optional<expr> argument.See:map-<buffer> for the optional<buffer> argument.
:una:unabbreviate:una[bbreviate] [<buffer>]{lhs}Remove abbreviation for{lhs} from the list. If noneis found, remove abbreviations in which{lhs} matcheswith the{rhs}. This is done so that you can evenremove abbreviations after expansion. To avoidexpansion insert aCTRL-V (type it twice).
:norea:noreabbrev:norea[bbrev] [<expr>] [<buffer>] [lhs] [rhs]same as ":ab", but no remapping for this{rhs}
:ca:cab:cabbrev:ca[bbrev] [<expr>] [<buffer>] [lhs] [rhs]same as ":ab", but for Command-line mode only.
:cuna:cunabbrev:cuna[bbrev] [<buffer>]{lhs}Same as ":una", but for Command-line mode only.
:cnorea:cnoreabbrev:cnorea[bbrev] [<expr>] [<buffer>] [lhs] [rhs]same as ":ab", but for Command-line mode only and noremapping for this{rhs}
:ia:iabbrev:ia[bbrev] [<expr>] [<buffer>] [lhs] [rhs]same as ":ab", but for Insert mode only.
:iuna:iunabbrev:iuna[bbrev] [<buffer>]{lhs}Same as ":una", but for insert mode only.
:inorea:inoreabbrev:inorea[bbrev] [<expr>] [<buffer>] [lhs] [rhs]same as ":ab", but for Insert mode only and noremapping for this{rhs}
:abc:abclear:abc[lear] [<buffer>]Remove all abbreviations.
:iabc:iabclear:iabc[lear] [<buffer>]Remove all abbreviations for Insert mode.
:cabc:cabclear:cabc[lear] [<buffer>]Remove all abbreviations for Command-line mode.
using_CTRL-V
It is possible to use special characters in the rhs of an abbreviation.CTRL-V has to be used to avoid the special meaning of most non printablecharacters. How manyCTRL-Vs need to be typed depends on how you enter theabbreviation. This also applies to mappings. Let's use an example here.
Suppose you want to abbreviate "esc" to enter an<Esc> character. When youtype the ":ab" command in Vim, you have to enter this: (here ^V is aCTRL-Vand ^[ is<Esc>)
You type: ab esc ^V^V^V^V^V^[
All keyboard input is subjected to ^V quote interpretation, sothe first, third, and fifth ^V characters simply allow the second,and fourth ^Vs, and the ^[, to be entered into the command-line.
You see: ab esc ^V^V^[
The command-line contains two actual ^Vs before the ^[. This ishow it should appear in your vimrc file, if you choose to go thatroute. The first ^V is there to quote the second ^V; the :abcommand uses ^V as its own quote character, so you can include quotedwhitespace or the | character in the abbreviation. The :ab commanddoesn't do anything special with the ^[ character, so it doesn't needto be quoted. (Although quoting isn't harmful; that's why typing 7[but not 8!] ^Vs works.)
Stored as: esc ^V^[
After parsing, the abbreviation's short form ("esc") and long form(the two characters "^V^[") are stored in the abbreviation table.If you give the :ab command with no arguments, this is how theabbreviation will be displayed.
Later, when the abbreviation is expanded because the user typed inthe word "esc", the long form is subjected to the same type of^V interpretation as keyboard input. So the ^V protects the ^[character from being interpreted as the "exit Insert mode" character.Instead, the ^[ is inserted into the text.
Expands to: ^[
[example given by Steve Kirkendall]

3. Local mappings and functionsscript-local

When using several Vim script files, there is the danger that mappings andfunctions used in one script use the same name as in other scripts. To avoidthis, they can be made local to the script.
<SID><SNR>E81The string "<SID>" can be used in a mapping or menu. This is useful if youhave a script-local function that you want to call from a mapping in the samescript. When executing the map command, Vim will replace "<SID>" with the specialkey code<SNR>, followed by a number that's unique for the script, and anunderscore. Example:
:map <SID>Add
would define a mapping "<SNR>23_Add".
When defining a function in a script, "s:" can be prepended to the name tomake it local to the script. But when a mapping is executed from outside ofthe script, it doesn't know in which script the function was defined. Toavoid this problem, use "<SID>" instead of "s:". The same translation is doneas for mappings. This makes it possible to define a call to the function ina mapping.
When a local function is executed, it runs in the context of the script it wasdefined in. This means that new functions and mappings it defines can alsouse "s:" or "<SID>" and it will use the same unique number as when thefunction itself was defined. Also, the "s:var" local script variables can beused.
When executing an autocommand or a user command, it will run in the context ofthe script it was defined in. This makes it possible that the command calls alocal function or uses a local mapping.
In case the value is used in a context where<SID> cannot be correctlyexpanded, use the expand() function:
let &includexpr = expand('<SID>') .. 'My_includeexpr()'
Otherwise, using "<SID>" outside of a script context is an error.
If you need to get the script number to use in a complicated script, you canuse this function:
func s:ScriptNumber()  return matchstr(expand('<SID>'), '<SNR>\zs\d\+\ze_')endfunc
The "<SNR>" will be shown when listing functions and mappings. This is usefulto find out what they are defined to.
The:scriptnames command can be used to see which scripts have been sourcedand what their<SNR> number is.

4. User-defined commandsuser-commands

It is possible to define your own Ex commands. A user-defined command can actjust like a built-in command (it can have a range or arguments, arguments canbe completed as filenames or buffer names, etc), except that when the commandis executed, it is transformed into a normal Ex command and then executed.
For starters: See section40.2 in the user manual.
E183E841user-cmd-ambiguousAll user defined commands must start with an uppercase letter, to avoidconfusion with builtin commands. Exceptions are these builtin commands::NextThey cannot be used for a user defined command.
The other characters of the user command can be uppercase letters, lowercaseletters or digits. When using digits, note that other commands that take anumeric argument may become ambiguous. For example, the command ":Cc2" couldbe the user command ":Cc2" without an argument, or the command ":Cc" withargument "2". It is advised to put a space between the command name and theargument to avoid these problems.
When using a user-defined command, the command can be abbreviated. However, ifan abbreviation is not unique, an error will be issued. Furthermore, abuilt-in command will always take precedence.
Example:
: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 inscripts.
:com[mand]:com:commandList all user-defined commands. When listing commands,the characters in the first columns are: !Command has the -bang attribute "Command has the -register attribute | Command has the -bar attribute bCommand is local to current buffer(see below for details on attributes)The list can be filtered on command name with:filter, e.g., to list all commands with "Pyth" inthe name:
filter Pyth command
:com[mand]{cmd}List the user-defined commands that start with{cmd}
:command-verbose
When'verbose' is non-zero, listing a command will also display where it waslast defined and any completion argument. Example:
:verbose command TOhtml
Name Args Range Complete Definition
TOhtml 0 % :call Convert2HTML(<line1>,<line2>)
Last set from /usr/share/vim/vim-7.0/plugin/tohtml.vim
See:verbose-cmd for more information.
E174E182:com[mand][!] [{attr}...]{cmd}{repl}Define a user command. The name of the command is{cmd} and its replacement text is{repl}. Thecommand's attributes (see below) are{attr}. If thecommand already exists, an error is reported, unless a! is specified, in which case the command isredefined. There is one exception: When sourcing ascript again, a command that was previously defined inthat script will be silently replaced.
:delc[ommand]{cmd}:delc:delcommandE184Delete the user-defined command{cmd}.
:delc[ommand] -buffer{cmd}E1237
Delete the user-defined command{cmd} that was definedfor the current buffer.
:comc[lear]:comc:comclearDelete all user-defined commands.
Command attributes
command-attributes
User-defined commands are treated by Nvim just like any other Ex commands. Theycan have arguments, or have a range specified. Arguments are subject tocompletion as filenames, buffers, etc. Exactly how this works depends upon thecommand's attributes, which are specified when the command is defined.
When defining a user command in a script, it will be able to call functionslocal to the script and use mappings local to the script. When the userinvokes the user command, it will run in the context of the script it wasdefined in. This matters if<SID> is used in a command.
There are a number of attributes, split into four categories: argumenthandling, completion behavior, range handling, and special cases. Theattributes are described below, by category.
Argument handling
E175E176:command-nargsBy default, a user defined command will take no arguments (and an error isreported if any are supplied). However, it is possible to specify that thecommand can take arguments, using the -nargs attribute. Valid cases are:
-nargs=0 No arguments are allowed (the default)-nargs=1 Exactly one argument is required, it includes spaces-nargs=* Any number of arguments are allowed (0, 1, or many), separated by white space-nargs=? 0 or 1 arguments are allowed-nargs=+ Arguments must be supplied, but any number are allowed
Arguments are considered to be separated by (unescaped) spaces or tabs in thiscontext, except when there is one argument, then the white space is part ofthe argument.
Note that arguments are used as text, not as expressions. Specifically,"s:var" will use the script-local variable in the script where the command wasdefined, not where it is invoked! Example: script1.vim:
:let s:error = "None":command -nargs=1 Error echoerr <args>
script2.vim:
:source script1.vim:let s:error = "Wrong!":Error s:error
Executing script2.vim will result in "None" being echoed. Not what youintended! Calling a function may be an alternative.
Completion behavior
:command-completionE179E180E181:command-complete
By default, the arguments of user defined commands do not undergo completion.However, by specifying one or the other of the following attributes, argumentcompletion can be enabled:
-complete=arglistfile names in argument list-complete=augroupautocmd groups-complete=breakpoint:breakadd suboptions-complete=bufferbuffer names-complete=colorcolor schemes-complete=commandEx command (and arguments)-complete=compilercompilers-complete=diff_bufferdiff buffer names-complete=dirdirectory names-complete=dir_in_pathdirectory names in'cdpath'-complete=environmentenvironment variable names-complete=eventautocommand events-complete=expressionVim expression-complete=filefile and directory names-complete=file_in_pathfile and directory names in'path'-complete=filetypefiletype names'filetype'-complete=functionfunction name-complete=helphelp subjects-complete=highlighthighlight groups-complete=history:history suboptions-complete=keymapkeyboard mappings-complete=localelocale names (as output of locale -a)-complete=luaLua expression:lua-complete=mapclearbuffer argument-complete=mappingmapping name-complete=menumenus-complete=messages:messages suboptions-complete=optionoptions-complete=packaddoptional packagepack-add names-complete=retab:retab suboptions-complete=runtimefile and directory names in'runtimepath'-complete=scriptnamessourced script names-complete=shellcmdShell command-complete=shellcmdlineFirst is a shell command and subsequent onesare filenames. The same behavior as:!cmd-complete=sign:sign suboptions-complete=syntaxsyntax file names'syntax'-complete=syntime:syntime suboptions-complete=tagtags-complete=tag_listfilestags, file names are shown whenCTRL-D is hit-complete=useruser names-complete=varuser variables-complete=custom,{func} custom completion, defined via{func}-complete=customlist,{func} custom completion, defined via{func}
If you specify completion while there is nothing to complete (-nargs=0, thedefault) then you get errorE1208 .Note: That some completion methods might expand environment variables.
Custom completion
:command-completion-custom
:command-completion-customlistE467E468It is possible to define customized completion schemes via the "custom,{func}"or the "customlist,{func}" completion argument. The{func} part should be afunction with the following signature:
:function {func}(ArgLead, CmdLine, CursorPos)
The function need not use all these arguments. The function should provide thecompletion candidates as the return value.
For the "custom" argument, the function should return the completioncandidates one per line in a newline separated string.
For the "customlist" argument, the function should return the completioncandidates as a Vim List. Non-string items in the list are ignored.
The function arguments are:ArgLeadthe leading portion of the argument currently beingcompleted onCmdLinethe entire command lineCursorPosthe cursor position in it (byte index)The function may use these for determining context. For the "custom"argument, it is not necessary to filter candidates against the (implicitpattern in) ArgLead. Vim will filter the candidates with its regexp engineafter function return, and this is probably more efficient in most cases. If'wildoptions' contains "fuzzy", then the candidates will be filtered usingfuzzy-matching. For the "customlist" argument, Vim will notfilter the returned completion candidates and the user supplied functionshould filter the candidates.
The following example lists user names to a Finger command
:com -complete=custom,ListUsers -nargs=1 Finger !finger <args>:fun ListUsers(A,L,P):    return system("cut -d: -f1 /etc/passwd"):endfun
The following example completes filenames from the directories specified inthe'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
This example does not work for file names with spaces!
Range handling
E177E178:command-range:command-countBy default, user-defined commands do not accept a line number range. However,it is possible to specify that the command does take a range (the -rangeattribute), or that it takes an arbitrary count value, either in the linenumber position (-range=N, like the:split command) or as a "count"argument (-count=N, like the:Next command). The count will then beavailable in the argument with<count>.
Possible attributes are:
-range Range allowed, default is current line-range=% Range allowed, default is whole file (1,$)-range=N A count (default N) which is specified in the line number position (like:split); allows for zero line number.-count=N A count (default N) which is specified either in the line number position, or as an initial argument (like:Next).-count Acts like -count=0
Note that -range=N and -count=N are mutually exclusive - only one should bespecified.
:command-addr
It is possible that the special characters in the range like.,$ or%which by default correspond to the current line, last line and the wholebuffer, relate to arguments, (loaded) buffers, windows or tab pages.
Possible values are (second column is the short name used in listing): -addr=linesRange of lines (this is the default for -range) -addr=arguments argRange for arguments -addr=buffers bufRange for buffers (also not loaded buffers) -addr=loaded_buffers loadRange for loaded buffers -addr=windows winRange for windows -addr=tabs tabRange for tab pages -addr=quickfix qfRange for quickfix entries -addr=other ?Other kind of range; can use ".", "$" and "%"as with "lines" (this is the default for-count)
Incremental preview
:command-preview{nvim-api}Commands can show an'inccommand' (as-you-type) preview by defining a previewhandler (only from Lua, seenvim_create_user_command()).
Before the preview callback is executed, Nvim will temporarily disable'cursorline' and'cursorcolumn' to avoid highlighting issues.
The preview callback must be a Lua function with this signature:
function cmdpreview(opts, ns, buf)
where "opts" has the same form as that given tonvim_create_user_command()callbacks, "ns" is the preview namespace id for highlights, and "buf" is thebuffer that your preview routine will directly modify to show the previewedresults (for "inccommand=split", or nil for "inccommand=nosplit").
Your command preview routine must implement this protocol:
1. Modify the target buffers as required for the preview (seenvim_buf_set_text() andnvim_buf_set_lines()).2. If preview buffer is provided, add necessary text to the preview buffer.3. Add required highlights to the target buffers. If preview buffer is provided, add required highlights to the preview buffer as well. All highlights must be added to the preview namespace which is provided as an argument to the preview callback (seevim.hl.range() andnvim_buf_set_extmark() for help on how to add highlights to a namespace).4. Return an integer (0, 1, 2) which controls how Nvim behaves as follows: 0: No preview is shown. 1: Preview is shown without preview window (even with "inccommand=split"). 2: Preview is shown and preview window is opened (if "inccommand=split"). For "inccommand=nosplit" this is the same as 1.
After preview ends, Nvim discards all changes to all buffers made during thepreview and clears all highlights in the preview namespace.
Here's an example of a command to trim trailing whitespace from lines thatsupports incremental command preview:
-- 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.hl.range(        buf,        preview_ns,        'Substitute',        {line1 + i - 2, start_idx - 1},        {line1 + i - 2, 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.hl.range(          preview_buf,          preview_ns,          'Substitute',          {preview_buf_line, #prefix + start_idx - 1},          {preview_buf_line, #prefix + end_idx},        )        preview_buf_line = preview_buf_line + 1      end    end  end  -- Return the value of the preview type  return 2end-- 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 commandvim.api.nvim_create_user_command(  'TrimTrailingWhitespace',  trim_space,  { nargs = '?', range = '%', addr = 'lines', preview = trim_space_preview })
Special cases
:command-bang:command-bar:command-register:command-buffer:command-keepscript
There are some special cases as well:
-bang The command can take a ! modifier (like :q or :w)-bar The command can be followed by a "|" and another command. A "|" inside the command argument is not allowed then. Also checks for a " to start a comment.-register The first argument to the command can be an optional register name (like :del, :put, :yank).-buffer The command will only be available in the current buffer.-keepscript Do not use the location of where the user command was defined for verbose messages, use the location of where the user command was invoked.
In the cases of the -count and -register attributes, if the optional argumentis supplied, it is removed from the argument list and is available to thereplacement text separately.Note that these arguments can be abbreviated, but that is a deprecatedfeature. Use the full name for new scripts.
Replacement text
The replacement text{repl} for a user defined command is scanned for specialescape sequences, using <...> notation. Escape sequences are replaced withvalues from the entered command line, and all other text is copied unchanged.The resulting string is executed as an Ex command. To avoid the replacementuse<lt> in place of the initial <. Thus to include "<bang>" literally use"<lt>bang>".
The valid escape sequences are
<line1>
<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 thecommand was executed with a ! modifier, otherwiseexpands to nothing.<mods><q-mods>:command-modifiers<mods> The command modifiers, if specified. Otherwise, expands tonothing. 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 |            \ endforfunction! SpecialEdit(files, mods)    for f in expand(a:files, 0, 1)        exe a:mods .. ' split ' .. f    endforendfunctioncommand! -nargs=+ -complete=file Sedit            \ call SpecialEdit(<q-args>, <q-mods>)
<reg><register><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 asnoted above, any count or register can consume someof the arguments, which are then not part of<args>).<lt>A single '<' (Less-Than) character. This is needed if youwant to get a literal copy of one of these escape sequencesinto the expansion - for example, to get<bang>, use<lt>bang>.
<q-args>
If the first two characters of an escape sequence are "q-" (for example,<q-args>) then the value is quoted in such a way as to make it a valid valuefor use in an expression. This uses the argument as one single value.When there is no argument<q-args> is an empty string. See theq-args-example below.<f-args>
To allow commands to pass their arguments on to a user-defined function, thereis a special form<f-args> ("function args"). This splits the commandarguments 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. Abackslash followed by a character other than white space or a backslashremains unmodified. Also seef-args-example below. Overview:
command<f-args>
XX ab "ab"XX a\b 'a\b'XX a\ b 'a b'XX a\ b 'a ', 'b'XX a\\b 'a\b'XX a\\ b 'a\', 'b'XX a\\\b 'a\\b'XX a\\\ b 'a\ b'XX a\\\\b 'a\\b'XX a\\\\ b 'a\\', 'b'XX [nothing]
Note that if the "no arguments" situation is to be handled, you have to makesure that the function can be called without arguments.
Examples for user commands:
" 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-example
Call a user function (example of<f-args>)
:com -nargs=* Mycmd call Myfunc(<f-args>)
When executed as:
:Mycmd arg1 arg2
This will invoke:
:call Myfunc("arg1","arg2")
q-args-example
A more substantial example:
: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 allfiles in the argument list. Usage example (note use of the "e" flag to ignoreerrors and the "update" command to write modified buffers):
:Allargs %s/foo/bar/ge|update
This will invoke:
:call Allargs("%s/foo/bar/ge|update")
Main
Commands index
Quick reference

1. Key mapping
1.1 MAP COMMANDS
1.2 SPECIAL ARGUMENTS
1.3 MAPPING AND MODES
1.4 LISTING MAPPINGS
1.5 MAPPING SPECIAL KEYS
1.6 SPECIAL CHARACTERS
1.7 WHAT KEYS TO MAP
1.8 EXAMPLES
1.9 USING MAPPINGS
1.10 MAPPING ALT-KEYS
1.11 MAPPING META-KEYS
1.13 MAPPING AN OPERATOR
2. Abbreviations
3. Local mappings and functions
4. User-defined commands

[8]ページ先頭

©2009-2025 Movatter.jp