One of Vim’s goals is making repetitive tasks easier, and core knowledge of the vim editor can be just as important as a good plugin to achieve that goal. Today we’re going to look at a simple plugin and then take a look at quickly doing repetitive tasks in vim using the dot operator.
This plugin gives you the `\’ operator (an operator is like ‘d’elete, ‘c’hange, ‘y’ank, etc) to comment blocks of code.
- e.g. to comment the line you’re on, `\'
- e.g. to comment the paragraph you’re in, `\ap’ (comment a paragraph)
It’s written by tpope, so you know it’s got to be good. If you’ve got Pathogen set up, just
`git submodule add https://github.com/tpope/vim-commentary bundle/commentary’
Think about the commands you use and how repeatable they are.
Suppose you had the line:
%w(red green yellow blue orange brown black indigo)
with the cursor on the ‘g’ in green, and you want to remove the items green, yellow, and blue.
You could quickly do this a few ways:
- d3w (delete 3 words)
- 3dw (3 times delete a word)
- (delete word, repeat twice)
These are all functionally equivalent, but there are a few differences:
- both `d3w’ and `3dw’ are one unit of work; hitting `u’ will undo all the changes
- it’s trivial in this case, but you have to count to know it’s 3 words you want to delete
- `dw’s unit of work is deleting one word and repeating the last command twice
The `dw..’ pattern is generally more reusable. Imagine that the sentence was an English list:
My favorite colors are red, orange, green, yellow, blue, and red.
and you wanted to remove orange, green, and yellow. `d2w..’ will let you delete the word and the comma, and then repeat. If you overshoot, `u’ un-does the last command. To me that’s easier than thinking “3 items * 2 because of the comma => d6w”.
Another example involves doing an interactive search and replace. Let’s start with a code block:
and lets say we wanted to replace all .save commands with .save!. It’s really only two things that are going on: find a token, make a change. We already know / can search and that n and N will cycle through results. Armed with knowledge of the dot operator, we can:
- /save(our re-usable search)
- cwsave!(our re-usable mutation)
- n. (to move us to the second .save and repeat the command
- nn. (to skip the save in Supersave but replace the save at the end of the line
In this example, you might say that the substitute operation (s/.save/.save!/) would be more appropriate, but you don’t have the flexibility to granularly skip instances or undo/redo single substitutions; the substitution command does everything in one unit of work.