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

How do I auto-indent a block of code using visual mode?

Answer

=

Explanation

Pressing = in visual mode auto-indents the selected lines according to Vim's built-in indentation rules. This is one of the fastest ways to fix messy indentation without manually adding or removing tabs and spaces.

How it works

  • Select the lines you want to re-indent using any visual mode (v, V, or <C-v>)
  • Press = to trigger the indent operator on the selection
  • Vim recalculates the proper indentation based on the current filetype, indentexpr, or cindent settings and adjusts every selected line

The = operator is not just a formatter — it understands code structure. In C-like languages it respects brace nesting, in Python it follows indentexpr rules, and in HTML it nests tags correctly.

Example

Given badly indented code:

function greet(name) {
const msg = "Hello, " + name;
    if (msg) {
console.log(msg);
}
}

Select all lines with ggVG, then press =:

function greet(name) {
	const msg = "Hello, " + name;
	if (msg) {
		console.log(msg);
	}
}

Every line is now correctly indented based on its nesting level.

Tips

  • Use gg=G to re-indent the entire file without entering visual mode — gg goes to the top, =G indents from cursor to the last line
  • =ap re-indents the current paragraph (block of code separated by blank lines)
  • =% re-indents from the current line to the matching bracket — perfect for fixing a single function or block
  • == re-indents just the current line
  • 5== re-indents the current line and the next 4 lines
  • Use > and < in visual mode to shift indentation left or right by one shiftwidth instead of auto-calculating
  • Make sure you have filetype indent on in your vimrc for language-aware indentation
  • If the results look wrong, check :set indentexpr? and :set cindent? to see which indent method Vim is using for the current file type

Next

How do I edit multiple lines at once using multiple cursors in Vim?