1 *tips.txt* For Vim version 5.8. Last change: 2000 Feb 09
4 VIM REFERENCE MANUAL by Bram Moolenaar
7 Tips and ideas for using Vim *tips*
9 Editing C programs |C-editing|
10 Finding where identifiers are used |ident-search|
11 Editing local HTML files (WWW) |html-editing|
12 Editing paragraphs without a line break |edit-no-break|
13 Switching screens in an xterm |xterm-screens|
14 Scrolling in Insert mode |scroll-insert|
15 Smooth scrolling |scroll-smooth|
16 Correcting common typing mistakes |type-mistakes|
17 Counting words, lines, etc. |count-items|
18 Restoring the cursor position |restore-position|
19 Renaming files |rename-files|
20 Speeding up external commands |speed-up|
21 Useful mappings |useful-mappings|
22 Compressing the help files |gzip-helpfile|
23 Hex editing |hex-editing|
24 Executing shell commands in a window |shell-window|
25 Using <> notation in autocommands |autocmd-<>|
27 ==============================================================================
28 Editing C programs *C-editing*
30 There are quite a few features in Vim to help you edit C program files. Here
31 is an overview with tags to jump to:
33 |C-indenting| Automatically set the indent of a line while typing
35 |=| Re-indent a few lines.
36 |format-comments| Format comments.
38 |:checkpath| Show all recursively included files.
39 |[i| Search for identifier under cursor in current and
41 |[_CTRL-I| Jump to match for "[i"
42 |[I| List all lines in current and included files where
43 identifier under the cursor matches.
44 |[d| Search for define under cursor in current and included
47 |CTRL-]| Jump to tag under cursor (e.g., definition of a
49 |CTRL-T| Jump back to before a CTRL-] command.
50 |:tselect| Select one tag out of a list of matching tags.
52 |gd| Go to Declaration of local variable under cursor.
53 |gD| Go to Declaration of global variable under cursor.
55 |gf| Go to file name under the cursor.
57 |%| Go to matching (), {}, [], /* */, #if, #else, #endif.
58 |[/| Go to previous start of comment.
59 |]/| Go to next end of comment.
60 |[#| Go back to unclosed #if, #ifdef, or #else.
61 |]#| Go forward to unclosed #else or #endif.
62 |[(| Go back to unclosed '('
63 |])| Go forward to unclosed ')'
64 |[{| Go back to unclosed '{'
65 |]}| Go forward to unclosed '}'
67 |v_ab| Select "a block" from "[(" to "])", including braces
68 |v_ib| Select "inner block" from "[(" to "])"
69 |v_aB| Select "a block" from "[{" to "]}", including brackets
70 |v_iB| Select "inner block" from "[{" to "]}"
72 ==============================================================================
73 Finding where identifiers are used *ident-search*
75 You probably already know that |tags| can be used to jump to the place where a
76 function or variable is defined. But sometimes you wish you could jump to all
77 the places where a function or variable is being used. This is possible in
79 1. Using "grep" and quickfix commands. This should work on most Unix systems,
80 but can be slow (it reads all files) and only searches in one directory.
81 2. Using ID utils. This is fast and works in multiple directories. It uses a
82 database to store locations. You will need some additional programs for
83 this to work. And you need to keep the database up to date.
87 Add one long line to your .vimrc:
88 > map _g :let efsave=&ef<Bar>let &ef=tempname()<Bar>exe ':!grep -n -w "<cword>" *.[cChH] *.cc *.cpp *.txt >'.&ef<CR>:cf<CR>:exe ":!rm ".&ef<CR>:let &ef=efsave<Bar>unlet efsave<CR><CR>:cc<CR>
90 NOTE: This requires that the '<' flag is excluded from 'cpoptions'.
92 That's all! You can use this by placing the cursor on any identifier, and
93 hitting "_g". Then go to further matches with ":cn". ":cc" and ":cp" can be
94 used to move around in the list of matches. Use ":cl" to see all matches.
97 This depends on the format of what grep produces and 'errorformat'. It should
98 work with the default settings.
100 Not all versions of "grep" accept the "-w" argument. You can try if replacing
104 works for you. A drawback is often that the '_' character is treated like a
105 non-word character. Thus "msg" will also match "msg_row".
108 2. With a combination of Vim and the GNU id-tools.
110 This is still is a rather simple tool, but it works.
114 - The GNU id-tools installed (mkid is needed to create ID and lid is needed to
116 - An identifier database file called "ID" in the current directory. You can
117 create it with the shell command "mkid file1 file2 ..".
119 Put this in your .vimrc:
120 > map _u :call ID_search()<Bar>execute "/\\<" . g:word . "\\>"<CR>
121 > map _n :n<Bar>execute "/\\<" . g:word . "\\>"<CR>
123 > function ID_search()
124 > let g:word = expand("<cword>")
125 > let x = system("lid --key=none ". g:word)
126 > let x = substitute(x, "\n", " ", "g")
127 > execute "next " . x
130 To use it, place the cursor on a word, type "_u" and vim will load the file
131 that contains the word. Search for the next ocurance of the word in the same
132 file with "n". Go to the next file with "_n".
134 This has been tested with id-utils-3.2 (which is the name name of the id-tools
135 archive file on your closest gnu-ftp-mirror).
137 [the idea for this comes from Andreas Kutschera]
139 ==============================================================================
140 Editing local HTML files (WWW) *html-editing*
142 Vim has some features which can help simplify the creation and maintenance of
143 HTML files, provided that the files you are editing are available on the local
144 file system. The "]f", "gf" and "CTRL-W f" commands can be used to jump to
145 the file whose name appears under the cursor, thus not only checking that the
146 link is valid (at least the file name part of the URL) but also providing a
147 quick and easy way to edit many related HTML pages at once. |gf|
148 A set of macros to help with editing html can be found on the Vim pages. |www|
150 If you want to view your HTML file, after writing a new version with Vim, have
151 a look at the "atchange" program. It can be used to automatically start a
152 viewer when the last-changed date/time of a file changes. You can find info
153 at: http://www-lmmb.ncifcrf.gov/~toms/atchange.html
155 ==============================================================================
156 Editing paragraphs without a line break *edit-no-break*
158 If you are typing text in Vim that will later go to a word processor, it is
159 useful to keep a paragraph as a single line. To make this more easy:
160 - set 'wrap' on, to make lines wrap |'wrap'|
161 - set 'linebreak' on, to make wrapping happen at a blank |'linebreak'|
162 - set 'textwidth' to zero, to avoid linebreaks |'tw'|
163 - use "gk" and "gj" to move one screen line up or down |gj|
165 You might also want to set 'showbreak' to recognize a line that is wrapped:
168 ==============================================================================
169 Switching screens in an xterm *xterm-screens* *xterm-save-screen*
171 (From comp.editors, by Juergen Weigert, in reply to a question)
173 :> Another question is that after exiting vim, the screen is left as it
174 :> was, i.e. the contents of the file I was viewing (editting) was left on
175 :> the screen. The output from my previous like "ls" were lost,
176 :> ie. no longer in the scrolling buffer. I know that there is a way to
177 :> restore the screen after exiting vim or other vi like editors,
178 :> I just don't know how. Helps are appreciated. Thanks.
180 :I imagine someone else can answer this. I assume though that vim and vi do
181 :the same thing as each other for a given xterm setup.
183 They not necessarily do the same thing, as this may be a termcap vs.
184 terminfo problem. You should be aware that there are two databases for
185 describing attributes of a particular type of terminal: termcap and
186 terminfo. This can cause differences when the entries differ AND when of
187 the programs in question one uses terminfo and the other uses termcap
188 (also see |+terminfo|).
190 In your particular problem, you are looking for the control sequences
191 ^[[?47h and ^[[?47l. These switch between xterms alternate and main screen
192 buffer. As a quick workaround a command sequence like
193 > echo -n "^[[?47h"; vim ... ; echo -n "^[[?47l"
194 may do what you want. (My notation ^[ means the ESC character, further down
195 you'll see that the databases use \E instead).
197 On startup, vim echoes the value of the termcap variable ti (terminfo:
198 smcup) to the terminal. When exiting, it echoes te (terminfo: rmcup). Thus
199 these two variables are the correct place where the above mentioned control
202 Compare your xterm termcap entry (found in /etc/termcap) with your xterm
203 terminfo entry (retrieved with /usr/5bin/infocmp -C xterm). Both should
204 contain entries similar to:
205 > :te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:
207 PS: If you find any difference, someone (your sysadmin?) should better check
208 the complete termcap and terminfo database for consistency.
210 NOTE 1: If you recompile Vim with SAVE_XTERM_SCREEN defined in feature.h, the
211 builtin xterm will include the mentioned "te" and "ti" entries.
213 NOTE 2: If you want to disable the screen switching, and you don't want to
214 change your termcap, you can add these lines to your .vimrc:
217 ==============================================================================
218 Scrolling in Insert mode *scroll-insert*
220 If you are in insert mode and you want to see something that is just off the
221 screen, you can use CTRL-X CTRL-E and CTRL-X CTRL-Y to scroll the screen.
224 To make this easier, you could use these mappings:
225 > :inoremap <C-E> <C-X><C-E>
226 > :inoremap <C-Y> <C-X><C-Y>
227 (Type this literally, make sure the '<' flag is not in 'cpoptions').
228 You then lose the ability to copy text from the line above/below the cursor
231 Also consider setting 'scrolloff' to a larger value, so that you can always see
232 some context around the cursor. If 'scrolloff' is bigger than half the window
233 height, the cursor will always be in the middle and the text is scrolled when
234 the cursor is moved up/down.
236 ==============================================================================
237 Smooth scrolling *scroll-smooth*
239 If you like the scrolling to go a bit smoother, you can use these mappings:
240 > :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>
241 > :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>
243 (Type this literally, make sure the '<' flag is not in 'cpoptions').
245 ==============================================================================
246 Correcting common typing mistakes *type-mistakes*
248 When there are a few words that you keep on typing in the wrong way, make
249 abbreviations that correct them. For example:
253 ==============================================================================
254 Counting words, lines, etc. *count-items*
256 To count how often any pattern occurs in a buffer, set 'report' to 0, and use
257 the substitute command to replace the pattern with itself. The reported
258 number of substitutions is the number of items. Examples:
261 > :%s/./&/g characters
264 > :%s/the/&/g "the" anywhere
265 > :%s/\<the\>/&/g "the" as a word
267 You might want to reset 'hlsearch' or do ":nohlsearch".
269 ==============================================================================
270 Restoring the cursor position *restore-position*
272 Sometimes you want to write a mapping that makes a change somewhere in the
273 file and restores the cursor position, without scrolling the text. For
274 example, to change the date mark in a file:
275 > map <F2> msHmtgg/Last [cC]hange:\s*/e+1<CR>"_D"=strftime("%Y %b %d")<CR>p'tzt`s
277 Breaking up saving the position:
278 ms store cursor position in the 's' mark
279 H go to the first line in the window
280 mt store this position in the 't' mark
282 Breaking up restoring the position:
283 't go to the line previously at the top of the window
284 zt scroll to move this line to the top of the window
285 `s jump to the original position of the cursor
287 ==============================================================================
288 Renaming files *rename-files*
290 Say I have a directory with the following files in them (directory picked at
298 and I want to rename *.c *.bla. I'd do it like this:
302 > :%s/\(.*\).c/mv & \1.bla
306 ==============================================================================
307 Speeding up external commands *speed-up*
309 In some situations, execution of an external command can be very slow. This
310 can also slow down wildcard expansion on Unix. Here are a few suggestions to
313 If your .cshrc (or other file, depending on the shell used) is very long, you
314 should separate it into a section for interactive use and a section for
315 non-interactive use (often called secondary shells). When you execute a
316 command from Vim like ":!ls", you do not need the interactive things (for
317 example, setting the prompt). Put the stuff that is not needed after these
320 > if ($?prompt == 0) then
324 Another way is to include the "-f" flag in the 'shell' option, e.g.:
328 (the backslash is needed to include the space in the option).
329 This will make csh completely skip the use of the .cshrc file. This may cause
330 some things to stop working though.
332 ==============================================================================
333 Useful mappings *useful-mappings*
335 Here are a few mappings that some people like to use.
339 Make the single quote work like a backtick. Puts the cursor on the column of
340 a mark, instead of going to the first non-blank character in the line.
343 For Emacs-style editing on the command-line:
345 > :cnoremap <C-A> <Home>
346 > " back one character
347 > :cnoremap <C-B> <Left>
348 > " delete character under cursor
349 > :cnoremap <C-D> <Del>
351 > :cnoremap <C-E> <End>
352 > " forward one character
353 > :cnoremap <C-F> <Right>
354 > " recall newer command-line
355 > :cnoremap <C-N> <Down>
356 > " recall previous (older) command-line
357 > :cnoremap <C-P> <Up>
359 > :cnoremap <Esc><C-B> <S-Left>
361 > :cnoremap <Esc><C-F> <S-Right>
363 NOTE: This requires that the '<' flag is excluded from 'cpoptions'. |<>|
366 This mapping will format any bullet list. It requires that there is an empty
367 line above and below each list entry. The expression commands are used to
368 be able to give comments to the parts of the mapping.
370 > let m = ":map _f :set ai<CR>" " need 'autoindent' set
371 > let m = m . "{O<Esc>" " add empty line above item
372 > let m = m . "}{)^W" " move to text after bullet
373 > let m = m . "i <CR> <Esc>" " add space for indent
374 > let m = m . "gq}" " format text after the bullet
375 > let m = m . "{dd" " remove the empty line
376 > let m = m . "5lDJ" " put text after bullet
377 > execute m |" define the mapping
379 (<> notation |<>|. Note that this is all typed literally. ^W is "^" "W", not
380 CTRL-W. You can copy/paste this into Vim if '<' is not included in
383 Note that the last comment starts with |", because the ":execute" command
384 doesn't accept a comment directly.
386 You also need to set 'textwidth' to a non-zero value, e.g.,
389 A mapping that does about the same, but takes the indent for the list from the
390 first line (Note: this mapping is a single long line with a lot of spaces):
391 > :map _f :set ai<CR>}{a <Esc>WWmmkD`mi<CR><Esc>kkddpJgq}'mJO<Esc>j
394 These two mappings reduce a sequence of empty (;b) or blank (;n) lines into a
396 > :map ;b GoZ<Esc>:g/^$/.,/./-j<CR>Gdd
397 > :map ;n GoZ<Esc>:g/^[ <Tab>]*$/.,/[^ <Tab>]/-j<CR>Gdd
399 ==============================================================================
400 Compressing the help files *gzip-helpfile*
402 For those of you who are really short on disk space, you can compress the help
403 files and still be able to view them with Vim. This makes accessing the help
404 files a bit slower and requires the "gzip" program.
406 (1) Compress all the help files: "gzip doc/*.txt".
408 (2) Edit "doc/tags" and change the ".txt" to ".txt.gz":
409 > :%s=\(\t.*\.txt\)\t=\1.gz\t=
411 (3) Add these lines to your vimrc:
414 > autocmd BufReadPre *.txt.gz set bin
415 > autocmd BufReadPost *.txt.gz let ch_save = &ch|set ch=2
416 > autocmd BufReadPost *.txt.gz '[,']!gunzip
417 > autocmd BufReadPost *.txt.gz set nobin
418 > autocmd BufReadPost *.txt.gz let &ch = ch_save|unlet ch_save
419 > autocmd BufReadPost *.txt.gz execute ":doautocmd BufReadPost " . expand("%:r")
421 > set helpfile={dirname}/help.txt.gz
423 Where {dirname} is the directory where the help files are. If you have
424 already included autocommands to edit ".gz" files (from
425 $VIMRUNTIME/vimrc_example.vim), you should omit the three "autocmd" lines.
426 Setting 'cmdheight' to two is to avoid the |hit-return| prompt; it is not
427 mandatory. You must also make sure that $VIMRUNTIME is set to where the other
428 Vim files are, when they are not in the same location as the compressed "doc"
429 directory. See |$VIMRUNTIME|.
431 ==============================================================================
432 Executing shell commands in a window *shell-window*
434 There have been questions for the possibility to execute a shell in a window
435 inside Vim. The answer: you can't! Including this would add a lot of code to
436 Vim, which is a good reason not to do this. After all, Vim is an editor, it
437 is not supposed to do non-editing tasks. However, to get something like this,
438 you might try splitting your terminal screen or display window with the
439 "splitvt" program. You can probably find it on some ftp server. The person
440 that knows more about this is Sam Lantinga <slouken@cs.ucdavis.edu>.
441 An alternative is the "window" command, found on BSD Unix systems, which
442 supports multiple overlapped windows. Or the "screen" program, found at
443 www.uni-erlangen.de, which supports a stack of windows.
445 ==============================================================================
446 Hex editing *hex-editing* *using-xxd*
448 When you need to edit binary data, and prefer to do that on a hexadecimal
449 listing, you can use the xxd program. Use this to convert from binary to
452 and use this to convert it back:
455 If one has a particular extension that one uses for binary files (such as exe,
456 bin, etc), you may find it helpful to automate the process with the following
457 bit of autocmds for your <.vimrc>. Change that "*.bin" to whatever
458 comma-separated list of extension(s) you find yourself wanting to edit:
460 > " vim -b : edit binary using xxd-format!
463 > au BufReadPre *.bin let &bin=1
464 > au BufReadPost *.bin if &bin | %!xxd
465 > au BufReadPost *.bin set ft=xxd | endif
466 > au BufWritePre *.bin if &bin | %!xxd -r
467 > au BufWritePre *.bin endif
468 > au BufWritePost *.bin if &bin | %!xxd
469 > au BufWritePost *.bin set nomod | endif
472 ==============================================================================
473 Using <> notation in autocommands *autocmd-<>*
475 The <> notation is not recognized in the argument of an :autocmd. To avoid
476 having to use special characters, you could use a self-destroying mapping to
477 get the <> notation and then call the mapping from the autocmd. Example:
480 > " This is for automatically adding the name of the file to the menu list.
481 > " It uses a self-destroying mapping!
482 > " 1. use a line in the buffer to convert the 'dots' in the file name to \.
483 > " 2. store that in register '"'
484 > " 3. add that name to the Buffers menu list
485 > " WARNING: this does have some side effects, like overwriting the
486 > " current register contents and removing any mapping for the "i" command.
488 > 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>
489 > autocmd BufNewFile,BufReadPre * normal i
491 Another method, perhaps better, is to use the ":execute" command. In the
492 string you can use the <> notation by preceding it with a backslash. Don't
493 forget to double the number of existing backslashes and put a backslash before
496 > 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>"
498 For a real buffer menu, user functions should be used (see |:function|), but
499 then the <> notation isn't used, which defeats using it as an example here.