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)
tips.txt  ForVim version 9.2.  Last change: 2026 Feb 14VIM REFERENCE MANUAL  by Bram MoolenaarTips and ideas for using VimtipsThese are justa few that we thought would be helpful for many users.You can find many moretips on the wiki.  The URL can be found onhttp://www.vim.orgDon't forget to browse the user manual,it also contains lots of usefultipsusr_toc.txt.EditingC programsC-editingFinding where identifiers are usedident-searchSwitching screens in an xtermxterm-screensScrolling inInsert modescroll-insertSmoothscrollingscroll-smoothCorrecting common typing mistakestype-mistakesCounting words, lines, etc.count-itemsRestoring the cursor positionrestore-positionRenaming filesrename-filesChangea name in multiple fileschange-nameSpeeding up external commandsspeed-upUseful mappingsuseful-mappingsCompressing thehelp filesgzip-helpfileExecuting shell commands inawindowshell-windowHex editinghex-editingUsing<>notation inautocommandsautocmd-<>Highlighting matching parensmatch-parensOpeninghelp in the currentwindowpackage-helpcurwin==============================================================================EditingC programsC-editingThere are quitea few features in Vim tohelp you editC program files.  Hereis an overview withtags to jump to:usr_29.txt  Moving through programs chapter in the user manual.usr_30.txt  Editing programs chapter in the user manual.C-indenting  Automatically set the indent ofa line while typingtext.=  Re-indenta few lines.format-comments  Format comments.:checkpath  Show all recursively included files.[i  Search for identifier under cursor in current andincluded files.[_CTRL-I  Jump to match for "[i"[IList all lines in current and included files whereidentifier under the cursor matches.[d  Search for define under cursor in current and includedfiles.CTRL-]  Jump totag under cursor (e.g., definition ofafunction).CTRL-T  Jump back to beforeaCTRL-] command.:tselectSelect onetag out ofalist of matching tags.gd  Go to Declaration of local variable under cursor.gD  Go to Declaration of global variable under cursor.gf  Go to file name under the cursor.%  Go to matching (), {}, [],/* */, #if, #else, #endif.[/  Go to previous start of comment.]/  Go to nextend of comment.[#  Go back to unclosed #if, #ifdef, or #else.]#  Go forward to unclosed #else or #endif.[(  Go back to unclosed '('])  Go forward to unclosed ')'[{  Go back to unclosed '{']}  Go forward to unclosed '}'v_abSelect "a block" from "[(" to "])", including bracesv_ibSelect "inner block" from "[(" to "])"v_aBSelect "a block" from "[{" to "]}", including bracketsv_iBSelect "inner block" from "[{" to "]}"==============================================================================Finding where identifiers are usedident-searchYou probably already know thattags can be used to jump to the place whereafunction or variableis defined.  But sometimes you wish you could jump to allthe places wherea function or variableis being used.  Thisis possible intwo ways:1. Using the:grep command.  This should work on mostUnix systems,   but can be slow (it reads all files) and only searches in one directory.2. Using ID utils.  Thisis fast and works in multiple directories.  It usesa   database to store locations.  You will need some additional programs for   this to work.  And you need to keep the database up to date.Using the GNU id-tools:What you need:- The GNU id-tools installed (mkidis needed to create ID andlidis needed to  use the macros).- An identifier database file called "ID" in the current directory.  You can  createit with the shell command "mkid file1 file2 ..".Put this in your .vimrc:map _u :call ID_search()<Bar>execute "/\\<" .. g:word .. "\\>"<CR>map _n :n<Bar>execute "/\\<" .. g:word .. "\\>"<CR>function! ID_search()  let g:word = expand("<cword>")  let x = system("lid --key=none " .. g:word)  let x = substitute(x, "\n", " ", "g")  execute "next " .. xendfunTo use it, place the cursor ona word, type "_u" and vim will load the filethat contains the word.  Search for the next occurrence of theword in thesame file with "n".  Go to the next file with "_n".This has been tested with id-utils-3.2 (whichis the name of the id-toolsarchive file on your closest gnu-ftp-mirror).[the idea for this comes from Andreas Kutschera]==============================================================================Switching screens in an xtermxterm-screensxterm-save-screen(From comp.editors, by Juergen Weigert, in reply toa question):> Another questionis that afterexiting vim, the screenis leftasit:> was, i.e. the contents of the fileI was viewing (editing) was left on:> the screen. The output from my previous like "ls" were lost,:> ie. no longer in thescrolling buffer.I know that thereisa way to:> restore the screen afterexiting vim or othervi like editors,:>I just don't know how. Helps are appreciated. Thanks.::I imagine someone else can answer this.I assume though that vim andvido:the same thingas each other fora given xterm setup.They not necessarilydo the same thing,as this may beatermcap vs.terminfo problem.  You should be aware that there are two databases fordescribing attributes ofa particular type of terminal:termcap andterminfo.  This can cause differences when the entries differ AND when ofthe programs in question one usesterminfo and the other usestermcap(also see+terminfo).In your particular problem, you are looking for thecontrol sequences^[[?47h and ^[[?47l.  These switch between xterms alternate and main screenbuffer.  Asa quick workarounda command sequence likeecho -n "^[[?47h"; vim ... ; echo -n "^[[?47l"maydo what you want.  (Mynotation ^[ means the ESC character, further downyou'll see that the databases use \E instead).On startup, vim echoes the value of thetermcap variable ti (terminfo:smcup) to the terminal.  When exiting,it echoes te (terminfo: rmcup).  Thusthese twovariables are the correct place where the above mentionedcontrolsequences should go.Compare your xtermtermcap entry (found in /etc/termcap) with your xtermterminfo entry (retrieved with "infocmp-C xterm").  Both should containentries similar to::te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:PS: If you find any difference, someone (your sysadmin?) should better check    the completetermcap andterminfo database for consistency.NOTE 1: If you recompile Vim with FEAT_XTERM_SAVE defined in feature.h, thebuiltin xterm will include the mentioned "te" and "ti" entries.NOTE 2: If you want to disable the screen switching, and you don't want tochange your termcap, you can add these lines to your .vimrc::set t_ti= t_te===============================================================================Scrolling inInsert modescroll-insertIf you are ininsert mode and you want to see something thatis just off thescreen, you can useCTRL-XCTRL-E andCTRL-XCTRL-Y to scroll the screen.i_CTRL-X_CTRL-ETo make this easier, you could use these mappings::inoremap <C-E> <C-X><C-E>:inoremap <C-Y> <C-X><C-Y>(Type this literally, make sure the '<' flagis not in'cpoptions').You then lose the ability to copy text from the line above/below the cursori_CTRL-E.Also consider setting'scrolloff' toa larger value, so that you can alwayssee some context around the cursor.  If'scrolloff'is bigger than half thewindow height, the cursor will always be in the middle and the textisscrolled when the cursoris moved up/down.==============================================================================Smoothscrollingscroll-smoothIf you like thescrolling togoa bit smoother, you can use these mappings::map <C-U> <C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y><C-Y>:map <C-D> <C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E><C-E>(Type this literally, make sure the '<' flagis not in'cpoptions').==============================================================================Correcting common typing mistakestype-mistakesWhen there area few words that you keep on typing in the wrong way, makeabbreviations that correct them.  For example::ab teh the:ab fro for==============================================================================Counting words, lines, etc.count-itemsTocount how often anypattern occurs in the current buffer use the substitutecommand and add the 'n' flag to avoid the substitution.  The reported numberof substitutionsis the number of items.  Examples::%s/./&/gncharacters:%s/\i\+/&/gnwords:%s/^//nlines:%s/the/&/gn"the" anywhere:%s/\<the\>/&/gn"the" as a wordYou might want to reset'hlsearch' ordo ":nohlsearch".Add the 'e' flag if you don't want an error when there are no matches.An alternativeis usingv_g_CTRL-G inVisual mode.If you want to find matches in multiple files use:vimgrep.count-bytesIf you want tocount bytes, you can use this:Visually select the characters (blockis also possible)Use "y" toyank the charactersUse thestrlen() function::echo strlen(@")A line breakis counted for one byte.==============================================================================Restoring the cursor positionrestore-positionSometimes you want to writeamapping that makesa change somewhere in thefile and restores the cursor position, withoutscrolling the text.  Forexample, to change the datemark ina file:   :map <F2> msHmtgg/Last [cC]hange:\s*/e+1<CR>"_D"=strftime("%Y %b %d")<CR>p'tzt`sBreaking up saving the position:msstore cursor position in the 's'markHgo to the first line in thewindowmtstore this position in the 't'markBreaking up restoring the position:'tgo to the line previouslyat the top of thewindowztscroll to move this line to the top of thewindow`sjump to the original position of the cursorFor something more advanced seewinsaveview() andwinrestview().==============================================================================Renaming filesrename-filesSayI havea directory with the following files in them (directory pickedatrandom :-):buffer.ccharset.cdigraph.c...andI want to rename *.c *.bla.  I'ddoit like this:$ vim:r !ls *.c:%s/\(.*\).c/mv & \1.bla:w !sh:q!==============================================================================Changea name in multiple fileschange-nameExample for usingascript file to changea name in several files:Createa file "subs.vim" containing substitute commands anda:updatecommand::%s/Jones/Smith/g:%s/Allen/Peter/g:updateExecute Vim on all files you want to change, and source thescript foreach argument:vim *.letargdo source subs.vimSee:argdo.==============================================================================Speeding up external commandsspeed-upIn some situations, execution of an external command can be very slow.  Thiscan also slow downwildcard expansion on Unix.  Here area few suggestions toincrease the speed.If your .cshrc (or other file, depending on the shell used)is very long, youshould separateit intoasection for interactive use andasection fornon-interactive use (often called secondary shells).  When you executeacommand from Vim like ":!ls", youdo not need the interactive things (forexample, setting the prompt).  Put the stuff thatis not needed after theselines:if ($?prompt == 0) thenexit 0endifAnother wayis to include the "-f" flag in the'shell' option, e.g.::set shell=csh\ -f(thebackslashis needed to include thespace in the option).This will make csh completely skip the use of the .cshrc file.  This may causesome things to stop working though.==============================================================================Useful mappingsuseful-mappingsHere area few mappings that some people like to use.map-backtick:map ' `Make the singlequote work likea backtick.  Puts the cursor on the column ofa mark, instead of going to the first non-blank character in the line.emacs-keysFor Emacs-style editing on the command-line:" start of line:cnoremap <C-A><Home>" back one character:cnoremap <C-B><Left>" delete character under cursor:cnoremap <C-D><Del>" end of line:cnoremap <C-E><End>" forward one character:cnoremap <C-F><Right>" recall newer command-line:cnoremap <C-N><Down>" recall previous (older) command-line:cnoremap <C-P><Up>" back one word:cnoremap <Esc><C-B><S-Left>" forward one word:cnoremap <Esc><C-F><S-Right>NOTE: This requires that the '<' flagis excluded from'cpoptions'.<>format-bullet-listThismapping will format any bullet list.  It requires that thereis an emptyline above and below eachlist entry.  Theexpression commands are used tobe able to give comments to the parts of the mapping.:let m =     ":map _f  :set ai<CR>"   " need 'autoindent' set:let m ..= "{O<Esc>"      " add empty line above item:let m ..= "}{)^W"      " move to text after bullet:let m ..= "i     <CR>     <Esc>"     " add space for indent:let m ..= "gq}"      " format text after the bullet:let m ..= "{dd"      " remove the empty line:let m ..= "5lDJ"      " put text after bullet:execute m      |" define the mapping(<>notation<>.Note that thisis all typed literally.  ^Wis "^" "W", notCTRL-W.  You can copy/paste this into Vim if '<'is not included in'cpoptions'.)Note that the last comment starts with |", because the ":execute" commanddoesn't accepta comment directly.You also need to set'textwidth' toa non-zero value, e.g.,:set tw=70Amapping that does about the same, but takes the indent for thelist from thefirst line (Note: thismappingisa single long line witha lot of spaces)::map _f :set ai<CR>}{a                                                          <Esc>WWmmkD`mi<CR><Esc>kkddpJgq}'mJO<Esc>jcollapseThese two mappings reducea sequence of empty (;b) or blank (;n) lines intoasingle line    :map ;b   GoZ<Esc>:g/^$/.,/./-j<CR>Gdd    :map ;n   GoZ<Esc>:g/^[ <Tab>]*$/.,/[^ <Tab>]/-j<CR>Gdd==============================================================================Compressing thehelp filesgzip-helpfileFor those of you who are really short on disk space, you cancompress thehelpfiles and still be able toview them with Vim.  This makes accessing thehelpfilesa bit slower and requires the "gzip" program.(1) Compress all thehelp files: "gzip doc/*.txt".(2) Edit "doc/tags" and change the ".txt" to ".txt.gz"::%s=\(\t.*\.txt\)\t=\1.gz\t=(3) Add this line to your vimrc:set helpfile={dirname}/help.txt.gzWhere{dirname}is the directory where thehelp files are.  Thegzippluginwill take care of decompressing the files.Youmust make sure that$VIMRUNTIMEis set to where the other Vim files are,when they are not in the same locationas the compressed "doc" directory.  See$VIMRUNTIME.==============================================================================Executing shell commands inawindowshell-windowSeeterminal.Another solutionis splitting yourterminal screen or displaywindow with the"splitvt" program.  You can probably findit on someftp server.  The personthat knows more about thisis Sam Lantinga <slouken@cs.ucdavis.edu>.Another alternativeis the "window" command, found on BSDUnix systems, whichsupports multiple overlapped windows.  Or the "screen" program, foundatwww.uni-erlangen.de, which supportsa stack of windows.==============================================================================Hex editinghex-editingusing-xxdSeesection23.4 of the user manual.If one hasa particular extension that one uses for binary files (suchas exe,bin, etc), you may findit helpful to automate the process with the followingbit of autocmds for your <.vimrc>.  Change that "*.bin" to whatevercomma-separatedlist of extension(s) you find yourself wanting to edit:" vim -b : edit binary using xxd-format!augroup Binary  autocmd!  autocmd BufReadPre  *.bin set binary  autocmd BufReadPost *.bin    \ if &binary    \ |   execute "silent %!xxd -c 32"    \ |   set filetype=xxd    \ |   redraw    \ | endif  autocmd BufWritePre *.bin    \ if &binary    \ |   let s:view = winsaveview()    \ |   execute "silent %!xxd -r -c 32"    \ | endif  autocmd BufWritePost *.bin    \ if &binary    \ |   execute "silent %!xxd -c 32"    \ |   set nomodified    \ |   call winrestview(s:view)    \ |   redraw    \ | endifaugroup END==============================================================================Using<>notation inautocommandsautocmd-<>The<>notationis not recognized in the argument of an :autocmd.  To avoidhaving to use special characters, you could usea self-destroyingmapping toget the<>notation and then call themapping from the autocmd.  Example:map-self-destroy " This is for automatically adding the name of the file to the menu list. " It uses a self-destroying mapping! " 1. use a line in the buffer to convert the 'dots' in the file name to \. " 2. store that in register '"' " 3. add that name to the Buffers menu list " WARNING: this does have some side effects, like overwriting the " current register contents and removing any mapping for the "i" command. " autocmd BufNewFile,BufReadPre * nmap i :nunmap i<CR>O<C-R>%<Esc>:.g/\./s/\./\\./g<CR>0"9y$u:menu Buffers.<C-R>9 :buffer <C-R>%<C-V><CR><CR> autocmd BufNewFile,BufReadPre * normal iAnother method, perhaps better,is to use the ":execute" command.  In thestring you can use the<>notation by precedingit witha backslash.  Don'tforget to double the number of existing backslashes andputabackslash before'"'.  autocmd BufNewFile,BufReadPre * exe "normal O\<C-R>%\<Esc>:.g/\\./s/\\./\\\\./g\<CR>0\"9y$u:menu Buffers.\<C-R>9 :buffer \<C-R>%\<C-V>\<CR>\<CR>"Fora real buffer menu, userfunctions should be used (see:function), butthen the<>notation isn't used, which defeats usingitas an example here.==============================================================================Highlighting matching parensmatch-parensThis example shows the use ofa few advanced tricks:- using theCursorMovedautocommand event- usingsearchpairpos() to finda matching paren- usingsynID() to detect whether the cursoris inastring or comment- using:match to highlight something- usingapattern to matcha specific position in the file.This should beput ina Vimscript file, sinceit usesscript-local variables.It skips matches in strings or comments, unless the cursor started instringor comment.  This requiressyntax highlighting.A slightly more advanced versionis used in thematchparen plugin.let s:paren_hl_on = 0function s:Highlight_Matching_Paren()  if s:paren_hl_on    match none    let s:paren_hl_on = 0  endif  let c_lnum = line('.')  let c_col = col('.')  let c = getline(c_lnum)[c_col - 1]  let plist = split(&matchpairs, ':\|,')  let i = index(plist, c)  if i < 0    return  endif  if i % 2 == 0    let s_flags = 'nW'    let c2 = plist[i + 1]  else    let s_flags = 'nbW'    let c2 = c    let c = plist[i - 1]  endif  if c == '['    let c = '\['    let c2 = '\]'  endif  let s_skip ='synIDattr(synID(line("."), col("."), 0), "name") ' ..\ '=~?"string\\|comment"'  execute 'if' s_skip '| let s_skip = 0 | endif'  let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip)  if m_lnum > 0 && m_lnum >= line('w0') && m_lnum <= line('w$')    exe 'match Search /\(\%' .. c_lnum .. 'l\%' .. c_col ..  \ 'c\)\|\(\%' .. m_lnum .. 'l\%' .. m_col .. 'c\)/'    let s:paren_hl_on = 1  endifendfunctionautocmd CursorMoved,CursorMovedI * call s:Highlight_Matching_Paren()autocmd InsertEnter * match none==============================================================================Openinghelp in the currentwindowpackage-helpcurwinBy default,helpis displayed ina split window.  In some scenarios, you mayprefer to open thehelp in the current window.  The optional helpcurwinpackage makes this possible.  Load the package manually, or in yourvimrc,with:    packadd helpcurwinAfterit has loaded:- The command:HelpCurwin{subject} can be used to openhelp in the current  window.- If the currentwindow containsa modified buffer, theplugin asks for  confirmation beforereplacing it.  If confirmed, the buffer becomes  hiddenhidden-buffer.- Thehelp file,helpcurwin.txt, will be available and describes theplugin  in more details. 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