Programming Adventures: Vim
Guide to vim for programmers.
Vim
Vim is a text editor.
It’s handy when working on most remote machines.
Many programmers use it as their default code editor.
I created this guide to act as a cheat-sheet for my personal use.
People who use vim regularly often create one for reference.
More detailed vim guides for various use cases can be found on the internet.
Overview
Linting is not available in plain vim.
A prowess in typing will make vim enjoyable:
- High typing speed; code completion is not available in plain vim.
- High typing accuracy; error correction is not available in plain vim.
Resources
vimtutorCommand-line program.:help _Visit vim’s documentation. Replace_with command.
Operations
Commands and actions are used to operate vim.
Ideally vim is supposed to be operated using only the keyboard.
Most commands can be called multiple times by prepending them with a number or range. A range is defined as _,_ where _ are numbers or marks or certain special characters:
.Current line.$Last line.%Entire file. Equivalent to1,$.*Last selection in visual mode.
Range can also be augmented with basic arithmetic.
Configuration
Vim configuration is stored in .vimrc file.
Vimscript is used to write the configuration.
Look for ~/.vimrc.
General Commands
Commands are made up of set followed by options. Options may hold value.
Boolean options can be toggled by appending ! to the option.
Boolean options can be unset by prepending no to the option.
Value of an option can be checked by appending ? to the option.
Value can be assigned to an option by appending = followed by the value to the option.
Value can be added to an option by appending += followed by the value to the option.
Value can be subtracted from an option by appending -= followed by the value to the option.
An option can be reset to default value by appending & to the option.
:set hlsearchSet highlight search results.:set nohUnset highlight search results.:set numberSet line numbers.:set nonumberUnset line numbers.:set ignorecaseSet to ignore case in patterns and words.:set smartcaseSet to consider case in patterns and words. Requires:set ignorecase.:set undofileSet to track changes to a file.:set undodir=~/example/pathSet file location to save track of change. Replace~/example/pathwith path and name of file. Requires:set undofile.:set undolevels=_Set number of changes to track for undo. Replace_with a number.:set foldenableSet to enable fold.:set foldmethod=_Set method to collapse blocks of code. Replace_with one ofmanual,indent,expr,syntax,diff,marker. Requires:set foldenable.:set foldcolumn=_Set number of folds to display on the sidebar. Replace_with a number.:set incsearchSet highlight pattern during input.:set statusline=example.expressionSet status line. Replaceexample.definitionwith format.:set background=_Set background scheme. Replace_with scheme name.:set encoding=_Set encoding. Replace_with name of encoding.:set expandtabSet to use spaces in place of tabs.:set tabstop=_Set number of spaces to place for each tab. Replace_with a number.:set shiftwidth=_Set number of spaces for each indentation. Replace_with a number.:set smarttabSet to use number of spaces depending upon the location of cursor.:set autoindentSet auto-indent. Equivalent to:set ai.:set smartindentSet to use auto-indent depending upon the location of cursor. Equivalent to:set si.:set cursorlineSet to show line underneath cursor.:set nocursorlineUnset cursorline.:set cursorcolumnSet to highlight the column of cursor.:set nocursorcolumnUnset cursorcolumn.:set warpSet line warp.:set nowarpUnset line warp.:set autoreadSet to re-read files modified on disk.:set noautoreadUnset autoread.:set titleSet to display file title.:set notileUnset title display.:set wildmenuDisplay tab complete options as menu.:set spellEnable spellchecking.:set listSet to display whitespaces.:set nolistUnset whitespaces display.:retabReplace all tabs with spaces.:syntax onEnable syntax highlight.:syntax offDisable syntax highlight.:colorscheme _Choose colorscheme for highlight. Replace_with colorscheme. Requires:syntax on.:filetype onEnable file type detection.:filetype plugin onEnable plugins for the detected filetype.:filetype plugin offDisable plugins for filetype.:filetype indent onEnable filetype specific indentation.:filetype indent offDisable filetype specific indentation.
Commands in .vimrc must be added without :.
Save Options and Sessions
:mk example.fileSave operations and mappings to file. Replaceexample.filewith name of file. Use:mk! example.fileto overwrite file.:mkexrc example/fileSave operations and mappings to file. Replaceexample/filewith path and name of file. Use:mkexrc! example/fileto overwrite file.:mks example/fileSave session to file. Equivalent to:mksession example/file. Replaceexample/filewith path and name of file. Use:mks! example/fileto overwrite file.:source example/fileRestore operations and mapping or session. Replaceexample/filewith path and name of file.
Buffers, Windows and Tabs
A buffer is an open file.
A window displays a buffer.
A tab contains one or more windows.
General Commands
:buffersList buffers.:buffer _Move to buffer. Replace_with id or name of the buffer.:lsList buffers. Equivalent to:buffers.:bnMove to next buffer. Equivalent to:bnext.:bpMove to previous buffer. Equivalent to:bprevious.:bfMove to first buffer. Equivalent to:bfirst.:blMove to last buffer. Equivalent to:blast.:badd example.fileAdd file to buffer. Replaceexample.filewith file path.:bdelete _Delete buffer. Replace_with id or name of the buffer.:_,_bdeleteDelete buffers. Replace_,_with start id and end id respectively.:bdDelete buffer. Equivalent to:bdelete.:BdeleteDelete buffer but do not close window.:jumpsDisplay jump list.:history :Command history.:history /Search command history.:history ?Search command history.:qallQuit all buffers.
Operations And Navigation
ctrl + ^Switch to alternate buffer._ctrl + ^Switch to specific buffer. Replace_with buffer id.ctrl + wfollowed bysSplit the current window horizontally.ctrl + wfollowed byvSplit the current window vertically.ctrl + wfollowed bynSplit the current window horizontally and edit a new file.ctrl + wfollowed by^Split the current window with alternate file._followed byctrl + wfollowed by^Split current window with specific buffer. Replace_with buffer id.ctrl + wfollowed byjMove to lower window.ctrl + wfollowed bykMove to upper window.ctrl + wfollowed byhMove to left window.ctrl + wfollowed bylMove to right window.ctrl + wfollowed byrRotate the windows.ctrl + wfollowed byxExchange current window with next window.ctrl + wfollowed by=Resize current window to fit.ctrl + wfollowed by-Decrease the height of current window.ctrl + wfollowed by+Increase the height of current window.ctrl + wfollowed by<Decrease the width of current window.ctrl + wfollowed by>Increase the width of current window.ctrl + oJump to previous cursor position.ctrl + iJump to next cursor position.
History
q:Open command history. Equivalent to:history :.q/Search command history. Equivalent to:history /.q?Search command history. Equivalent to:history ?.@:Repeat last command.
Normal Mode
Mode defines the purpose for which vim is being used.
The default mode in vim is NORMAL mode.
All general commands are accessible in this mode.
Use ctrl + c or ctrl + [ to activate NORMAL mode.
Use : to switch to COMMAND mode:
ctrl + rfollowed byctrl + fCopy filename under cursor.ctrl + rfollowed byctrl + wCopy word under cursor.ctrl + rfollowed byctrl + lCopy line under cursor.
General Commands
:helpVim’s help.:qQuit vim. Use:q!to Force quit vim.:wWrite file to disk.:w example.fileWrite fileexample.fileto disk. Replaceexample.filewith name of file. Use:w! example.fileto overwrite fileexample.fileto disk.:wqWrite file to disk and quit.:xWrite file to disk and quit. Same as:wq.:e example.fileEdit existing file. Replaceexample.filewith name of file.:pwdDisplay present working directory.:cd example/directoryChange directory. Replaceexample/directorywith directory path.:regDisplay register. Equivalent to:register.:s/example.pattern/replace.pattern/_Substituteexample.patternwithreplace.pattern. Replaceexample.patternwith search pattern.replace.patterncan be left empty. Replace_with&,c,g,i,I,nor leave empty.:g/example.pattern/_Execute command globally. Replaceexample.patternwith search pattern. Replace_with command.:marksDisplay list of marks.:marks _Display specific mark. Replace_with names of marks.:delm _Delete mark. Replace_with name of mark. Equivalent todelmarks _.:delm!Delete all marks. Equivalent todelmarks!.:digDisplay digraphs. Equivalent to:digraphs.:! example.commandExecute shell command. Replaceexample.commandwith shell command.:!!Execute last shell command.:r! example.commandExecute shell command and insert output. Equivalent to:read! example.command. Replaceexample.commandwith shell command.:r!!Execute last shell command and insert output. Equivalent to:read!! example.command.:foldoOpen all folds. Equivalent to:foldopen.:foldo!Open all folds recursively.:foldcClose all folds. Equivalent to:foldclose.:foldc!Close all folds recursively.:foldd example.commandExecute command on all open folds. Equivalent to:folddoopen example.command. Replaceexample.commandwith command to execute.:folddoc example.commandExecute command on all closed folds. Equivalent to:folddoclosed example.command. Replaceexample.commandwith command to execute.:abList abbreviations. Equivalent to:abbreviate. Use:iabfor INSERT mode abbreviations. Use:cabfor COMMAND mode abbreviations.:ab egList abbreviations beginning witheg. Equivalent to:abbreviate eg. Replaceegwith any string. Use:iab egfor INSERT mode abbreviations. Use:cab egfor COMMAND mode abbreviations.:ab eg example givenAbbreviateexample givenwitheg. Equivalent to:abbreviate eg example given. Replaceegwith any string. Replaceexample givenwith replacement strings. Use:iab eg example givenfor INSERT mode abbreviations. Use:cab eg example givenfor COMMAND mode abbreviations.:una egRemove abbreviationeg. Equivalent to:unabbreviate eg. Replaceegwith abbreviation string. Use:iuna egfor INSERT mode abbreviations. Use:cuna egfor COMMAND mode abbreviations.:abcRemove all abbreviations. Equivalent to:abclear. Use:iabcfor INSERT mode abbreviations. Use:cabcfor COMMAND mode abbreviations.:splitSplit file horizontally.:vsplitSplit file vertically.
Search
/example.patternSearch pattern forward in current file. Replaceexample.patternwith search pattern.?example.patternSearch pattern backward in current file. Replaceexample.patternwith search pattern./Example.Pattern\CSearch case sensitive pattern forward in current file. ReplaceExample.Patternwith cased search pattern.?Example.Pattern\CSearch case sensitive pattern backward in current file. ReplaceExample.Patternwith cased search pattern./example.pattern\cSearch case insensitive pattern forward in current file. Replaceexample.patternwith search pattern.?example.pattern\cSearch case insensitive pattern backward in current file. Replaceexample.patternwith search pattern.//Search previous pattern.*Search word under cursor forward.#Search word under cursor backward.g*Search pattern under cursor forward.g#Search pattern under cursor backward.gnSelect last search result.nNext search result.NPrevious search result.ctrl + gNext search result from COMMAND mode. Requires:set incsearch.ctrl + tPrevious search result from COMMAND mode. Requires:set incsearch.
Navigation
hMove one character left.jMove one line down.kMove one line up.lMove one character right.wMove one word forward.bMove one word backward.0Move to start of line.^Move to first non whitespace character of line.$Move to end of line.%Move to the other bracket of the pair.f_Find character forward on line. Replace_with character.F_Find character backward on line. Replace_with character.m_Move to character forward on line. Replace_with character.M_Move to character backward on line. Replace_with character.;Go forward on line. Requiresf_orF_orm_orM_.,Go backward on line. Requiresf_orF_orm_orM_._GMove to start of line. Replace_with line number.GMove to start of last line of file.ggMove to start of first line of file. Equivalent to1G.ctrl + uMove half screen up.ctrl + dMove half screen down.ctrl + yScroll upwards.ctrl + eScroll downwards.g;Move to next position of change.g,Move to previous position of change.giMove to last position of change and switch to INSERT mode.gIMove to start of line and switch to INSERT mode.[mMove to start of method.m]Move to end of method.'_Move to first non whitespace character on marked line. Replace_with name of mark.`_Move to position of mark. Replace_with name of mark.[zMove to start of fold.]zMove to end of fold.zjMove to start of next fold.zkMove to start of previous fold.
Operations
Operators may be used in conjuction to navigation commands.
uUndo.ctrl + rRedo..Repeat last command.ddCopy and delete line.d$Delete to end of line.dggDelete to beginning of file.dGDelete to end of file.ggdGDelete entire content of file.diwDelete inside word.dipDelete inside paragraph.ciwChange inside word.pPaste.&Repeat last substitute.ziToggle foldenable.zfCreate fold. Requires selection in VISUAL mode.zdDelete fold under cursor.zDDelete fold under cursor recursively.zEEliminate all folds.zoOpen fold under cursor.zOOpen fold under cursor recursively.zcClose fold under cursor.zCClose fold under cursor recursively.zaToggle fold under cursor.zAToggle fold under cursor recursively.zxOpen fold under cursor and close all other folds.zmClose all folds.zMClose all folds recursively.zrOpen all folds.zROpen all folds recursively.ctrl + aIncrement next number on line.ctrl + xDecrement next number on line.
Registers
"_Set active register. Replace_with name of register (a - z).q_Start recording. Replace_with name of register (a - z).qStop recording. Requiresq_.@_Execute register. Replace_with name of register (a - z).
Marks
m_Mark the current line. Replace_with name of mark (a - z for local, A - Z for global).
Miscellaneous
gfOpen and edit file located at path under cursor.ctrl + wfollowed byctrl + fOpen and edit file located at path under cursor in separate window.gxOpen file located at path under cursor.gaGet code of the character under cursor.
Insert Mode
Insert content.
Use i in NORMAL mode to INSERT before the current character.
Use a in NORMAL mode to INSERT after the current character.
Use A in NORMAL mode to INSERT after the end of line.
Use o in NORMAL mode to INSERT below the current line.
Use O in NORMAL mode to INSERT above the current line.
Operations and Navigation
ctrl + rfollowed by_Insert content of register. Replace_with name of register.ctrl + rfollowed by=Expression register. Enter expression to evaluate and insert.ctrl + kfollowed by__Insert digraph. Replace__with digraph code.ctrl + aInsert last content that was inserted.ctrl + @Insert last content that was inserted.ctrl + hDelete character before cursor.ctrl + wDelete word under cursor.ctrl + uDelete everything before cursor.ctrl + tAdd indentation.ctrl + dRemove indentation.ctrl + vfollowed by_Insert character. Replace_with character literal. Equivalent toctrl + qfollowed by_.ctrl + gfollowed byuSplit undo sequence.ctrl + xfollowed byctrl + yScroll up.ctrl + xfollowed byctrl + eScroll down.ctrl + xfollowed byctrl + lWhole line completion.ctrl + xfollowed byctrl + fFile name completion.ctrl + xfollowed bysSpelling suggestion.ctrl + xfollowed byctrl + vCommand-line completion.ctrl + xfollowed byctrl + iPath pattern completion.
Visual Mode
Modify, edit or copy selection.
Use v in NORMAL mode.
Use shift + v in NORMAL mode to activate VISUAL LINE mode.
Use ctrl + v in NORMAL mode to activate VISUAL BLOCK mode.
Use ctrl + q in NORMAL mode to activate VISUAL BLOCK mode.
Use gv in NORMAL mode to select the last selection made using VISUAL mode.
Operations
oMove to other end of selection. In VISUAL BLOCK mode.OMove to other side of selection. In VISUAL BLOCK mode.RRewrite selection. Equivalent toSSubstitute selection.UUppercase selection.IInsert at start of selected line.AAppend at end of selected line.cSubstitute selected lines.