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