blob: dcecc29ee453368cf2ba87cf9055e847ad5bb2cd [file] [log] [blame]
Bram Moolenaarf9393ef2006-04-24 19:47:27 +00001*tips.txt* For Vim version 7.0f. Last change: 2006 Apr 24
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7Tips and ideas for using Vim *tips*
8
9Don't forget to browse the user manual, it also contains lots of useful tips
10|usr_toc.txt|.
11
12Editing C programs |C-editing|
13Finding where identifiers are used |ident-search|
14Switching screens in an xterm |xterm-screens|
15Scrolling in Insert mode |scroll-insert|
16Smooth scrolling |scroll-smooth|
17Correcting common typing mistakes |type-mistakes|
18Counting words, lines, etc. |count-items|
19Restoring the cursor position |restore-position|
20Renaming files |rename-files|
21Speeding up external commands |speed-up|
22Useful mappings |useful-mappings|
23Compressing the help files |gzip-helpfile|
24Hex editing |hex-editing|
25Executing shell commands in a window |shell-window|
26Using <> notation in autocommands |autocmd-<>|
Bram Moolenaar1d2ba7f2006-02-14 22:29:30 +000027Highlighting matching parens |match-parens|
Bram Moolenaar071d4272004-06-13 20:20:40 +000028
29==============================================================================
30Editing C programs *C-editing*
31
32There are quite a few features in Vim to help you edit C program files. Here
33is an overview with tags to jump to:
34
35|usr_29.txt| Moving through programs chapter in the user manual.
36|usr_30.txt| Editing programs chapter in the user manual.
37|C-indenting| Automatically set the indent of a line while typing
38 text.
39|=| Re-indent a few lines.
40|format-comments| Format comments.
41
42|:checkpath| Show all recursively included files.
43|[i| Search for identifier under cursor in current and
44 included files.
45|[_CTRL-I| Jump to match for "[i"
46|[I| List all lines in current and included files where
47 identifier under the cursor matches.
48|[d| Search for define under cursor in current and included
49 files.
50
51|CTRL-]| Jump to tag under cursor (e.g., definition of a
52 function).
53|CTRL-T| Jump back to before a CTRL-] command.
54|:tselect| Select one tag out of a list of matching tags.
55
56|gd| Go to Declaration of local variable under cursor.
57|gD| Go to Declaration of global variable under cursor.
58
59|gf| Go to file name under the cursor.
60
61|%| Go to matching (), {}, [], /* */, #if, #else, #endif.
62|[/| Go to previous start of comment.
63|]/| Go to next end of comment.
64|[#| Go back to unclosed #if, #ifdef, or #else.
65|]#| Go forward to unclosed #else or #endif.
66|[(| Go back to unclosed '('
67|])| Go forward to unclosed ')'
68|[{| Go back to unclosed '{'
69|]}| Go forward to unclosed '}'
70
71|v_ab| Select "a block" from "[(" to "])", including braces
72|v_ib| Select "inner block" from "[(" to "])"
73|v_aB| Select "a block" from "[{" to "]}", including brackets
74|v_iB| Select "inner block" from "[{" to "]}"
75
76==============================================================================
77Finding where identifiers are used *ident-search*
78
79You probably already know that |tags| can be used to jump to the place where a
80function or variable is defined. But sometimes you wish you could jump to all
81the places where a function or variable is being used. This is possible in
82two ways:
831. Using the |:grep| command. This should work on most Unix systems,
84 but can be slow (it reads all files) and only searches in one directory.
852. Using ID utils. This is fast and works in multiple directories. It uses a
86 database to store locations. You will need some additional programs for
87 this to work. And you need to keep the database up to date.
88
89Using the GNU id-tools:
90
91What you need:
92- The GNU id-tools installed (mkid is needed to create ID and lid is needed to
93 use the macros).
94- An identifier database file called "ID" in the current directory. You can
95 create it with the shell command "mkid file1 file2 ..".
96
97Put this in your .vimrc: >
98 map _u :call ID_search()<Bar>execute "/\\<" . g:word . "\\>"<CR>
99 map _n :n<Bar>execute "/\\<" . g:word . "\\>"<CR>
100
101 function! ID_search()
102 let g:word = expand("<cword>")
103 let x = system("lid --key=none ". g:word)
104 let x = substitute(x, "\n", " ", "g")
105 execute "next " . x
106 endfun
107
108To use it, place the cursor on a word, type "_u" and vim will load the file
109that contains the word. Search for the next occurrence of the word in the
110same file with "n". Go to the next file with "_n".
111
112This has been tested with id-utils-3.2 (which is the name of the id-tools
113archive file on your closest gnu-ftp-mirror).
114
115[the idea for this comes from Andreas Kutschera]
116
117==============================================================================
118Switching screens in an xterm *xterm-screens* *xterm-save-screen*
119
120(From comp.editors, by Juergen Weigert, in reply to a question)
121
122:> Another question is that after exiting vim, the screen is left as it
123:> was, i.e. the contents of the file I was viewing (editing) was left on
124:> the screen. The output from my previous like "ls" were lost,
125:> ie. no longer in the scrolling buffer. I know that there is a way to
126:> restore the screen after exiting vim or other vi like editors,
127:> I just don't know how. Helps are appreciated. Thanks.
128:
129:I imagine someone else can answer this. I assume though that vim and vi do
130:the same thing as each other for a given xterm setup.
131
132They not necessarily do the same thing, as this may be a termcap vs.
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000133terminfo problem. You should be aware that there are two databases for
Bram Moolenaar071d4272004-06-13 20:20:40 +0000134describing attributes of a particular type of terminal: termcap and
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000135terminfo. This can cause differences when the entries differ AND when of
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136the programs in question one uses terminfo and the other uses termcap
137(also see |+terminfo|).
138
139In your particular problem, you are looking for the control sequences
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000140^[[?47h and ^[[?47l. These switch between xterms alternate and main screen
141buffer. As a quick workaround a command sequence like >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142 echo -n "^[[?47h"; vim ... ; echo -n "^[[?47l"
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000143may do what you want. (My notation ^[ means the ESC character, further down
Bram Moolenaar071d4272004-06-13 20:20:40 +0000144you'll see that the databases use \E instead).
145
146On startup, vim echoes the value of the termcap variable ti (terminfo:
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000147smcup) to the terminal. When exiting, it echoes te (terminfo: rmcup). Thus
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148these two variables are the correct place where the above mentioned control
149sequences should go.
150
151Compare your xterm termcap entry (found in /etc/termcap) with your xterm
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000152terminfo entry (retrieved with /usr/5bin/infocmp -C xterm). Both should
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153contain entries similar to: >
154 :te=\E[2J\E[?47l\E8:ti=\E7\E[?47h:
155
156PS: If you find any difference, someone (your sysadmin?) should better check
157 the complete termcap and terminfo database for consistency.
158
159NOTE 1: If you recompile Vim with FEAT_XTERM_SAVE defined in feature.h, the
160builtin xterm will include the mentioned "te" and "ti" entries.
161
162NOTE 2: If you want to disable the screen switching, and you don't want to
163change your termcap, you can add these lines to your .vimrc: >
164 :set t_ti= t_te=
165
166==============================================================================
167Scrolling in Insert mode *scroll-insert*
168
169If you are in insert mode and you want to see something that is just off the
170screen, you can use CTRL-X CTRL-E and CTRL-X CTRL-Y to scroll the screen.
171 |i_CTRL-X_CTRL-E|
172
173To make this easier, you could use these mappings: >
174 :inoremap <C-E> <C-X><C-E>
175 :inoremap <C-Y> <C-X><C-Y>
176(Type this literally, make sure the '<' flag is not in 'cpoptions').
177You then lose the ability to copy text from the line above/below the cursor
178|i_CTRL-E|.
179
180Also consider setting 'scrolloff' to a larger value, so that you can always see
181some context around the cursor. If 'scrolloff' is bigger than half the window
182height, the cursor will always be in the middle and the text is scrolled when
183the cursor is moved up/down.
184
185==============================================================================
186Smooth scrolling *scroll-smooth*
187
188If you like the scrolling to go a bit smoother, you can use these mappings: >
189 :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>
190 :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>
191
192(Type this literally, make sure the '<' flag is not in 'cpoptions').
193
194==============================================================================
195Correcting common typing mistakes *type-mistakes*
196
197When there are a few words that you keep on typing in the wrong way, make
198abbreviations that correct them. For example: >
199 :ab teh the
200 :ab fro for
201
202==============================================================================
203Counting words, lines, etc. *count-items*
204
Bram Moolenaar05159a02005-02-26 23:04:13 +0000205To count how often any pattern occurs in the current buffer use the substitute
206command and add the 'n' flag to avoid the substitution. The reported number
207of substitutions is the number of items. Examples: >
Bram Moolenaar071d4272004-06-13 20:20:40 +0000208
Bram Moolenaar05159a02005-02-26 23:04:13 +0000209 :%s/./&/gn characters
210 :%s/\i\+/&/gn words
211 :%s/^//n lines
212 :%s/the/&/gn "the" anywhere
213 :%s/\<the\>/&/gn "the" as a word
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214
215You might want to reset 'hlsearch' or do ":nohlsearch".
Bram Moolenaar05159a02005-02-26 23:04:13 +0000216Add the 'e' flag if you don't want an error when there are no matches.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217
Bram Moolenaar05159a02005-02-26 23:04:13 +0000218An alternative is using |v_g_CTRL-G| in Visual mode.
219
220If you want to find matches in multiple files use |:vimgrep|.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221
222 *count-bytes*
223If you want to count bytes, you can use this:
224
225 Visually select the characters (block is also possible)
226 Use "y" to yank the characters
227 Use the strlen() function: >
228 :echo strlen(@")
229A line break is counted for one byte.
230
231==============================================================================
232Restoring the cursor position *restore-position*
233
234Sometimes you want to write a mapping that makes a change somewhere in the
235file and restores the cursor position, without scrolling the text. For
236example, to change the date mark in a file: >
237 :map <F2> msHmtgg/Last [cC]hange:\s*/e+1<CR>"_D"=strftime("%Y %b %d")<CR>p'tzt`s
238
239Breaking up saving the position:
240 ms store cursor position in the 's' mark
241 H go to the first line in the window
242 mt store this position in the 't' mark
243
244Breaking up restoring the position:
245 't go to the line previously at the top of the window
246 zt scroll to move this line to the top of the window
247 `s jump to the original position of the cursor
248
249==============================================================================
250Renaming files *rename-files*
251
252Say I have a directory with the following files in them (directory picked at
253random :-):
254
255buffer.c
256charset.c
257digraph.c
258...
259
260and I want to rename *.c *.bla. I'd do it like this: >
261
262 $ vim
Bram Moolenaarfe5cafe2005-04-19 21:37:59 +0000263 :r !ls *.c
Bram Moolenaar071d4272004-06-13 20:20:40 +0000264 :%s/\(.*\).c/mv & \1.bla
265 :w !sh
266 :q!
267
268==============================================================================
269Speeding up external commands *speed-up*
270
271In some situations, execution of an external command can be very slow. This
272can also slow down wildcard expansion on Unix. Here are a few suggestions to
273increase the speed.
274
275If your .cshrc (or other file, depending on the shell used) is very long, you
276should separate it into a section for interactive use and a section for
277non-interactive use (often called secondary shells). When you execute a
278command from Vim like ":!ls", you do not need the interactive things (for
279example, setting the prompt). Put the stuff that is not needed after these
280lines: >
281
282 if ($?prompt == 0) then
283 exit 0
284 endif
285
286Another way is to include the "-f" flag in the 'shell' option, e.g.: >
287
288 :set shell=csh\ -f
289
290(the backslash is needed to include the space in the option).
291This will make csh completely skip the use of the .cshrc file. This may cause
292some things to stop working though.
293
294==============================================================================
295Useful mappings *useful-mappings*
296
297Here are a few mappings that some people like to use.
298
299 *map-backtick* >
300 :map ' `
301Make the single quote work like a backtick. Puts the cursor on the column of
302a mark, instead of going to the first non-blank character in the line.
303
304 *emacs-keys*
305For Emacs-style editing on the command-line: >
306 " start of line
307 :cnoremap <C-A> <Home>
308 " back one character
309 :cnoremap <C-B> <Left>
310 " delete character under cursor
311 :cnoremap <C-D> <Del>
312 " end of line
313 :cnoremap <C-E> <End>
314 " forward one character
315 :cnoremap <C-F> <Right>
316 " recall newer command-line
317 :cnoremap <C-N> <Down>
318 " recall previous (older) command-line
319 :cnoremap <C-P> <Up>
320 " back one word
321 :cnoremap <Esc><C-B> <S-Left>
322 " forward one word
323 :cnoremap <Esc><C-F> <S-Right>
324
325NOTE: This requires that the '<' flag is excluded from 'cpoptions'. |<>|
326
327 *format-bullet-list*
328This mapping will format any bullet list. It requires that there is an empty
329line above and below each list entry. The expression commands are used to
330be able to give comments to the parts of the mapping. >
331
332 :let m = ":map _f :set ai<CR>" " need 'autoindent' set
333 :let m = m . "{O<Esc>" " add empty line above item
334 :let m = m . "}{)^W" " move to text after bullet
335 :let m = m . "i <CR> <Esc>" " add space for indent
336 :let m = m . "gq}" " format text after the bullet
337 :let m = m . "{dd" " remove the empty line
338 :let m = m . "5lDJ" " put text after bullet
339 :execute m |" define the mapping
340
341(<> notation |<>|. Note that this is all typed literally. ^W is "^" "W", not
342CTRL-W. You can copy/paste this into Vim if '<' is not included in
Bram Moolenaar402d2fe2005-04-15 21:00:38 +0000343'cpoptions'.)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344
345Note that the last comment starts with |", because the ":execute" command
346doesn't accept a comment directly.
347
348You also need to set 'textwidth' to a non-zero value, e.g., >
349 :set tw=70
350
351A mapping that does about the same, but takes the indent for the list from the
352first line (Note: this mapping is a single long line with a lot of spaces): >
353 :map _f :set ai<CR>}{a <Esc>WWmmkD`mi<CR><Esc>kkddpJgq}'mJO<Esc>j
354<
355 *collapse*
356These two mappings reduce a sequence of empty (;b) or blank (;n) lines into a
357single line >
358 :map ;b GoZ<Esc>:g/^$/.,/./-j<CR>Gdd
359 :map ;n GoZ<Esc>:g/^[ <Tab>]*$/.,/[^ <Tab>]/-j<CR>Gdd
360
361==============================================================================
362Compressing the help files *gzip-helpfile*
363
364For those of you who are really short on disk space, you can compress the help
365files and still be able to view them with Vim. This makes accessing the help
366files a bit slower and requires the "gzip" program.
367
368(1) Compress all the help files: "gzip doc/*.txt".
369
370(2) Edit "doc/tags" and change the ".txt" to ".txt.gz": >
371 :%s=\(\t.*\.txt\)\t=\1.gz\t=
372
373(3) Add this line to your vimrc: >
374 set helpfile={dirname}/help.txt.gz
375
376Where {dirname} is the directory where the help files are. The |gzip| plugin
377will take care of decompressing the files.
378You must make sure that $VIMRUNTIME is set to where the other Vim files are,
379when they are not in the same location as the compressed "doc" directory. See
380|$VIMRUNTIME|.
381
382==============================================================================
383Executing shell commands in a window *shell-window*
384
385There have been questions for the possibility to execute a shell in a window
386inside Vim. The answer: you can't! Including this would add a lot of code to
387Vim, which is a good reason not to do this. After all, Vim is an editor, it
388is not supposed to do non-editing tasks. However, to get something like this,
389you might try splitting your terminal screen or display window with the
390"splitvt" program. You can probably find it on some ftp server. The person
391that knows more about this is Sam Lantinga <slouken@cs.ucdavis.edu>.
392An alternative is the "window" command, found on BSD Unix systems, which
393supports multiple overlapped windows. Or the "screen" program, found at
394www.uni-erlangen.de, which supports a stack of windows.
395
396==============================================================================
397Hex editing *hex-editing* *using-xxd*
398
399See section |23.4| of the user manual.
400
401If one has a particular extension that one uses for binary files (such as exe,
402bin, etc), you may find it helpful to automate the process with the following
403bit of autocmds for your <.vimrc>. Change that "*.bin" to whatever
404comma-separated list of extension(s) you find yourself wanting to edit: >
405
406 " vim -b : edit binary using xxd-format!
407 augroup Binary
408 au!
409 au BufReadPre *.bin let &bin=1
410 au BufReadPost *.bin if &bin | %!xxd
411 au BufReadPost *.bin set ft=xxd | endif
412 au BufWritePre *.bin if &bin | %!xxd -r
413 au BufWritePre *.bin endif
414 au BufWritePost *.bin if &bin | %!xxd
415 au BufWritePost *.bin set nomod | endif
416 augroup END
417
418==============================================================================
419Using <> notation in autocommands *autocmd-<>*
420
421The <> notation is not recognized in the argument of an :autocmd. To avoid
422having to use special characters, you could use a self-destroying mapping to
423get the <> notation and then call the mapping from the autocmd. Example:
424
425 *map-self-destroy* >
426 " This is for automatically adding the name of the file to the menu list.
427 " It uses a self-destroying mapping!
428 " 1. use a line in the buffer to convert the 'dots' in the file name to \.
429 " 2. store that in register '"'
430 " 3. add that name to the Buffers menu list
431 " WARNING: this does have some side effects, like overwriting the
432 " current register contents and removing any mapping for the "i" command.
433 "
434 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>
435 autocmd BufNewFile,BufReadPre * normal i
436
437Another method, perhaps better, is to use the ":execute" command. In the
438string you can use the <> notation by preceding it with a backslash. Don't
439forget to double the number of existing backslashes and put a backslash before
440'"'.
441>
442 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>"
443
444For a real buffer menu, user functions should be used (see |:function|), but
445then the <> notation isn't used, which defeats using it as an example here.
446
Bram Moolenaar1d2ba7f2006-02-14 22:29:30 +0000447==============================================================================
448Highlighting matching parens *match-parens*
449
450This example shows the use of a few advanced tricks:
451- using the |CursorMoved| autocommand event
452- using |searchpairpos()| to find a matching paren
Bram Moolenaar7e8fd632006-02-18 22:14:51 +0000453- using |synID()| to detect whether the cursor is in a string or comment
Bram Moolenaar1d2ba7f2006-02-14 22:29:30 +0000454- using |:match| to highlight something
455- using a |pattern| to match a specific position in the file.
456
457This should be put in a Vim script file, since it uses script-local variables.
Bram Moolenaar7e8fd632006-02-18 22:14:51 +0000458It skips matches in strings or comments, unless the cursor started in string
459or comment. This requires syntax highlighting.
Bram Moolenaarfd2ac762006-03-01 22:09:21 +0000460
461A slightly more advanced version is used in the |matchparen| plugin.
Bram Moolenaar1d2ba7f2006-02-14 22:29:30 +0000462>
463 let s:paren_hl_on = 0
464 function s:Highlight_Matching_Paren()
465 if s:paren_hl_on
466 match none
467 let s:paren_hl_on = 0
468 endif
469
470 let c_lnum = line('.')
471 let c_col = col('.')
472
473 let c = getline(c_lnum)[c_col - 1]
474 let plist = split(&matchpairs, ':\|,')
475 let i = index(plist, c)
476 if i < 0
477 return
478 endif
479 if i % 2 == 0
480 let s_flags = 'nW'
481 let c2 = plist[i + 1]
482 else
483 let s_flags = 'nbW'
484 let c2 = c
485 let c = plist[i - 1]
486 endif
487 if c == '['
488 let c = '\['
489 let c2 = '\]'
490 endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +0000491 let s_skip ='synIDattr(synID(line("."), col("."), 0), "name") ' .
492 \ '=~? "string\\|comment"'
493 execute 'if' s_skip '| let s_skip = 0 | endif'
Bram Moolenaar1d2ba7f2006-02-14 22:29:30 +0000494
Bram Moolenaar7e8fd632006-02-18 22:14:51 +0000495 let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip)
Bram Moolenaar1d2ba7f2006-02-14 22:29:30 +0000496
497 if m_lnum > 0 && m_lnum >= line('w0') && m_lnum <= line('w$')
498 exe 'match Search /\(\%' . c_lnum . 'l\%' . c_col .
499 \ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
500 let s:paren_hl_on = 1
501 endif
502 endfunction
503
Bram Moolenaarf740b292006-02-16 22:11:02 +0000504 autocmd CursorMoved,CursorMovedI * call s:Highlight_Matching_Paren()
Bram Moolenaar1d2ba7f2006-02-14 22:29:30 +0000505 autocmd InsertEnter * match none
506<
507
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508 vim:tw=78:ts=8:ft=help:norl: