Vim Tricks

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

🕒 1 min read

Category: Linux

Tags: vim, vi, linux

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.

Non-greedy search

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

Useful links