vim-indent-object is a great Vim plugin that adds an i text object for an indented block of text, very useful in Python!

  • vii selects all lines at the same indentation level as the current line.

    For example just the body of a method and not the method signature or any empty lines below the method. Or just the body of a try clause and not the try line itself.

  • vai selects all lines at the same indentation level as the current line, and the first unindented line above the indented block (e.g. the method signature, if the indented block is a method, or the try if the indented block is a try clause, etc).

    This also selects any blank lines below the indented block, if it’s followed directly by empty lines.

  • vaI selects an indentation level and both the unindented line above and the unindented line below it.

    For a method this will select the method’s signature (unindented line above) and the signature of the next method below (unindented line below) (as well as any empty lines between the two methods).

    For a try clause it’ll select both the try above and the first except below (but not the body of the except clause).

  • In visual mode you can keep repeating one of the above mappings to keep extending the selection to more and more text at higher and higher indentation levels. For example:

    vii (goes into visual mode and selects the body of a try clause), ii (widens the selection to the entire method), ii (widens the selection again, to the entire class body), ii (widens the selection to also include the class signature). After this, further ii’s start selecting lines and blocks above the class.

You can combine the ai, ii and aI text objects with other operators besides v for visual mode, e.g. cii, dii, yii etc. For example >ii or <ii will indent or dedent an indented block. If you have vim-commentary installed then gcii will comment out an indented block.

All posts tagged “vim”: