Vim 101: Visual Mode

Hint: To make your Vim look the same as my screenshots, download usevim-vimrc and run Vim with vim -u usevim-vimrc.

In a typical GUI editor, a block of text can be selected by clicking the mouse and dragging over a number of lines or characters. Vim introduced Visual mode which allows us to reuse the motion commands and operators that we've learned to manipulate blocks of text.

When in Normal mode, press v to start making a selection. The arrow keys or good ol' hjkl can be used to make a selection:

Visual mode

If you make a mistake during highlighting, pressing <Esc> will stop it and return to Normal mode.

Typing gv will switch back into Visual mode with the last selection. This is incredibly useful when another operation needs to be applied to the previous selection. Prefixing v with a number will reselect the last selection, but will multiply the length of the selection by the number. In the example below I've made a selection, pressed <Esc>, then typed 3v:

Visual mode with numbers

While making a selection, pressing o will go to the other end of the visual selection. I find myself using this a lot when I need to quickly make a small change to a selection:

Visual mode with numbers

All of the motion commands you're familiar with will work as well. For example, pressing w will select words, pressing 9k will select nine lines up from the current cursor positions.

Operating on Selections

As we saw in Vim 101: Registers, yanking blocks of text from Visual mode is extremely useful. However, there's more! Once a selection has been made, there are several operators that can be applied. For example, pressing ~ will switch the line's case, and ! can be used to filter the selection through an external command.

I find myself typing < and > all the time -- these shift the text left or right, which is great for correcting code indentation.

Another important thing to master is pressing : to enter Ex commands. Making a selection with v then pressing : and entering a regular expression is a good way to limit the effects of a regular expression to a block of text.

To read about all of the operators and commands that can be applied to blocks, take a look at :help visual-operators.

blog comments powered by Disqus