VimTrick: Indenting code
A quick primer on keeping code neat and tidy in Vim
Vim provides == and = as tools to aide in keeping your code formatted and tidy. Double equal can be used to quickly properly indent the current line. Similarly, 10== will indent 10 lines, inclusive of the one you’re one.
Consider this Ruby method, painful to look at it because the indentation is all over the place:
def longest(strings)
strings.sort(&:length)
.last
endWith our cursor on the d in def, we want to change this method into:
def longest(strings)
strings.sort(&:length)
.last
end
There are a few options to achieve the same result:
4==will indent the current line, and the next three.=apwill indent around the current paragraph. Having no empty lines, this method qualifies as a paragraph.=%will indent to the the end of the method. Note this implies the use of the matchit plugin. But%works with common curly brace blocks, parens, etc out of the box.V3j=will do a visual select on the current line and the three below and apply indenting to them.
These cover a lot of ground when trying to keep your code tidy.
Lastly, the nuclear option gg=G can be used to indent an entire file.
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote:


To add on: oftentimes people lose where they were after they use gg=G. Another nice trick would be to save your current position in a mark first (, say, "mx"), then "gg=G", then jump back to mark with "`x" (that's a back-tick). Note that x can be any letter.
I think the usefulness of this varies on the language. In most cases you are better of setting up an LSP if able, setting formatexpr, and using gq.