tips.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. *tips.txt* Nvim
  2. VIM REFERENCE MANUAL by Bram Moolenaar
  3. Tips and ideas for using Vim *tips*
  4. These are just a few that we thought would be helpful for many users.
  5. You can find many more tips on the wiki. The URL can be found on
  6. https://www.vim.org
  7. Don't forget to browse the user manual, it also contains lots of useful tips
  8. |usr_toc.txt|.
  9. Type |gO| to see the table of contents.
  10. ==============================================================================
  11. Editing C programs *C-editing*
  12. There are quite a few features in Vim to help you edit C program files. Here
  13. is an overview with tags to jump to:
  14. |usr_29.txt| Moving through programs chapter in the user manual.
  15. |usr_30.txt| Editing programs chapter in the user manual.
  16. |C-indenting| Automatically set the indent of a line while typing
  17. text.
  18. |=| Re-indent a few lines.
  19. |format-comments| Format comments.
  20. |:checkpath| Show all recursively included files.
  21. |[i| Search for identifier under cursor in current and
  22. included files.
  23. |[_CTRL-I| Jump to match for "[i"
  24. |[I| List all lines in current and included files where
  25. identifier under the cursor matches.
  26. |[d| Search for define under cursor in current and included
  27. files.
  28. |CTRL-]| Jump to tag under cursor (e.g., definition of a
  29. function).
  30. |CTRL-T| Jump back to before a CTRL-] command.
  31. |:tselect| Select one tag out of a list of matching tags.
  32. |gd| Go to Declaration of local variable under cursor.
  33. |gD| Go to Declaration of global variable under cursor.
  34. |gf| Go to file name under the cursor.
  35. |%| Go to matching (), {}, [], /* */, #if, #else, #endif.
  36. |[/| Go to previous start of comment.
  37. |]/| Go to next end of comment.
  38. |[#| Go back to unclosed #if, #ifdef, or #else.
  39. |]#| Go forward to unclosed #else or #endif.
  40. |[(| Go back to unclosed '('
  41. |])| Go forward to unclosed ')'
  42. |[{| Go back to unclosed '{'
  43. |]}| Go forward to unclosed '}'
  44. |v_ab| Select "a block" from "[(" to "])", including braces
  45. |v_ib| Select "inner block" from "[(" to "])"
  46. |v_aB| Select "a block" from "[{" to "]}", including brackets
  47. |v_iB| Select "inner block" from "[{" to "]}"
  48. ==============================================================================
  49. Finding where identifiers are used *ident-search*
  50. You probably already know that |tags| can be used to jump to the place where a
  51. function or variable is defined. But sometimes you wish you could jump to all
  52. the places where a function or variable is being used. This is possible in
  53. two ways:
  54. 1. Using the |:grep| command. This should work on most Unix systems,
  55. but can be slow (it reads all files) and only searches in one directory.
  56. 2. Using ID utils. This is fast and works in multiple directories. It uses a
  57. database to store locations. You will need some additional programs for
  58. this to work. And you need to keep the database up to date.
  59. Using the GNU id-tools:
  60. What you need:
  61. - The GNU id-tools installed (mkid is needed to create ID and lid is needed to
  62. use the macros).
  63. - An identifier database file called "ID" in the current directory. You can
  64. create it with the shell command "mkid file1 file2 ..".
  65. Put this in your |init.vim|: >
  66. map _u :call ID_search()<Bar>execute "/\\<" .. g:word .. "\\>"<CR>
  67. map _n :n<Bar>execute "/\\<" .. g:word .. "\\>"<CR>
  68. function! ID_search()
  69. let g:word = expand("<cword>")
  70. let x = system("lid --key=none " .. g:word)
  71. let x = substitute(x, "\n", " ", "g")
  72. execute "next " .. x
  73. endfun
  74. To use it, place the cursor on a word, type "_u" and vim will load the file
  75. that contains the word. Search for the next occurrence of the word in the
  76. same file with "n". Go to the next file with "_n".
  77. This has been tested with id-utils-3.2 (which is the name of the id-tools
  78. archive file on your closest gnu-ftp-mirror).
  79. [the idea for this comes from Andreas Kutschera]
  80. ==============================================================================
  81. Scrolling in Insert mode *scroll-insert*
  82. If you are in insert mode and you want to see something that is just off the
  83. screen, you can use CTRL-X CTRL-E and CTRL-X CTRL-Y to scroll the screen.
  84. |i_CTRL-X_CTRL-E|
  85. To make this easier, you could use these mappings: >
  86. :inoremap <C-E> <C-X><C-E>
  87. :inoremap <C-Y> <C-X><C-Y>
  88. You then lose the ability to copy text from the line above/below the cursor
  89. |i_CTRL-E|.
  90. Also consider setting 'scrolloff' to a larger value, so that you can always see
  91. some context around the cursor. If 'scrolloff' is bigger than half the window
  92. height, the cursor will always be in the middle and the text is scrolled when
  93. the cursor is moved up/down.
  94. ==============================================================================
  95. Smooth scrolling *scroll-smooth*
  96. If you like the scrolling to go a bit smoother, you can use these mappings: >
  97. :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>
  98. :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>
  99. ==============================================================================
  100. Correcting common typing mistakes *type-mistakes*
  101. When there are a few words that you keep on typing in the wrong way, make
  102. abbreviations that correct them. For example: >
  103. :ab teh the
  104. :ab fro for
  105. ==============================================================================
  106. Counting words, lines, etc. *count-items*
  107. To count how often any pattern occurs in the current buffer use the substitute
  108. command and add the 'n' flag to avoid the substitution. The reported number
  109. of substitutions is the number of items. Examples: >
  110. :%s/./&/gn characters
  111. :%s/\i\+/&/gn words
  112. :%s/^//n lines
  113. :%s/the/&/gn "the" anywhere
  114. :%s/\<the\>/&/gn "the" as a word
  115. You might want to reset 'hlsearch' or do ":nohlsearch".
  116. Add the 'e' flag if you don't want an error when there are no matches.
  117. An alternative is using |v_g_CTRL-G| in Visual mode.
  118. If you want to find matches in multiple files use |:vimgrep|.
  119. *count-bytes*
  120. If you want to count bytes, you can use this:
  121. Visually select the characters (block is also possible)
  122. Use "y" to yank the characters
  123. Use the strlen() function: >
  124. :echo strlen(@")
  125. A line break is counted for one byte.
  126. ==============================================================================
  127. Restoring the cursor position *restore-position*
  128. Sometimes you want to write a mapping that makes a change somewhere in the
  129. file and restores the cursor position, without scrolling the text. For
  130. example, to change the date mark in a file: >
  131. :map <F2> msHmtgg/Last [cC]hange:\s*/e+1<CR>"_D"=strftime("%Y %b %d")<CR>p'tzt`s
  132. Breaking up saving the position:
  133. ms store cursor position in the 's' mark
  134. H go to the first line in the window
  135. mt store this position in the 't' mark
  136. Breaking up restoring the position:
  137. 't go to the line previously at the top of the window
  138. zt scroll to move this line to the top of the window
  139. `s jump to the original position of the cursor
  140. For something more advanced see |winsaveview()| and |winrestview()|.
  141. ==============================================================================
  142. Renaming files *rename-files*
  143. Say I have a directory with the following files in them (directory picked at
  144. random :-):
  145. buffer.c
  146. charset.c
  147. digraph.c
  148. ...
  149. and I want to rename *.c *.bla. I'd do it like this: >
  150. $ vim
  151. :r !ls *.c
  152. :%s/\(.*\).c/mv & \1.bla
  153. :w !sh
  154. :q!
  155. ==============================================================================
  156. Change a name in multiple files *change-name*
  157. Example for using a script file to change a name in several files:
  158. Create a file "subs.vim" containing substitute commands and a :update
  159. command: >
  160. :%s/Jones/Smith/g
  161. :%s/Allen/Peter/g
  162. :update
  163. <
  164. Execute Vim on all files you want to change, and source the script for
  165. each argument: >
  166. vim *.let
  167. argdo source subs.vim
  168. See |:argdo|.
  169. ==============================================================================
  170. Speeding up external commands *speed-up*
  171. In some situations, execution of an external command can be very slow. This
  172. can also slow down wildcard expansion on Unix. Here are a few suggestions to
  173. increase the speed.
  174. If your .cshrc (or other file, depending on the shell used) is very long, you
  175. should separate it into a section for interactive use and a section for
  176. non-interactive use (often called secondary shells). When you execute a
  177. command from Vim like ":!ls", you do not need the interactive things (for
  178. example, setting the prompt). Put the stuff that is not needed after these
  179. lines: >
  180. if ($?prompt == 0) then
  181. exit 0
  182. endif
  183. Another way is to include the "-f" flag in the 'shell' option, e.g.: >
  184. :set shell=csh\ -f
  185. (the backslash is needed to include the space in the option).
  186. This will make csh completely skip the use of the .cshrc file. This may cause
  187. some things to stop working though.
  188. ==============================================================================
  189. Useful mappings *useful-mappings*
  190. Here are a few mappings that some people like to use.
  191. *map-backtick* >
  192. :map ' `
  193. Make the single quote work like a backtick. Puts the cursor on the column of
  194. a mark, instead of going to the first non-blank character in the line.
  195. *emacs-keys*
  196. For Emacs-style editing on the command-line: >
  197. " start of line
  198. :cnoremap <C-A> <Home>
  199. " back one character
  200. :cnoremap <C-B> <Left>
  201. " delete character under cursor
  202. :cnoremap <C-D> <Del>
  203. " end of line
  204. :cnoremap <C-E> <End>
  205. " forward one character
  206. :cnoremap <C-F> <Right>
  207. " recall newer command-line
  208. :cnoremap <C-N> <Down>
  209. " recall previous (older) command-line
  210. :cnoremap <C-P> <Up>
  211. " back one word
  212. :cnoremap <Esc><C-B> <S-Left>
  213. " forward one word
  214. :cnoremap <Esc><C-F> <S-Right>
  215. <
  216. *format-bullet-list*
  217. This mapping will format any bullet list. It requires that there is an empty
  218. line above and below each list entry. The expression commands are used to
  219. be able to give comments to the parts of the mapping. >
  220. :let m = ":map _f :set ai<CR>" " need 'autoindent' set
  221. :let m ..= "{O<Esc>" " add empty line above item
  222. :let m ..= "}{)^W" " move to text after bullet
  223. :let m ..= "i <CR> <Esc>" " add space for indent
  224. :let m ..= "gq}" " format text after the bullet
  225. :let m ..= "{dd" " remove the empty line
  226. :let m ..= "5lDJ" " put text after bullet
  227. :execute m |" define the mapping
  228. (<> notation |<>|. Note that this is all typed literally. ^W is "^" "W", not
  229. CTRL-W.)
  230. Note that the last comment starts with |", because the ":execute" command
  231. doesn't accept a comment directly.
  232. You also need to set 'textwidth' to a non-zero value, e.g., >
  233. :set tw=70
  234. A mapping that does about the same, but takes the indent for the list from the
  235. first line (Note: this mapping is a single long line with a lot of spaces): >
  236. :map _f :set ai<CR>}{a <Esc>WWmmkD`mi<CR><Esc>kkddpJgq}'mJO<Esc>j
  237. <
  238. *collapse*
  239. These two mappings reduce a sequence of empty (;b) or blank (;n) lines into a
  240. single line >
  241. :map ;b GoZ<Esc>:g/^$/.,/./-j<CR>Gdd
  242. :map ;n GoZ<Esc>:g/^[ <Tab>]*$/.,/[^ <Tab>]/-j<CR>Gdd
  243. ==============================================================================
  244. Compressing the help files *gzip-helpfile*
  245. For those of you who are really short on disk space, you can compress the help
  246. files and still be able to view them with Vim. This makes accessing the help
  247. files a bit slower and requires the "gzip" program.
  248. (1) Compress all the help files: "gzip doc/*.txt".
  249. (2) Edit "doc/tags" and change the ".txt" to ".txt.gz": >
  250. :%s=\(\t.*\.txt\)\t=\1.gz\t=
  251. (3) Add this line to your vimrc: >
  252. set helpfile={dirname}/help.txt.gz
  253. Where {dirname} is the directory where the help files are. The |gzip| plugin
  254. will take care of decompressing the files.
  255. You must make sure that $VIMRUNTIME is set to where the other Vim files are,
  256. when they are not in the same location as the compressed "doc" directory. See
  257. |$VIMRUNTIME|.
  258. ==============================================================================
  259. Hex editing *hex-editing* *using-xxd*
  260. See section |23.3| of the user manual.
  261. If one has a particular extension that one uses for binary files (such as exe,
  262. bin, etc), you may find it helpful to automate the process with the following
  263. bit of autocmds for your |init.vim|. Change that "*.bin" to whatever
  264. comma-separated list of extension(s) you find yourself wanting to edit: >
  265. " vim -b : edit binary using xxd-format!
  266. augroup Binary
  267. au!
  268. au BufReadPre *.bin let &bin=1
  269. au BufReadPost *.bin if &bin | %!xxd
  270. au BufReadPost *.bin set ft=xxd | endif
  271. au BufWritePre *.bin if &bin | %!xxd -r
  272. au BufWritePre *.bin endif
  273. au BufWritePost *.bin if &bin | %!xxd
  274. au BufWritePost *.bin set nomod | endif
  275. augroup END
  276. ==============================================================================
  277. Using <> notation in autocommands *autocmd-<>*
  278. The <> notation is not recognized in the argument of an :autocmd. To avoid
  279. having to use special characters, you could use a self-destroying mapping to
  280. get the <> notation and then call the mapping from the autocmd. Example:
  281. *map-self-destroy* >
  282. " This is for automatically adding the name of the file to the menu list.
  283. " It uses a self-destroying mapping!
  284. " 1. use a line in the buffer to convert the 'dots' in the file name to \.
  285. " 2. store that in register '"'
  286. " 3. add that name to the Buffers menu list
  287. " WARNING: this does have some side effects, like overwriting the
  288. " current register contents and removing any mapping for the "i" command.
  289. "
  290. 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>
  291. autocmd BufNewFile,BufReadPre * normal i
  292. Another method, perhaps better, is to use the ":execute" command. In the
  293. string you can use the <> notation by preceding it with a backslash. Don't
  294. forget to double the number of existing backslashes and put a backslash before
  295. '"'.
  296. >
  297. 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>"
  298. For a real buffer menu, user functions should be used (see |:function|), but
  299. then the <> notation isn't used, which defeats using it as an example here.
  300. ==============================================================================
  301. Highlighting matching parens *match-parens*
  302. This example shows the use of a few advanced tricks:
  303. - using the |CursorMoved| autocommand event
  304. - using |searchpairpos()| to find a matching paren
  305. - using |synID()| to detect whether the cursor is in a string or comment
  306. - using |:match| to highlight something
  307. - using a |pattern| to match a specific position in the file.
  308. This should be put in a Vim script file, since it uses script-local variables.
  309. It skips matches in strings or comments, unless the cursor started in string
  310. or comment. This requires syntax highlighting.
  311. A slightly more advanced version is used in the |matchparen| plugin.
  312. >
  313. let s:paren_hl_on = 0
  314. function s:Highlight_Matching_Paren()
  315. if s:paren_hl_on
  316. match none
  317. let s:paren_hl_on = 0
  318. endif
  319. let c_lnum = line('.')
  320. let c_col = col('.')
  321. let c = getline(c_lnum)[c_col - 1]
  322. let plist = split(&matchpairs, ':\|,')
  323. let i = index(plist, c)
  324. if i < 0
  325. return
  326. endif
  327. if i % 2 == 0
  328. let s_flags = 'nW'
  329. let c2 = plist[i + 1]
  330. else
  331. let s_flags = 'nbW'
  332. let c2 = c
  333. let c = plist[i - 1]
  334. endif
  335. if c == '['
  336. let c = '\['
  337. let c2 = '\]'
  338. endif
  339. let s_skip ='synIDattr(synID(line("."), col("."), 0), "name") ' ..
  340. \ '=~? "string\\|comment"'
  341. execute 'if' s_skip '| let s_skip = 0 | endif'
  342. let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip)
  343. if m_lnum > 0 && m_lnum >= line('w0') && m_lnum <= line('w$')
  344. exe 'match Search /\(\%' .. c_lnum .. 'l\%' .. c_col ..
  345. \ 'c\)\|\(\%' .. m_lnum .. 'l\%' .. m_col .. 'c\)/'
  346. let s:paren_hl_on = 1
  347. endif
  348. endfunction
  349. autocmd CursorMoved,CursorMovedI * call s:Highlight_Matching_Paren()
  350. autocmd InsertEnter * match none
  351. <
  352. ==============================================================================
  353. Opening help in the current window *help-curwin*
  354. By default, help is displayed in a split window. If you prefer it opens in
  355. the current window, try this custom `:HelpCurwin` command:
  356. >
  357. command -bar -nargs=? -complete=help HelpCurwin execute s:HelpCurwin(<q-args>)
  358. let s:did_open_help = v:false
  359. function s:HelpCurwin(subject) abort
  360. let mods = 'silent noautocmd keepalt'
  361. if !s:did_open_help
  362. execute mods .. ' help'
  363. execute mods .. ' helpclose'
  364. let s:did_open_help = v:true
  365. endif
  366. if !empty(getcompletion(a:subject, 'help'))
  367. execute mods .. ' edit ' .. &helpfile
  368. set buftype=help
  369. endif
  370. return 'help ' .. a:subject
  371. endfunction
  372. <
  373. vim:tw=78:ts=8:noet:ft=help:norl: