Vim
Comands
- Replace tabs with spaces:
:retab - Make and source session file to restore vim state.
- Make (create):
:mks session.vim - Source (restore):
vim -S session.vimor:source session.vim
- Make (create):
- Change case:
gU(to uppercase) orgu(to lowercase) followed by a movement. :nohclear highlighting.:g/^/m0reverse all lines./[^\x00-\x7F]find non-ascii characters.- Multiline editing:
C-vVisual-block mode; Highlight area;IMultiline Insert. Can also highlight multiple lines and then user:normalcommand to apply normal commands to the selection. iSwitch to edit mode, insert before cursor (aInsert after cursor;IStart of line;AEnd of line;oInsert new line after;OInsert new line before).:sortSort all or Visual selection.:[r]s/foo/bar/[a]Replace. (e.g.:%s/foo/bar/greplace all 'foo' with 'bar'); Add 0 prefix to all lines beginning 2-9::%s/^[2-9]/0&/g; Replace double-space with tab:%s/ /\t/g. Remove carriage returns (^M):%s/^M//g(UseC-QC-Mto enter^M).[r]Range:nothingCurrent line;numberLine to change;%Entire file.[a]Arguments:nothingReplace first occurrence;gReplace all occurrences;iIgnore case;IDon't ignore case;cConfirm (y,nto skip this match,aAll,qQuit substitution).suses\rto represent newline character. To put a new line before "rate"::%s/"rate"/"tier_from": "0",\r "rate"/g
- Activate spell checker (en-uk by default):
:set spell. Usez+=in command mode to get correction suggestions. - Disable smart indentation:
:set paste; Re-enable::set paste!. - Vim help: Follow link with
C-]. Find links with/](.\{-}]( - Multiple Files:
- Open multiple files at once:
vi *.json - Show current buffers:
:ls - Add another file:
:arga(or remove/delete one with:argd) - Run command on all files:
:argdo [command](e.g. change cmd to command and save withargdo %s/cmd/command/ge ]( w) - Tabs:
:tabe [filename]New tabWith;gtNext tab;gTPrevious tab. - Split screen:
:sp [filename]Open new split;C-wthenwFor next split;Wfor previous split.
- Open multiple files at once:
.Replay last command. For more than one command use macros.- Recording Macros:
qStart macro-recording. Next0-9a-zA-Zis macro/buffer name (q1records the macro to buffer "1").qagain ends the recording. Replay the macro at any time using@1. - Convert a dos/windows file (with CRLF/x0d0a line endings) to unix (Check file format with
:set ff? ffs?)::e ++ff=dosEdit as dos file (if not doing so already).:setlocal ff=unix:w
- Delete all lines:
- Which do not contain
{{::v/{{/d. Variant of:[range]v[global]/{pattern}/[cmd]. - Matching pattern:
:g/[pattern]/d(e.g.:g/@login_required/d). - Which do not begin with
-::g!/^[-]/d
- Which do not contain
- Save readonly file as root:
:w !sudo tee %. - Command history: Enter
:or/and use up and down arrows to navigate history. Command line window: Typeq:for commands, orq/for searches;C-c C-cto exit. History is stored in~/.viminfo, if no history is found then check you have update access to that file as it may have been created byroot. /Search forwards;?Search backwards;nNext match;NPrevious match.:%s/[pattern]//gnCount matches in file.*Search for word under cursor (#Reverse search).:g/[pattern]/#Find all occurrences.:browse oldList recently opened files.uUndo the last action (UUndo all the latest changes that were made to the current line;C-rRedo).vSelect block by character (VBy line;C-vBlock visual mode).- On selected text:
~Changecase. (>Shift right;<Shift left;cChange the highlighted text;ccChange line;yYank;yyYank line;dDelete;ddDelete line;pPaste after;PPaste before;"_dDelete and place in black-hole_register to reserve what had been yanked before). - In Edit mode:
C-tIncrease indent;C-dDecrease indent. 0Start of line;^First non-blank character of the line;wNext word;WNext word, ignore punctuation;eWord-end;EWord-end, ignore punctuation;bWord-beginning;BWord-beginning, ignore punctuation;gePrevious word-ending;gEPrevious word-ending, ignore punctuation;g_Last non-blank character of the line;$Last character of the line.GGo to end of file;:1Start of file;:[n]Line number;HFirst line of the screen;MMiddle line of the screen;LLast line of the screen.:![command]Run external command::![command] %Filter file through external command.:r![command]Insert command output.:%!xxdRun file through hexdump filter (:%!xxd -rConvert dump from hex back to binary).
:e .File explorer (:SexOpen explorer in new window):set nuShow line numbers;:set nu!Hide line numbers.
Completion
While you are typing, it's pretty common to use the same word over and over again. Using C-p Vim searches the currently typed text backwards for a word starting with the same characters as already typed. C-x C-l completes the whole line.
If you're not sure how to type some word and you've enabled spell-checking (:set spell), you can type C-x C-k to do a dictionary lookup for the already typed characters.
Use ^n and ^p to go back and forth in the suggestion list:
^x^nfor JUST this file^x^ffor filenames^x^]for tags only^x^lwhole line^nfor anything specified by thecompleteoption
Buffers and Windows
:b [N]Switch to buffer[N].:lsor:buffersShow buffer list. Explanation:%Current window.#Alternate buffer (switch using:e#or:b#).aActive (loaded and visible).hHidden (loaded but not visible).+Modified.
:bdUnload the buffer and remove it from bufferlist (don't close Vim, even on the last buffer).:bununload the buffer but stay in bufferlist.:sp [N]split current window and edit buffer[N].:wWrite the current buffer to disk.:e fileLoad a file from disk.:qCloses current window (and Vim if it's the last one).:newNew empty window.:onclose all windows but the active one (C-w o).C-wandh j k lMove between windows.C-w =equalise window sizes.
Marks
Vim automatically sets various marks like
0-9Last 10 positions of closed files (0the last,1the last but one).<and>Left and right position of marked texts.(and)Start or end of the current sentence.{and}Start or end of the current paragraph.[and]First or last character of the last yanked or changed text..Last change.'or`Position before the last jump."Position before the last exit of the file (local to a file).^position of the last insert-stop.
To set a manual mark, use m[a-zA-Z]. To jump to one of the marks (manual or automatic) you can choose between ' and `:
'Sets the cursor to the first non-blank character in the marked line.`Sets the cursor to the exact position where the mark was set.
There is a little difference between lower-case and upper-case characters:
a-zAre local to a file.A-ZAre stored and available over sessions (associated with a file).
You can use L for your work-log and T for your time-table for example, and quickly update the information there.
For example you can jump to the last known position of a file before it was closed by typing `" (it's easy to configure Vim to do it automatically at start).
To get a list of all marks Vim knows about type :marks. To delete marks use :delmarks (:delmarks a b c removes marks a and b and c, to delete all marks use :delmarks!).
vimdiff
vimdiff file1 file2 highlights differences between files.
Commands
]cjump to next change ([cprevious change).:diffget [buffer_id]replace current change with equivalent in other buffer.C-W C-Wswitch to the other buffer.:diffupdaterefresh display.:colorscheme eveningchange colours.:lslist buffers.zoopen folded text.zcclose folded text .:syntax off- If using only two buffers:
doget change from other buffer.dpput the changes from current buffer into the other.