Tips of Vim

Vim is my preferred text editor, and I have installed the vim plugin in every IDE on my computer. With my extensive experience in using vim, I would like to share some useful tips with you.

Copy contents into system clipboard

Unlike conventional text editors, Vim uses a unique feature called "register" to store copied content. By default, when you use the y (yank) or p (paste) commands, Vim utilizes the default register. This can cause issues when trying to paste text from inside Vim to outside applications or when attempting to copy text in the opposite direction. To overcome this limitation, you can utilize the + register. Simply prefix your p or y commands with " followed by + to interact directly with the system clipboard.

Paste text in command-line mode

Typing the word you want to search or replace by hand in search/command mode can be quite annoying. Luckily, Vim provides a way to directly paste word in the command-line. First, copy the content you want to search/replace into a Vim register (use + register if the content to copy is from outside Vim). Then, type Ctrl + R + register-name to paste the content in that register into Vim command line.

If you simply want to paste a word under your cursor, try Ctrl + R + Ctrl + W.

Interactive string substitution

Vim enables global string substitution, but occasionally, unintended strings are replaced. For example, if you intend to replace the word bar with foo globally, a word like barbie would inadvertently change to foobie. To avoid this, you can append a c to the command.

For example, to interactively replace bar with foo, you can use the command :%s/bar/foo/gc.

substitute texts within visual selection

To substitute text within a visual selection, use following command after selecting the desired text:

:'<,'>s/\%Vpattern/replacement/g

Explanation of components:

  • :'<,'>: is automatically generated upon entering command mode (:) after making a visual selection.
  • %V: This modifier limits the substitution operation to the text that has been visually selected.