Vim: Having a look at vib

In the previous command of the day post, we were acquainted with the command ciw, which we could use to quickly replace words.

Today we are going to have a look at the concepts behind the command vib, and its closely related cousins, viB and vi". At the end of the post, we are going to combine the lessons learned in this post with the lessons learned in the mentioned command of the day post.

Similarly to ciw, the vib command is technically speaking a composition of two commands, v and ib. The command v puts us in Visual Mode, and ib makes a text-object selection, selecting an inner () block.

Put less technically: the vib command selects everything in between a set of matching parentheses.

Say we have the following line of code:

bool solveWorldProblems(Nation* nations, |Problem* problems);

Where the pipe-sign (|) represents our cursor. Using the vib command here, we would select:

Nation* nations, Problem* problems

Note that our parentheses are not included in the selection.

We can expand on this simple command by varying the value of the last character in our command. As we just noted, the ib command makes a text-object seclection, selecting the inner parts of a set of matching parentheses. Vim, of course, supplies many different text-object selections which we can use to select different chunks of text. For instance:

viB: Selects everything within a {}-block

vi": Selects everything within a ""- block

vi[: Selects everything within a []- block

If we want to make our selections include the enclosing block (say, the parentheses' in vib), we would only have to change the i in all our commands with a: vab selects everything inside and including a set of matching parentheses, vaB selects everything inside and including a set of matching curly-brackets, and so on.

In the previously mentioned command of the day post, we learned about the command c (in combination with the selection iw), which changes a selection; that is, it removes the selection and jumps into insert mode at the start of the selection. We can of course combine the text-object selections we have just learned with the command c, or indeed any other command we might deem feasible.

Running the command ciB would remove everything inside a set of matching curly-brackets, and then put us in insert mode at the start of the opening curly-brace. Similarly, running the command yib would yank (copy) everything inside a set of matching parentheses.

On the other hand, we can also (correctly) deduce that viw would select an inner word.

I often use the command ci" and ci', which changes everything within double- or single-quotation strings, respectively. Also handy are commands such as diB, which can be used to clear everything inside a set of matching curly-brackets.

For a complete reference of text-objects that can be used for selections, see this link.