How do I make Vim's indent commands always align to a clean shiftwidth boundary?
Answer
:set shiftround
Explanation
shiftround causes indent commands (>, <, and their visual equivalents) to round the indentation level to the nearest multiple of shiftwidth rather than adding or subtracting a fixed number of spaces. This keeps indentation on clean column boundaries, especially useful when editing code with mixed or inconsistent indentation.
How it works
- Without
shiftround:>always adds exactlyshiftwidthspaces to whatever indentation the line already has - With
shiftround:>rounds up to the next multiple ofshiftwidth;<rounds down - Applies to
>>,<<,>/<with motions, and visual indent operations
Example
With shiftwidth=4 and shiftround enabled:
Before: 6 spaces of indentation
After `>`: 8 spaces (rounded up to next multiple of 4)
After `<`: 4 spaces (rounded down to previous multiple of 4)
Without shiftround those would become 10 and 2, breaking alignment relative to surrounding code.
Tips
- Add to your vimrc alongside your tab settings:
set shiftwidth=4 shiftround - Particularly valuable when working in mixed-indentation codebases where some lines start at odd column positions
- Works correctly even with
expandtabenabled (operates on soft spaces, not hard tabs)