vimtricks.wiki Concise Vim tricks, one at a time.

How do I select or operate on a block of code based on its indentation level?

Answer

ii / ai / aI (vim-indent-object)

Explanation

vim-indent-object (by Michael Smith) adds text objects that select code blocks based on indentation level rather than brackets or syntax. ii selects all lines at the same indent level as the current line, ai includes the line above (like a header), and aI includes lines above and below. This is perfect for Python, YAML, CoffeeScript, and any language where indentation defines structure.

Text objects

Object Selects
ii Inner indent block — lines at the same level
ai Above + indent block — includes the line above (e.g., function def, if statement)
aI Above + indent block + line below (e.g., includes closing line)

Install with: Plug 'michaeljsmith/vim-indent-object'

Example

def greet(name):
    msg = f"Hello {name}"
    print(msg)        # cursor here
    return True

def other():
    pass

With cursor on print(msg):

  • vii selects the 3 indented lines (msg = ..., print(...), return True)
  • vai selects those 3 lines PLUS the def greet(name): line above
  • dai deletes the entire function

Works with operators

  • dii — delete the indent block
  • cii — change (replace) the indent block
  • yai — yank the block including its header line
  • >ii — indent the block one more level
  • <ii — unindent the block

Tips

  • Handles blank lines within an indent block — they do not break the selection
  • Works with any indentation style (tabs or spaces) and any indent width
  • Essential for Python where brackets do not define scope
  • Combine with vim-textobj-user to create your own custom text objects using the same framework

Next

How do I run a search and replace only within a visually selected region?