Vim Tip of the Day: Selecting Things

Although you can do a lot just with verbs like c, d, and y combined with the various nouns, you may often want to get visual feedback prior to making changes. For this purpose, use v just like you would use a verb, i.e. along with a noun, to (v)isually select the area first (e.g. vis). Then hit c/d/y/whatever to do the operation on the selection.

But visual mode isn’t just for feedback. By allowing you to indicate arbitrary pieces of text, it enables you to bypass Vim’s linguistic facility to directly indicate an underlying Vim noun (i.e. a range). So it’s also a recourse for whenever something can’t be expressed in a simple linguistic way.

  • v — visual mode (for arbitrary selection)
  • V — visual line mode (select by line instead of by cursor)
    • Useful for reliably copying blocks of text, e.g. functions or anything longer than a line. I tend to use this about as often as or more often than v.
  • C-v — visual block mode (select by XY coordinates)
    • Very useful, e.g. to add something at the start of or at the same position in every selected line. Has some overlapping usecases with multiple-cursors in other editors. I have seen even experienced vimmers be amazed by the things you can do with visual block mode.

Once in visual mode, you can expand the selection by using any combination of nouns (e.g. ap, j }), and in either direction by using o to switch to the (o)ther end.

Visual mode is more expressive than normal linguistic editing, but at the cost of fluency. You could manually select the text inside a delimiter to delete it but it’s better to say dib (or vibd, for feedback) instead. It should be used not as a crutch but as a recourse and an aid.

Leave a Reply

Your email address will not be published. Required fields are marked *