blob: 1ee0e40d5ad0d595b6d2df03f42fbc55c4bbe748 [file] [log] [blame]
Bram Moolenaar779b74b2006-04-10 14:55:34 +00001*map.txt* For Vim version 7.0d. Last change: 2006 Mar 20
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7Key mapping, abbreviations and user-defined commands.
8
9This subject is introduced in sections |05.3|, |24.7| and |40.1| of the user
10manual.
11
121. Key mapping |key-mapping|
Bram Moolenaar5b962cf2005-12-12 21:58:40 +000013 1.1 MAP COMMANDS |:map-commands|
14 1.2 Special arguments |:map-arguments|
15 1.3 Mapping and modes |:map-modes|
16 1.4 Listing mappings |map-listing|
17 1.5 Mapping special keys |:map-special-keys|
18 1.6 Special characters |:map-special-chars|
19 1.7 What keys to map |map-which-keys|
20 1.8 Examples |map-examples|
21 1.9 Using mappings |map-typing|
22 1.10 Mapping alt-keys |:map-alt-keys|
23 1.11 Mapping an operator |:map-operator|
Bram Moolenaar071d4272004-06-13 20:20:40 +0000242. Abbreviations |abbreviations|
253. Local mappings and functions |script-local|
264. User-defined commands |user-commands|
27
28==============================================================================
291. Key mapping *key-mapping* *mapping* *macro*
30
31Key mapping is used to change the meaning of typed keys. The most common use
32is to define a sequence commands for a function key. Example: >
33
34 :map <F2> a<C-R>=strftime("%c")<CR><Esc>
35
Bram Moolenaar402d2fe2005-04-15 21:00:38 +000036This appends the current date and time after the cursor (in <> notation |<>|).
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
Bram Moolenaar5b962cf2005-12-12 21:58:40 +000038
391.1 MAP COMMANDS *:map-commands*
40
Bram Moolenaar071d4272004-06-13 20:20:40 +000041There are commands to enter new mappings, remove mappings and list mappings.
42See |map-overview| for the various forms of "map" and their relationships with
43modes.
44
45{lhs} means left-hand-side *{lhs}*
46{rhs} means right-hand-side *{rhs}*
47
Bram Moolenaar06b5db92006-02-10 23:11:56 +000048:map {lhs} {rhs} |mapmode-nvo| *:map*
49:nm[ap] {lhs} {rhs} |mapmode-n| *:nm* *:nmap*
50:vm[ap] {lhs} {rhs} |mapmode-v| *:vm* *:vmap*
Bram Moolenaar371d5402006-03-20 21:47:49 +000051:xm[ap] {lhs} {rhs} |mapmode-x| *:xm* *:xmap*
52:smap {lhs} {rhs} |mapmode-s| *:smap*
Bram Moolenaar06b5db92006-02-10 23:11:56 +000053:om[ap] {lhs} {rhs} |mapmode-o| *:om* *:omap*
54:map! {lhs} {rhs} |mapmode-ic| *:map!*
55:im[ap] {lhs} {rhs} |mapmode-i| *:im* *:imap*
56:lm[ap] {lhs} {rhs} |mapmode-l| *:lm* *:lmap*
57:cm[ap] {lhs} {rhs} |mapmode-c| *:cm* *:cmap*
Bram Moolenaar071d4272004-06-13 20:20:40 +000058 Map the key sequence {lhs} to {rhs} for the modes
59 where the map command applies. The result, including
60 {rhs}, is then further scanned for mappings. This
61 allows for nested and recursive use of mappings.
62
63
Bram Moolenaar06b5db92006-02-10 23:11:56 +000064:no[remap] {lhs} {rhs} |mapmode-nvo| *:no* *:noremap*
65:nn[oremap] {lhs} {rhs} |mapmode-n| *:nn* *:nnoremap*
66:vn[oremap] {lhs} {rhs} |mapmode-v| *:vn* *:vnoremap*
Bram Moolenaar371d5402006-03-20 21:47:49 +000067:xn[oremap] {lhs} {rhs} |mapmode-x| *:xn* *:xnoremap*
68:snor[emap] {lhs} {rhs} |mapmode-s| *:snor* *:snoremap*
Bram Moolenaar06b5db92006-02-10 23:11:56 +000069:ono[remap] {lhs} {rhs} |mapmode-o| *:ono* *:onoremap*
70:no[remap]! {lhs} {rhs} |mapmode-ic| *:no!* *:noremap!*
71:ino[remap] {lhs} {rhs} |mapmode-i| *:ino* *:inoremap*
72:ln[oremap] {lhs} {rhs} |mapmode-l| *:ln* *:lnoremap*
73:cno[remap] {lhs} {rhs} |mapmode-c| *:cno* *:cnoremap*
Bram Moolenaar071d4272004-06-13 20:20:40 +000074 Map the key sequence {lhs} to {rhs} for the modes
75 where the map command applies. Disallow mapping of
76 {rhs}, to avoid nested and recursive mappings. Often
77 used to redefine a command. {not in Vi}
78
79
Bram Moolenaar06b5db92006-02-10 23:11:56 +000080:unm[ap] {lhs} |mapmode-nvo| *:unm* *:unmap*
81:nun[map] {lhs} |mapmode-n| *:nun* *:nunmap*
82:vu[nmap] {lhs} |mapmode-v| *:vu* *:vunmap*
Bram Moolenaar371d5402006-03-20 21:47:49 +000083:xu[nmap] {lhs} |mapmode-x| *:xu* *:xunmap*
84:sunm[ap] {lhs} |mapmode-s| *:sunm* *:sunmap*
Bram Moolenaar06b5db92006-02-10 23:11:56 +000085:ou[nmap] {lhs} |mapmode-o| *:ou* *:ounmap*
86:unm[ap]! {lhs} |mapmode-ic| *:unm!* *:unmap!*
87:iu[nmap] {lhs} |mapmode-i| *:iu* *:iunmap*
88:lu[nmap] {lhs} |mapmode-l| *:lu* *:lunmap*
89:cu[nmap] {lhs} |mapmode-c| *:cu* *:cunmap*
Bram Moolenaar071d4272004-06-13 20:20:40 +000090 Remove the mapping of {lhs} for the modes where the
91 map command applies. The mapping may remain defined
92 for other modes where it applies.
93 Note: Trailing spaces are included in the {lhs}. This
94 unmap does NOT work: >
95 :map @@ foo
96 :unmap @@ | print
97
Bram Moolenaar06b5db92006-02-10 23:11:56 +000098:mapc[lear] |mapmode-nvo| *:mapc* *:mapclear*
99:nmapc[lear] |mapmode-n| *:nmapc* *:nmapclear*
100:vmapc[lear] |mapmode-v| *:vmapc* *:vmapclear*
Bram Moolenaar371d5402006-03-20 21:47:49 +0000101:xmapc[lear] |mapmode-x| *:xmapc* *:xmapclear*
102:smapc[lear] |mapmode-s| *:smapc* *:smapclear*
Bram Moolenaar06b5db92006-02-10 23:11:56 +0000103:omapc[lear] |mapmode-o| *:omapc* *:omapclear*
104:mapc[lear]! |mapmode-ic| *:mapc!* *:mapclear!*
105:imapc[lear] |mapmode-i| *:imapc* *:imapclear*
106:lmapc[lear] |mapmode-l| *:lmapc* *:lmapclear*
107:cmapc[lear] |mapmode-c| *:cmapc* *:cmapclear*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108 Remove ALL mappings for the modes where the map
109 command applies. {not in Vi}
110 Warning: This also removes the default mappings.
111
Bram Moolenaar06b5db92006-02-10 23:11:56 +0000112:map |mapmode-nvo|
113:nm[ap] |mapmode-n|
114:vm[ap] |mapmode-v|
Bram Moolenaar371d5402006-03-20 21:47:49 +0000115:xm[ap] |mapmode-x|
116:sm[ap] |mapmode-s|
Bram Moolenaar06b5db92006-02-10 23:11:56 +0000117:om[ap] |mapmode-o|
118:map! |mapmode-ic|
119:im[ap] |mapmode-i|
120:lm[ap] |mapmode-l|
121:cm[ap] |mapmode-c|
Bram Moolenaar071d4272004-06-13 20:20:40 +0000122 List all key mappings for the modes where the map
123 command applies. Note that ":map" and ":map!" are
124 used most often, because they include the other modes.
125
Bram Moolenaar06b5db92006-02-10 23:11:56 +0000126:map {lhs} |mapmode-nvo| *:map_l*
127:nm[ap] {lhs} |mapmode-n| *:nmap_l*
128:vm[ap] {lhs} |mapmode-v| *:vmap_l*
Bram Moolenaar371d5402006-03-20 21:47:49 +0000129:xm[ap] {lhs} |mapmode-x| *:xmap_l*
130:sm[ap] {lhs} |mapmode-s| *:smap_l*
Bram Moolenaar06b5db92006-02-10 23:11:56 +0000131:om[ap] {lhs} |mapmode-o| *:omap_l*
132:map! {lhs} |mapmode-ic| *:map_l!*
133:im[ap] {lhs} |mapmode-i| *:imap_l*
134:lm[ap] {lhs} |mapmode-l| *:lmap_l*
135:cm[ap] {lhs} |mapmode-c| *:cmap_l*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136 List the key mappings for the key sequences starting
137 with {lhs} in the modes where the map command applies.
138 {not in Vi}
139
140These commands are used to map a key or key sequence to a string of
141characters. You can use this to put command sequences under function keys,
142translate one key into another, etc. See |:mkexrc| for how to save and
143restore the current mappings.
144
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000145 *map-ambiguous*
146When two mappings start with the same sequence of characters, they are
147ambiguous. Example: >
148 :imap aa foo
149 :imap aaa bar
150When Vim has read "aa", it will need to get another character to be able to
151decide if "aa" or "aaa" should be mapped. This means that after typing "aa"
152that mapping won't get expanded yet, Vim is waiting for another character.
153If you type a space, then "foo" will get inserted, plus the space. If you
154type "a", then "bar" will get inserted.
155{Vi does not allow ambiguous mappings}
156
157
1581.2 SPECIAL ARGUMENTS *:map-arguments*
159
Bram Moolenaar4e427192006-03-10 21:34:27 +0000160"<buffer>", "<silent>", "<script>", "<expr>" and "<unique>" can be used in any
161order. They must appear right after the command, before any other arguments.
162
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163 *:map-local* *:map-<buffer>* *E224* *E225*
164If the first argument to one of these commands is "<buffer>" it will apply to
165mappings locally to the current buffer only. Example: >
166 :map <buffer> ,w /[.,;]<CR>
167Then you can map ",w" to something else in another buffer: >
168 :map <buffer> ,w /[#&!]<CR>
169The local buffer mappings are used before the global ones.
170The "<buffer>" argument can also be used to clear mappings: >
171 :unmap <buffer> ,w
172 :mapclear <buffer>
173Local mappings are also cleared when a buffer is deleted, but not when it is
174unloaded. Just like local option values.
175
176 *:map-<silent>* *:map-silent*
177To define a mapping which will not be echoed on the command line, add
178"<silent>" as the first argument. Example: >
179 :map <silent> ,h /Header<CR>
180The search string will not be echoed when using this mapping. Messages from
181the executed command are still given though. To shut them up too, add a
182":silent" in the executed command: >
183 :map <silent> ,h :exe ":silent normal /Header\r"<CR>
184Prompts will still be given, e.g., for inputdialog().
185Using "<silent>" for an abbreviation is possible, but will cause redrawing of
186the command line to fail.
187
188 *:map-<script>* *:map-script*
189If the first argument to one of these commands is "<script>" and it is used to
190define a new mapping or abbreviation, the mapping will only remap characters
191in the {rhs} using mappings that were defined local to a script, starting with
192"<SID>". This can be used to avoid that mappings from outside a script
193interfere (e.g., when CTRL-V is remapped in mswin.vim), but do use other
194mappings defined in the script.
195Note: ":map <script>" and ":noremap <script>" do the same thing. The
196"<script>" overrules the command name. Using ":noremap <script>" is
197preferred, because it's clearer that remapping is (mostly) disabled.
198
199 *:map-<unique>* *E226* *E227*
200If the first argument to one of these commands is "<unique>" and it is used to
201define a new mapping or abbreviation, the command will fail if the mapping or
202abbreviation already exists. Example: >
203 :map <unique> ,w /[#&!]<CR>
204When defining a local mapping, there will also be a check if a global map
205already exists which is equal.
206Example of what will fail: >
207 :map ,w /[#&!]<CR>
208 :map <buffer> <unique> ,w /[.,;]<CR>
Bram Moolenaara40ceaf2006-01-13 22:35:40 +0000209If you want to map a key and then have it do what it was originally mapped to,
210have a look at |maparg()|.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211
Bram Moolenaar4e427192006-03-10 21:34:27 +0000212 *:map-<expr>* *:map-expression*
213If the first argument to one of these commands is "<expr>" and it is used to
214define a new mapping or abbreviation, the argument is an expression. The
215expression is evaluated to obtain the {rhs} that is used. Example: >
216 :inoremap <expr> . InsertDot()
217The result of the InsertDot() function will be inserted. It could check the
218text before the cursor and start omni completion when some condition is met.
219
220Be very careful about side effects! The expression is evaluated while
221obtaining characters, if you change buffer text, move the cursor, edit another
222file, etc. you may very well make command disfunctional.
223
224Here is an example that inserts a list number that increases: >
225 let counter = 0
226 inoremap <expr> <C-L> ListItem()
227 inoremap <expr> <C-R> ListReset()
228
229 func ListItem()
230 let g:counter += 1
231 return g:counter . '. '
232 endfunc
233
234 func ListReset()
235 let g:counter = 0
236 return ''
237 endfunc
238
Bram Moolenaard9967712006-03-11 21:18:15 +0000239CTRL-L inserts the next number, CTRL-R resets the count. CTRL-R returns an
Bram Moolenaar4e427192006-03-10 21:34:27 +0000240empty string, so that nothing is inserted.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241
242
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00002431.3 MAPPING AND MODES *:map-modes*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000244
245There are five sets of mappings
246- For Normal mode: When typing commands.
247- For Visual mode: When typing commands while the Visual area is highlighted.
248- For Operator-pending mode: When an operator is pending (after "d", "y", "c",
249 etc.). Example: ":omap { w" makes "y{" work like "yw" and "d{" like "dw".
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000250- For Insert mode. These are also used in Replace mode.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251- For Command-line mode: When entering a ":" or "/" command.
252
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253Special case: While typing a count for a command in Normal mode, mapping zero
254is disabled. This makes it possible to map zero without making it impossible
255to type a count with a zero.
256
257 *map-overview* *map-modes*
258Overview of which map command works in which mode:
259
Bram Moolenaar06b5db92006-02-10 23:11:56 +0000260 *mapmode-nvo* *mapmode-n* *mapmode-v* *mapmode-o*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000261 commands: modes: ~
Bram Moolenaar371d5402006-03-20 21:47:49 +0000262 Normal Visual+Select Operator-pending ~
263:map :noremap :unmap :mapclear yes yes yes
264:nmap :nnoremap :nunmap :nmapclear yes - -
265:vmap :vnoremap :vunmap :vmapclear - yes -
266:omap :onoremap :ounmap :omapclear - - yes
267
268 *mapmode-x* *mapmode-s*
269Some commands work both in Visual and Select mode, some in only one. Note
270that quite often "Visual" is mentioned where both Visual and Select mode
271apply. |Select-mode-mapping|
272
273 commands: modes: ~
274 Visual Select ~
275:vmap :vnoremap :vunmap :vmapclear yes yes
276:xmap :xnoremap :xunmap :xmapclear yes -
277:smap :snoremap :sunmap :smapclear - yes
Bram Moolenaar071d4272004-06-13 20:20:40 +0000278
Bram Moolenaar06b5db92006-02-10 23:11:56 +0000279 *mapmode-ic* *mapmode-i* *mapmode-c* *mapmode-l*
Bram Moolenaar371d5402006-03-20 21:47:49 +0000280Some commands work both in Insert mode and Command-line mode, some not:
281
282 commands: modes: ~
Bram Moolenaar071d4272004-06-13 20:20:40 +0000283 Insert Command-line Lang-Arg ~
284:map! :noremap! :unmap! :mapclear! yes yes -
285:imap :inoremap :iunmap :imapclear yes - -
286:cmap :cnoremap :cunmap :cmapclear - yes -
287:lmap :lnoremap :lunmap :lmapclear yes* yes* yes*
288
289The original Vi did not have separate mappings for
290Normal/Visual/Operator-pending mode and for Insert/Command-line mode.
291Therefore the ":map" and ":map!" commands enter and display mappings for
292several modes. In Vim you can use the ":nmap", ":vmap", ":omap", ":cmap" and
293":imap" commands to enter mappings for each mode separately.
294
295To enter a mapping for Normal and Visual mode, but not Operator-pending mode,
296first define it for all three modes, then unmap it for Operator-pending mode:
297 :map xx something-difficult
298 :ounmap xx
299Likewise for a mapping for Visual and Operator-pending mode or Normal and
300Operator-pending mode.
301
302 *language-mapping*
303":lmap" defines a mapping that applies to:
304- Insert mode
305- Command-line mode
306- when entering a search pattern
307- the argument of the commands that accept a text character, such as "r" and
308 "f"
309- for the input() line
310Generally: Whenever a character is to be typed that is part of the text in the
311buffer, not a Vim command character. "Lang-Arg" isn't really another mode,
312it's just used here for this situation.
313 The simplest way to load a set of related language mappings is by using the
314'keymap' option. See |45.5|.
315 In Insert mode and in Command-line mode the mappings can be disabled with
316the CTRL-^ command |i_CTRL-^| |c_CTRL-^|. When starting to enter a normal
317command line (not a search pattern) the mappings are disabled until a CTRL-^
318is typed. The state last used is remembered for Insert mode and Search
319patterns separately. The state for Insert mode is also used when typing a
320character as an argument to command like "f" or "t".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000321 Language mappings will never be applied to already mapped characters. They
322are only used for typed characters. This assumes that the language mapping
323was already done when typing the mapping.
324
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00003261.4 LISTING MAPPINGS *map-listing*
327
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328When listing mappings the characters in the first two columns are:
329
330 CHAR MODE ~
331 <Space> Normal, Visual and Operator-pending
332 n Normal
333 v Visual
334 o Operator-pending
335 ! Insert and Command-line
336 i Insert
337 l ":lmap" mappings for Insert, Command-line and Lang-Arg
338 c Command-line
339
340Just before the {rhs} a special character can appear:
341 * indicates that it is not remappable
342 & indicates that only script-local mappings are remappable
343 @ indicates a buffer-local mapping
344
345Everything from the first non-blank after {lhs} up to the end of the line
346(or '|') is considered to be part of {rhs}. This allows the {rhs} to end
347with a space.
348
349Note: When using mappings for Visual mode, you can use the "'<" mark, which
350is the start of the last selected Visual area in the current buffer |'<|.
351
Bram Moolenaarae5bce12005-08-15 21:41:48 +0000352 *:map-verbose*
353When 'verbose' is non-zero, listing a key map will also display where it was
354last defined. Example: >
355
356 :verbose map <C-W>*
357 n <C-W>* * <C-W><C-S>*
358 Last set from /home/abcd/.vimrc
359
Bram Moolenaar5195e452005-08-19 20:32:47 +0000360See |:verbose-cmd| for more information.
Bram Moolenaarae5bce12005-08-15 21:41:48 +0000361
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000362
3631.5 MAPPING SPECIAL KEYS *:map-special-keys*
364
365There are three ways to map a special key:
3661. The Vi-compatible method: Map the key code. Often this is a sequence that
367 starts with <Esc>. To enter a mapping like this you type ":map " and then
368 you have to type CTRL-V before hitting the function key. Note that when
369 the key code for the key is in the termcap (the t_ options), it will
370 automatically be translated into the internal code and become the second
371 way of mapping (unless the 'k' flag is included in 'cpoptions').
3722. The second method is to use the internal code for the function key. To
373 enter such a mapping type CTRL-K and then hit the function key, or use
374 the form "#1", "#2", .. "#9", "#0", "<Up>", "<S-Down>", "<S-F7>", etc.
375 (see table of keys |key-notation|, all keys from <Up> can be used). The
376 first ten function keys can be defined in two ways: Just the number, like
377 "#2", and with "<F>", like "<F2>". Both stand for function key 2. "#0"
378 refers to function key 10, defined with option 't_f10', which may be
379 function key zero on some keyboards. The <> form cannot be used when
380 'cpoptions' includes the '<' flag.
3813. Use the termcap entry, with the form <t_xx>, where "xx" is the name of the
382 termcap entry. Any string entry can be used. For example: >
383 :map <t_F3> G
384< Maps function key 13 to "G". This does not work if 'cpoptions' includes
385 the '<' flag.
386
387The advantage of the second and third method is that the mapping will work on
388different terminals without modification (the function key will be
389translated into the same internal code or the actual key code, no matter what
390terminal you are using. The termcap must be correct for this to work, and you
391must use the same mappings).
392
393DETAIL: Vim first checks if a sequence from the keyboard is mapped. If it
394isn't the terminal key codes are tried (see |terminal-options|). If a
395terminal code is found it is replaced with the internal code. Then the check
396for a mapping is done again (so you can map an internal code to something
397else). What is written into the script file depends on what is recognized.
398If the terminal key code was recognized as a mapping the key code itself is
399written to the script file. If it was recognized as a terminal code the
400internal code is written to the script file.
401
402
4031.6 SPECIAL CHARACTERS *:map-special-chars*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 *map_backslash*
405Note that only CTRL-V is mentioned here as a special character for mappings
406and abbreviations. When 'cpoptions' does not contain 'B', a backslash can
407also be used like CTRL-V. The <> notation can be fully used then |<>|. But
408you cannot use "<C-V>" like CTRL-V to escape the special meaning of what
409follows.
410
411To map a backslash, or use a backslash literally in the {rhs}, the special
412sequence "<Bslash>" can be used. This avoids the need to double backslashes
413when using nested mappings.
414
Bram Moolenaar1e015462005-09-25 22:16:38 +0000415 *map_CTRL-C*
416Using CTRL-C in the {lhs} is possible, but it will only work when Vim is
417waiting for a key, not when Vim is busy with something. When Vim is busy
418CTRL-C interrupts/breaks the command.
419When using the GUI version on MS-Windows CTRL-C can be mapped to allow a Copy
420command to the clipboard. Use CTRL-Break to interrupt Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421
422 *map_space_in_lhs*
423To include a space in {lhs} precede it with a CTRL-V (type two CTRL-Vs for
424each space).
425 *map_space_in_rhs*
426If you want a {rhs} that starts with a space, use "<Space>". To be fully Vi
427compatible (but unreadable) don't use the |<>| notation, precede {rhs} with a
428single CTRL-V (you have to type CTRL-V two times).
429 *map_empty_rhs*
430You can create an empty {rhs} by typing nothing after a single CTRL-V (you
431have to type CTRL-V two times). Unfortunately, you cannot do this in a vimrc
432file.
433 *<Nop>*
434A easier way to get a mapping that doesn't produce anything, is to use "<Nop>"
435for the {rhs}. This only works when the |<>| notation is enabled. For
436example, to make sure that function key 8 does nothing at all: >
437 :map <F8> <Nop>
438 :map! <F8> <Nop>
439<
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000440 *map-multibyte*
441It is possible to map multibyte characters, but only the whole character. You
442cannot map the first byte only. This was done to prevent problems in this
443scenario: >
444 :set encoding=latin1
445 :imap <M-C> foo
446 :set encoding=utf-8
447The mapping for <M-C> is defined with the latin1 encoding, resulting in a 0xc3
448byte. If you type the character á (0xea <M-a>) in UTF-8 encoding this is the
449two bytes 0xc3 0xa1. You don't want the 0xc3 byte to be mapped then,
450otherwise it would be impossible to type the á character.
451
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 *<Leader>* *mapleader*
453To define a mapping which uses the "mapleader" variable, the special string
454"<Leader>" can be used. It is replaced with the string value of "mapleader".
455If "mapleader" is not set or empty, a backslash is used instead. Example: >
456 :map <Leader>A oanother line<Esc>
457Works like: >
458 :map \A oanother line<Esc>
459But after: >
460 :let mapleader = ","
461It works like: >
462 :map ,A oanother line<Esc>
463
464Note that the value of "mapleader" is used at the moment the mapping is
465defined. Changing "mapleader" after that has no effect for already defined
466mappings.
467
468 *<LocalLeader>* *maplocalleader*
469Just like <Leader>, except that it uses "maplocalleader" instead of
470"mapleader". <LocalLeader> is to be used for mappings which are local to a
471buffer. Example: >
472 :map <LocalLeader>q \DoItNow
473<
474In a global plugin <Leader> should be used and in a filetype plugin
475<LocalLeader>. "mapleader" and "maplocalleader" can be equal. Although, if
476you make them different, there is a smaller chance of mappings from global
477plugins to clash with mappings for filetype plugins. For example, you could
478keep "mapleader" at the default backslash, and set "maplocalleader" to an
479underscore.
480
481 *map-<SID>*
482In a script the special key name "<SID>" can be used to define a mapping
483that's local to the script. See |<SID>| for details.
484
485 *<Plug>*
486The special key name "<Plug>" can be used for an internal mapping, which is
487not to be matched with any key sequence. This is useful in plugins
488|using-<Plug>|.
489
490 *<Char>* *<Char->*
491To map a character by its decimal, octal or hexadecimal number the <Char>
492construct can be used:
493 <Char-123> character 123
494 <Char-033> character 27
495 <Char-0x7f> character 127
496This is useful to specify a (multi-byte) character in a 'keymap' file.
497Upper and lowercase differences are ignored.
498
499 *map-comments*
500It is not possible to put a comment after these commands, because the '"'
501character is considered to be part of the {lhs} or {rhs}.
502
503 *map_bar*
504Since the '|' character is used to separate a map command from the next
505command, you will have to do something special to include a '|' in {rhs}.
506There are three methods:
507 use works when example ~
508 <Bar> '<' is not in 'cpoptions' :map _l :!ls <Bar> more^M
509 \| 'b' is not in 'cpoptions' :map _l :!ls \| more^M
510 ^V| always, in Vim and Vi :map _l :!ls ^V| more^M
511
512(here ^V stands for CTRL-V; to get one CTRL-V you have to type it twice; you
513cannot use the <> notation "<C-V>" here).
514
515All three work when you use the default setting for 'cpoptions'.
516
517When 'b' is present in 'cpoptions', "\|" will be recognized as a mapping
518ending in a '\' and then another command. This is Vi compatible, but
519illogical when compared to other commands.
520
521 *map_return*
522When you have a mapping that contains an Ex command, you need to put a line
523terminator after it to have it executed. The use of <CR> is recommended for
524this (see |<>|). Example: >
525 :map _ls :!ls -l %<CR>:echo "the end"<CR>
526
527To avoid mapping of the characters you type in insert or Command-line mode,
528type a CTRL-V first. The mapping in Insert mode is disabled if the 'paste'
529option is on.
530
531Note that when an error is encountered (that causes an error message or beep)
532the rest of the mapping is not executed. This is Vi-compatible.
533
534Note that the second character (argument) of the commands @zZtTfF[]rm'`"v
535and CTRL-X is not mapped. This was done to be able to use all the named
536registers and marks, even when the command with the same name has been
537mapped.
538
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000539
5401.7 WHAT KEYS TO MAP *map-which-keys*
541
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542If you are going to map something, you will need to choose which key(s) to use
543for the {lhs}. You will have to avoid keys that are used for Vim commands,
544otherwise you would not be able to use those commands anymore. Here are a few
545suggestions:
546- Function keys <F2>, <F3>, etc.. Also the shifted function keys <S-F1>,
547 <S-F2>, etc. Note that <F1> is already used for the help command.
Bram Moolenaarcdbac1e2005-12-11 21:27:22 +0000548- Meta-keys (with the ALT key pressed). |:map-alt-keys|
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549- Use the '_' or ',' character and then any other character. The "_" and ","
550 commands do exist in Vim (see |_| and |,|), but you probably never use them.
551- Use a key that is a synonym for another command. For example: CTRL-P and
552 CTRL-N. Use an extra character to allow more mappings.
553
554See the file "index" for keys that are not used and thus can be mapped without
555losing any builtin function. You can also use ":help {key}^D" to find out if
556a key is used for some command. ({key} is the specific key you want to find
557out about, ^D is CTRL-D).
558
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000559
5601.8 EXAMPLES *map-examples*
561
Bram Moolenaar071d4272004-06-13 20:20:40 +0000562A few examples (given as you type them, for "<CR>" you type four characters;
563the '<' flag must not be present in 'cpoptions' for this to work). >
564
565 :map <F3> o#include
566 :map <M-g> /foo<CR>cwbar<Esc>
567 :map _x d/END/e<CR>
568 :map! qq quadrillion questions
569<
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000570
5711.9 USING MAPPINGS *map-typing*
572
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573Vim will compare what you type with the start of a mapped sequence. If there
574is an incomplete match, it will get more characters until there either is a
575complete match or until there is no match at all. Example: If you map! "qq",
576the first 'q' will not appear on the screen until you type another
577character. This is because Vim cannot know if the next character will be a
578'q' or not. If the 'timeout' option is on (which is the default) Vim will
579only wait for one second (or as long as specified with the 'timeoutlen'
580option). After that it assumes that the 'q' is to be interpreted as such. If
581you type slowly, or your system is slow, reset the 'timeout' option. Then you
582might want to set the 'ttimeout' option.
583
584 *map-keys-fails*
Bram Moolenaarcdbac1e2005-12-11 21:27:22 +0000585There are situations where key codes might not be recognized:
Bram Moolenaar071d4272004-06-13 20:20:40 +0000586- Vim can only read part of the key code. Mostly this is only the first
587 character. This happens on some Unix versions in an xterm.
588- The key code is after character(s) that are mapped. E.g., "<F1><F1>" or
589 "g<F1>".
Bram Moolenaarcdbac1e2005-12-11 21:27:22 +0000590
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591The result is that the key code is not recognized in this situation, and the
Bram Moolenaarcdbac1e2005-12-11 21:27:22 +0000592mapping fails. There are two actions needed to avoid this problem:
593
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594- Remove the 'K' flag from 'cpoptions'. This will make Vim wait for the rest
595 of the characters of the function key.
596- When using <F1> to <F4> the actual key code generated may correspond to
597 <xF1> to <xF4>. There are mappings from <xF1> to <F1>, <xF2> to <F2>, etc.,
598 but these are not recognized after another half a mapping. Make sure the
599 key codes for <F1> to <F4> are correct: >
600 :set <F1>=<type CTRL-V><type F1>
601< Type the <F1> as four characters. The part after the "=" must be done with
602 the actual keys, not the literal text.
603Another solution is to use the actual key code in the mapping for the second
604special key: >
605 :map <F1><Esc>OP :echo "yes"<CR>
606Don't type a real <Esc>, Vim will recognize the key code and replace it with
607<F1> anyway.
608
Bram Moolenaarcdbac1e2005-12-11 21:27:22 +0000609Another problem may be that when keeping ALT or Meta pressed the terminal
610prepends ESC instead of setting the 8th bit. See |:map-alt-keys|.
611
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 *recursive_mapping*
613If you include the {lhs} in the {rhs} you have a recursive mapping. When
614{lhs} is typed, it will be replaced with {rhs}. When the {lhs} which is
615included in {rhs} is encountered it will be replaced with {rhs}, and so on.
616This makes it possible to repeat a command an infinite number of times. The
617only problem is that the only way to stop this is by causing an error. The
618macros to solve a maze uses this, look there for an example. There is one
619exception: If the {rhs} starts with {lhs}, the first character is not mapped
620again (this is Vi compatible).
621For example: >
622 :map ab abcd
623will execute the "a" command and insert "bcd" in the text. The "ab" in the
624{rhs} will not be mapped again.
625
626If you want to exchange the meaning of two keys you should use the :noremap
627command. For example: >
628 :noremap k j
629 :noremap j k
630This will exchange the cursor up and down commands.
631
632With the normal :map command, when the 'remap' option is on, mapping takes
633place until the text is found not to be a part of a {lhs}. For example, if
634you use: >
635 :map x y
636 :map y x
637Vim will replace x with y, and then y with x, etc. When this has happened
638'maxmapdepth' times (default 1000), Vim will give the error message
639"recursive mapping".
640
641 *:map-undo*
642If you include an undo command inside a mapped sequence, this will bring the
643text back in the state before executing the macro. This is compatible with
644the original Vi, as long as there is only one undo command in the mapped
645sequence (having two undo commands in a mapped sequence did not make sense
646in the original Vi, you would get back the text before the first undo).
647
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00006491.10 MAPPING ALT-KEYS *:map-alt-keys*
Bram Moolenaarcdbac1e2005-12-11 21:27:22 +0000650
651In the GUI Vim handles the Alt key itself, thus mapping keys with ALT should
652always work. But in a terminal Vim gets a sequence of bytes and has to figure
653out whether ALT was pressed or not.
654
655By default Vim assumes that pressing the ALT key sets the 8th bit of a typed
Bram Moolenaar97d29a12005-12-17 22:02:57 +0000656character. Most decent terminals can work that way, such as xterm, aterm and
Bram Moolenaarcdbac1e2005-12-11 21:27:22 +0000657rxvt. If your <A-k> mappings don't work it might be that the terminal is
658prefixing the character with an ESC character. But you can just as well type
659ESC before a character, thus Vim doesn't know what happened (except for
660checking the delay between characters, which is not reliable).
661
662As of this writing, some mainstream terminals like gnome-terminal and konsole
663use the ESC prefix. There doesn't appear a way to have them use the 8th bit
Bram Moolenaar97d29a12005-12-17 22:02:57 +0000664instead. Xterm should work well by default. Aterm and rxvt should work well
665when started with the "--meta8" argument. You can also tweak resources like
666"metaSendsEscape", "eightBitInput" and "eightBitOutput".
Bram Moolenaarcdbac1e2005-12-11 21:27:22 +0000667
668On the Linux console, this behavior can be toggled with the "setmetamode"
669command. Bear in mind that not using an ESC prefix could get you in trouble
670with other programs. You should make sure that bash has the "convert-meta"
671option set to "on" in order for your Meta keybindings to still work on it
672(it's the default readline behavior, unless changed by specific system
673configuration). For that, you can add the line: >
674
675 set convert-meta on
676
677to your ~/.inputrc file. If you're creating the file, you might want to use: >
678
679 $include /etc/inputrc
680
681as the first line, if that file exists on your system, to keep global options.
682This may cause a problem for entering special characters, such as the umlaut.
683Then you should use CTRL-V before that character.
684
685Bear in mind that convert-meta has been reported to have troubles when used in
686UTF-8 locales. On terminals like xterm, the "metaSendsEscape" resource can be
687toggled on the fly through the "Main Options" menu, by pressing Ctrl-LeftClick
688on the terminal; that's a good last resource in case you want to send ESC when
689using other applications but not when inside VIM.
690
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000691
6921.11 MAPPING AN OPERATOR *:map-operator*
693
694An operator is used before a {motion} command. To define your own operator
695you must create mapping that first sets the 'operatorfunc' option and then
696invoke the |g@| operator. After the user types the {motion} command the
697specified function will be called.
698
Bram Moolenaara40ceaf2006-01-13 22:35:40 +0000699 *g@* *E774* *E775*
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000700g@{motion} Call the function set by the 'operatorfunc' option.
701 The '[ mark is positioned at the start of the text
702 moved over by {motion}, the '] mark on the last
703 character of the text.
704 The function is called with one String argument:
705 "line" {motion} was |linewise|
706 "char" {motion} was |characterwise|
707 "block" {motion} was |blockwise-visual||
708 Although "block" would rarely appear, since it can
709 only result from Visual mode where "g@" is not useful.
710 {not available when compiled without the +eval
711 feature}
712
713Here is an example that counts the number of spaces with <F4>: >
714
715 nmap <silent> <F4> :set opfunc=CountSpaces<CR>g@
716 vmap <silent> <F4> :<C-U>call CountSpaces(visualmode(), 1)<CR>
717
718 function! CountSpaces(type, ...)
719 let sel_save = &selection
720 let &selection = "inclusive"
721 let reg_save = @@
722
723 if a:0 " Invoked from Visual mode, use '< and '> marks.
724 silent exe "normal! `<" . a:type . "`>y"
725 elseif a:type == 'line'
726 silent exe "normal! '[V']y"
727 elseif a:type == 'block'
728 silent exe "normal! `[\<C-V>`]y"
729 else
730 silent exe "normal! `[v`]y"
731 endif
732
733 echomsg strlen(substitute(@@, '[^ ]', '', 'g'))
734
735 let &selection = sel_save
736 let @@ = reg_save
737 endfunction
738
739Note that the 'selection' option is temporarily set to "inclusive" to be able
740to yank exactly the right text by using Visual mode from the '[ to the ']
741mark.
742
743Also note that there is a separate mapping for Visual mode. It removes the
744"'<,'>" range that ":" inserts in Visual mode and invokes the function with
745visualmode() and an extra argument.
746
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747==============================================================================
7482. Abbreviations *abbreviations* *Abbreviations*
749
750Abbreviations are used in Insert mode, Replace mode and Command-line mode.
751If you enter a word that is an abbreviation, it is replaced with the word it
752stands for. This can be used to save typing for often used long words. And
753you can use it to automatically correct obvious spelling errors.
754Examples:
755
756 :iab ms MicroSoft
757 :iab tihs this
758
759There are three types of abbreviations:
760
761full-id The "full-id" type consists entirely of keyword characters (letters
762 and characters from 'iskeyword' option). This is the most common
763 abbreviation.
764
765 Examples: "foo", "g3", "-1"
766
767end-id The "end-id" type ends in a keyword character, but all the other
768 characters are not keyword characters.
769
770 Examples: "#i", "..f", "$/7"
771
772non-id The "non-id" type ends in a non-keyword character, the other
773 characters may be of any type, excluding space and Tab. {this type
774 is not supported by Vi}
775
776 Examples: "def#", "4/7$"
777
778Examples of strings that cannot be abbreviations: "a.b", "#def", "a b", "_$r"
779
780An abbreviation is only recognized when you type a non-keyword character.
781This can also be the <Esc> that ends insert mode or the <CR> that ends a
782command. The non-keyword character which ends the abbreviation is inserted
783after the expanded abbreviation. An exception to this is the character <C-]>,
784which is used to expand an abbreviation without inserting any extra
785characters.
786
787Example: >
788 :ab hh hello
789< "hh<Space>" is expanded to "hello<Space>"
790 "hh<C-]>" is expanded to "hello"
791
792The characters before the cursor must match the abbreviation. Each type has
793an additional rule:
794
795full-id In front of the match is a non-keyword character, or this is where
796 the line or insertion starts. Exception: When the abbreviation is
797 only one character, it is not recognized if there is a non-keyword
798 character in front of it, other than a space or a <Tab>.
799
800end-id In front of the match is a keyword character, or a space or a <Tab>,
801 or this is where the line or insertion starts.
802
803non-id In front of the match is a space, <Tab> or the start of the line or
804 the insertion.
805
806Examples: ({CURSOR} is where you type a non-keyword character) >
807 :ab foo four old otters
808< " foo{CURSOR}" is expanded to " four old otters"
809 " foobar{CURSOR}" is not expanded
810 "barfoo{CURSOR}" is not expanded
811>
812 :ab #i #include
813< "#i{CURSOR}" is expanded to "#include"
814 ">#i{CURSOR}" is not expanded
815>
Bram Moolenaar81695252004-12-29 20:58:21 +0000816 :ab ;; <endofline>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817< "test;;" is not expanded
818 "test ;;" is expanded to "test <endofline>"
819
820To avoid the abbreviation in insert mode: Type part of the abbreviation, exit
821insert mode with <Esc>, re-enter insert mode with "a" and type the rest. Or
822type CTRL-V before the character after the abbreviation.
823To avoid the abbreviation in Command-line mode: Type CTRL-V twice somewhere in
824the abbreviation to avoid it to be replaced. A CTRL-V in front of a normal
825character is mostly ignored otherwise.
826
827It is possible to move the cursor after an abbreviation: >
828 :iab if if ()<Left>
829This does not work if 'cpoptions' includes the '<' flag. |<>|
830
831You can even do more complicated things. For example, to consume the space
832typed after an abbreviation: >
833 func Eatchar(pat)
Bram Moolenaar32466aa2006-02-24 23:53:04 +0000834 let c = nr2char(getchar(0))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835 return (c =~ a:pat) ? '' : c
836 endfunc
837 iabbr <silent> if if ()<Left><C-R>=Eatchar('\s')<CR>
838
839There are no default abbreviations.
840
841Abbreviations are never recursive. You can use ":ab f f-o-o" without any
842problem. But abbreviations can be mapped. {some versions of Vi support
843recursive abbreviations, for no apparent reason}
844
845Abbreviations are disabled if the 'paste' option is on.
846
847 *:abbreviate-local* *:abbreviate-<buffer>*
848Just like mappings, abbreviations can be local to a buffer. This is mostly
849used in a |filetype-plugin| file. Example for a C plugin file: >
850 :abb <buffer> FF for (i = 0; i < ; ++i)
851<
852 *:ab* *:abbreviate*
853:ab[breviate] list all abbreviations. The character in the first
854 column indicates the mode where the abbreviation is
855 used: 'i' for insert mode, 'c' for Command-line
856 mode, '!' for both. These are the same as for
857 mappings, see |map-listing|.
858
Bram Moolenaare344bea2005-09-01 20:46:49 +0000859 *:abbreviate-verbose*
860When 'verbose' is non-zero, listing an abbreviation will also display where it
861was last defined. Example: >
862
863 :verbose abbreviate
864 ! teh the
865 Last set from /home/abcd/vim/abbr.vim
866
867See |:verbose-cmd| for more information.
868
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869:ab[breviate] {lhs} list the abbreviations that start with {lhs}
870 You may need to insert a CTRL-V (type it twice) to
871 avoid that a typed {lhs} is expanded, since
872 command-line abbreviations apply here.
873
874:ab[breviate] {lhs} {rhs}
875 add abbreviation for {lhs} to {rhs}. If {lhs} already
876 existed it is replaced with the new {rhs}. {rhs} may
877 contain spaces.
878
879 *:una* *:unabbreviate*
880:una[bbreviate] {lhs} Remove abbreviation for {lhs} from the list. If none
881 is found, remove abbreviations in which {lhs} matches
882 with the {rhs}. This is done so that you can even
883 remove abbreviations after expansion. To avoid
884 expansion insert a CTRL-V (type it twice).
885
886 *:norea* *:noreabbrev*
887:norea[bbrev] [lhs] [rhs]
888 same as ":ab", but no remapping for this {rhs} {not
889 in Vi}
890
891 *:ca* *:cabbrev*
892:ca[bbrev] [lhs] [rhs] same as ":ab", but for Command-line mode only. {not
893 in Vi}
894
895 *:cuna* *:cunabbrev*
896:cuna[bbrev] {lhs} same as ":una", but for Command-line mode only. {not
897 in Vi}
898
899 *:cnorea* *:cnoreabbrev*
900:cnorea[bbrev] [lhs] [rhs]
901 same as ":ab", but for Command-line mode only and no
902 remapping for this {rhs} {not in Vi}
903
904 *:ia* *:iabbrev*
905:ia[bbrev] [lhs] [rhs] same as ":ab", but for Insert mode only. {not in Vi}
906
907 *:iuna* *:iunabbrev*
908:iuna[bbrev] {lhs} same as ":una", but for insert mode only. {not in
909 Vi}
910
911 *:inorea* *:inoreabbrev*
912:inorea[bbrev] [lhs] [rhs]
913 same as ":ab", but for Insert mode only and no
914 remapping for this {rhs} {not in Vi}
915
916 *:abc* *:abclear*
917:abc[lear] Remove all abbreviations. {not in Vi}
918
919 *:iabc* *:iabclear*
920:iabc[lear] Remove all abbreviations for Insert mode. {not in Vi}
921
922 *:cabc* *:cabclear*
923:cabc[lear] Remove all abbreviations for Command-line mode. {not
924 in Vi}
925
926 *using_CTRL-V*
927It is possible to use special characters in the rhs of an abbreviation.
928CTRL-V has to be used to avoid the special meaning of most non printable
929characters. How many CTRL-Vs need to be typed depends on how you enter the
930abbreviation. This also applies to mappings. Let's use an example here.
931
932Suppose you want to abbreviate "esc" to enter an <Esc> character. When you
933type the ":ab" command in Vim, you have to enter this: (here ^V is a CTRL-V
934and ^[ is <Esc>)
935
936You type: ab esc ^V^V^V^V^V^[
937
938 All keyboard input is subjected to ^V quote interpretation, so
939 the first, third, and fifth ^V characters simply allow the second,
940 and fourth ^Vs, and the ^[, to be entered into the command-line.
941
942You see: ab esc ^V^V^[
943
944 The command-line contains two actual ^Vs before the ^[. This is
945 how it should appear in your .exrc file, if you choose to go that
946 route. The first ^V is there to quote the second ^V; the :ab
947 command uses ^V as its own quote character, so you can include quoted
Bram Moolenaar81695252004-12-29 20:58:21 +0000948 whitespace or the | character in the abbreviation. The :ab command
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949 doesn't do anything special with the ^[ character, so it doesn't need
950 to be quoted. (Although quoting isn't harmful; that's why typing 7
951 [but not 8!] ^Vs works.)
952
953Stored as: esc ^V^[
954
955 After parsing, the abbreviation's short form ("esc") and long form
956 (the two characters "^V^[") are stored in the abbreviation table.
957 If you give the :ab command with no arguments, this is how the
958 abbreviation will be displayed.
959
960 Later, when the abbreviation is expanded because the user typed in
961 the word "esc", the long form is subjected to the same type of
962 ^V interpretation as keyboard input. So the ^V protects the ^[
Bram Moolenaar81695252004-12-29 20:58:21 +0000963 character from being interpreted as the "exit Insert mode" character.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964 Instead, the ^[ is inserted into the text.
965
966Expands to: ^[
967
968[example given by Steve Kirkendall]
969
970==============================================================================
9713. Local mappings and functions *script-local*
972
973When using several Vim script files, there is the danger that mappings and
974functions used in one script use the same name as in other scripts. To avoid
975this, they can be made local to the script.
976
977 *<SID>* *<SNR>* *E81*
978The string "<SID>" can be used in a mapping or menu. This requires that the
979'<' flag is not present in 'cpoptions'.
980 When executing the map command, Vim will replace "<SID>" with the special
981key code <SNR>, followed by a number that's unique for the script, and an
982underscore. Example: >
983 :map <SID>Add
984could define a mapping "<SNR>23_Add".
985
986When defining a function in a script, "s:" can be prepended to the name to
987make it local to the script. But when a mapping is executed from outside of
988the script, it doesn't know in which script the function was defined. To
989avoid this problem, use "<SID>" instead of "s:". The same translation is done
990as for mappings. This makes it possible to define a call to the function in
Bram Moolenaar81695252004-12-29 20:58:21 +0000991a mapping.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992
993When a local function is executed, it runs in the context of the script it was
994defined in. This means that new functions and mappings it defines can also
995use "s:" or "<SID>" and it will use the same unique number as when the
996function itself was defined. Also, the "s:var" local script variables can be
997used.
998
999When executing an autocommand or a user command, it will run in the context of
1000the script it was defined in. This makes it possible that the command calls a
1001local function or uses a local mapping.
1002
1003Otherwise, using "<SID>" outside of a script context is an error.
1004
1005If you need to get the script number to use in a complicated script, you can
Bram Moolenaar4770d092006-01-12 23:22:24 +00001006use this function: >
1007 function s:SID()
1008 return matchstr(expand('<sfile>'), '<SNR>\zs\d\+\ze_SID$')
1009 endfun
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010
1011The "<SNR>" will be shown when listing functions and mappings. This is useful
1012to find out what they are defined to.
1013
1014The |:scriptnames| command can be used to see which scripts have been sourced
1015and what their <SNR> number is.
1016
1017This is all {not in Vi} and {not available when compiled without the +eval
1018feature}.
1019
1020==============================================================================
10214. User-defined commands *user-commands*
1022
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001023It is possible to define your own Ex commands. A user-defined command can act
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024just like a built-in command (it can have a range or arguments, arguments can
1025be completed as filenames or buffer names, etc), except that when the command
1026is executed, it is transformed into a normal ex command and then executed.
1027
1028For starters: See section |40.2| in the user manual.
1029
1030 *E183* *user-cmd-ambiguous*
1031All user defined commands must start with an uppercase letter, to avoid
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001032confusion with builtin commands. (There are a few builtin commands, notably
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033:Next, :Print and :X, which do start with an uppercase letter. The builtin
1034will always take precedence in these cases). The other characters of the user
1035command can be uppercase letters, lowercase letters or digits. When using
1036digits, note that other commands that take a numeric argument may become
1037ambiguous. For example, the command ":Cc2" could be the user command ":Cc2"
1038without an argument, or the command ":Cc" with argument "2". It is advised to
1039put a space between the command name and the argument to avoid these problems.
1040
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001041When using a user-defined command, the command can be abbreviated. However, if
1042an abbreviation is not unique, an error will be issued. Furthermore, a
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043built-in command will always take precedence.
1044
1045Example: >
1046 :command Rename ...
1047 :command Renumber ...
1048 :Rena " Means "Rename"
1049 :Renu " Means "Renumber"
1050 :Ren " Error - ambiguous
1051 :command Paste ...
1052 :P " The built-in :Print
1053
1054It is recommended that full names for user-defined commands are used in
1055scripts.
1056
1057:com[mand] *:com* *:command*
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001058 List all user-defined commands. When listing commands,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059 the characters in the first two columns are
1060 ! Command has the -bang attribute
1061 " Command has the -register attribute
1062 b Command is local to current buffer
1063 (see below for details on attributes)
1064
1065:com[mand] {cmd} List the user-defined commands that start with {cmd}
1066
Bram Moolenaar5b8d8fd2005-08-16 23:01:50 +00001067 *:command-verbose*
1068When 'verbose' is non-zero, listing a command will also display where it was
1069last defined. Example: >
1070
1071 :verbose command TOhtml
1072 Name Args Range Complete Definition
1073 TOhtml 0 % :call Convert2HTML(<line1>, <line2>)
1074 Last set from /usr/share/vim/vim-7.0/plugin/tohtml.vim
1075<
Bram Moolenaar5195e452005-08-19 20:32:47 +00001076See |:verbose-cmd| for more information.
Bram Moolenaar5b8d8fd2005-08-16 23:01:50 +00001077
Bram Moolenaar071d4272004-06-13 20:20:40 +00001078 *E174* *E182*
1079:com[mand][!] [{attr}...] {cmd} {rep}
1080 Define a user command. The name of the command is
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001081 {cmd} and its replacement text is {rep}. The command's
1082 attributes (see below) are {attr}. If the command
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 already exists, an error is reported, unless a ! is
1084 specified, in which case the command is redefined.
1085
1086:delc[ommand] {cmd} *:delc* *:delcommand* *E184*
1087 Delete the user-defined command {cmd}.
1088
1089:comc[lear] *:comc* *:comclear*
1090 Delete all user-defined commands.
1091
1092Command attributes
1093
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001094User-defined commands are treated by Vim just like any other ex commands. They
1095can have arguments, or have a range specified. Arguments are subject to
1096completion as filenames, buffers, etc. Exactly how this works depends upon the
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097command's attributes, which are specified when the command is defined.
1098
1099There are a number of attributes, split into four categories: argument
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001100handling, completion behavior, range handling, and special cases. The
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101attributes are described below, by category.
1102
1103Argument handling *E175* *E176*
1104
1105By default, a user defined command will take no arguments (and an error is
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001106reported if any are supplied). However, it is possible to specify that the
1107command can take arguments, using the -nargs attribute. Valid cases are:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108
1109 -nargs=0 No arguments are allowed (the default)
1110 -nargs=1 Exactly one argument is required
1111 -nargs=* Any number of arguments are allowed (0, 1, or many)
1112 -nargs=? 0 or 1 arguments are allowed
1113 -nargs=+ Arguments must be supplied, but any number are allowed
1114
1115Arguments are considered to be separated by (unescaped) spaces or Tabs in this
1116context.
1117
1118Note that arguments are used as text, not as expressions. Specifically,
1119"s:var" will use the script-local variable in the script where the command was
1120defined, not where it is invoked! Example:
1121 script1.vim: >
1122 :let s:error = "None"
1123 :command -nargs=1 Error echoerr <args>
1124< script2.vim: >
1125 :source script1.vim
1126 :let s:error = "Wrong!"
1127 :Error s:error
1128Executing script2.vim will result in "None" to be echoed. Not what you
1129intended! Calling a function may be an alternative.
1130
1131Completion behavior *:command-completion*
1132 *E179* *E180* *E181*
1133By default, the arguments of user defined commands do not undergo completion.
1134However, by specifying one or the other of the following attributes, argument
1135completion can be enabled:
1136
1137 -complete=augroup autocmd groups
1138 -complete=buffer buffer names
1139 -complete=command Ex command (and arguments)
1140 -complete=dir directory names
1141 -complete=environment environment variable names
1142 -complete=event autocommand events
1143 -complete=expression Vim expression
1144 -complete=file file and directory names
Bram Moolenaar362e1a32006-03-06 23:29:24 +00001145 -complete=shellcmd Shell command
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146 -complete=function function name
1147 -complete=help help subjects
1148 -complete=highlight highlight groups
1149 -complete=mapping mapping name
1150 -complete=menu menus
1151 -complete=option options
1152 -complete=tag tags
1153 -complete=tag_listfiles tags, file names are shown when CTRL-D is hit
1154 -complete=var user variables
1155 -complete=custom,{func} custom completion, defined via {func}
Bram Moolenaara466c992005-07-09 21:03:22 +00001156 -complete=customlist,{func} custom completion, defined via {func}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157
Bram Moolenaara5792f52005-11-23 21:25:05 +00001158
1159Custom completion *:command-completion-custom*
1160 *:command-completion-customlist*
1161 *E467* *E468*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162It is possible to define customized completion schemes via the "custom,{func}"
Bram Moolenaara466c992005-07-09 21:03:22 +00001163or the "customlist,{func}" completion argument. The {func} part should be a
1164function with the following prototype >
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165
1166 :function {func}(ArgLead, CmdLine, CursorPos)
1167
Bram Moolenaara466c992005-07-09 21:03:22 +00001168The function need not use all these arguments. The function should provide the
1169completion candidates as the return value.
1170
1171For the "custom" argument, the function should return the completion
1172candidates one per line in a newline separated string.
1173
1174For the "customlist" argument, the function should return the completion
Bram Moolenaara5792f52005-11-23 21:25:05 +00001175candidates as a Vim List. Non-string items in the list are ignored.
Bram Moolenaara466c992005-07-09 21:03:22 +00001176
1177The function arguments are:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 ArgLead the leading portion of the argument currently being
1179 completed on
1180 CmdLine the entire command line
Bram Moolenaara5792f52005-11-23 21:25:05 +00001181 CursorPos the cursor position in it (byte index)
Bram Moolenaara466c992005-07-09 21:03:22 +00001182The function may use these for determining context. For the "custom"
1183argument, it is not necessary to filter candidates against the (implicit
1184pattern in) ArgLead. Vim will do filter the candidates with its regexp engine
1185after function return, and this is probably more efficient in most cases. For
1186the "customlist" argument, Vim will not filter the returned completion
1187candidates and the user supplied function should filter the candidates.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188
1189The following example lists user names to a Finger command >
1190 :com -complete=custom,ListUsers -nargs=1 Finger !finger <args>
1191 :fun ListUsers(A,L,P)
1192 : return system("cut -d: -f1 /etc/passwd")
1193 :endfun
1194
Bram Moolenaara466c992005-07-09 21:03:22 +00001195The following example completes filenames from the directories specified in
1196the 'path' option: >
1197 :com -nargs=1 -bang -complete=customlist,EditFileComplete
1198 \ EditFile edit<bang> <args>
1199 :fun EditFileComplete(A,L,P)
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00001200 : return split(globpath(&path, a:ArgLead), "\n")
Bram Moolenaara466c992005-07-09 21:03:22 +00001201 :endfun
1202<
Bram Moolenaara5792f52005-11-23 21:25:05 +00001203
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204Range handling *E177* *E178*
1205
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001206By default, user-defined commands do not accept a line number range. However,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207it is possible to specify that the command does take a range (the -range
1208attribute), or that it takes an arbitrary count value, either in the line
1209number position (-range=N, like the |:split| command) or as a "count"
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001210argument (-count=N, like the |:Next| command). Possible attributes are:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211
1212 -range Range allowed, default is current line
1213 -range=% Range allowed, default is whole file (1,$)
1214 -range=N A count (default N) which is specified in the line
1215 number position (like |:split|)
1216 -count=N A count (default N) which is specified either in the line
Bram Moolenaar32e7b2d2005-02-27 22:36:47 +00001217 number position, or as an initial argument (like |:Next|).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218 Specifying -count (without a default) acts like -count=0
1219
1220Note that -range=N and -count=N are mutually exclusive - only one should be
1221specified.
1222
1223Special cases
1224
1225There are some special cases as well:
1226
1227 -bang The command can take a ! modifier (like :q or :w)
1228 -bar The command can be followed by a "|" and another command.
1229 A "|" inside the command argument is not allowed then.
1230 Also checks for a " to start a comment.
1231 -register The first argument to the command can be an optional
1232 register name (like :del, :put, :yank).
1233 -buffer The command will only be available in the current buffer.
1234
1235In the cases of the -count and -register attributes, if the optional argument
1236is supplied, it is removed from the argument list and is available to the
1237replacement text separately.
1238
1239Replacement text
1240
1241The replacement text for a user defined command is scanned for special escape
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001242sequences, using <...> notation. Escape sequences are replaced with values
1243from the entered command line, and all other text is copied unchanged. The
Bram Moolenaar371d5402006-03-20 21:47:49 +00001244resulting string is executed as an Ex command. To avoid the replacement use
1245<lt> in plade of the initial <. Thus to include "<bang>" literally use
1246"<lt>bang>".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001247
1248The valid escape sequences are
1249
1250 *<line1>*
1251 <line1> The starting line of the command range.
1252 *<line2>*
1253 <line2> The final line of the command range.
1254 *<count>*
1255 <count> Any count supplied (as described for the '-range'
1256 and '-count' attributes).
1257 *<bang>*
1258 <bang> (See the '-bang' attribute) Expands to a ! if the
1259 command was executed with a ! modifier, otherwise
1260 expands to nothing.
1261 *<reg>* *<register>*
1262 <reg> (See the '-register' attribute) The optional register,
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001263 if specified. Otherwise, expands to nothing. <register>
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264 is a synonym for this.
1265 *<args>*
1266 <args> The command arguments, exactly as supplied (but as
1267 noted above, any count or register can consume some
1268 of the arguments, which are then not part of <args>).
1269 <lt> A single '<' (Less-Than) character. This is needed if you
1270 want to get a literal copy of one of these escape sequences
1271 into the expansion - for example, to get <bang>, use
1272 <lt>bang>.
1273
1274 *<q-args>*
1275If the first two characters of an escape sequence are "q-" (for example,
1276<q-args>) then the value is quoted in such a way as to make it a valid value
1277for use in an expression. This uses the argument as one single value.
Bram Moolenaar51485f02005-06-04 21:55:20 +00001278When there is no argument <q-args> is an empty string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001279
1280To allow commands to pass their arguments on to a user-defined function, there
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00001281is a special form <f-args> ("function args"). This splits the command
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282arguments at spaces and Tabs, quotes each argument individually, and the
1283<f-args> sequence is replaced by the comma-separated list of quoted arguments.
Bram Moolenaar5b8d8fd2005-08-16 23:01:50 +00001284See the Mycmd example below. If no arguments are given <f-args> is removed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285
1286Examples >
1287
1288 " Delete everything after here to the end
1289 :com Ddel +,$d
1290
1291 " Rename the current buffer
1292 :com -nargs=1 -bang -complete=file Ren f <args>|w<bang>
1293
1294 " Replace a range with the contents of a file
1295 " (Enter this all as one line)
1296 :com -range -nargs=1 -complete=file
1297 Replace <line1>-pu_|<line1>,<line2>d|r <args>|<line1>d
1298
1299 " Count the number of lines in the range
Bram Moolenaar81695252004-12-29 20:58:21 +00001300 :com! -range -nargs=0 Lines echo <line2> - <line1> + 1 "lines"
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301
1302 " Call a user function (example of <f-args>)
1303 :com -nargs=* Mycmd call Myfunc(<f-args>)
1304
1305When executed as: >
1306 :Mycmd arg1 arg2
1307This will invoke: >
1308 :call Myfunc("arg1","arg2")
1309
1310 :" A more substantial example
1311 :function Allargs(command)
1312 : let i = 0
1313 : while i < argc()
1314 : if filereadable(argv(i))
1315 : execute "e " . argv(i)
1316 : execute a:command
1317 : endif
1318 : let i = i + 1
1319 : endwhile
1320 :endfunction
1321 :command -nargs=+ -complete=command Allargs call Allargs(<q-args>)
1322
1323The command Allargs takes any Vim command(s) as argument and executes it on all
1324files in the argument list. Usage example (note use of the "e" flag to ignore
1325errors and the "update" command to write modified buffers): >
1326 :Allargs %s/foo/bar/ge|update
1327This will invoke: >
1328 :call Allargs("%s/foo/bar/ge|update")
1329<
1330When defining an user command in a script, it will be able to call functions
1331local to the script and use mappings local to the script. When the user
1332invokes the user command, it will run in the context of the script it was
1333defined in. This matters if |<SID>| is used in a command.
1334
1335 vim:tw=78:ts=8:ft=help:norl: