Ensuring aligned indentation
If you are writing code in Vim and you care about your code’s alignment, Vim has a setting you probably want to be using called shiftround. With :set shiftround enabled, Vim will round the indents to a multiple of shiftwidth when using the > and < commands:
set shiftround– Rounds the indent spacing to the next multiple ofshiftwidth
You may already know about > and < to indent and outdent the current line, or multiple lines:
>– Indent current line or selected lines<– Outdent current line or selected lines
The number of spaces indented by this operation is determined by the shiftwidth setting. This setting is also honored by == and =, which we have written about in the past. For example, I write mostly Ruby and the Ruby community generally prefers 2 spaces, so that’s what I use:
set shiftwidth=2– Auto indent to two spaces
Now, back to shiftround. How is it useful? Let’s say I erroneously indented something 3 characters. Perhaps I pasted from somewhere else and didn’t line things up properly. Well, without shiftround enabled, using the > command to indent, will simply add 2 to the existing 3, leaving my indent still off by one character. With shiftround enabled, indenting with > will true things up again by indenting just one character.
Take a look at the demo below. In it, I have two sets of lines, each of which suffer from an off-by-one indentation issue. For the first one, I do not have shiftround enabled, and when I indent, it’s still off by one. For the second one, I first enable shiftround. Then, when I indent with >, the indent trues it up to the expected location: indented 6 spaces.