Movatterモバイル変換


[0]ホーム

URL:


Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq
Go to keyword (shortcut:k)
Site search (shortcut:s)
usr_40.txt  ForVim version 9.2.  Last change: 2026 Feb 14     VIM USER MANUALbyBramMoolenaar      Make new commandsVimis an extensible editor.  You can takea sequence of commands you useoften and turnit intoa new command.  Or redefine an existing command.Autocommands makeit possible to execute commands automatically.40.1  Keymapping40.2  Defining command-line commands40.3  Autocommands     Next chapter:usr_41.txt  Writea Vimscript Previous chapter:usr_32.txt  Theundo treeTable of contents:usr_toc.txt==============================================================================40.1  KeymappingA simplemapping was explained insection05.4.  The principleis that onesequence of key strokesis translated into another sequence of key strokes.Thisisa simple, yet powerful mechanism.   The simplest formis that one keyis mapped toa sequence of keys.  Sincethe function keys, except<F1>, have no predefined meaning in Vim, these aregood choices to map.  Example::map <F2> GoDate: <Esc>:read !date<CR>kJThis shows how three modes are used.  After going to the last line with "G",the "o" command opensa new line and startsInsert mode.  The text "Date: "isinserted and<Esc> takes you out ofinsert mode.   Notice the use of special keys inside <>.  Thisis called angle bracketnotation.  You type theseas separate characters, not by pressing the keyitself.  This makes the mappings better readable and you can copy and pastethe text without problems.   The ":" character takes Vim to the command line.  The ":read !date" commandreads the output from the "date" command and appendsit below the currentline.  The<CR>is required to execute the ":read" command.   At this point of execution the text looks like this:Date:Fri Jun 15 12:54:34 CEST 2001Now "kJ" moves the cursor up and joins the lines together.   To decide which key or keys you use for mapping, seemap-which-keys.MAPPING AND MODESThe ":map" command defines remapping for keys inNormal mode.  You can alsodefine mappings for other modes.  For example, ":imap" applies toInsert mode.You can useit toinserta date below the cursor::imap <F2> <CR>Date: <Esc>:read !date<CR>kJIt looksa lot like themapping for<F2> inNormal mode, only the startisdifferent.  The<F2>mapping forNormal modeis still there.  Thus you can mapthe same key differently for each mode.   Notice that, although thismapping starts inInsert mode,it ends inNormalmode.  If you wantit to continue inInsert mode, append an "a" to themapping.Hereis an overview of map commands and in which mode they work::mapNormal,Visual andOperator-pending:vmapVisual:nmapNormal:omapOperator-pending:map!Insert andCommand-line:imapInsert:cmapCommand-lineOperator-pending modeis when you typed anoperator character, suchas "d" or"y", and you are expected to type the motion command ora text object.  Thuswhen you type "dw", the "w"is entered in operator-pending mode.Suppose that you want to define<F7> so that the command d<F7> deletesaCprogram block (text enclosed in curly braces, {}).  Similarly y<F7> wouldyankthe program block into the unnamed register.  Therefore, what you need todois to define<F7> to select the current program block.  You cando this withthe following command::omap <F7> a{This causes<F7> to performa select block "a{" in operator-pending mode, justlike you typed it.  Thismappingis useful if typinga{ on your keyboardisabit difficult.LISTING MAPPINGSTo see the currently defined mappings, use ":map" without arguments.  Or oneof the variants that include the mode in which they work.  The output couldlook like this:   _g :call MyGrep(1)<CR>v  <F2> :s/^/> /<CR>:noh<CR>``n  <F2> :.,$s/^/> /<CR>:noh<CR>``<xHome><Home><xEnd><End>The first column of thelist shows in which mode themappingis effective.Thisis "n" forNormal mode, "i" forInsert mode, etc.A blankis used foramapping defined with ":map", thus effective in bothNormal andVisual mode.   One useful purpose of listing themappingis to check if special keys in<>form have been recognized (this only works when coloris supported).  Forexample, when<Esc>is displayed in color,it stands for theescape character.Whenit has the same coloras the other text,itis five characters.REMAPPINGThe result ofamappingis inspected for other mappings in it.  For example,the mappings for<F2> above could be shortened to::map <F2> G<F3>:imap <F2> <Esc><F3>:map <F3>  oDate: <Esc>:read !date<CR>kJForNormal mode<F2>is mapped togo to the last line, and then behave like<F3> was pressed.  InInsert mode<F2> stopsInsert mode with<Esc> and thenalso uses<F3>.  Then<F3>is mapped todo the actual work.Suppose you hardly ever useEx mode, and want to use the "Q" command to formattext (this was so in old versions of Vim).  Thismapping willdo it::map Q gqBut, in rare cases you need to useEx mode anyway.  Let's map "gQ" to Q, sothat you can stillgo toEx mode::map gQ QWhat happens nowis that when you type "gQ"itis mapped to "Q".  So far sogood.  But then "Q"is mapped to "gq", thus typing "gQ" results in "gq", andyou don't get toEx modeat all.   To avoid keys to be mapped again, use the ":noremap" command::noremap gQ QNow Vim knows that the "Q"is not to be inspected for mappings that apply toit.  Thereisa similar command for every mode::noremapNormal,Visual andOperator-pending:vnoremapVisual:nnoremapNormal:onoremapOperator-pending:noremap!Insert andCommand-line:inoremapInsert:cnoremapCommand-lineRECURSIVE MAPPINGWhenamapping triggers itself,it will run forever.  This can be used torepeat an action an unlimited number of times.   For example, you havealist of files that containa version number in thefirst line.  You edit these files with "vim *.txt".  You are now editing thefirst file.  Define this mapping::map ,, :s/5.1/5.2/<CR>:wnext<CR>,,Now you type ",,".  This triggers the mapping.  It replaces "5.1" with "5.2"in the first line.  Thenit doesa ":wnext" to write the file and edit thenext one.  Themapping ends in ",,".  This triggers the samemapping again,thus doing the substitution, etc.   This continues until thereis an error.  In thiscaseit could bea filewhere the substitute command doesn't finda match for "5.1".  You can thenmakea change toinsert "5.1" and continue by typing ",," again.  Or the":wnext" fails, because you are in the last file in the list.   Whenamapping runs into an error halfway, the rest of themappingisdiscarded.CTRL-C interrupts themapping (CTRL-Break on MS-Windows).DELETE A MAPPINGTo removeamapping use the ":unmap" command.  Again, the mode the unmappingapplies to depends on the command used::unmapNormal,Visual andOperator-pending:vunmapVisual:nunmapNormal:ounmapOperator-pending:unmap!Insert andCommand-line:iunmapInsert:cunmapCommand-lineThereisa trick to defineamapping that works inNormal andOperator-pendingmode, but not inVisual mode.  First defineit for all three modes, thendeleteit forVisual mode::map <C-A> /---><CR>:vunmap <C-A>Notice that the five characters "<C-A>" stand for the single keyCTRL-A.To remove all mappings use the:mapclear command.  You can guess thevariations for different modes by now.  Be careful with this command,it can'tbe undone.SPECIAL CHARACTERSThe ":map" command can be followed by another command.A | characterseparates the two commands.  This also means thata | character can't be usedinsidea map command.  To include one, use<Bar> (five characters).  Example::map <F8> :write <Bar> !checkin %:S<CR>The same problem applies to the ":unmap" command, with the addition that youhave to watch out for trailing white space.  These two commands are different::unmap a | unmap b:unmap a| unmap bThe first command tries to unmap "a ", witha trailing space.When usingaspace insidea mapping, use<Space> (seven characters)::map <Space> WThis makes the spacebar movea blank-separatedword forward.Itis not possible toputa comment directly aftera mapping, because the "characteris considered to be part of the mapping.  You can use |", thisstartsa new, empty command witha comment.  Example::map <Space> W|     " Use spacebar to move forward a wordMAPPINGS AND ABBREVIATIONSAbbreviations area lot likeInsert mode mappings.  The arguments are handledin the same way.  The main differenceis the way they are triggered.  Anabbreviationis triggered by typinga non-word character after the word.Amappingis triggered when typing the last character.   Another differenceis that the characters you type for an abbreviation areinserted in the text while you type them.  When the abbreviationis triggeredthese characters are deleted and replaced by what the abbreviation produces.When typing the characters fora mapping, nothingis inserted until you typethe last character that triggers it.  If the'showcmd' optionis set, thetyped characters are displayed in the last line of the Vim window.   An exceptionis whenamappingis ambiguous.  Suppose you have done twomappings::imap aa foo:imap aaa barNow, when you type "aa", Vim doesn't know ifit should apply the first or thesecond mapping.  It waits for another character to be typed.  Ifitis an "a",the secondmappingis applied and results in "bar".  Ifitisa space, forexample, the firstmappingis applied, resulting in "foo", and then thespaceis inserted.ADDITIONALLY...The<script> keyword can be used to makeamapping local toa script.  See:map-<script>.The<buffer> keyword can be used to makeamapping local toa specific buffer.See:map-<buffer>The<unique> keyword can be used to make defininga newmapping fail whenitalready exists.  Otherwisea newmapping simply overwrites the old one.  See:map-<unique>.To makea keydo nothing, mapit to<Nop> (five characters).  This will makethe<F7> keydo nothingat all::map <F7> <Nop>| map! <F7> <Nop>Theremust be nospace after<Nop>.==============================================================================40.2  Defining command-line commandsThe Vim editor enables you to define your own commands.  You execute thesecommands just like any otherCommand-line mode command.   To definea command, use the ":command" command,as follows::command DeleteFirst 1deleteNow when you execute the command ":DeleteFirst" Vim executes ":1delete", whichdeletes the first line.Note:User-defined commandsmust start witha capital letter.  You cannotuse ":X", ":Next" and ":Print".  The underscore cannot be used!  Youcan use digits, but thisis discouraged.Tolist the user-defined commands, execute the following command::commandJust like with the builtin commands, the user defined commands can beabbreviated.  You need to type just enough to distinguish the command fromanother.  Command line completion can be used to get the full name.NUMBER OF ARGUMENTSUser-defined commands can takea series of arguments.  The number of argumentsmust be specified by the -nargs option.  For instance, the example:DeleteFirst command takes no arguments, so you could have defineditasfollows::command -nargs=0 DeleteFirst 1deleteHowever, because zero argumentsis the default, youdo not need to add"-nargs=0".  The other values of -nargs areas follows:-nargs=0No arguments-nargs=1One argument-nargs=*Any number of arguments-nargs=?Zero or one argument-nargs=+One or more argumentsUSING THE ARGUMENTSInside the command definition, the arguments are represented by the<args> keyword.  For example::command -nargs=+ Say :echo "<args>"Now when you type:Say Hello WorldVim echoes "Hello World".  However, if you adda double quote,it won't work.For example::Say he said "hello"To get special characters turned intoa string, properly escaped to useas anexpression, use "<q-args>"::command -nargs=+ Say :echo <q-args>Now the above ":Say" command will result in this to be executed::echo "he said \"hello\""The<f-args> keyword contains the same informationas the<args> keyword,except ina format suitable for useas function call arguments.  For example::command -nargs=* DoIt :call AFunction(<f-args>):DoIt a b cExecutes the following command::call AFunction("a", "b", "c")LINE RANGESome commands takea rangeas their argument.  To tell Vim that you aredefining sucha command, you need to specifya -range option.  The values forthis option areas follows:-rangeRangeis allowed; defaultis the current line.-range=%Rangeis allowed; defaultis the whole file.-range={count}Rangeis allowed; the last number initis usedasasingle number whose defaultis{count}.Whena rangeis specified, the keywords<line1> and<line2> get the values ofthe first and last line in the range.  For example, the following commanddefines the SaveIt command, which writes out the specified range to the file"save_file"::command -range=% SaveIt :<line1>,<line2>write! save_fileOTHER OPTIONSSome of the otheroptions and keywords areas follows:-count={number}The command can takeacount whose defaultis{number}.  The resultingcount can be usedthrough the<count> keyword.-bangYou can usea !.  If present, using<bang>will result ina !.-registerYou can specifya register.  (The defaultisthe unnamed register.)The register specificationis availableas<reg> (a.k.a.<register>).-complete={type}Type of command-line completion used.  See:command-completion for thelist of possiblevalues.-barThe command can be followed by | and anothercommand, or " anda comment.-bufferThe commandis only available for the currentbuffer.Finally, you have the<lt> keyword.  It stands for the character <.  Use thistoescape the special meaning of the<> items mentioned.REDEFINING AND DELETINGTo redefine the same command use the! argument::command -nargs=+ Say :echo "<args>":command! -nargs=+ Say :echo <q-args>To deletea user command use ":delcommand".  It takesa single argument, whichis the name of the command.  Example::delcommand SaveItTo delete all the user commands::comclearCareful, this can't be undone!More details about all this in thereference manual:user-commands.==============================================================================40.3  AutocommandsAnautocommandisa command thatis executed automatically in response to someevent, suchasa file being read or written ora buffer change.  Through theuse ofautocommands you can train Vim to edit compressed files, for example.Thatis used in thegzip plugin.   Autocommands are very powerful.  Use them with care and they willhelp youavoid typing many commands.  Use them carelessly and they will causea lot oftrouble.Suppose you want to replacea datestamp on theend ofa file every timeitiswritten.  First you definea function::function DateInsert():  $delete:  read !date:endfunctionYou want this function to be called each time, just beforea bufferis writtentoa file.  This will make that happen::autocmd BufWritePre *  call DateInsert()"BufWritePre"is the event for which thisautocommandis triggered: Justbefore (pre)writinga buffer toa file.  The "*"isapattern to match withthe file name.  In thiscaseit matches all files.   With this command enabled, when youdoa ":write", Vim checks for anymatchingBufWritePreautocommands and executes them, and thenitperforms the ":write".   The general form of the:autocmd commandisas follows::autocmd [group] {events} {file-pattern} [++nested] {command}The[group] nameis optional.  Itis used in managing and calling the commands(more on this later).  The{events} parameterisalist of events (commaseparated) that trigger the command.{file-pattern}isa filename, usually with wildcards.  For example, using"*.txt" makes theautocommand be used for all files whose nameend in ".txt".The optional [++nested] flag allows for nesting ofautocommands (see below),and finally,{command}is the command to be executed.When adding anautocommand the already existing ones remain.  To avoid addingtheautocommand several times you should use this form::augroup updateDate:  autocmd!:  autocmd BufWritePre *  call DateInsert():augroup ENDThis will delete any previously definedautocommand with:autocmd! beforedefining the new one.  Groups are explained later.EVENTSOne of the most useful eventsis BufReadPost.  Itis triggered aftera newfileis being edited.  Itis commonly used to set option values.  For example,you know that "*.gsm" files are GNU assembly language.  To get thesyntax fileright, define this autocommand::autocmd BufReadPost *.gsm  set filetype=asmIf Vimis able to detect the type of file,it will set the'filetype' optionfor you.  This triggers the Filetype event.  Use this todo something whenacertain type of fileis edited.  For example, to loadalist ofabbreviationsfor text files::autocmd Filetype text  source ~/.vim/abbrevs.vimWhenstarting to edita new file, you could make Viminserta skeleton::autocmd BufNewFile *.[ch]  0read ~/skeletons/skel.cSeeautocmd-events fora completelist of events.PATTERNSThe{file-pattern} argument can actually bea comma-separatedlist of filepatterns.  For example: "*.c,*.h" matches files ending in ".c" and ".h".   The usual filewildcards can be used.  Hereisa summary of the most oftenused ones:*Match any character any number of times?Match any character once[abc]Match the character a,b orc.Matchesa dota{b,c}Matches "ab" and "ac"When thepattern includesa slash (/) Vim will compare directory names.Without the slash only the last part ofa file nameis used.  For example,"*.txt" matches "/home/biep/readme.txt".  Thepattern "/home/biep/*" wouldalso match it.  But "home/foo/*.txt" wouldn't.   When includinga slash, Vim matches thepattern against both the full pathof the file("/home/biep/readme.txt") and the relative path (e.g.,"biep/readme.txt").Note:When working ona system that usesabackslashas file separator, suchas MS-Windows, you still use forward slashes in autocommands.  Thismakesit easier to write the pattern, sinceabackslash hasa specialmeaning.  It also makes theautocommands portable.DELETINGTo delete an autocommand, use the same commandas whatit was defined with,but leave out the{command}at theend and usea !.  Example::autocmd! FileWritePre *This will delete allautocommands for the "FileWritePre" event that use the"*" pattern.LISTINGTolist all the currently defined autocommands, use this::autocmdThelist can be very long, especially whenfiletype detectionis used.  Tolist only part of the commands, specify the group, event and/or pattern.  Forexample, tolist allBufNewFile autocommands::autocmd BufNewFileTolist allautocommands for thepattern "*.c"::autocmd * *.cUsing "*" for the event willlist all the events.  Tolist allautocommandsfor the cprograms group::autocmd cprogramsGROUPSThe{group} item, used when defining an autocommand, groups relatedautocommands together.  This can be used to delete all theautocommands inacertain group, for example.   When defining severalautocommands fora certain group, use the ":augroup"command.  For example, let's defineautocommands forC programs::augroup cprograms:  autocmd BufReadPost *.c,*.h :set sw=4 sts=4:  autocmd BufReadPost *.cpp   :set sw=3 sts=3:augroup ENDThis willdo the same as::autocmd cprograms BufReadPost *.c,*.h :set sw=4 sts=4:autocmd cprograms BufReadPost *.cpp   :set sw=3 sts=3To delete allautocommands in the "cprograms" group::autocmd! cprogramsNESTINGGenerally, commands executedas the result of anautocommand event will nottrigger any new events.  If you reada file in response toaFileChangedShellevent,it will not trigger theautocommands that would set the syntax, forexample.  To make the events triggered, add the "nested" argument::autocmd FileChangedShell * ++nested  editEXECUTING AUTOCOMMANDSItis possible to trigger anautocommand by pretending an event has occurred.Thisis useful to have oneautocommand trigger another one.  Example::autocmd BufReadPost *.new  execute "doautocmd BufReadPost " .. expand("<afile>:r")This defines anautocommand thatis triggered whena new file has been edited.The file namemustend in ".new".  The ":execute" command usesexpressionevaluation to forma new command and execute it.  When editing the file"tryout.c.new" the executed command will be::doautocmd BufReadPost tryout.cTheexpand() function takes the "<afile>" argument, which stands for the filename theautocommand was executed for, and takes the root of the file namewith ":r".":doautocmd" executes on the current buffer.  The ":doautoall" command workslike "doautocmd" exceptit executes on all the buffers.USING NORMAL MODE COMMANDSThe commands executed by anautocommand areCommand-line commands.  If youwant to useaNormal mode command, the ":normal" command can be used.Example::autocmd BufReadPost *.log normal GThis will make the cursor jump to the last line of *.log files when you startto edit it.   Using the ":normal" commandisa bit tricky.  First of all, make sure itsargumentisa complete command, including all the arguments.  When you use "i"togo toInsert mode, theremust also bea<Esc> to leaveInsert mode again.If you usea "/" to starta search pattern, theremust bea<CR> to executeit.   The ":normal" command uses all the text afteritas commands.  Thus therecan be no | and another command following.  To work around this,put the":normal" command inside an ":execute" command.  This also makesit possibleto pass unprintable characters ina convenient way.  Example::autocmd BufReadPost *.chg execute "normal ONew entry:\<Esc>" |\ 1read !dateThis also shows the use ofabackslash to breaka long command into morelines.  This can be used in Vim scripts (notat the command line).When you want theautocommanddo something complicated, which involves jumpingaround in the file and then returning to the original position, you may wantto restore theview on the file.  Seerestore-position for an example.IGNORING EVENTSAt times, you will not want to trigger an autocommand.  The'eventignore'option containsalist of events that will be totally ignored.  For example,the following causes events for entering and leavingawindow to be ignored::set eventignore=WinEnter,WinLeaveTo ignore all events, use the following command::set eventignore=allTo setit back to the normal behavior, make'eventignore' empty::set eventignore===============================================================================Next chapter:usr_41.txt  Writea VimscriptCopyright: seemanual-copyright  vim:tw=78:ts=8:noet:ft=help:norl:

Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq


[8]ページ先頭

©2009-2026 Movatter.jp