Best Vim Tips
From Vim Tips Wiki
Tip 305 Previous Tip • Next Tip
Created: August 10, 2002 Complexity: intermediate Author: zzapper Minimum version: 5.7 Karma: 5111/1537 Imported from: Tip#305
Here's a necessarily cryptic list of my Best Vim Tips, gleaned from various sources.
See the updated version at http://www.rayninfo.co.uk/vimtips.html
[edit] Absolutely essential
vim.sf.net : Visit frequently
comp.editors : Vim dominated newsgroup
* # g* g# : find word under cursor (forwards/backwards)
% : match brackets {}[]()
matchit.vim : % now matches tags <tr><td><script> etc
<C-N> <C-P> : word completion in insert mode
<C-X><C-L> : Line complete SUPER USEFUL
/<C-R><C-W> : Pull <cword> onto search/command line
:set ignorecase # you nearly always want this
:syntax on : colour syntax in Perl,HTML,PHP etc
:h slash<C-D> : type control-D and get a list all help topics containing slash
(plus use TAB for Help completion)
[edit] Make it easy to update/reload _vimrc
:nmap ,s :source $VIM/_vimrc :nmap ,v :e $VIM/_vimrc
[edit] VISUAL MODE Mappings
:vmap sb "zdi<b><C-R>z</b><ESC> : wrap <b></b> around VISUALLY selected Text :vmap st "zdi<?= <C-R>z ?><ESC> : wrap <?= ?> around VISUALLY selected Text
[edit] Exploring
:Ex : file explorer note capital Ex \be : builtin buffer explorer :ls : list of buffers(eg following) :cd .. : move to parent directory
[edit] Great
guu : lowercase line gUU : uppercase line gf : open file name under cursor (SUPER) ga : display hex,ascii value of character under cursor ggVGg? : rot13 whole file CTRL-A,CTRL-X : increment,decerement number under cursor win32 users must remap CTRL-A [[http://vim.wikia.com/wiki/VimTip30]] CTRL-R=5*5 : insert 25 into text
[edit] Easter Eggs
:h 42 :h holy-grail :help! :help mapmode-nvo (comment about :nunmap) :help UserGettingBored
[edit] Markers & moving about
'. : jump to last modification line (SUPER)
`. : jump to exact spot in last modification line
<C-O> : retrace your movements in file (old)
<C-I> : retrace your movements in file (new)
:ju(mps) : list of your movements {{help|jump-motions}}
:history : list of all your commands
[edit] Abbreviations & maps
:map <f7> :'a,'bw! c:/aaa/x :map <f8> :r c:/aaa/x :map <f9> :w<CR>:!c:/php/php.exe %<CR> :map <f11> :.w! c:/aaa/xr<CR> :map <f12> :r c:/aaa/xr<CR> :ab php : list of abbreviations beginning php :map , : list of maps beginning ,
[edit] For use in Maps
<CR> : carriage Return for maps <ESC> : Escape <LEADER> : normally \ <BAR> : | pipe
[edit] List your Registers
:reg : display contents of all registers "1p.... : retrieve numeric buffers
[edit] Execute vim command from buffer contents
"ayy@a : execute "Vim command" in a text file yy@" : same thing using unnamed register
[edit] Get output from other commands
The following uses external programs – sort is just an example (see :help :sort to learn how to use Vim's built-in sort).
:r!ls : reads in output of ls (use dir on Windows) :r !grep "^ebay" file.txt : grepping in content :20,25 !rot13 : rot13 lines 20 to 25 :r!date : same thing " Sorting with external sort :%!sort -u : use an external program to filter content :'a,'b!sort -u : use an external program to filter content !1} sort -u : sorts paragraph (note normal mode!) :g/^$/;,/^$/-1!sort : sort each block (note the crucial ;) " Using !!command in normal mode will automatically translate to :.!command " This will send the current line to the command, and replace the current line " With command's result !!date : Replaces current line with date !!which 'command': Replace current line with the absolute path to 'command' !!tr -d abcd : Delete a,b,c,d from the current line " You can also use ! on a visual selection. Select an area with one of the visualmode " commands, and then type !command to pipe the whole selection through command. (Note " that this is equivalent to :'<,'>!command). For example, after selecting multiple lines " with visualmode: !sort : Filters the lines through the sort program !grep word : delete all lines not containing 'word'
[edit] Multiple Files Management
:wn : write file and move to next (SUPER) :bd : remove file from buffer list (SUPER) :sav php.html : Save current file as php.html and "move" to php.html :sp fred.txt : open fred.txt into a split :e! : return to unmodified file :w c:/aaa/% : save file elsewhere :e # : edit alternative file :e % :rew : rewwind to first file in ARGS :bn : next file :bp : next file :brew
[edit] Recording (BEST TIP of ALL)
qq # record to register q your commands q @q to execute @@ to Repeat # editing a register/recording "qp <you can now see register contents, edit as required> "add @a
[edit] vimrc essentials
:set incsearch : jumps to search word as you type (annoying but excellent) :set wildignore=*.o,*.obj,*.bak,*.exe :set shiftwidth=3
[edit] Launching Windows IE
:nmap ,f :update<CR>:silent !start c:\progra~1\intern~1\iexplore.exe file://%:p<CR> :nmap ,i :update<CR>: !start c:\progra~1\intern~1\iexplore.exe <cWORD><CR>
[edit] FTPing from Vim
cmap ,r :Nread ftp://209.51.134.122/public_html/index.html cmap ,w :Nwrite ftp://209.51.134.122/public_html/index.html gvim ftp://209.51.134.122/public_html/index.html
[edit] Appending to registers (use CAPITAL)
# yank 5 lines into "a" then add a further 5 "a5yy 10j "A5yy [I : show lines matching word under cursor <cword>
[edit] Conventional shifting
:'a,'b>> # visual shifting (builtin-repeat) :vnoremap < <gv :vnoremap > >gv
[edit] Searching
/^joe.*fred.*bill/ : normal /^[A-J]\+/ : search for lines beginning A-J followed by at leat 1 A-J /forum\(\_.\)*pent search over possible multiple lines /fred\_s*joe/i : any whitespace including newline /fred\|joe : Search for FRED OR JOE
[edit] Substitution
:%s/fred/joe/igc : general substitute command
:%s/\r//g : Delete DOS returns ^M
:'a,'bg/fred/s/dick/joe/gc : VERY USEFUL
:s/\(.*\):\(.*\)/\2 : \1/ : reverse fields separated by :
:%s/^.\{-}pdf/new.pdf/ non greedy matching (ie to first pdf)
:s/fred/<c-r>a/g substitute "fred" with contents of register "a"
:%s/^\(.*\)\n\1/\1$/ delete duplicate lines
# non-greedy matching \{-}
:%s/^.\{-}pdf/new.pdf/
:help /\{-}
:s/fred/<c-r>a/g substitute "fred" with contents of register "a"
# multiple commands
:%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/
:%s/suck\|buck/loopy/gc : ORing
:s/__date__/\=strftime("%c")/ : insert datestring
[edit] Global command
:g/^\s*$/d :delete all blank lines :g!/^dd/d : delete lines not containing string :v/^dd/d : delete lines not containing string :g/fred/,/joe/d : not line based :v/./.,/./-1join : compress empty lines :'a,'b g/^Error/ . w >> errors.txt :g/cmap\|form/p : ORing
[edit] Paste register *
:redir @* : redirect commands to paste :redir END "*yy : yank to paste "*p : insert paste buffer
[edit] Formatting text
gq<CR> gqap (a is motion p paragraph (visual mode))
[edit] Operate command over multiple files
:argdo %s/foo/bar/ :bufdo %s/foo/bar/ :windo %s/foo/bar/
[edit] Command line tricks
gvim -h ls | gvim - : edit a PIPE! # vg.ksh (shell script) # vi all files in directory containing keyword $1 and jump to $1 gvim.exe -c "/$1" $(grep -isl "$1" *) &
[edit] Comments
More tips:
# Vim traps
In regular expressions you must backslash + (match 1 or more)
/fred\+/ : matches fred/freddy but not free
----------------------------------------
# \v or very magic (usually) reduces backslashing
/codes\(\n\|\s\)*where : normal regexp
/\vcodes(\n|\s)*where : very magic
----------------------------------------
# pulling objects onto command/search line (SUPER)
CTRL-R CTRL-W Pull word under the cursor into a command line or search
CTRL-R - : pull small register
CTRL-R [0-9a-z] : pull named registers
CTRL-R % : pull file name (also #)
----------------------------------------
# manipulating registers
map <f11> "qyy:let --AT--q=--AT--q."zzz"
----------------------------------------
# help
:h visual<C-D><tab> : obtain list of all visual help topics
: Then use tab to step thru them
----------------------------------------
# where was an option set
:verbose set history : reveals value of history and where set
----------------------------------------
# running file thru an external program (eg php)
map <f9> :w<CR>:!c:/php/php.exe %<CR>
----------------------------------------
# Inserting Carriage Returns
:%s/nubian/<C-V><C-M>&/g : that's what you type
:%s/nubian/<C-Q><C-M>&/g : for Win32
:%s/nubian/^M&/g : what you'll see where ^M is ONE character
----------------------------------------
# Retrieving last command line command for copy & pasting into text
<c-r>:
# Retrieving last Search Command for copy & pasting into text
<c-r>/
----------------------------------------
# doing things over multiple lines \_ means including newline
/<!--\_p\{-}--> : search for multiple line comments
/fred\_s*joe/i : any whitespace including newline
/bugs\(\_.\)*bunny : bugs followed by bunny anywhere in file
:h \_ : help
----------------------------------------
# more completions
<C-X><C-F> :insert name of a file in current directory
----------------------------------------
# help for help
:h visual<C-D><tab> : obtain list of all visual help topics
: Then use tab to step thru them
:h ctrl<C-D> : list help of all control keys
:h :r : help for :ex command
:h CTRL-R : normal mode
:h \r : what's \r in a regexp
:h i_CTRL-R : help for say <C-R> in insert mode
:h c_CTRL-R : help for say <C-R> in command mode
:h v_CTRL-V : visual mode
----------------------------------------
This is an extension to
# pulling objects onto command/search line
If you use
/CTRL-R CTRL-A
it brings the whole word under the cursor including any special characters.
For eample, if you are in an HTML page and the cursor is under a keyword <table>
/CTRL-R CTRL-A brings /<table> /CTRL-R CTRL-W brings /table (depending on what the letter under your cursor is ... table or < or >
The Buffer Explorer scripts mentioned above (\be \bs) rely on the very popular Vim script bufexplorer.vim.
Have recently started to appreciate taglist.vim (the most popular Vim script) it really comes into it's own with very long programs containting lots of subroutines/functions as it shows which function/sub you're in etc script#273.
- ftping with vim - great functionality
for ascii file transfers add the following line to your profile
let g:netrw_ftpmode="ascii"
If you want to delete multiple duplicate lines in a sorted file:
:%s/^\(.*\)\n\(\1\n\)*/\1<NL>/
where <NL> is the character sequence that represents a return in your file type. For Windows, the easiest way to get this is to highlight a return character in another program (open a new notepad, hit return once, select all, and copy) and then use Edit -> Paste in Vim to insert it.
If you want to number the lines in the file try:
:%! nl -ba
I think rot13 of the whole file can be improved by this:
ggg?G
It's so much better to read. Saves one byte over ggVGg? Also, it does not require the overhead of selecting the whole file, especially if the file is huge.
In the message above by junk4todd about getting the <NL> character, you can get the <NL> character by typing:
<Ctrl-V><CR>
The Ctrl-V character is the "escape"-like character and prints the literal of what the next sequence is (it works in vi, and seems to work in vim, too)
I'm confused. I'm a long time vi/vim user. I've often used ctrl-v to enter escaped characters, but I haven't done it in a while. I just tried, and ctrl-v puts me in visual mode block selection... as documented. Well, the docs also make reference to ctrl-v being used as an escape. So which is it? How can ctrl-v be documented to do both things?
Ctrl-V only lets you enter escaped characters when in insert mode.
You need to use Ctrl-Q on default Windows systems.
:g/^\s\+$/d
delete all lines containing whitespace only.
:g/^\s*$/d
delete all empty lines with no whitespace.
:v/^\d/d
delete all lines that don't start with a digit.
I use
:map <F12> :set number!<CR>
like this:
map <F12> :set number!<bar>set number?<CR>
or:
map <F11> :set hls!<bar>set hls?<CR> map <F10> :set paste!<bar>set paste?<CR> map <F9> :set wrap!<bar>set wrap?<CR>
so I can see what the current state is (not really usefull for number, but better for hlsearch with nothing highlighted on your current view)
> How delete any line that contains DTE unless that line also contains STX or ETX?
:g/^/call setreg(0,getline(".")) | if (--AT--0=~#"DTE") && !((--AT--0=~#"STX") || (--AT--0=~#"ETX")) | d | endif
Each line is searched for the strings DTE, STX, ETX and according to the given rule only the lines matching the specified condition are deleted. If you replace =~# with =~ then the search will be case insensitive. The vertical bar separates the commands to be entered all in one line First copying the lines in a register and then examining the register avoids calling the getline() function several times. See :help eval.
If you do not want to remove windows key mappings, keep the line
noremap <C-kPlus> <C-A>
in your vimrc.
Then you can use Ctrl-NumPad+ to increment numbers as others do with <C-A>
Another very useful mapping:
noremap <C-J> gj noremap <C-K> gk
That's really useful when dealing with long lines. It lets you use Control-J and Control-K to move up and down screen lines instead of buffer lines with j and k. Control-J isn't really mapped to anything by default, it's like hitting enter, but Control-K is something to do with digraphs. However, noremap won't remove this ability in insert mode.
Alternatively, you could use:
noremap <Up> gk noremap <Down> gj
which would map the arrow keys to screen line movement instead of buffer line movement.
To substitute any word (say FILE) by actual filename you can use
:%s/FILE/\=expand("%:t")
Simple but useful, to reopen a file, (revert to the last saved version), anybody can use:
:open
