blob: 90664163e7ca025604c14466ca7557a6f2e32f42 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001*usr_40.txt* For Vim version 7.0aa. Last change: 2004 Feb 13
2
3 VIM USER MANUAL - by Bram Moolenaar
4
5 Make new commands
6
7
8Vim is an extensible editor. You can take a sequence of commands you use
9often and turn it into a new command. Or redefine an existing command.
10Autocommands make it possible to execute commands automatically.
11
12|40.1| Key mapping
13|40.2| Defining command-line commands
14|40.3| Autocommands
15
16 Next chapter: |usr_41.txt| Write a Vim script
17 Previous chapter: |usr_31.txt| Exploiting the GUI
18Table of contents: |usr_toc.txt|
19
20==============================================================================
21*40.1* Key mapping
22
23A simple mapping was explained in section |05.3|. The principle is that one
24sequence of key strokes is translated into another sequence of key strokes.
25This is a simple, yet powerful mechanism.
26 The simplest form is that one key is mapped to a sequence of keys. Since
27the function keys, except <F1>, have no predefined meaning in Vim, these are a
28good choice to map. Example: >
29
30 :map <F2> GoDate: <Esc>:read !date<CR>kJ
31
32This shows how three modes are used. After going to the last line with "G",
33the "o" command opens a new line and starts Insert mode. The text "Date: " is
34inserted and <Esc> takes you out of insert mode.
35 Notice the use of special keys inside <>. This is called angle bracket
36notation. You type these as separate characters, not by pressing the key
37itself. This makes the mappings better readable and you can copy and paste
38the text without problems.
39 The ":" character takes Vim to the command line. The ":read !date" command
40reads the output from the "date" command and appends it below the current
41line. The <CR> is required to execute the ":read" command.
42 At this point of execution the text looks like this:
43
44 Date: ~
45 Fri Jun 15 12:54:34 CEST 2001 ~
46
47Now "kJ" moves the cursor up and joins the lines together.
48 To decide which key or keys you use for mapping, see |map-which-keys|.
49
50
51MAPPING AND MODES
52
53The ":map" command defines remapping for keys in Normal mode. You can also
54define mappings for other modes. For example, ":imap" applies to Insert mode.
55You can use it to insert a date below the cursor: >
56
57 :imap <F2> <CR>Date: <Esc>:read !date<CR>kJ
58
59It looks a lot like the mapping for <F2> in Normal mode, only the start is
60different. The <F2> mapping for Normal mode is still there. Thus you can map
61the same key differently for each mode.
62 Notice that, although this mapping starts in Insert mode, it ends in Normal
63mode. If you want it to continue in Insert mode, append a "a" to the mapping.
64
65Here is an overview of map commands and in which mode they work:
66
67 :map Normal, Visual and Operator-pending
68 :vmap Visual
69 :nmap Normal
70 :omap Operator-pending
71 :map! Insert and Command-line
72 :imap Insert
73 :cmap Command-line
74
75Operator-pending mode is when you typed an operator character, such as "d" or
76"y", and you are expected to type the motion command or a text object. Thus
77when you type "dw", the "w" is entered in operator-pending mode.
78
79Suppose that you want to define <F7> so that the command d<F7> deletes a C
80program block (text enclosed in curly braces, {}). Similarly y<F7> would yank
81the program block into the unnamed register. Therefore, what you need to do
82is to define <F7> to select the current program block. You can do this with
83the following command: >
84
85 :omap <F7> a{
86
87This causes <F7> to perform a select block "a{" in operator-pending mode, just
88like you typed it. This mapping is useful if typing a { on your keyboard is a
89bit difficult.
90
91
92LISTING MAPPINGS
93
94To see the currently defined mappings, use ":map" without arguments. Or one
95of the variants that include the mode in which they work. The output could
96look like this:
97
98 _g :call MyGrep(1)<CR> ~
99 v <F2> :s/^/> /<CR>:noh<CR>`` ~
100 n <F2> :.,$s/^/> /<CR>:noh<CR>`` ~
101 <xHome> <Home>
102 <xEnd> <End>
103
104
105The first column of the list shows in which mode the mapping is effective.
106This is "n" for Normal mode, "i" for Insert mode, etc. A blank is used for a
107mapping defined with ":map", thus effective in both Normal and Visual mode.
108 One useful purpose of listing the mapping is to check if special keys in <>
109form have been recognized (this only works when color is supported). For
110example, when <Esc> is displayed in color, it stands for the escape character.
111When it has the same color as the other text, it is five characters.
112
113
114REMAPPING
115
116The result of a mapping is inspected for other mappings in it. For example,
117the mappings for <F2> above could be shortened to: >
118
119 :map <F2> G<F3>
120 :imap <F2> <Esc><F3>
121 :map <F3> oDate: <Esc>:read !date<CR>kJ
122
123For Normal mode <F2> is mapped to go to the last line, and then behave like
124<F3> was pressed. In Insert mode <F2> stops Insert mode with <Esc> and then
125also uses <F3>. Then <F3> is mapped to do the actual work.
126
127Suppose you hardly ever use Ex mode, and want to use the "Q" command to format
128text (this was so in old versions of Vim). This mapping will do it: >
129
130 :map Q gq
131
132But, in rare cases you need to use Ex mode anyway. Let's map "gQ" to Q, so
133that you can still go to Ex mode: >
134
135 :map gQ Q
136
137What happens now is that when you type "gQ" it is mapped to "Q". So far so
138good. But then "Q" is mapped to "gq", thus typing "gQ" results in "gq", and
139you don't get to Ex mode at all.
140 To avoid keys to be mapped again, use the ":noremap" command: >
141
142 :noremap gQ Q
143
144Now Vim knows that the "Q" is not to be inspected for mappings that apply to
145it. There is a similar command for every mode:
146
147 :noremap Normal, Visual and Operator-pending
148 :vnoremap Visual
149 :nnoremap Normal
150 :onoremap Operator-pending
151 :noremap! Insert and Command-line
152 :inoremap Insert
153 :cnoremap Command-line
154
155
156RECURSIVE MAPPING
157
158When a mapping triggers itself, it will run forever. This can be used to
159repeat an action an unlimited number of times.
160 For example, you have a list of files that contain a version number in the
161first line. You edit these files with "vim *.txt". You are now editing the
162first file. Define this mapping: >
163
164 :map ,, :s/5.1/5.2/<CR>:wnext<CR>,,
165
166Now you type ",,". This triggers the mapping. It replaces "5.1" with "5.2"
167in the first line. Then it does a ":wnext" to write the file and edit the
168next one. The mapping ends in ",,". This triggers the same mapping again,
169thus doing the substitution, etc.
170 This continues until there is an error. In this case it could be a file
171where the substitute command doesn't find a match for "5.1". You can then
172make a change to insert "5.1" and continue by typing ",," again. Or the
173":wnext" fails, because you are in the last file in the list.
174 When a mapping runs into an error halfway, the rest of the mapping is
175discarded. CTRL-C interrupts the mapping (CTRL-Break on MS-Windows).
176
177
178DELETE A MAPPING
179
180To remove a mapping use the ":unmap" command. Again, the mode the unmapping
181applies to depends on the command used:
182
183 :unmap Normal, Visual and Operator-pending
184 :vunmap Visual
185 :nunmap Normal
186 :ounmap Operator-pending
187 :unmap! Insert and Command-line
188 :iunmap Insert
189 :cunmap Command-line
190
191There is a trick to define a mapping that works in Normal and Operator-pending
192mode, but not in Visual mode. First define it for all three modes, then
193delete it for Visual mode: >
194
195 :map <C-A> /---><CR>
196 :vunmap <C-A>
197
198Notice that the five characters "<C-A>" stand for the single key CTRL-A.
199
200To remove all mappings use the |:mapclear| command. You can guess the
201variations for different modes by now. Be careful with this command, it can't
202be undone.
203
204
205SPECIAL CHARACTERS
206
207The ":map" command can be followed by another command. A | character
208separates the two commands. This also means that a | character can't be used
209inside a map command. To include one, use <Bar> (five characters). Example:
210>
211 :map <F8> :write <Bar> !checkin %<CR>
212
213The same problem applies to the ":unmap" command, with the addition that you
214have to watch out for trailing white space. These two commands are different:
215>
216 :unmap a | unmap b
217 :unmap a| unmap b
218
219The first command tries to unmap "a ", with a trailing space.
220
221When using a space inside a mapping, use <Space> (seven characters): >
222
223 :map <Space> W
224
225This makes the spacebar move a blank-separated word forward.
226
227It is not possible to put a comment directly after a mapping, because the "
228character is considered to be part of the mapping. You can use |", this
229starts a new, empty command with a comment. Example: >
230
231 :map <Space> W| " Use spacebar to move forward a word
232
233
234MAPPINGS AND ABBREVIATIONS
235
236Abbreviations are a lot like Insert mode mappings. The arguments are handled
237in the same way. The main difference is the way they are triggered. An
238abbreviation is triggered by typing a non-word character after the word. A
239mapping is triggered when typing the last character.
240 Another difference is that the characters you type for an abbreviation are
241inserted in the text while you type them. When the abbreviation is triggered
242these characters are deleted and replaced by what the abbreviation produces.
243When typing the characters for a mapping, nothing is inserted until you type
244the last character that triggers it. If the 'showcmd' option is set, the
245typed characters are displayed in the last line of the Vim window.
246 An exception is when a mapping is ambiguous. Suppose you have done two
247mappings: >
248
249 :imap aa foo
250 :imap aaa bar
251
252Now, when you type "aa", Vim doesn't know if it should apply the first or the
253second mapping. It waits for another character to be typed. If it is an "a",
254the second mapping is applied and results in "bar". If it is a space, for
255example, the first mapping is applied, resulting in "foo", and then the space
256is inserted.
257
258
259ADDITIONALLY...
260
261The <script> keyword can be used to make a mapping local to a script. See
262|:map-<script>|.
263
264The <buffer> keyword can be used to make a mapping local to a specific buffer.
265See |:map-<buffer>|
266
267The <unique> keyword can be used to make defining a new mapping fail when it
268already exists. Otherwise a new mapping simply overwrites the old one. See
269|:map-<unique>|.
270
271To make a key do nothing, map it to <Nop> (five characters). This will make
272the <F7> key do nothing at all: >
273
274 :map <F7> <Nop>| map! <F7> <Nop>
275
276There must be no space after <Nop>.
277
278==============================================================================
279*40.2* Defining command-line commands
280
281The Vim editor enables you to define your own commands. You execute these
282commands just like any other Command-line mode command.
283 To define a command, use the ":command" command, as follows: >
284
285 :command DeleteFirst 1delete
286
287Now when you execute the command ":DeleteFirst" Vim executes ":1delete", which
288deletes the first line.
289
290 Note:
291 User-defined commands must start with a capital letter. You cannot
292 use ":X", ":Next" and ":Print". The underscore cannot be used! You
293 can use digits, but this is discouraged.
294
295To list the user-defined commands, execute the following command: >
296
297 :command
298
299Just like with the builtin commands, the user defined commands can be
300abbreviated. You need to type just enough to distinguish the command from
301another. Command line completion can be used to get the full name.
302
303
304NUMBER OF ARGUMENTS
305
306User-defined commands can take a series of arguments. The number of arguments
307must be specified by the -nargs option. For instance, the example
308:DeleteFirst command takes no arguments, so you could have defined it as
309follows: >
310
311 :command -nargs=0 DeleteFirst 1delete
312
313However, because zero arguments is the default, you do not need to add
314"-nargs=0". The other values of -nargs are as follows:
315
316 -nargs=0 No arguments
317 -nargs=1 One argument
318 -nargs=* Any number of arguments
319 -nargs=? Zero or one argument
320 -nargs=+ One or more arguments
321
322
323USING THE ARGUMENTS
324
325Inside the command definition, the arguments are represented by the
326<args> keyword. For example: >
327
328 :command -nargs=+ Say :echo "<args>"
329
330Now when you type >
331
332 :Say Hello World
333
334Vim echoes "Hello World". However, if you add a double quote, it won't work.
335For example: >
336
337 :Say he said "hello"
338
339To get special characters turned into a string, properly escaped to use as an
340expression, use "<q-args>": >
341
342 :command -nargs=+ Say :echo <q-args>
343
344Now the above ":Say" command will result in this to be executed: >
345
346 :echo "he said \"hello\""
347
348The <f-args> keyword contains the same information as the <args> keyword,
349except in a format suitable for use as function call arguments. For example:
350>
351 :command -nargs=* DoIt :call AFunction(<f-args>)
352 :DoIt a b c
353
354Executes the following command: >
355
356 :call AFunction("a", "b", "c")
357
358
359LINE RANGE
360
361Some commands take a range as their argument. To tell Vim that you are
362defining such a command, you need to specify a -range option. The values for
363this option are as follows:
364
365 -range Range is allowed; default is the current line.
366 -range=% Range is allowed; default is the whole file.
367 -range={count} Range is allowed; the last number in it is used as a
368 single number whose default is {count}.
369
370When a range is specified, the keywords <line1> and <line2> get the values of
371the first and last line in the range. For example, the following command
372defines the SaveIt command, which writes out the specified range to the file
373"save_file": >
374
375 :command -range=% SaveIt :<line1>,<line2>write! save_file
376
377
378OTHER OPTIONS
379
380Some of the other options and keywords are as follows:
381
382 -count={number} The command can take a count whose default is
383 {number}. The resulting count can be used
384 through the <count> keyword.
385 -bang You can use a !. If present, using <bang> will
386 result in a !.
387 -register You can specify a register. (The default is
388 the unnamed register.)
389 The register specification is available as
390 <reg> (a.k.a. <register>).
391 -complete={type} Type of command-line completion used. See
392 |:command-completion| for the list of possible
393 values.
394 -bar The command can be followed by | and another
395 command, or " and a comment.
396 -buffer The command is only available for the current
397 buffer.
398
399Finally, you have the <lt> keyword. It stands for the character <. Use this
400to escape the special meaning of the <> items mentioned.
401
402
403REDEFINING AND DELETING
404
405To redefine the same command use the ! argument: >
406
407 :command -nargs=+ Say :echo "<args>"
408 :command! -nargs=+ Say :echo <q-args>
409
410To delete a user command use ":delcommand". It takes a single argument, which
411is the name of the command. Example: >
412
413 :delcommand SaveIt
414
415To delete all the user commands: >
416
417 :comclear
418
419Careful, this can't be undone!
420
421More details about all this in the reference manual: |user-commands|.
422
423==============================================================================
424*40.3* Autocommands
425
426An autocommand is a command that is executed automatically in response to some
427event, such as a file being read or written or a buffer change. Through the
428use of autocommands you can train Vim to edit compressed files, for example.
429That is used in the |gzip| plugin.
430 Autocommands are very powerful. Use them with care and they will help you
431avoid typing many commands. Use them carelessly and they will cause a lot of
432trouble.
433
434Suppose you want to replace a date stamp on the end of a file every time it is
435written. First you define a function: >
436
437 :function DateInsert()
438 : $delete
439 : read !date
440 :endfunction
441
442You want this function to be called each time, just before a file is written.
443This will make that happen: >
444
445 :autocmd FileWritePre * call DateInsert()
446
447"FileWritePre" is the event for which this autocommand is triggered: Just
448before (pre) writing a file. The "*" is a pattern to match with the file
449name. In this case it matches all files.
450 With this command enabled, when you do a ":write", Vim checks for any
451matching FileWritePre autocommands and executes them, and then it
452performs the ":write".
453 The general form of the :autocmd command is as follows: >
454
455 :autocmd [group] {events} {file_pattern} [nested] {command}
456
457The [group] name is optional. It is used in managing and calling the commands
458(more on this later). The {events} parameter is a list of events (comma
459separated) that trigger the command.
460 {file_pattern} is a filename, usually with wildcards. For example, using
461"*.txt" makes the autocommand be used for all files whose name end in ".txt".
462The optional [nested] flag allows for nesting of autocommands (see below), and
463finally, {command} is the command to be executed.
464
465
466EVENTS
467
468One of the most useful events is BufReadPost. It is triggered after a new
469file is being edited. It is commonly used to set option values. For example,
470you know that "*.gsm" files are GNU assembly language. To get the syntax file
471right, define this autocommand: >
472
473 :autocmd BufReadPost *.gsm set filetype=asm
474
475If Vim is able to detect the type of file, it will set the 'filetype' option
476for you. This triggers the Filetype event. Use this to do something when a
477certain type of file is edited. For example, to load a list of abbreviations
478for text files: >
479
480 :autocmd Filetype text source ~/.vim/abbrevs.vim
481
482When starting to edit a new file, you could make Vim insert a skeleton: >
483
484 :autocmd BufNewFile *.[ch] 0read ~/skeletons/skel.c
485
486See |autocmd-events| for a complete list of events.
487
488
489PATTERNS
490
491The {file_pattern} argument can actually be a comma-separated list of file
492patterns. For example: "*.c,*.h" matches files ending in ".c" and ".h".
493 The usual file wildcards can be used. Here is a summary of the most often
494used ones:
495
496 * Match any character any number of times
497 ? Match any character once
498 [abc] Match the character a, b or c
499 . Matches a dot
500 a{b,c} Matches "ab" and "ac"
501
502When the pattern includes a slash (/) Vim will compare directory names.
503Without the slash only the last part of a file name is used. For example,
504"*.txt" matches "/home/biep/readme.txt". The pattern "/home/biep/*" would
505also match it. But "home/foo/*.txt" wouldn't.
506 When including a slash, Vim matches the pattern against both the full path
507of the file ("/home/biep/readme.txt") and the relative path (e.g.,
508"biep/readme.txt").
509
510 Note:
511 When working on a system that uses a backslash as file separator, such
512 as MS-Windows, you still use forward slashes in autocommands. This
513 makes it easier to write the pattern, since a backslash has a special
514 meaning. It also makes the autocommands portable.
515
516
517DELETING
518
519To delete an autocommand, use the same command as what it was defined with,
520but leave out the {command} at the end and use a !. Example: >
521
522 :autocmd! FileWritePre *
523
524This will delete all autocommands for the "FileWritePre" event that use the
525"*" pattern.
526
527
528LISTING
529
530To list all the currently defined autocommands, use this: >
531
532 :autocmd
533
534The list can be very long, especially when filetype detection is used. To
535list only part of the commands, specify the group, event and/or pattern. For
536example, to list all BufNewFile autocommands: >
537
538 :autocmd BufNewFile
539
540To list all autocommands for the pattern "*.c": >
541
542 :autocmd * *.c
543
544Using "*" for the event will list all the events. To list all autocommands
545for the cprograms group: >
546
547 :autocmd cprograms
548
549
550GROUPS
551
552The {group} item, used when defining an autocommand, groups related autocommands
553together. This can be used to delete all the autocommands in a certain group,
554for example.
555 When defining several autocommands for a certain group, use the ":augroup"
556command. For example, let's define autocommands for C programs: >
557
558 :augroup cprograms
559 : autocmd BufReadPost *.c,*.h :set sw=4 sts=4
560 : autocmd BufReadPost *.cpp :set sw=3 sts=3
561 :augroup END
562
563This will do the same as: >
564
565 :autocmd cprograms BufReadPost *.c,*.h :set sw=4 sts=4
566 :autocmd cprograms BufReadPost *.cpp :set sw=3 sts=3
567
568To delete all autocommands in the "cprograms" group: >
569
570 :autocmd! cprograms
571
572
573NESTING
574
575Generally, commands executed as the result of an autocommand event will not
576trigger any new events. If you read a file in response to a FileChangedShell
577event, it will not trigger the autocommands that would set the syntax, for
578example. To make the events triggered, add the "nested" argument: >
579
580 :autocmd FileChangedShell * nested edit
581
582
583EXECUTING AUTOCOMMANDS
584
585It is possible to trigger an autocommand by pretending an event has occurred.
586This is useful to have one autocommand trigger another one. Example: >
587
588 :autocmd BufReadPost *.new execute "doautocmd BufReadPost " . expand("<afile>:r")
589
590This defines an autocommand that is triggered when a new file has been edited.
591The file name must end in ".new". The ":execute" command uses expression
592evaluation to form a new command and execute it. When editing the file
593"tryout.c.new" the executed command will be: >
594
595 :doautocmd BufReadPost tryout.c
596
597The expand() function takes the "<afile>" argument, which stands for the file
598name the autocommand was executed for, and takes the root of the file name
599with ":r".
600
601":doautocmd" executes on the current buffer. The ":doautoall" command works
602like "doautocmd" except it executes on all the buffers.
603
604
605USING NORMAL MODE COMMANDS
606
607The commands executed by an autocommand are Command-line command. If you want
608to use a Normal mode command, the ":normal" command can be used. Example: >
609
610 :autocmd BufReadPost *.log normal G
611
612This will make the cursor jump to the last line of *.log files when you start
613to edit it.
614 Using the ":normal" command is a bit tricky. First of all, make sure its
615argument is a complete command, including all the arguments. When you use "i"
616to go to Insert mode, there must also be a <Esc> to leave Insert mode again.
617If you use a "/" to start a search pattern, there must be a <CR> to execute
618it.
619 The ":normal" command uses all the text after it as commands. Thus there
620can be no | and another command following. To work around this, put the
621":normal" command inside an ":execute" command. This also makes it possible
622to pass unprintable characters in a convenient way. Example: >
623
624 :autocmd BufReadPost *.chg execute "normal ONew entry:\<Esc>" |
625 \ 1read !date
626
627This also shows the use of a backslash to break a long command into more
628lines. This can be used in Vim scripts (not at the command line).
629
630When you want the autocommand do something complicated, which involves jumping
631around in the file and then returning to the original position, you may want
632to restore the view on the file. See |restore-position| for an example.
633
634
635IGNORING EVENTS
636
637At times, you will not want to trigger an autocommand. The 'eventignore'
638option contains a list of events that will be totally ignored. For example,
639the following causes events for entering and leaving a window to be ignored: >
640
641 :set eventignore=WinEnter,WinLeave
642
643To ignore all events, use the following command: >
644
645 :set eventignore=all
646
647To set it back to the normal behavior, make 'eventignore' empty: >
648
649 :set eventignore=
650
651==============================================================================
652
653Next chapter: |usr_41.txt| Write a Vim script
654
655Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl: