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, orcindentsettings 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=Gto re-indent the entire file without entering visual mode —gggoes to the top,=Gindents from cursor to the last line =apre-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 line5==re-indents the current line and the next 4 lines- Use
>and<in visual mode to shift indentation left or right by oneshiftwidthinstead of auto-calculating - Make sure you have
filetype indent onin 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