map.txt 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804
  1. *map.txt* Nvim
  2. VIM REFERENCE MANUAL by Bram Moolenaar
  3. Key mapping, abbreviations and user-defined commands.
  4. This subject is introduced in sections |05.3|, |24.7| and |40.1| of the user
  5. manual.
  6. Type |gO| to see the table of contents.
  7. ==============================================================================
  8. 1. Key mapping *keybind* *key-mapping* *mapping*
  9. Key mapping is used to change the meaning of typed keys. The most common use
  10. is to define a sequence of commands for a function key. Example: >
  11. :map <F2> a<C-R>=strftime("%c")<CR><Esc>
  12. This appends the current date and time after the cursor (in <> notation |<>|).
  13. 1.1 MAP COMMANDS *:map-commands*
  14. There are commands to enter new mappings, remove mappings and list mappings.
  15. See |map-overview| for the various forms of "map" and their relationships with
  16. modes.
  17. {lhs} means left-hand-side *{lhs}*
  18. {rhs} means right-hand-side *{rhs}*
  19. :map {lhs} {rhs} |mapmode-nvo| *:map*
  20. :nm[ap] {lhs} {rhs} |mapmode-n| *:nm* *:nmap*
  21. :vm[ap] {lhs} {rhs} |mapmode-v| *:vm* *:vmap*
  22. :xm[ap] {lhs} {rhs} |mapmode-x| *:xm* *:xmap*
  23. :smap {lhs} {rhs} |mapmode-s| *:smap*
  24. :om[ap] {lhs} {rhs} |mapmode-o| *:om* *:omap*
  25. :map! {lhs} {rhs} |mapmode-ic| *:map!*
  26. :im[ap] {lhs} {rhs} |mapmode-i| *:im* *:imap*
  27. :lm[ap] {lhs} {rhs} |mapmode-l| *:lm* *:lma* *:lmap*
  28. :cm[ap] {lhs} {rhs} |mapmode-c| *:cm* *:cmap*
  29. :tma[p] {lhs} {rhs} |mapmode-t| *:tma* *:tmap*
  30. Map the key sequence {lhs} to {rhs} for the modes
  31. where the map command applies. The result, including
  32. {rhs}, is then further scanned for mappings. This
  33. allows for nested and recursive use of mappings.
  34. Note: Trailing spaces are included in the {rhs},
  35. because space is a valid Normal mode command.
  36. See |map-trailing-white|.
  37. *:nore* *:norem*
  38. :no[remap] {lhs} {rhs} |mapmode-nvo| *:no* *:noremap* *:nor*
  39. :nn[oremap] {lhs} {rhs} |mapmode-n| *:nn* *:nnoremap*
  40. :vn[oremap] {lhs} {rhs} |mapmode-v| *:vn* *:vnoremap*
  41. :xn[oremap] {lhs} {rhs} |mapmode-x| *:xn* *:xnoremap*
  42. :snor[emap] {lhs} {rhs} |mapmode-s| *:snor* *:snore* *:snoremap*
  43. :ono[remap] {lhs} {rhs} |mapmode-o| *:ono* *:onoremap*
  44. :no[remap]! {lhs} {rhs} |mapmode-ic| *:no!* *:noremap!*
  45. :ino[remap] {lhs} {rhs} |mapmode-i| *:ino* *:inor* *:inoremap*
  46. :ln[oremap] {lhs} {rhs} |mapmode-l| *:ln* *:lnoremap*
  47. :cno[remap] {lhs} {rhs} |mapmode-c| *:cno* *:cnor* *:cnoremap*
  48. :tno[remap] {lhs} {rhs} |mapmode-t| *:tno* *:tnoremap*
  49. Map the key sequence {lhs} to {rhs} for the modes
  50. where the map command applies. Disallow mapping of
  51. {rhs}, to avoid nested and recursive mappings. Often
  52. used to redefine a command.
  53. Note: Keys in {rhs} also won't trigger abbreviation,
  54. with the exception of |i_CTRL-]| and |c_CTRL-]|.
  55. Note: When <Plug> appears in the {rhs} this part is
  56. always applied even if remapping is disallowed.
  57. :unm[ap] {lhs} |mapmode-nvo| *:unm* *:unmap*
  58. :nun[map] {lhs} |mapmode-n| *:nun* *:nunmap*
  59. :vu[nmap] {lhs} |mapmode-v| *:vu* *:vunmap*
  60. :xu[nmap] {lhs} |mapmode-x| *:xu* *:xunmap*
  61. :sunm[ap] {lhs} |mapmode-s| *:sunm* *:sunmap*
  62. :ou[nmap] {lhs} |mapmode-o| *:ou* *:ounmap*
  63. :unm[ap]! {lhs} |mapmode-ic| *:unm!* *:unmap!*
  64. :iu[nmap] {lhs} |mapmode-i| *:iu* *:iunmap*
  65. :lu[nmap] {lhs} |mapmode-l| *:lu* *:lunmap*
  66. :cu[nmap] {lhs} |mapmode-c| *:cu* *:cun* *:cunmap*
  67. :tunma[p] {lhs} |mapmode-t| *:tunma* *:tunmap*
  68. Remove the mapping of {lhs} for the modes where the
  69. map command applies. The mapping may remain defined
  70. for other modes where it applies.
  71. It also works when {lhs} matches the {rhs} of a
  72. mapping. This is for when an abbreviation applied.
  73. Note: Trailing spaces are included in the {lhs}.
  74. See |map-trailing-white|.
  75. :mapc[lear] |mapmode-nvo| *:mapc* *:mapclear*
  76. :nmapc[lear] |mapmode-n| *:nmapc* *:nmapclear*
  77. :vmapc[lear] |mapmode-v| *:vmapc* *:vmapclear*
  78. :xmapc[lear] |mapmode-x| *:xmapc* *:xmapclear*
  79. :smapc[lear] |mapmode-s| *:smapc* *:smapclear*
  80. :omapc[lear] |mapmode-o| *:omapc* *:omapclear*
  81. :mapc[lear]! |mapmode-ic| *:mapc!* *:mapclear!*
  82. :imapc[lear] |mapmode-i| *:imapc* *:imapclear*
  83. :lmapc[lear] |mapmode-l| *:lmapc* *:lmapclear*
  84. :cmapc[lear] |mapmode-c| *:cmapc* *:cmapclear*
  85. :tmapc[lear] |mapmode-t| *:tmapc* *:tmapclear*
  86. Remove ALL mappings for the modes where the map
  87. command applies.
  88. Use the <buffer> argument to remove buffer-local
  89. mappings |:map-<buffer>|
  90. Warning: This also removes the |default-mappings|.
  91. :map |mapmode-nvo|
  92. :nm[ap] |mapmode-n|
  93. :vm[ap] |mapmode-v|
  94. :xm[ap] |mapmode-x|
  95. :sm[ap] |mapmode-s|
  96. :om[ap] |mapmode-o|
  97. :map! |mapmode-ic|
  98. :im[ap] |mapmode-i|
  99. :lm[ap] |mapmode-l|
  100. :cm[ap] |mapmode-c|
  101. :tma[p] |mapmode-t|
  102. List all key mappings for the modes where the map
  103. command applies. Note that ":map" and ":map!" are
  104. used most often, because they include the other modes.
  105. :map {lhs} |mapmode-nvo| *:map_l*
  106. :nm[ap] {lhs} |mapmode-n| *:nmap_l*
  107. :vm[ap] {lhs} |mapmode-v| *:vmap_l*
  108. :xm[ap] {lhs} |mapmode-x| *:xmap_l*
  109. :sm[ap] {lhs} |mapmode-s| *:smap_l*
  110. :om[ap] {lhs} |mapmode-o| *:omap_l*
  111. :map! {lhs} |mapmode-ic| *:map_l!*
  112. :im[ap] {lhs} |mapmode-i| *:imap_l*
  113. :lm[ap] {lhs} |mapmode-l| *:lmap_l*
  114. :cm[ap] {lhs} |mapmode-c| *:cmap_l*
  115. :tma[p] {lhs} |mapmode-t| *:tmap_l*
  116. List the key mappings for the key sequences starting
  117. with {lhs} in the modes where the map command applies.
  118. These commands are used to map a key or key sequence to a string of
  119. characters. You can use this to put command sequences under function keys,
  120. translate one key into another, etc. See |:mkexrc| for how to save and
  121. restore the current mappings.
  122. *map-ambiguous*
  123. When two mappings start with the same sequence of characters, they are
  124. ambiguous. Example: >
  125. :imap aa foo
  126. :imap aaa bar
  127. When Vim has read "aa", it will need to get another character to be able to
  128. decide if "aa" or "aaa" should be mapped. This means that after typing "aa"
  129. that mapping won't get expanded yet, Vim is waiting for another character.
  130. If you type a space, then "foo" will get inserted, plus the space. If you
  131. type "a", then "bar" will get inserted.
  132. Trailing white space ~
  133. *map-trailing-white*
  134. This unmap command does NOT work: >
  135. :map @@ foo
  136. :unmap @@ | print
  137. Because it tries to unmap "@@ ", including the white space before the command
  138. separator "|". Other examples with trailing white space: >
  139. unmap @@
  140. unmap @@ " comment
  141. An error will be issued, which is very hard to identify, because the ending
  142. whitespace character in `unmap @@ ` is not visible.
  143. A generic solution is to put the command separator "|" right after the mapped
  144. keys. After that white space and a comment may follow: >
  145. unmap @@| " comment
  146. 1.2 SPECIAL ARGUMENTS *:map-arguments*
  147. "<buffer>", "<nowait>", "<silent>", "<script>", "<expr>" and
  148. "<unique>" can be used in any order. They must appear right after the
  149. command, before any other arguments.
  150. *:map-local* *:map-<buffer>* *:map-buffer*
  151. *E224* *E225*
  152. If the first argument to one of these commands is "<buffer>" the mapping will
  153. be effective in the current buffer only. Example: >
  154. :map <buffer> ,w /[.,;]<CR>
  155. Then you can map ",w" to something else in another buffer: >
  156. :map <buffer> ,w /[#&!]<CR>
  157. The local buffer mappings are used before the global ones. See <nowait> below
  158. to make a short local mapping not taking effect when a longer global one
  159. exists.
  160. The "<buffer>" argument can also be used to clear mappings: >
  161. :unmap <buffer> ,w
  162. :mapclear <buffer>
  163. Local mappings are also cleared when a buffer is deleted, but not when it is
  164. unloaded. Just like local option values.
  165. Also see |map-precedence|.
  166. *:map-<nowait>* *:map-nowait*
  167. When defining a buffer-local mapping for "," there may be a global mapping
  168. that starts with ",". Then you need to type another character for Vim to know
  169. whether to use the "," mapping or the longer one. To avoid this add the
  170. <nowait> argument. Then the mapping will be used when it matches, Vim does
  171. not wait for more characters to be typed. However, if the characters were
  172. already typed they are used.
  173. Note that this works when the <nowait> mapping fully matches and is found
  174. before any partial matches. This works when:
  175. - There is only one matching buffer-local mapping, since these are always
  176. found before global mappings.
  177. - There is another buffer-local mapping that partly matches, but it is
  178. defined earlier (last defined mapping is found first).
  179. *:map-<silent>* *:map-silent*
  180. To define a mapping which will not be echoed on the command line, add
  181. "<silent>" as the first argument. Example: >
  182. :map <silent> ,h /Header<CR>
  183. The search string will not be echoed when using this mapping. Messages from
  184. the executed command are still given though. To shut them up too, add a
  185. ":silent" in the executed command: >
  186. :map <silent> ,h :exe ":silent normal /Header\r"<CR>
  187. Note that the effect of a command might also be silenced, e.g., when the
  188. mapping selects another entry for command line completion it won't be
  189. displayed.
  190. Prompts will still be given, e.g., for inputdialog().
  191. Using "<silent>" for an abbreviation is possible, but will cause redrawing of
  192. the command line to fail.
  193. *:map-<script>* *:map-script*
  194. If the first argument to one of these commands is "<script>" and it is used to
  195. define a new mapping or abbreviation, the mapping will only remap characters
  196. in the {rhs} using mappings that were defined local to a script, starting with
  197. "<SID>". This can be used to avoid that mappings from outside a script
  198. interfere (e.g., when CTRL-V is remapped in mswin.vim), but do use other
  199. mappings defined in the script.
  200. Note: ":map <script>" and ":noremap <script>" do the same thing. The
  201. "<script>" overrules the command name. Using ":noremap <script>" is
  202. preferred, because it's clearer that remapping is (mostly) disabled.
  203. *:map-<unique>* *:map-unique* *E226* *E227*
  204. If the first argument to one of these commands is "<unique>" and it is used to
  205. define a new mapping or abbreviation, the command will fail if the mapping or
  206. abbreviation already exists. Example: >
  207. :map <unique> ,w /[#&!]<CR>
  208. When defining a local mapping, there will also be a check if a global map
  209. already exists which is equal.
  210. Example of what will fail: >
  211. :map ,w /[#&!]<CR>
  212. :map <buffer> <unique> ,w /[.,;]<CR>
  213. If you want to map a key and then have it do what it was originally mapped to,
  214. have a look at |maparg()|.
  215. *:map-<expr>* *:map-expression*
  216. If the first argument to one of these commands is "<expr>" and it is used to
  217. define a new mapping or abbreviation, the argument is an expression. The
  218. expression is evaluated to obtain the {rhs} that is used. Example: >
  219. :inoremap <expr> . <SID>InsertDot()
  220. The result of the s:InsertDot() function will be inserted. It could check the
  221. text before the cursor and start omni completion when some condition is met.
  222. Using a script-local function is preferred, to avoid polluting the global
  223. namespace. Use <SID> in the RHS so that the script that the mapping was
  224. defined in can be found.
  225. For abbreviations |v:char| is set to the character that was typed to trigger
  226. the abbreviation. You can use this to decide how to expand the {lhs}. You
  227. should not either insert or change the v:char.
  228. In case you want the mapping to not do anything, you can have the expression
  229. evaluate to an empty string. If something changed that requires Vim to
  230. go through the main loop (e.g. to update the display), return "\<Ignore>".
  231. This is similar to "nothing" but makes Vim return from the loop that waits for
  232. input.
  233. Keep in mind that the expression may be evaluated when looking for
  234. typeahead, before the previous command has been executed. For example: >
  235. func StoreColumn()
  236. let g:column = col('.')
  237. return 'x'
  238. endfunc
  239. nnoremap <expr> x StoreColumn()
  240. nmap ! f!x
  241. You will notice that g:column has the value from before executing "f!",
  242. because "x" is evaluated before "f!" is executed.
  243. This can be solved by inserting <Ignore> before the character that is
  244. expression-mapped: >
  245. nmap ! f!<Ignore>x
  246. Be very careful about side effects! The expression is evaluated while
  247. obtaining characters, you may very well make the command dysfunctional.
  248. Therefore the following is blocked for <expr> mappings:
  249. - Changing the buffer text |textlock|.
  250. - Editing another buffer.
  251. - The |:normal| command.
  252. - Moving the cursor is allowed, but it is restored afterwards.
  253. - If the cmdline is changed, the old text and cursor position are restored.
  254. If you want the mapping to do any of these let the returned characters do
  255. that, or use a |<Cmd>| mapping instead.
  256. You can use getchar(), it consumes typeahead if there is any. E.g., if you
  257. have these mappings: >
  258. inoremap <expr> <C-L> nr2char(getchar())
  259. inoremap <expr> <C-L>x "foo"
  260. If you now type CTRL-L nothing happens yet, Vim needs the next character to
  261. decide what mapping to use. If you type 'x' the second mapping is used and
  262. "foo" is inserted. If you type any other key the first mapping is used,
  263. getchar() gets the typed key and returns it.
  264. Here is an example that inserts a list number that increases: >
  265. let counter = 0
  266. inoremap <expr> <C-L> ListItem()
  267. inoremap <expr> <C-R> ListReset()
  268. func ListItem()
  269. let g:counter += 1
  270. return g:counter .. '. '
  271. endfunc
  272. func ListReset()
  273. let g:counter = 0
  274. return ''
  275. endfunc
  276. CTRL-L inserts the next number, CTRL-R resets the count. CTRL-R returns an
  277. empty string, so that nothing is inserted.
  278. Note that using 0x80 as a single byte before other text does not work, it will
  279. be seen as a special key.
  280. *<Cmd>* *:map-cmd*
  281. The <Cmd> pseudokey begins a "command mapping", which executes the command
  282. directly without changing modes. Where you might use ":...<CR>" in the
  283. {rhs} of a mapping, you can instead use "<Cmd>...<CR>".
  284. Example: >
  285. noremap x <Cmd>echo mode(1)<CR>
  286. <
  287. This is more flexible than `:<C-U>` in Visual and Operator-pending mode, or
  288. `<C-O>:` in Insert mode, because the commands are executed directly in the
  289. current mode, instead of always going to Normal mode. Visual mode is
  290. preserved, so tricks with |gv| are not needed. Commands can be invoked
  291. directly in Command-line mode (which would otherwise require timer hacks).
  292. Example of using <Cmd> halfway Insert mode: >
  293. nnoremap <F3> aText <Cmd>echo mode(1)<CR> Added<Esc>
  294. Unlike <expr> mappings, there are no special restrictions on the <Cmd>
  295. command: it is executed as if an (unrestricted) |autocommand| was invoked
  296. or an async event was processed.
  297. Note:
  298. - Because <Cmd> avoids mode-changes (unlike ":") it does not trigger
  299. |CmdlineEnter| and |CmdlineLeave| events. This helps performance.
  300. - For the same reason, |keycodes| like <C-R><C-W> are interpreted as plain,
  301. unmapped keys.
  302. - The command is not echo'ed, no need for <silent>.
  303. - The {rhs} is not subject to abbreviations nor to other mappings, even if the
  304. mapping is recursive.
  305. - In Visual mode you can use `line('v')` and `col('v')` to get one end of the
  306. Visual area, the cursor is at the other end.
  307. *E1255* *E1136*
  308. <Cmd> commands must terminate, that is, they must be followed by <CR> in the
  309. {rhs} of the mapping definition. |Command-line| mode is never entered. To use
  310. a literal <CR> in the {rhs}, use |<lt>|.
  311. 1.3 MAPPING AND MODES *:map-modes*
  312. *mapmode-nvo* *mapmode-n* *mapmode-v* *mapmode-o* *mapmode-t*
  313. There are seven sets of mappings
  314. - For Normal mode: When typing commands.
  315. - For Visual mode: When typing commands while the Visual area is highlighted.
  316. - For Select mode: like Visual mode but typing text replaces the selection.
  317. - For Operator-pending mode: When an operator is pending (after "d", "y", "c",
  318. etc.). See below: |omap-info|.
  319. - For Insert mode. These are also used in Replace mode.
  320. - For Command-line mode: When entering a ":" or "/" command.
  321. - For Terminal mode: When typing in a |:terminal| buffer.
  322. Special case: While typing a count for a command in Normal mode, mapping zero
  323. is disabled. This makes it possible to map zero without making it impossible
  324. to type a count with a zero.
  325. *map-overview* *map-modes*
  326. Overview of which map command works in which mode. More details below.
  327. COMMANDS MODES ~
  328. :map :noremap :unmap Normal, Visual, Select, Operator-pending
  329. :nmap :nnoremap :nunmap Normal
  330. :vmap :vnoremap :vunmap Visual and Select
  331. :smap :snoremap :sunmap Select
  332. :xmap :xnoremap :xunmap Visual
  333. :omap :onoremap :ounmap Operator-pending
  334. :map! :noremap! :unmap! Insert and Command-line
  335. :imap :inoremap :iunmap Insert
  336. :lmap :lnoremap :lunmap Insert, Command-line, Lang-Arg
  337. :cmap :cnoremap :cunmap Command-line
  338. :tmap :tnoremap :tunmap Terminal
  339. Same information in a table:
  340. *map-table*
  341. Mode | Norm | Ins | Cmd | Vis | Sel | Opr | Term | Lang | ~
  342. Command +------+-----+-----+-----+-----+-----+------+------+ ~
  343. [nore]map | yes | - | - | yes | yes | yes | - | - |
  344. n[nore]map | yes | - | - | - | - | - | - | - |
  345. [nore]map! | - | yes | yes | - | - | - | - | - |
  346. i[nore]map | - | yes | - | - | - | - | - | - |
  347. c[nore]map | - | - | yes | - | - | - | - | - |
  348. v[nore]map | - | - | - | yes | yes | - | - | - |
  349. x[nore]map | - | - | - | yes | - | - | - | - |
  350. s[nore]map | - | - | - | - | yes | - | - | - |
  351. o[nore]map | - | - | - | - | - | yes | - | - |
  352. t[nore]map | - | - | - | - | - | - | yes | - |
  353. l[nore]map | - | yes | yes | - | - | - | - | yes |
  354. COMMANDS MODES ~
  355. Normal Visual+Select Operator-pending ~
  356. :map :noremap :unmap :mapclear yes yes yes
  357. :nmap :nnoremap :nunmap :nmapclear yes - -
  358. :vmap :vnoremap :vunmap :vmapclear - yes -
  359. :omap :onoremap :ounmap :omapclear - - yes
  360. :nunmap can also be used outside of a monastery.
  361. *mapmode-x* *mapmode-s*
  362. Some commands work both in Visual and Select mode, some in only one. Note
  363. that quite often "Visual" is mentioned where both Visual and Select mode
  364. apply. |Select-mode-mapping|
  365. NOTE: Mapping a printable character in Select mode may confuse the user. It's
  366. better to explicitly use :xmap and :smap for printable characters. Or use
  367. :sunmap after defining the mapping.
  368. COMMANDS MODES ~
  369. Visual Select ~
  370. :vmap :vnoremap :vunmap :vmapclear yes yes
  371. :xmap :xnoremap :xunmap :xmapclear yes -
  372. :smap :snoremap :sunmap :smapclear - yes
  373. *mapmode-ic* *mapmode-i* *mapmode-c* *mapmode-l*
  374. Some commands work both in Insert mode and Command-line mode, some not:
  375. COMMANDS MODES ~
  376. Insert Command-line Lang-Arg ~
  377. :map! :noremap! :unmap! :mapclear! yes yes -
  378. :imap :inoremap :iunmap :imapclear yes - -
  379. :cmap :cnoremap :cunmap :cmapclear - yes -
  380. :lmap :lnoremap :lunmap :lmapclear yes* yes* yes*
  381. * If 'iminsert' is 1, see |language-mapping| below.
  382. The original Vi did not have separate mappings for
  383. Normal/Visual/Operator-pending mode and for Insert/Command-line mode.
  384. Therefore the ":map" and ":map!" commands enter and display mappings for
  385. several modes. In Vim you can use the ":nmap", ":vmap", ":omap", ":cmap" and
  386. ":imap" commands to enter mappings for each mode separately.
  387. *omap-info*
  388. Operator-pending mappings can be used to define a movement command that can be
  389. used with any operator. Simple example: >
  390. :omap { w
  391. makes "y{" work like "yw" and "d{" like "dw".
  392. To ignore the starting cursor position and select different text, you can have
  393. the omap start Visual mode to select the text to be operated upon. Example
  394. that operates on a function name in the current line: >
  395. onoremap <silent> F :<C-U>normal! 0f(hviw<CR>
  396. The CTRL-U (<C-U>) is used to remove the range that Vim may insert. The
  397. Normal mode commands find the first '(' character and select the first word
  398. before it. That usually is the function name.
  399. To enter a mapping for Normal and Visual mode, but not Operator-pending mode,
  400. first define it for all three modes, then unmap it for
  401. Operator-pending mode: >
  402. :map xx something-difficult
  403. :ounmap xx
  404. Likewise for a mapping for Visual and Operator-pending mode or Normal and
  405. Operator-pending mode.
  406. *language-mapping*
  407. ":lmap" defines a mapping that applies to:
  408. - Insert mode
  409. - Command-line mode
  410. - when entering a search pattern
  411. - the argument of the commands that accept a text character, such as "r" and
  412. "f"
  413. - for the input() line
  414. Generally: Whenever a character is to be typed that is part of the text in the
  415. buffer, not a Vim command character. "Lang-Arg" isn't really another mode,
  416. it's just used here for this situation.
  417. The simplest way to load a set of related language mappings is by using the
  418. 'keymap' option. See |45.5|.
  419. In Insert mode and in Command-line mode the mappings can be disabled with
  420. the CTRL-^ command |i_CTRL-^| |c_CTRL-^|. These commands change the value of
  421. the 'iminsert' option. When starting to enter a normal command line (not a
  422. search pattern) the mappings are disabled until a CTRL-^ is typed. The state
  423. last used is remembered for Insert mode and Search patterns separately. The
  424. state for Insert mode is also used when typing a character as an argument to
  425. command like "f" or "t".
  426. Language mappings will never be applied to already mapped characters. They
  427. are only used for typed characters. This assumes that the language mapping
  428. was already done when typing the mapping. Correspondingly, language mappings
  429. are applied when recording macros, rather than when applying them.
  430. 1.4 LISTING MAPPINGS *map-listing*
  431. When listing mappings the characters in the first two columns are:
  432. CHAR MODE ~
  433. <Space> Normal, Visual, Select and Operator-pending
  434. n Normal
  435. v Visual and Select
  436. s Select
  437. x Visual
  438. o Operator-pending
  439. ! Insert and Command-line
  440. i Insert
  441. l ":lmap" mappings for Insert, Command-line and Lang-Arg
  442. c Command-line
  443. t Terminal-Job
  444. Just before the {rhs} a special character can appear:
  445. * indicates that it is not remappable
  446. & indicates that only script-local mappings are remappable
  447. @ indicates a buffer-local mapping
  448. Everything from the first non-blank after {lhs} up to the end of the line
  449. (or '|') is considered to be part of {rhs}. This allows the {rhs} to end
  450. with a space.
  451. Note: When using mappings for Visual mode, you can use the "'<" mark, which
  452. is the start of the last selected Visual area in the current buffer |'<|.
  453. The |:filter| command can be used to select what mappings to list. The
  454. pattern is matched against the {lhs} and {rhs} in the raw form. If a
  455. description was added using |nvim_set_keymap()| or |nvim_buf_set_keymap()|
  456. then the pattern is also matched against it.
  457. *:map-verbose*
  458. When 'verbose' is non-zero, listing a key map will also display where it was
  459. last defined. Example: >
  460. :verbose map <C-W>*
  461. n <C-W>* * <C-W><C-S>*
  462. Last set from ~/.config/nvim/init.vim
  463. See |:verbose-cmd| for more information.
  464. 1.5 MAPPING SPECIAL KEYS *:map-special-keys*
  465. To map a function key, use the internal code for it. To enter such a mapping
  466. type CTRL-K and then hit the function key, or use the form "<F2>", "<F10>",
  467. "<Up>", "<S-Down>", "<S-F7>", etc. (see table of keys |key-notation|, all keys
  468. from <Up> can be used).
  469. 1.6 SPECIAL CHARACTERS *:map-special-chars*
  470. *map_backslash* *map-backslash*
  471. Note that only CTRL-V is mentioned here as a special character for mappings
  472. and abbreviations. When 'cpoptions' does not contain 'B', a backslash can
  473. also be used like CTRL-V. The <> notation can be fully used then |<>|. But
  474. you cannot use "<C-V>" like CTRL-V to escape the special meaning of what
  475. follows.
  476. To map a backslash, or use a backslash literally in the {rhs}, the special
  477. sequence "<Bslash>" can be used. This avoids the need to double backslashes
  478. when using nested mappings.
  479. *map_CTRL-C* *map-CTRL-C*
  480. Using CTRL-C in the {lhs} is possible, but it will only work when Vim is
  481. waiting for a key, not when Vim is busy with something. When Vim is busy
  482. CTRL-C interrupts/breaks the command.
  483. When using the GUI version on MS-Windows CTRL-C can be mapped to allow a Copy
  484. command to the clipboard. Use CTRL-Break to interrupt Vim.
  485. *map_space_in_lhs* *map-space_in_lhs*
  486. To include a space in {lhs} precede it with a CTRL-V (type two CTRL-Vs for
  487. each space).
  488. *map_space_in_rhs* *map-space_in_rhs*
  489. If you want a {rhs} that starts with a space, use "<Space>". To be fully Vi
  490. compatible (but unreadable) don't use the |<>| notation, precede {rhs} with a
  491. single CTRL-V (you have to type CTRL-V two times).
  492. *map_empty_rhs* *map-empty-rhs*
  493. You can create an empty {rhs} by typing nothing after a single CTRL-V (you
  494. have to type CTRL-V two times). Unfortunately, you cannot do this in a vimrc
  495. file.
  496. |<Nop>|
  497. An easier way to get a mapping that doesn't produce anything, is to use
  498. "<Nop>" for the {rhs}. For example, to disable function key 8: >
  499. :map <F8> <Nop>
  500. :map! <F8> <Nop>
  501. <
  502. *map-multibyte*
  503. It is possible to map multibyte characters, but only the whole character. You
  504. cannot map the first byte only. This was done to prevent problems in this
  505. scenario: >
  506. :set encoding=latin1
  507. :imap <M-C> foo
  508. :set encoding=utf-8
  509. The mapping for <M-C> is defined with the latin1 encoding, resulting in a 0xc3
  510. byte. If you type the character á (0xe1 <M-a>) in UTF-8 encoding this is the
  511. two bytes 0xc3 0xa1. You don't want the 0xc3 byte to be mapped then or
  512. otherwise it would be impossible to type the á character.
  513. *<Leader>* *mapleader*
  514. To define a mapping which uses the "g:mapleader" variable, the special string
  515. "<Leader>" can be used. It is replaced with the string value of
  516. "g:mapleader". If "g:mapleader" is not set or empty, a backslash is used
  517. instead. Example: >
  518. map <Leader>A oanother line<Esc>
  519. Works like: >
  520. map \A oanother line<Esc>
  521. But after: >
  522. let mapleader = ","
  523. It works like: >
  524. map ,A oanother line<Esc>
  525. Note that the value of "g:mapleader" is used at the moment the mapping is
  526. defined. Changing "g:mapleader" after that has no effect for already defined
  527. mappings.
  528. *<LocalLeader>* *maplocalleader*
  529. <LocalLeader> is just like <Leader>, except that it uses "maplocalleader"
  530. instead of "mapleader". <LocalLeader> is to be used for mappings which are
  531. local to a buffer. Example: >
  532. :map <buffer> <LocalLeader>A oanother line<Esc>
  533. <
  534. In a global plugin <Leader> should be used and in a filetype plugin
  535. <LocalLeader>. "mapleader" and "maplocalleader" can be equal. Although, if
  536. you make them different, there is a smaller chance of mappings from global
  537. plugins to clash with mappings for filetype plugins. For example, you could
  538. keep "mapleader" at the default backslash, and set "maplocalleader" to an
  539. underscore.
  540. *map-<SID>*
  541. In a script the special key name "<SID>" can be used to define a mapping
  542. that's local to the script. See |<SID>| for details.
  543. *<Plug>*
  544. The special key name "<Plug>" can be used for an internal mapping, which is
  545. not to be matched with any key sequence. This is useful in plugins
  546. |using-<Plug>|.
  547. *<MouseMove>*
  548. The special key name "<MouseMove>" can be used to handle mouse movement. It
  549. needs to be enabled with 'mousemoveevent'.
  550. The |getmousepos()| function can be used to obtain the mouse position.
  551. *<Char>* *<Char->*
  552. To map a character by its decimal, octal or hexadecimal number the <Char>
  553. construct can be used:
  554. <Char-123> character 123
  555. <Char-033> character 27
  556. <Char-0x7f> character 127
  557. <S-Char-114> character 114 ('r') shifted ('R')
  558. This is useful to specify a (multibyte) character in a 'keymap' file.
  559. Upper and lowercase differences are ignored.
  560. *map-comments*
  561. It is not possible to put a comment after these commands, because the `"`
  562. character is considered to be part of the {lhs} or {rhs}. However, one can
  563. use `|"`, since this starts a new, empty command with a comment.
  564. *map_bar* *map-bar*
  565. Since the '|' character is used to separate a map command from the next
  566. command, you will have to do something special to include a '|' in {rhs}.
  567. There are three methods:
  568. use works when example ~
  569. <Bar> always :map _l :!ls <Bar> more^M
  570. \| 'b' is not in 'cpoptions' :map _l :!ls \| more^M
  571. ^V| always :map _l :!ls ^V| more^M
  572. (here ^V stands for CTRL-V; to get one CTRL-V you have to type it twice; you
  573. cannot use the <> notation "<C-V>" here).
  574. All three work when you use the default setting for 'cpoptions'.
  575. When 'b' is present in 'cpoptions', "\|" will be recognized as a mapping
  576. ending in a '\' and then another command. This is Vi compatible, but
  577. illogical when compared to other commands.
  578. *map_return* *map-return*
  579. When you have a mapping that contains an Ex command, you need to put a line
  580. terminator after it to have it executed. The use of <CR> is recommended for
  581. this (see |<>|). Example: >
  582. :map _ls :!ls -l %:S<CR>:echo "the end"<CR>
  583. To avoid mapping of the characters you type in insert or Command-line mode,
  584. type a CTRL-V first.
  585. *map-error*
  586. Note that when an error is encountered (that causes an error message or might
  587. cause a beep) the rest of the mapping is not executed. This is Vi-compatible.
  588. Note that the second character (argument) of the commands @zZtTfF[]rm'`"v
  589. and CTRL-X is not mapped. This was done to be able to use all the named
  590. registers and marks, even when the command with the same name has been
  591. mapped.
  592. 1.7 WHAT KEYS TO MAP *map-which-keys*
  593. If you are going to map something, you will need to choose which key(s) to use
  594. for the {lhs}. You will have to avoid keys that are used for Vim commands,
  595. otherwise you would not be able to use those commands anymore. Here are a few
  596. suggestions:
  597. - Function keys <F2>, <F3>, etc.. Also the shifted function keys <S-F1>,
  598. <S-F2>, etc. Note that <F1> is already used for the help command.
  599. - Meta-keys (with the ALT key pressed). Depending on your keyboard accented
  600. characters may be used as well. |:map-alt-keys|
  601. - Use the '_' or ',' character and then any other character. The "_" and ","
  602. commands do exist in Vim (see |_| and |,|), but you probably never use them.
  603. - Use a key that is a synonym for another command. For example: CTRL-P and
  604. CTRL-N. Use an extra character to allow more mappings.
  605. - The key defined by <Leader> and one or more other keys. This is especially
  606. useful in scripts. |mapleader|
  607. See the file "index" for keys that are not used and thus can be mapped without
  608. losing any builtin function. You can also use ":help {key}^D" to find out if
  609. a key is used for some command. ({key} is the specific key you want to find
  610. out about, ^D is CTRL-D).
  611. 1.8 EXAMPLES *map-examples*
  612. A few examples (as you type them: for "<CR>" you type four characters). >
  613. :map <F3> o#include
  614. :map <M-g> /foo<CR>cwbar<Esc>
  615. :map _x d/END/e<CR>
  616. :map! qq quadrillion questions
  617. Multiplying a count
  618. When you type a count before triggering a mapping, it's like the count was
  619. typed before the {lhs}. For example, with this mapping: >
  620. :map <F4> 3w
  621. Typing 2<F4> will result in "23w". Thus not moving 2 * 3 words but 23 words.
  622. If you want to multiply counts use the expression register: >
  623. :map <F4> @='3w'<CR>
  624. The part between quotes is the expression being executed. |@=|
  625. 1.9 USING MAPPINGS *map-typing*
  626. Vim will compare what you type with the start of a mapped sequence. If there
  627. is an incomplete match, it will get more characters until there either is a
  628. complete match or until there is no match at all. Example: If you map! "qq",
  629. the first 'q' will not appear on the screen until you type another
  630. character. This is because Vim cannot know if the next character will be a
  631. 'q' or not. If the 'timeout' option is on (which is the default) Vim will
  632. only wait for one second (or as long as specified with the 'timeoutlen'
  633. option). After that it assumes that the 'q' is to be interpreted as such. If
  634. you type slowly, or your system is slow, reset the 'timeout' option. Then you
  635. might want to set the 'ttimeout' option.
  636. *map-precedence*
  637. Buffer-local mappings (defined using |:map-<buffer>|) take precedence over
  638. global mappings. When a buffer-local mapping is the same as a global mapping,
  639. Vim will use the buffer-local mapping. In addition, Vim will use a complete
  640. mapping immediately if it was defined with <nowait>, even if a longer mapping
  641. has the same prefix. For example, given the following two mappings: >
  642. :map <buffer> <nowait> \a :echo "Local \a"<CR>
  643. :map \abc :echo "Global \abc"<CR>
  644. When typing \a the buffer-local mapping will be used immediately. Vim will
  645. not wait for more characters to see if the user might be typing \abc.
  646. *map-keys-fails*
  647. There are situations where key codes might not be recognized:
  648. - Vim can only read part of the key code. Mostly this is only the first
  649. character. This happens on some Unix versions in an xterm.
  650. - The key code is after character(s) that are mapped. E.g., "<F1><F1>" or
  651. "g<F1>".
  652. The result is that the key code is not recognized in this situation, and the
  653. mapping fails. There are two actions needed to avoid this problem:
  654. - Remove the 'K' flag from 'cpoptions'. This will make Vim wait for the rest
  655. of the characters of the function key.
  656. - When using <F1> to <F4> the actual key code generated may correspond to
  657. <xF1> to <xF4>. There are mappings from <xF1> to <F1>, <xF2> to <F2>, etc.,
  658. but these are not recognized after another half a mapping. Make sure the
  659. key codes for <F1> to <F4> are correct: >
  660. :set <F1>=<type CTRL-V><type F1>
  661. < Type the <F1> as four characters. The part after the "=" must be done with
  662. the actual keys, not the literal text.
  663. Another solution is to use the actual key code in the mapping for the second
  664. special key: >
  665. :map <F1><Esc>OP :echo "yes"<CR>
  666. Don't type a real <Esc>, Vim will recognize the key code and replace it with
  667. <F1> anyway.
  668. *recursive_mapping*
  669. If you include the {lhs} in the {rhs} you have a recursive mapping. When
  670. {lhs} is typed, it will be replaced with {rhs}. When the {lhs} which is
  671. included in {rhs} is encountered it will be replaced with {rhs}, and so on.
  672. This makes it possible to repeat a command an infinite number of times. The
  673. only problem is that the only way to stop this is by causing an error. The
  674. macros to solve a maze uses this, look there for an example. There is one
  675. exception: If the {rhs} starts with {lhs}, the first character is not mapped
  676. again (this is Vi compatible).
  677. For example: >
  678. :map ab abcd
  679. will execute the "a" command and insert "bcd" in the text. The "ab" in the
  680. {rhs} will not be mapped again.
  681. If you want to exchange the meaning of two keys you should use the :noremap
  682. command. For example: >
  683. :noremap k j
  684. :noremap j k
  685. This will exchange the cursor up and down commands.
  686. With the normal :map command mapping takes place until the text is found not
  687. to be a part of a {lhs}. For example, if you use: >
  688. :map x y
  689. :map y x
  690. Vim will replace x with y, and then y with x, etc. When this has happened
  691. 'maxmapdepth' times (default 1000), Vim will give the error message
  692. "recursive mapping".
  693. *:map-undo*
  694. If you include an undo command inside a mapped sequence, this will bring the
  695. text back in the state before executing the macro. This is compatible with
  696. the original Vi, as long as there is only one undo command in the mapped
  697. sequence (having two undo commands in a mapped sequence did not make sense
  698. in the original Vi, you would get back the text before the first undo).
  699. 1.10 MAPPING ALT-KEYS *:map-alt-keys*
  700. For a readable mapping command the <A-k> form can be used. Note that <A-k>
  701. and <A-K> are different, the latter will use an upper case letter. Actually,
  702. <A-K> and <A-S-K> are the same. Instead of "A" you can use "M". If you have
  703. an actual Meta modifier key, please see |:map-meta-keys|.
  704. In the GUI Nvim handles the |ALT| key itself, thus mapping keys with ALT
  705. should always work. But in a terminal Nvim gets a sequence of bytes and has
  706. to figure out whether ALT was pressed. Terminals may use ESC to indicate that
  707. ALT was pressed. If ESC is followed by a {key} within 'ttimeoutlen'
  708. milliseconds, the ESC is interpreted as:
  709. <ALT-{key}>
  710. otherwise it is interpreted as two key presses:
  711. <ESC> {key}
  712. 1.11 MAPPING META-KEYS *:map-meta-keys*
  713. Mapping keys with the Meta modifier works very similar to using the Alt key.
  714. What key on your keyboard produces the Meta modifier depends on your keyboard
  715. and configuration.
  716. Note that mapping <M-a> actually is for using the Alt key. That can be
  717. confusing! It cannot be changed, it would not be backwards compatible.
  718. For the Meta modifier the "T" character is used. For example, to map Meta-b
  719. in Insert mode: >
  720. :imap <T-b> terrible
  721. 1.12 MAPPING SUPER-KEYS or COMMAND-KEYS *:map-super-keys* *:map-cmd-key*
  722. The Super / Command modifier is available if the terminal or GUI supports it.
  723. The character "D" is used for the Super / Command modifier.
  724. For example, to map Command-b in Insert mode: >
  725. :imap <D-b> barritone
  726. 1.13 MAPPING AN OPERATOR *:map-operator*
  727. An operator is used before a {motion} command. To define your own operator
  728. you must create a mapping that first sets the 'operatorfunc' option and then
  729. invoke the |g@| operator. After the user types the {motion} command the
  730. specified function will be called.
  731. *g@* *E774* *E775*
  732. g@{motion} Call the function set by the 'operatorfunc' option.
  733. The '[ mark is positioned at the start of the text
  734. moved over by {motion}, the '] mark on the last
  735. character of the text.
  736. The function is called with one String argument:
  737. "line" {motion} was |linewise|
  738. "char" {motion} was |charwise|
  739. "block" {motion} was |blockwise-visual|
  740. The type can be forced, see |forced-motion|.
  741. Here is an example that counts the number of spaces with <F4>: >
  742. nnoremap <expr> <F4> CountSpaces()
  743. xnoremap <expr> <F4> CountSpaces()
  744. " doubling <F4> works on a line
  745. nnoremap <expr> <F4><F4> CountSpaces() .. '_'
  746. function CountSpaces(context = {}, type = '') abort
  747. if a:type == ''
  748. let context = #{
  749. \ dot_command: v:false,
  750. \ extend_block: '',
  751. \ virtualedit: [&l:virtualedit, &g:virtualedit],
  752. \ }
  753. let &operatorfunc = function('CountSpaces', [context])
  754. set virtualedit=block
  755. return 'g@'
  756. endif
  757. let save = #{
  758. \ clipboard: &clipboard,
  759. \ selection: &selection,
  760. \ virtualedit: [&l:virtualedit, &g:virtualedit],
  761. \ register: getreginfo('"'),
  762. \ visual_marks: [getpos("'<"), getpos("'>")],
  763. \ }
  764. try
  765. set clipboard= selection=inclusive virtualedit=
  766. let commands = #{
  767. \ line: "'[V']",
  768. \ char: "`[v`]",
  769. \ block: "`[\<C-V>`]",
  770. \ }[a:type]
  771. let [_, _, col, off] = getpos("']")
  772. if off != 0
  773. let vcol = getline("'[")->strpart(0, col + off)->strdisplaywidth()
  774. if vcol >= [line("'["), '$']->virtcol() - 1
  775. let a:context.extend_block = '$'
  776. else
  777. let a:context.extend_block = vcol .. '|'
  778. endif
  779. endif
  780. if a:context.extend_block != ''
  781. let commands ..= 'oO' .. a:context.extend_block
  782. endif
  783. let commands ..= 'y'
  784. execute 'silent noautocmd keepjumps normal! ' .. commands
  785. echomsg getreg('"')->count(' ')
  786. finally
  787. call setreg('"', save.register)
  788. call setpos("'<", save.visual_marks[0])
  789. call setpos("'>", save.visual_marks[1])
  790. let &clipboard = save.clipboard
  791. let &selection = save.selection
  792. let [&l:virtualedit, &g:virtualedit] = get(a:context.dot_command ? save : a:context, 'virtualedit')
  793. let a:context.dot_command = v:true
  794. endtry
  795. endfunction
  796. An <expr> mapping is used to be able to fetch any prefixed count and register.
  797. This also avoids using a command line, which would trigger CmdlineEnter and
  798. CmdlineLeave autocommands.
  799. Note that the 'selection' option is temporarily set to "inclusive" to be able
  800. to yank exactly the right text by using Visual mode from the '[ to the ']
  801. mark.
  802. Also note that the 'clipboard' option is temporarily emptied to avoid
  803. clobbering the `"*` or `"+` registers, if its value contains the item `unnamed`
  804. or `unnamedplus`.
  805. The `mode()` function will return the state as it will be after applying the
  806. operator.
  807. Here is an example for using a lambda function to create a normal-mode
  808. operator to add quotes around text in the current line: >
  809. nnoremap <F4> <Cmd>let &opfunc='{t ->
  810. \ getline(".")
  811. \ ->split("\\zs")
  812. \ ->insert("\"", col("'']"))
  813. \ ->insert("\"", col("''[") - 1)
  814. \ ->join("")
  815. \ ->setline(".")}'<CR>g@
  816. ==============================================================================
  817. 2. Abbreviations *abbreviation* *abbreviations* *Abbreviations*
  818. Abbreviations are used in Insert mode, Replace mode and Command-line mode.
  819. If you enter a word that is an abbreviation, it is replaced with the word it
  820. stands for. This can be used to save typing for often used long words. And
  821. you can use it to automatically correct obvious spelling errors.
  822. Examples:
  823. :iab ms Microsoft
  824. :iab tihs this
  825. There are three types of abbreviations:
  826. full-id The "full-id" type consists entirely of keyword characters (letters
  827. and characters from 'iskeyword' option). This is the most common
  828. abbreviation.
  829. Examples: "foo", "g3", "-1"
  830. end-id The "end-id" type ends in a keyword character, but all the other
  831. characters are not keyword characters.
  832. Examples: "#i", "..f", "$/7"
  833. non-id The "non-id" type ends in a non-keyword character, the other
  834. characters may be of any type, excluding space and tab.
  835. Examples: "def#", "4/7$"
  836. Examples of strings that cannot be abbreviations: "a.b", "#def", "a b", "_$r"
  837. An abbreviation is only recognized when you type a non-keyword character.
  838. This can also be the <Esc> that ends Insert mode or the <CR> that ends a
  839. command. The non-keyword character which ends the abbreviation is inserted
  840. after the expanded abbreviation. An exception to this is the character <C-]>,
  841. which is used to expand an abbreviation without inserting any extra
  842. characters.
  843. Example: >
  844. :ab hh hello
  845. < "hh<Space>" is expanded to "hello<Space>"
  846. "hh<C-]>" is expanded to "hello"
  847. The characters before the cursor must match the abbreviation. Each type has
  848. an additional rule:
  849. full-id In front of the match is a non-keyword character, or this is where
  850. the line or insertion starts. Exception: When the abbreviation is
  851. only one character, it is not recognized if there is a non-keyword
  852. character in front of it, other than a space or a tab. However, for
  853. the command line "'<,'>" (or any other marks) is ignored, as if the
  854. command line starts after it.
  855. end-id In front of the match is a keyword character, or a space or a tab,
  856. or this is where the line or insertion starts.
  857. non-id In front of the match is a space, tab or the start of the line or
  858. the insertion.
  859. Examples: ({CURSOR} is where you type a non-keyword character) >
  860. :ab foo four old otters
  861. < " foo{CURSOR}" is expanded to " four old otters"
  862. " foobar{CURSOR}" is not expanded
  863. "barfoo{CURSOR}" is not expanded
  864. >
  865. :ab #i #include
  866. < "#i{CURSOR}" is expanded to "#include"
  867. ">#i{CURSOR}" is not expanded
  868. >
  869. :ab ;; <endofline>
  870. < "test;;" is not expanded
  871. "test ;;" is expanded to "test <endofline>"
  872. To avoid the abbreviation in Insert mode: Type CTRL-V before the character
  873. that would trigger the abbreviation. E.g. CTRL-V <Space>. Or type part of
  874. the abbreviation, exit insert mode with <Esc>, re-enter insert mode with "a"
  875. and type the rest.
  876. To avoid the abbreviation in Command-line mode: Type CTRL-V twice somewhere in
  877. the abbreviation to avoid it to be replaced. A CTRL-V in front of a normal
  878. character is mostly ignored otherwise.
  879. It is possible to move the cursor after an abbreviation: >
  880. :iab if if ()<Left>
  881. You can even do more complicated things. For example, to consume the space
  882. typed after an abbreviation: >
  883. func Eatchar(pat)
  884. let c = nr2char(getchar(0))
  885. return (c =~ a:pat) ? '' : c
  886. endfunc
  887. iabbr <silent> if if ()<Left><C-R>=Eatchar('\s')<CR>
  888. There are no default abbreviations.
  889. Abbreviations are never recursive. You can use ":ab f f-o-o" without any
  890. problem. But abbreviations can be mapped.
  891. *:abbreviate-local* *:abbreviate-<buffer>*
  892. Just like mappings, abbreviations can be local to a buffer. This is mostly
  893. used in a |filetype-plugin| file. Example for a C plugin file: >
  894. :abb <buffer> FF for (i = 0; i < ; ++i)
  895. <
  896. *:ab* *:abbreviate*
  897. :ab[breviate] list all abbreviations. The character in the first
  898. column indicates the mode where the abbreviation is
  899. used: 'i' for insert mode, 'c' for Command-line
  900. mode, '!' for both. These are the same as for
  901. mappings, see |map-listing|.
  902. *:abbreviate-verbose*
  903. When 'verbose' is non-zero, listing an abbreviation will also display where it
  904. was last defined. Example: >
  905. :verbose abbreviate
  906. ! teh the
  907. Last set from /home/abcd/vim/abbr.vim
  908. See |:verbose-cmd| for more information.
  909. :ab[breviate] {lhs} list the abbreviations that start with {lhs}
  910. You may need to insert a CTRL-V (type it twice) to
  911. avoid that a typed {lhs} is expanded, since
  912. command-line abbreviations apply here.
  913. :ab[breviate] [<expr>] [<buffer>] {lhs} {rhs}
  914. add abbreviation for {lhs} to {rhs}. If {lhs} already
  915. existed it is replaced with the new {rhs}. {rhs} may
  916. contain spaces.
  917. See |:map-<expr>| for the optional <expr> argument.
  918. See |:map-<buffer>| for the optional <buffer> argument.
  919. *:una* *:unabbreviate*
  920. :una[bbreviate] [<buffer>] {lhs}
  921. Remove abbreviation for {lhs} from the list. If none
  922. is found, remove abbreviations in which {lhs} matches
  923. with the {rhs}. This is done so that you can even
  924. remove abbreviations after expansion. To avoid
  925. expansion insert a CTRL-V (type it twice).
  926. *:norea* *:noreabbrev*
  927. :norea[bbrev] [<expr>] [<buffer>] [lhs] [rhs]
  928. same as ":ab", but no remapping for this {rhs}
  929. *:ca* *:cab* *:cabbrev*
  930. :ca[bbrev] [<expr>] [<buffer>] [lhs] [rhs]
  931. same as ":ab", but for Command-line mode only.
  932. *:cuna* *:cunabbrev*
  933. :cuna[bbrev] [<buffer>] {lhs}
  934. Same as ":una", but for Command-line mode only.
  935. *:cnorea* *:cnoreabbrev*
  936. :cnorea[bbrev] [<expr>] [<buffer>] [lhs] [rhs]
  937. same as ":ab", but for Command-line mode only and no
  938. remapping for this {rhs}
  939. *:ia* *:iabbrev*
  940. :ia[bbrev] [<expr>] [<buffer>] [lhs] [rhs]
  941. same as ":ab", but for Insert mode only.
  942. *:iuna* *:iunabbrev*
  943. :iuna[bbrev] [<buffer>] {lhs}
  944. Same as ":una", but for insert mode only.
  945. *:inorea* *:inoreabbrev*
  946. :inorea[bbrev] [<expr>] [<buffer>] [lhs] [rhs]
  947. same as ":ab", but for Insert mode only and no
  948. remapping for this {rhs}
  949. *:abc* *:abclear*
  950. :abc[lear] [<buffer>] Remove all abbreviations.
  951. *:iabc* *:iabclear*
  952. :iabc[lear] [<buffer>] Remove all abbreviations for Insert mode.
  953. *:cabc* *:cabclear*
  954. :cabc[lear] [<buffer>] Remove all abbreviations for Command-line mode.
  955. *using_CTRL-V*
  956. It is possible to use special characters in the rhs of an abbreviation.
  957. CTRL-V has to be used to avoid the special meaning of most non printable
  958. characters. How many CTRL-Vs need to be typed depends on how you enter the
  959. abbreviation. This also applies to mappings. Let's use an example here.
  960. Suppose you want to abbreviate "esc" to enter an <Esc> character. When you
  961. type the ":ab" command in Vim, you have to enter this: (here ^V is a CTRL-V
  962. and ^[ is <Esc>)
  963. You type: ab esc ^V^V^V^V^V^[
  964. All keyboard input is subjected to ^V quote interpretation, so
  965. the first, third, and fifth ^V characters simply allow the second,
  966. and fourth ^Vs, and the ^[, to be entered into the command-line.
  967. You see: ab esc ^V^V^[
  968. The command-line contains two actual ^Vs before the ^[. This is
  969. how it should appear in your vimrc file, if you choose to go that
  970. route. The first ^V is there to quote the second ^V; the :ab
  971. command uses ^V as its own quote character, so you can include quoted
  972. whitespace or the | character in the abbreviation. The :ab command
  973. doesn't do anything special with the ^[ character, so it doesn't need
  974. to be quoted. (Although quoting isn't harmful; that's why typing 7
  975. [but not 8!] ^Vs works.)
  976. Stored as: esc ^V^[
  977. After parsing, the abbreviation's short form ("esc") and long form
  978. (the two characters "^V^[") are stored in the abbreviation table.
  979. If you give the :ab command with no arguments, this is how the
  980. abbreviation will be displayed.
  981. Later, when the abbreviation is expanded because the user typed in
  982. the word "esc", the long form is subjected to the same type of
  983. ^V interpretation as keyboard input. So the ^V protects the ^[
  984. character from being interpreted as the "exit Insert mode" character.
  985. Instead, the ^[ is inserted into the text.
  986. Expands to: ^[
  987. [example given by Steve Kirkendall]
  988. ==============================================================================
  989. 3. Local mappings and functions *script-local*
  990. When using several Vim script files, there is the danger that mappings and
  991. functions used in one script use the same name as in other scripts. To avoid
  992. this, they can be made local to the script.
  993. *<SID>* *<SNR>* *E81*
  994. The string "<SID>" can be used in a mapping or menu. This is useful if you
  995. have a script-local function that you want to call from a mapping in the same
  996. script.
  997. When executing the map command, Vim will replace "<SID>" with the special
  998. key code <SNR>, followed by a number that's unique for the script, and an
  999. underscore. Example: >
  1000. :map <SID>Add
  1001. would define a mapping "<SNR>23_Add".
  1002. When defining a function in a script, "s:" can be prepended to the name to
  1003. make it local to the script. But when a mapping is executed from outside of
  1004. the script, it doesn't know in which script the function was defined. To
  1005. avoid this problem, use "<SID>" instead of "s:". The same translation is done
  1006. as for mappings. This makes it possible to define a call to the function in
  1007. a mapping.
  1008. When a local function is executed, it runs in the context of the script it was
  1009. defined in. This means that new functions and mappings it defines can also
  1010. use "s:" or "<SID>" and it will use the same unique number as when the
  1011. function itself was defined. Also, the "s:var" local script variables can be
  1012. used.
  1013. When executing an autocommand or a user command, it will run in the context of
  1014. the script it was defined in. This makes it possible that the command calls a
  1015. local function or uses a local mapping.
  1016. In case the value is used in a context where <SID> cannot be correctly
  1017. expanded, use the expand() function: >
  1018. let &includexpr = expand('<SID>') .. 'My_includeexpr()'
  1019. Otherwise, using "<SID>" outside of a script context is an error.
  1020. If you need to get the script number to use in a complicated script, you can
  1021. use this function: >
  1022. func s:ScriptNumber()
  1023. return matchstr(expand('<SID>'), '<SNR>\zs\d\+\ze_')
  1024. endfunc
  1025. The "<SNR>" will be shown when listing functions and mappings. This is useful
  1026. to find out what they are defined to.
  1027. The |:scriptnames| command can be used to see which scripts have been sourced
  1028. and what their <SNR> number is.
  1029. ==============================================================================
  1030. 4. User-defined commands *user-commands*
  1031. It is possible to define your own Ex commands. A user-defined command can act
  1032. just like a built-in command (it can have a range or arguments, arguments can
  1033. be completed as filenames or buffer names, etc), except that when the command
  1034. is executed, it is transformed into a normal Ex command and then executed.
  1035. For starters: See section |40.2| in the user manual.
  1036. *E183* *E841* *user-cmd-ambiguous*
  1037. All user defined commands must start with an uppercase letter, to avoid
  1038. confusion with builtin commands. Exceptions are these builtin commands:
  1039. :Next
  1040. They cannot be used for a user defined command.
  1041. The other characters of the user command can be uppercase letters, lowercase
  1042. letters or digits. When using digits, note that other commands that take a
  1043. numeric argument may become ambiguous. For example, the command ":Cc2" could
  1044. be the user command ":Cc2" without an argument, or the command ":Cc" with
  1045. argument "2". It is advised to put a space between the command name and the
  1046. argument to avoid these problems.
  1047. When using a user-defined command, the command can be abbreviated. However, if
  1048. an abbreviation is not unique, an error will be issued. Furthermore, a
  1049. built-in command will always take precedence.
  1050. Example: >
  1051. :command Rename ...
  1052. :command Renumber ...
  1053. :Rena " Means "Rename"
  1054. :Renu " Means "Renumber"
  1055. :Ren " Error - ambiguous
  1056. :command Paste ...
  1057. It is recommended that full names for user-defined commands are used in
  1058. scripts.
  1059. :com[mand] *:com* *:command*
  1060. List all user-defined commands. When listing commands,
  1061. the characters in the first columns are:
  1062. ! Command has the -bang attribute
  1063. " Command has the -register attribute
  1064. | Command has the -bar attribute
  1065. b Command is local to current buffer
  1066. (see below for details on attributes)
  1067. The list can be filtered on command name with
  1068. |:filter|, e.g., to list all commands with "Pyth" in
  1069. the name: >
  1070. filter Pyth command
  1071. :com[mand] {cmd} List the user-defined commands that start with {cmd}
  1072. *:command-verbose*
  1073. When 'verbose' is non-zero, listing a command will also display where it was
  1074. last defined and any completion argument. Example: >
  1075. :verbose command TOhtml
  1076. < Name Args Range Complete Definition ~
  1077. TOhtml 0 % :call Convert2HTML(<line1>, <line2>) ~
  1078. Last set from /usr/share/vim/vim-7.0/plugin/tohtml.vim ~
  1079. See |:verbose-cmd| for more information.
  1080. *E174* *E182*
  1081. :com[mand][!] [{attr}...] {cmd} {repl}
  1082. Define a user command. The name of the command is
  1083. {cmd} and its replacement text is {repl}. The
  1084. command's attributes (see below) are {attr}. If the
  1085. command already exists, an error is reported, unless a
  1086. ! is specified, in which case the command is
  1087. redefined. There is one exception: When sourcing a
  1088. script again, a command that was previously defined in
  1089. that script will be silently replaced.
  1090. :delc[ommand] {cmd} *:delc* *:delcommand* *E184*
  1091. Delete the user-defined command {cmd}.
  1092. :delc[ommand] -buffer {cmd} *E1237*
  1093. Delete the user-defined command {cmd} that was defined
  1094. for the current buffer.
  1095. :comc[lear] *:comc* *:comclear*
  1096. Delete all user-defined commands.
  1097. Command attributes ~
  1098. *command-attributes*
  1099. User-defined commands are treated by Nvim just like any other Ex commands. They
  1100. can have arguments, or have a range specified. Arguments are subject to
  1101. completion as filenames, buffers, etc. Exactly how this works depends upon the
  1102. command's attributes, which are specified when the command is defined.
  1103. When defining a user command in a script, it will be able to call functions
  1104. local to the script and use mappings local to the script. When the user
  1105. invokes the user command, it will run in the context of the script it was
  1106. defined in. This matters if |<SID>| is used in a command.
  1107. There are a number of attributes, split into four categories: argument
  1108. handling, completion behavior, range handling, and special cases. The
  1109. attributes are described below, by category.
  1110. Argument handling ~
  1111. *E175* *E176* *:command-nargs*
  1112. By default, a user defined command will take no arguments (and an error is
  1113. reported if any are supplied). However, it is possible to specify that the
  1114. command can take arguments, using the -nargs attribute. Valid cases are:
  1115. -nargs=0 No arguments are allowed (the default)
  1116. -nargs=1 Exactly one argument is required, it includes spaces
  1117. -nargs=* Any number of arguments are allowed (0, 1, or many),
  1118. separated by white space
  1119. -nargs=? 0 or 1 arguments are allowed
  1120. -nargs=+ Arguments must be supplied, but any number are allowed
  1121. Arguments are considered to be separated by (unescaped) spaces or tabs in this
  1122. context, except when there is one argument, then the white space is part of
  1123. the argument.
  1124. Note that arguments are used as text, not as expressions. Specifically,
  1125. "s:var" will use the script-local variable in the script where the command was
  1126. defined, not where it is invoked! Example:
  1127. script1.vim: >
  1128. :let s:error = "None"
  1129. :command -nargs=1 Error echoerr <args>
  1130. < script2.vim: >
  1131. :source script1.vim
  1132. :let s:error = "Wrong!"
  1133. :Error s:error
  1134. Executing script2.vim will result in "None" being echoed. Not what you
  1135. intended! Calling a function may be an alternative.
  1136. Completion behavior ~
  1137. *:command-completion* *E179* *E180* *E181*
  1138. *:command-complete*
  1139. By default, the arguments of user defined commands do not undergo completion.
  1140. However, by specifying one or the other of the following attributes, argument
  1141. completion can be enabled:
  1142. -complete=arglist file names in argument list
  1143. -complete=augroup autocmd groups
  1144. -complete=breakpoint |:breakadd| suboptions
  1145. -complete=buffer buffer names
  1146. -complete=color color schemes
  1147. -complete=command Ex command (and arguments)
  1148. -complete=compiler compilers
  1149. -complete=diff_buffer diff buffer names
  1150. -complete=dir directory names
  1151. -complete=dir_in_path directory names in |'cdpath'|
  1152. -complete=environment environment variable names
  1153. -complete=event autocommand events
  1154. -complete=expression Vim expression
  1155. -complete=file file and directory names
  1156. -complete=file_in_path file and directory names in |'path'|
  1157. -complete=filetype filetype names |'filetype'|
  1158. -complete=function function name
  1159. -complete=help help subjects
  1160. -complete=highlight highlight groups
  1161. -complete=history |:history| suboptions
  1162. -complete=keymap keyboard mappings
  1163. -complete=locale locale names (as output of locale -a)
  1164. -complete=lua Lua expression |:lua|
  1165. -complete=mapclear buffer argument
  1166. -complete=mapping mapping name
  1167. -complete=menu menus
  1168. -complete=messages |:messages| suboptions
  1169. -complete=option options
  1170. -complete=packadd optional package |pack-add| names
  1171. -complete=runtime file and directory names in |'runtimepath'|
  1172. -complete=scriptnames sourced script names
  1173. -complete=shellcmd Shell command
  1174. -complete=shellcmdline First is a shell command and subsequent ones
  1175. are filenames. The same behavior as |:!cmd|
  1176. -complete=sign |:sign| suboptions
  1177. -complete=syntax syntax file names |'syntax'|
  1178. -complete=syntime |:syntime| suboptions
  1179. -complete=tag tags
  1180. -complete=tag_listfiles tags, file names are shown when CTRL-D is hit
  1181. -complete=user user names
  1182. -complete=var user variables
  1183. -complete=custom,{func} custom completion, defined via {func}
  1184. -complete=customlist,{func} custom completion, defined via {func}
  1185. If you specify completion while there is nothing to complete (-nargs=0, the
  1186. default) then you get error *E1208* .
  1187. Note: That some completion methods might expand environment variables.
  1188. Custom completion ~
  1189. *:command-completion-custom*
  1190. *:command-completion-customlist* *E467* *E468*
  1191. It is possible to define customized completion schemes via the "custom,{func}"
  1192. or the "customlist,{func}" completion argument. The {func} part should be a
  1193. function with the following signature: >
  1194. :function {func}(ArgLead, CmdLine, CursorPos)
  1195. The function need not use all these arguments. The function should provide the
  1196. completion candidates as the return value.
  1197. For the "custom" argument, the function should return the completion
  1198. candidates one per line in a newline separated string.
  1199. For the "customlist" argument, the function should return the completion
  1200. candidates as a Vim List. Non-string items in the list are ignored.
  1201. The function arguments are:
  1202. ArgLead the leading portion of the argument currently being
  1203. completed on
  1204. CmdLine the entire command line
  1205. CursorPos the cursor position in it (byte index)
  1206. The function may use these for determining context. For the "custom"
  1207. argument, it is not necessary to filter candidates against the (implicit
  1208. pattern in) ArgLead. Vim will filter the candidates with its regexp engine
  1209. after function return, and this is probably more efficient in most cases. If
  1210. 'wildoptions' contains "fuzzy", then the candidates will be filtered using
  1211. |fuzzy-matching|. For the "customlist" argument, Vim will not
  1212. filter the returned completion candidates and the user supplied function
  1213. should filter the candidates.
  1214. The following example lists user names to a Finger command >
  1215. :com -complete=custom,ListUsers -nargs=1 Finger !finger <args>
  1216. :fun ListUsers(A,L,P)
  1217. : return system("cut -d: -f1 /etc/passwd")
  1218. :endfun
  1219. The following example completes filenames from the directories specified in
  1220. the 'path' option: >
  1221. :com -nargs=1 -bang -complete=customlist,EditFileComplete
  1222. \ EditFile edit<bang> <args>
  1223. :fun EditFileComplete(A,L,P)
  1224. : return split(globpath(&path, a:A), "\n")
  1225. :endfun
  1226. <
  1227. This example does not work for file names with spaces!
  1228. Range handling ~
  1229. *E177* *E178* *:command-range* *:command-count*
  1230. By default, user-defined commands do not accept a line number range. However,
  1231. it is possible to specify that the command does take a range (the -range
  1232. attribute), or that it takes an arbitrary count value, either in the line
  1233. number position (-range=N, like the |:split| command) or as a "count"
  1234. argument (-count=N, like the |:Next| command). The count will then be
  1235. available in the argument with |<count>|.
  1236. Possible attributes are:
  1237. -range Range allowed, default is current line
  1238. -range=% Range allowed, default is whole file (1,$)
  1239. -range=N A count (default N) which is specified in the line
  1240. number position (like |:split|); allows for zero line
  1241. number.
  1242. -count=N A count (default N) which is specified either in the line
  1243. number position, or as an initial argument (like |:Next|).
  1244. -count Acts like -count=0
  1245. Note that -range=N and -count=N are mutually exclusive - only one should be
  1246. specified.
  1247. *:command-addr*
  1248. It is possible that the special characters in the range like `.`, `$` or `%`
  1249. which by default correspond to the current line, last line and the whole
  1250. buffer, relate to arguments, (loaded) buffers, windows or tab pages.
  1251. Possible values are (second column is the short name used in listing):
  1252. -addr=lines Range of lines (this is the default for -range)
  1253. -addr=arguments arg Range for arguments
  1254. -addr=buffers buf Range for buffers (also not loaded buffers)
  1255. -addr=loaded_buffers load Range for loaded buffers
  1256. -addr=windows win Range for windows
  1257. -addr=tabs tab Range for tab pages
  1258. -addr=quickfix qf Range for quickfix entries
  1259. -addr=other ? Other kind of range; can use ".", "$" and "%"
  1260. as with "lines" (this is the default for
  1261. -count)
  1262. Incremental preview ~
  1263. *:command-preview* {nvim-api}
  1264. Commands can show an 'inccommand' (as-you-type) preview by defining a preview
  1265. handler (only from Lua, see |nvim_create_user_command()|).
  1266. Before the preview callback is executed, Nvim will temporarily disable
  1267. 'cursorline' and 'cursorcolumn' to avoid highlighting issues.
  1268. The preview callback must be a Lua function with this signature: >
  1269. function cmdpreview(opts, ns, buf)
  1270. <
  1271. where "opts" has the same form as that given to |nvim_create_user_command()|
  1272. callbacks, "ns" is the preview namespace id for highlights, and "buf" is the
  1273. buffer that your preview routine will directly modify to show the previewed
  1274. results (for "inccommand=split", or nil for "inccommand=nosplit").
  1275. Your command preview routine must implement this protocol:
  1276. 1. Modify the target buffers as required for the preview (see
  1277. |nvim_buf_set_text()| and |nvim_buf_set_lines()|).
  1278. 2. If preview buffer is provided, add necessary text to the preview buffer.
  1279. 3. Add required highlights to the target buffers. If preview buffer is
  1280. provided, add required highlights to the preview buffer as well. All
  1281. highlights must be added to the preview namespace which is provided as an
  1282. argument to the preview callback (see |nvim_buf_add_highlight()| and
  1283. |nvim_buf_set_extmark()| for help on how to add highlights to a namespace).
  1284. 4. Return an integer (0, 1, 2) which controls how Nvim behaves as follows:
  1285. 0: No preview is shown.
  1286. 1: Preview is shown without preview window (even with "inccommand=split").
  1287. 2: Preview is shown and preview window is opened (if "inccommand=split").
  1288. For "inccommand=nosplit" this is the same as 1.
  1289. After preview ends, Nvim discards all changes to all buffers made during the
  1290. preview and clears all highlights in the preview namespace.
  1291. Here's an example of a command to trim trailing whitespace from lines that
  1292. supports incremental command preview:
  1293. >
  1294. -- If invoked as a preview callback, performs 'inccommand' preview by
  1295. -- highlighting trailing whitespace in the current buffer.
  1296. local function trim_space_preview(opts, preview_ns, preview_buf)
  1297. vim.cmd('hi clear Whitespace')
  1298. local line1 = opts.line1
  1299. local line2 = opts.line2
  1300. local buf = vim.api.nvim_get_current_buf()
  1301. local lines = vim.api.nvim_buf_get_lines(buf, line1 - 1, line2, false)
  1302. local preview_buf_line = 0
  1303. for i, line in ipairs(lines) do
  1304. local start_idx, end_idx = string.find(line, '%s+$')
  1305. if start_idx then
  1306. -- Highlight the match
  1307. vim.api.nvim_buf_add_highlight(
  1308. buf,
  1309. preview_ns,
  1310. 'Substitute',
  1311. line1 + i - 2,
  1312. start_idx - 1,
  1313. end_idx
  1314. )
  1315. -- Add lines and set highlights in the preview buffer
  1316. -- if inccommand=split
  1317. if preview_buf then
  1318. local prefix = string.format('|%d| ', line1 + i - 1)
  1319. vim.api.nvim_buf_set_lines(
  1320. preview_buf,
  1321. preview_buf_line,
  1322. preview_buf_line,
  1323. false,
  1324. { prefix .. line }
  1325. )
  1326. vim.api.nvim_buf_add_highlight(
  1327. preview_buf,
  1328. preview_ns,
  1329. 'Substitute',
  1330. preview_buf_line,
  1331. #prefix + start_idx - 1,
  1332. #prefix + end_idx
  1333. )
  1334. preview_buf_line = preview_buf_line + 1
  1335. end
  1336. end
  1337. end
  1338. -- Return the value of the preview type
  1339. return 2
  1340. end
  1341. -- Trims all trailing whitespace in the current buffer.
  1342. local function trim_space(opts)
  1343. local line1 = opts.line1
  1344. local line2 = opts.line2
  1345. local buf = vim.api.nvim_get_current_buf()
  1346. local lines = vim.api.nvim_buf_get_lines(buf, line1 - 1, line2, false)
  1347. local new_lines = {}
  1348. for i, line in ipairs(lines) do
  1349. new_lines[i] = string.gsub(line, '%s+$', '')
  1350. end
  1351. vim.api.nvim_buf_set_lines(buf, line1 - 1, line2, false, new_lines)
  1352. end
  1353. -- Create the user command
  1354. vim.api.nvim_create_user_command(
  1355. 'TrimTrailingWhitespace',
  1356. trim_space,
  1357. { nargs = '?', range = '%', addr = 'lines', preview = trim_space_preview }
  1358. )
  1359. <
  1360. Special cases ~
  1361. *:command-bang* *:command-bar*
  1362. *:command-register* *:command-buffer*
  1363. *:command-keepscript*
  1364. There are some special cases as well:
  1365. -bang The command can take a ! modifier (like :q or :w)
  1366. -bar The command can be followed by a "|" and another command.
  1367. A "|" inside the command argument is not allowed then.
  1368. Also checks for a " to start a comment.
  1369. -register The first argument to the command can be an optional
  1370. register name (like :del, :put, :yank).
  1371. -buffer The command will only be available in the current buffer.
  1372. -keepscript Do not use the location of where the user command was
  1373. defined for verbose messages, use the location of where
  1374. the user command was invoked.
  1375. In the cases of the -count and -register attributes, if the optional argument
  1376. is supplied, it is removed from the argument list and is available to the
  1377. replacement text separately.
  1378. Note that these arguments can be abbreviated, but that is a deprecated
  1379. feature. Use the full name for new scripts.
  1380. Replacement text ~
  1381. The replacement text {repl} for a user defined command is scanned for special
  1382. escape sequences, using <...> notation. Escape sequences are replaced with
  1383. values from the entered command line, and all other text is copied unchanged.
  1384. The resulting string is executed as an Ex command. To avoid the replacement
  1385. use <lt> in place of the initial <. Thus to include "<bang>" literally use
  1386. "<lt>bang>".
  1387. The valid escape sequences are
  1388. *<line1>*
  1389. <line1> The starting line of the command range.
  1390. *<line2>*
  1391. <line2> The final line of the command range.
  1392. *<range>*
  1393. <range> The number of items in the command range: 0, 1 or 2
  1394. *<count>*
  1395. <count> Any count supplied (as described for the '-range'
  1396. and '-count' attributes).
  1397. *<bang>*
  1398. <bang> (See the '-bang' attribute) Expands to a ! if the
  1399. command was executed with a ! modifier, otherwise
  1400. expands to nothing.
  1401. *<mods>* *<q-mods>* *:command-modifiers*
  1402. <mods> The command modifiers, if specified. Otherwise, expands to
  1403. nothing. Supported modifiers are |:aboveleft|, |:belowright|,
  1404. |:botright|, |:browse|, |:confirm|, |:hide|, |:horizontal|,
  1405. |:keepalt|, |:keepjumps|, |:keepmarks|, |:keeppatterns|,
  1406. |:leftabove|, |:lockmarks|, |:noautocmd|, |:noswapfile|,
  1407. |:rightbelow|, |:sandbox|, |:silent|, |:tab|, |:topleft|,
  1408. |:unsilent|, |:verbose|, and |:vertical|.
  1409. Note that |:filter| is not supported.
  1410. Examples: >
  1411. command! -nargs=+ -complete=file MyEdit
  1412. \ for f in expand(<q-args>, 0, 1) |
  1413. \ exe '<mods> split ' .. f |
  1414. \ endfor
  1415. function! SpecialEdit(files, mods)
  1416. for f in expand(a:files, 0, 1)
  1417. exe a:mods .. ' split ' .. f
  1418. endfor
  1419. endfunction
  1420. command! -nargs=+ -complete=file Sedit
  1421. \ call SpecialEdit(<q-args>, <q-mods>)
  1422. <
  1423. *<reg>* *<register>*
  1424. <reg> (See the '-register' attribute) The optional register,
  1425. if specified. Otherwise, expands to nothing. <register>
  1426. is a synonym for this.
  1427. *<args>*
  1428. <args> The command arguments, exactly as supplied (but as
  1429. noted above, any count or register can consume some
  1430. of the arguments, which are then not part of <args>).
  1431. <lt> A single '<' (Less-Than) character. This is needed if you
  1432. want to get a literal copy of one of these escape sequences
  1433. into the expansion - for example, to get <bang>, use
  1434. <lt>bang>.
  1435. *<q-args>*
  1436. If the first two characters of an escape sequence are "q-" (for example,
  1437. <q-args>) then the value is quoted in such a way as to make it a valid value
  1438. for use in an expression. This uses the argument as one single value.
  1439. When there is no argument <q-args> is an empty string. See the
  1440. |q-args-example| below.
  1441. *<f-args>*
  1442. To allow commands to pass their arguments on to a user-defined function, there
  1443. is a special form <f-args> ("function args"). This splits the command
  1444. arguments at spaces and tabs, quotes each argument individually, and the
  1445. <f-args> sequence is replaced by the comma-separated list of quoted arguments.
  1446. See the Mycmd example below. If no arguments are given <f-args> is removed.
  1447. To embed whitespace into an argument of <f-args>, prepend a backslash.
  1448. <f-args> replaces every pair of backslashes (\\) with one backslash. A
  1449. backslash followed by a character other than white space or a backslash
  1450. remains unmodified. Also see |f-args-example| below. Overview:
  1451. command <f-args> ~
  1452. XX ab "ab"
  1453. XX a\b 'a\b'
  1454. XX a\ b 'a b'
  1455. XX a\ b 'a ', 'b'
  1456. XX a\\b 'a\b'
  1457. XX a\\ b 'a\', 'b'
  1458. XX a\\\b 'a\\b'
  1459. XX a\\\ b 'a\ b'
  1460. XX a\\\\b 'a\\b'
  1461. XX a\\\\ b 'a\\', 'b'
  1462. XX [nothing]
  1463. Note that if the "no arguments" situation is to be handled, you have to make
  1464. sure that the function can be called without arguments.
  1465. Examples for user commands: >
  1466. " Delete everything after here to the end
  1467. :com Ddel +,$d
  1468. " Rename the current buffer
  1469. :com -nargs=1 -bang -complete=file Ren f <args>|w<bang>
  1470. " Replace a range with the contents of a file
  1471. " (Enter this all as one line)
  1472. :com -range -nargs=1 -complete=file
  1473. Replace <line1>-pu_|<line1>,<line2>d|r <args>|<line1>d
  1474. " Count the number of lines in the range
  1475. :com! -range -nargs=0 Lines echo <line2> - <line1> + 1 "lines"
  1476. < *f-args-example*
  1477. Call a user function (example of <f-args>) >
  1478. :com -nargs=* Mycmd call Myfunc(<f-args>)
  1479. When executed as: >
  1480. :Mycmd arg1 arg2
  1481. This will invoke: >
  1482. :call Myfunc("arg1","arg2")
  1483. < *q-args-example*
  1484. A more substantial example: >
  1485. :function Allargs(command)
  1486. : let i = 0
  1487. : while i < argc()
  1488. : if filereadable(argv(i))
  1489. : execute "e " .. argv(i)
  1490. : execute a:command
  1491. : endif
  1492. : let i = i + 1
  1493. : endwhile
  1494. :endfunction
  1495. :command -nargs=+ -complete=command Allargs call Allargs(<q-args>)
  1496. The command Allargs takes any Vim command(s) as argument and executes it on all
  1497. files in the argument list. Usage example (note use of the "e" flag to ignore
  1498. errors and the "update" command to write modified buffers): >
  1499. :Allargs %s/foo/bar/ge|update
  1500. This will invoke: >
  1501. :call Allargs("%s/foo/bar/ge|update")
  1502. <
  1503. vim:tw=78:ts=8:noet:ft=help:norl: