Movin' and Shakin'

Gabe Berke-Williams

Time for some self-VIMprovement! As you might know, the thoughtbot crew uses Vim a lot (one, two, and three).

I sit next to Ben and Mike, two great Vim users, and I learned a lot just from being around them. I’ve said before that I could probably sell our conversations as an advanced Vim book. Movements are just one of the concepts that has improved my Vimming. Note that in my Vim examples, I’m performing each motion with my cursor on the beginning of the phrase.

Movements are a key part of using Vim effectively. Vim commands function as simple phrases, e.g. “change this word” or “delete until end of line”. I knew the verbs, but didn’t know how to complete the phrase: dd (delete current line) and yy (yank current line) were my mainstays. To delete 4 characters, I’d hit x 4 times in a row. Turns out there’s a much better way: motions!

You see, d and y are the verbs: “delete” and “yank”. They need to know what to delete or yank. And that’s where motions come in. They offer fine-grained control over verbs so you can yank a single word, or an entire paragraph (or method block).

t and f are two of my most frequently used motions. t means “‘til” and performs the action 'til a given character. So dtl turns “hi darling” into “ling”. f can be thought of as “first occurrence”. It deletes up to and including a given character, so one character more than “t”. So dfl turns hi darling into ing. T and F do the same thing as t and f, except backwards. So dTa deletes backwards til a, while dFa deletes backwards up to and including the a.

I recently learned about the even more useful i and a motions. i means “inside” and unsurprisingly it moves inside characters. For example, given (hello world), di( from anywhere inside the parentheses deletes inside the parentheses and gives you (). It erases the text inside the parentheses, but not the parentheses themselves.

a means “around” and it’s kind of like the f to i’s t, in that a includes a bit more characters than “i” does. So da( changes “(hello world)” into “” (an empty string). To delete a paragraph, use dap. In code, a paragraph means a method definition - so you can delete entire method definitions with three keys!

For more on motions, check out the official documentation: :help navigation. It can tell you about the motions (like a) as well as the “noun”, like the p in dap.

And don’t forget about the first Boston Vim Meetup on October 24th!