ViM
- Basic commands
- Movements
- Removal and Substitution
- Text formatting
- Windows
- Folding
- Searches
- Spell Checking
- Buffers
- Registers
- Ctags
- Various Commands
- Macros
- Tips
Basic commands
J= Join next to current line:%j= Join all lines (make the file all on a single line in practice)u= UndoCtrl+r= Repeat last command (Redo).= Repeat last command (escluding Undo, Redo and command of the:commandtype):w filename= Save current file, or the selection, tofilenamei= Enter insert mode at the cursor positiona= Enter insert mode after the cursor positiono= Add an empty line below the current oneO= Add an empty line above the current one:q!= Quit Vi without saving changesV= Start visual mode, selecting by linesCtrl+V= Start visual mode, selecting by rowsp= Pastey= Copy“*P= Paste clipboard’s contents“*y= Copy selection to clipboard”+y= Copy selection to x11-selection (different from clipboard!)”+p= Paste x11-selection contents"%p= Paste the current file name:put *= Paste clipboard’s contents”<buffer>y= Paste selection to <buffer> (usually a single character for brevity reasons)m<a>= Mark current position as <a>:1,4up <newfile>= Save file contents from line 1 through 4 into <newfile>. Can be applied also to selections
Movements
b= Move back a word, going to the end of the previous one or at the beginning of the current onew= Jump at the beginning of the next worde= Jump at the end of the next word:n= Go tonlineCtrl+AltGr+]= Follow a url like|url|Ctrl+T= Go back to where was before following a link10w= Go forward 10 words10b= Go back 10 words-= Go back to the beginning of the previous line+= Go to the beginning of the next line0= Go at the beginning of the current line$= Go at the end of the current lineEnd= Move to the end of the current line. It accepts a number to jump multiple linesfj= Go to the next occurrence ofjFj= Go to the previous occurrence ofj12G= Go to the specified line. In the example, go to the 12th lineG= Go to the end of the current buffer10%= Move to the 10% of the current bufferCtrl+W= Jump to the next Vi window'.= Go to the last modified line\.` = Go to the exact point where last edit happened\`` = Go back to the point before the last search was madegt= Go to the next tabgT= Go to the previous tabgi= Go to the exact point where last edit happened, like\.`, but also enter insert modem= Go to the markmH= Go to the first line of the screen (which is not the first line of the file!)M= Go to the middle of the screenL= Go to the bottom of the screenCtrl+U= Scroll a page upCtrl+D= Scroll a page downn= Go to the next occurrence of a search termN= Go to the previous occurrence of a search termg*= Go to the next occurrence of the word under the cursorg#= Go to the previous occurrence of the word under the cursor%= Go to the end of the current block (which can be a if/then/else block, a comment, a text between parentheses etc.)[[= Go back to the beginning of the current functiongd= Go to the first occurrence of the variable under the cursor, following the scope (thus first local then global variables)gD= Go to the first occurrence of the variable under the cursor, starting from the beginning of the file (thus ignoring scope; generally it’s then the definition of the variable)(= Go to the beginning of the previous phrase (often it’s the first character after a period or a newline))= Go to the beginning of the next phrase{= Go to the beginning of the previous or current paragraph or code block}= Go to the end of the next or current paragraph or code block
Removal and Substitution
x= Delete the character under the cursorX= Delete the character before the cursordd= Delete the current lined11w= Delete multiple words, in the example, 11daw= Delete the word under the cursor. This works also if not at the beginning of word, differently fromdwd^= Delete everything from the cursor to the beginning of the lined$= Delete everything from the cursor to the end of the linedG= Delete everything from the cursor to the end of the filec11wAAA= Substitutes withAAAmultiple words, in the example, 11C= Delete next line and enter insert mode11rAAA= Substitutes multiple times, here 11, the textAAAwith what’s after the cursor:%s/stringtosubstitute/stringtoinsert/g= Substitutesstringtosubstitutewithstringtoinserin the file, all occurrences (g). Without the%, substitutes only in the current lineg?= ROT13 encrypt the current line, or the selected onesCtrl+a= Add 1 to the number below the cursorCtrl+x= Subtract 1 to the number below the cursorxp= Switch character under the cursor with the following oneddp= Switch the current line with the following oneIstring<ESC>= Add string at the beginning of every line previously selected withCtrl+vAstring<ESC>= Add string at the end of every line previously selected withCtrl+vCtrl+W= When in insert mode, delete the word before the cursorRstring= Overwrites the text from the cursor with stringrcharacter= Insert character right under the cursor:sort u= Remove all double lines and sort them alphabetically:v/regexp/d= Remove all lines that do not match regexp:g/regexp/d= Remove all lines that do match regexp:g/regexp/m$= Move all lines matching regexp at the end of the file ($){d}= Go to the end of the current paragraph, or the previous if the cursor is on an empty line, and delete itd/regexp= Delete everything between the cursor and the first occurrence of regexpcas= Substitute a sentence (delete all its contents and go in insert mode)cap= As above but on a whole paragraphdap= Remove the current paragraphci"= Remove everything between the previous"and the next"and go in insert mode. It’s not necessary to actually have the cursor between 2", it’ll automatically move to the next occurrencedi"= As above but it only delete the text
Text formatting
gUw= Make a word all uppercase (starting from the cursor)guw= Like above but lowercaseguuorgUU= Make lowercase or uppercase a whole lineg~~= Switch every character in the whole line, from uppercase to lowercase and viceversa~= Switch the character under the cursor (uppercase/lowercase)>>= Increase indentation<<= Remove a level of indentationCtrl+t= Increase indentation (in insert mode)Ctrl+d= Remove a level of indentation (in insert mode):set textwidth=number= Set line margin tonumbergq= Justify the current linegq}= Justify the curren paragraphgggqG= Justify all the file:center= Center the selection:right= Right align the selection:left= Left align the selection:set autoindent= Respect indentation when starting to edit a new line:set linebreak= Set linebreak of a word if it doesn’t fit in the line, preventing it to be split across two lines:set fileformat=(unix|dos)= Set newline format to unix or dos:retab= Transform tabs in whitespaces and viceversa in the whole file, respecting current settings (likeexpandtab,shiftwidthandtabstop):1,$j= Join all lines from the first (1) to the last ($) in a single line:1G!Gsort= Go to the first line (1G) and then sort the whole file
Windows
:split file= Open file in a new split window. Also:newto simply open an empty file:vsplit file= As above but the split window will be vertical:res -n= Shrink window ofnlines:res +n= Enlarge window ofnlinesz10= Shrink window of 10 lines:qwall= Quit, closing and saving all changes in all windows:qall!= As above but don’t save changes:windo= Execute a command in all windows
Folding
zf3j= Fold 3 lineszfa(= Fold from the parentheses “(” to the matching closing parentheses. Any symbol can be used. Cursor needs to be on the opening symbol:20,25 fold= Fold from line 20 through line 25zo= Open the fold under cursorzc= Close, fold again, the last opened foldzr= Open all the first level folds (those that aren’t inside another fold)zR= Open all the foldszm= Close all first level foldszM= Close all foldszd= Delete the fold under the cursor:set nofoldenable= Delete all folds in current file
Searches
/string= Search string. Usento jump between results:g/regexp/= Show all lines matching regexp:g/regexp/#= As above but also show the line number next to the matching linesq/= Show last searches*= Search word under the cursor forward in the file#= Search word under the cursor backward in the file:%s/pattern//gn= Count the occurrences ofpatternin current buffer, without modifying anything
Spell Checking
:set spell= Enable spell checking.:set nospellto disable it:set spelllang=xx= Set spell checking language to xx. Dictionary files have to be in /usr/share/vim/spell or ~/.vim/spell]s= Go to the next wrong word[s= Go to the previous wrong wordzg= Add word under the cursor to the main dictionaryzG= Add word under the cursor to a supplementary dictionary, separated from the main onezw= Add word under the cursor to the dictionary of wrong wordszW= Add word under the cursor to a supplementary dictionary of wrong words, separated from the main onez== Show possible correction for the word under cursor
Buffers
:badd file= Add file to the buffer list but don’t open it:buffers= Show all buffers:ls= Show all buffers:bdelete= Delete a buffer. Needs its name or its number. This doesn’t dump the information about it so it’s quicker to reopen it if needed:bwipeout= As above but delete also its information:1,3bdelete= Delete buffers from 1 to the 3:buffer= Show a buffer.:bfirst= Go to the first buffer:bn= Go to the next buffer:bp= Go to the previous buffer:blast= Go to the last buffer:ball= Open all buffer in as many split windows as needed:bmodified= Go to the last modified buffer:bufdo= Execute a command in all opened buffers
Registers
:registers= Show the contents of all registers"0= The register containing the most recent yanked text but never deleted text"1-9= Registers 1 through 9 contain the most recent deleted text, from the most recent (1) to the oldest (9)"%= The register containing the name of current buffer’s file. It’s a read-only register":= The register containing the most recent executed command""= The “unnamed” register. Every operation gets written into it, no matter what it is or if it’s specifically saved to another register"_= A “discard” register. Everything written into it is lost"-= The register that saves any delete operations that is smaller than 1 line length. If the operation is explicitly saved to another register, it won’t be saved here too- `"/" = The register containing the most recent search pattern
"=expression<Enter>p" = The=register evaluates theexpressionandppaste it at the current cursor position. For instance,"=5*5p` will paste output 25 :22put r= Insert contents of registerrat line 22. Without a number, defaults to the current line
Ctags
Ctrl+]= Jump to the first occurrence Vim finds of the class/method/function/variable/whatever the cursor is atCtrl+t= Get back to where you were before jumping withCtrl+]:tnext= Go to the next tag:tprev= Go to the previous tag:ltag= Load the tags in the location list window, that can be shown with:lopenCtrl+x Ctrl+]= Insert the first tag that starts with the characters before the cursor among tags and insert it in front of the cursor (in insert mode)
Various Commands
:h holy-grail= Show a general list of commands:set all= Show the options:set list= Show non-printable characters:set paste= Enable paste mode, useful to paste text without formatting it, exactly as it is. Disable it with:set nopaste:set patchmode=.ext= Make a copy of the current file with an extension ext:set key== Remove the password set to open the file, making it plain text:set number= Show line numbers:ab abb string= Create an abbreviation, substituting string each time abb is typed:una abb= Cancel the previously created abbreviation abb:ascii= Show the decimal, hexadecimal and octal numbers of the characters under the cursor in the ASCII table:digraph= Show all special symbols that can be inserted and how:noh= Clean the screen from all highlightings:e directory= Open directory in Vi:r!cmd= Insert in Vi the output of shell command cmd:r file= Insert the contents of file under the cursor. Also:2rto insert at line 2gf= Open the filename or whole path under the cursor. To show the path Vi look for files, use:echo &path. Should work also with http or ftp urlsq:= Show last executed commands:tabe file= Open file in a new tab:tabc= Close current tab:tabn= Go to next tab:tabc= Go to previous tab!!date= Insert date and timeCtrl+L= Clear screen from all messages and warningsCtrl+k= Activate the insertion of special symbol and characters (those shown by:digraphs)g<Ctrl+g>= Show some statistics about current filegv= Select again last visual selectionCtrl+n= Show a list of possible completions for the word under cursor (based on the opened file)Ctrl+xandCtrl+l= Show a list of possible completions for the whole line (in insert mode)Ctrl+xandCtrl+f= Show a list of possible completions for the whole line with an existing path (in insert mode)Ctrl+y= Insert the character directly above the cursor. Useful to quickly copy the above line with very few edits (in insert mode)Ctrl+v character= Insert a literal character (as <Esc> or an ASCII code or an Unicode character likeu<unicode_number>Ctrl+o= In insert mode, execute a command as if it was in normal mode and then return to insert:echom message= Print message to the command line. Unlike:echo, the message stays visible until another substitutes it:mksession file= Save all open buffers in file (defaults to Session.vim) in the current directory. Withvi -S filethen the session can be quickly restored:scriptnames= List all plugins and files loaded at start, in the order they were loadedvi +q --startuptime startup.txt file= Save debug info instartup.txt. Useful to see load times, what plugins and files are loaded etc.:args= Modify the arguments list. By default it corresponds to the opened files but with, for example,:args *.cit becomes all .c files in the current directory:argdo cmd= Execute cmd for every file in the arguments list:diffupdate= Recalculate the diff (in vimdiff orvi -dmode):set noscrollbind= Disable simultaneous scrolling of the diff buffers. Reenable it then with:set scrollbindga= Show the decimal, octal and hexadecimal index of the character under the cursor:au= Show all the autocommands in effect:silent cmd= addingsilentbefore any command suppresses messages it may produce. Useful to not have to pressat startup to confirm enabling a plugin or a command :$!xxd= enters hex edit mode, to edit an hexadecimal file. Return to normal mode with:%!xxd -rbefore saving and quitting ViM
Macros
Some macros I find useful
:g/^\s*$/d= Delete all empty lines:%s/^/\=line('.'). ''= Add at the beginning of every line its number:%s/^/\=strpart(line(”.”).” ”, 0, 5)= As above but add a space between the number and the following text:runtime! syntax/2html.vim= Output the current file as html:%s#<\_.\{-1,}>##g= Remove all html tags:g/regexp/,/regexp/d= Remove all lines where the first or the second regexp appears:%s/^\(.*\)\n\1$/\1/= Remove all duplicated lines in the current file
##Tips
Change statusline colours
Edit in the colour theme file the hi Statusline line. ctermfg is the foreground colour, ctermbg is the background. Use :he cterm-colors to see which colours can be used. Up until 256 colours, if the terminal supports it, can be used, see here
Regexp
Instead of backslashing special characters, it’s possible to add \v at the
very beginning of a regexp so that everything that’s not a letter, a number or
an underscore is taken to have a special meaning unless explicitly escaped. For
example:
:%s/\v^%(abc){1,3}(.+)$/\1/
doesn’t need backslashing before parentheses, plus sign and curly brackets.
Also, \c turns off case sensitivity. Its opposite is \C, forcing case
sensitivity on.
Identify corresponding opening/closing HTML tag
Typing v + a + t will select everything inside the html tag where is the cursor. Subsequently o will jump between the opening and closing tag, c will change content and y will yank
Plugins
Other than using a plugin helper, from ViM 8 onward it is possible to install a plugin directly in the .vim/pack/ directory and load it without touching the configuration at all.
If the plugin is on Github, it can be automatically installed and set to autoload with this command:
git clone --depth 1 https://github.com/account/pluginname .vim/pack/dist/start/pluginname