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):
viiselects the 3 indented lines (msg = ...,print(...),return True)vaiselects those 3 lines PLUS thedef greet(name):line abovedaideletes the entire function
Works with operators
dii— delete the indent blockcii— change (replace) the indent blockyai— 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-userto create your own custom text objects using the same framework