- Last update:

Vim Tricks

A few tricks for Vim that I have learned over all my years of using this incredible tool.

🕒 4 min read

Category: Linux

Tags: vim, vi, linux

Left-right and up-down motions

Text objects motions

Text objects (only in visual mode or after an operator)

Copying and moving text / Inserting text

Examples

General rule: [optional number to repeat]{command}{text object or motion}.

Registers

Autocomplete (in insert mode)

(^n is disabled by YouCompleteMe.)

Regex

Interactive find and replace

:%s/foo/bar/gc

% means whole document, not just the current line.

/g means every occurence, not just the first one. /c is the interactive option.

Capturing groups

:%s/abc\(def\)ghi/ko\1ok/g

Will print kodefok.

Normally, to search in a non-greedy way, we add a punctuation mark, as in .*? which means any string of characters as short as possible. For instance:

/<.>(.*?)<.>/

Applied to the string abc<p>def<a>ghi<b>jkl would match <p>def<a> and capture def. To make non-greedy searches with Vim, replace *? with \{-}.

Misc

Split the screen in half and display two different parts of a given file

:vsp
:set scrollbind

Then, on the right pane, scroll down or up, further in the file, and do:

:set scrollbind

From that point on, as you scroll on one pane, the other one will follow. To undo:

:set noscrollbind

Other

Useful links