neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

tips.txt (17325B)


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