How do I re-indent a block of code to match the surrounding indentation?
Answer
=i{ or =ap
Explanation
The = operator performs smart indentation based on Vim's filetype-aware indent rules. Combined with text objects, it re-indents code blocks to match the surrounding context — no manual counting of spaces needed.
How it works
=is the indent operator- Combine it with any motion or text object
- Vim uses the
indentexprorcindentrules for the current filetype
Common patterns
=i{ " Re-indent everything inside the current braces
=ap " Re-indent the current paragraph
=G " Re-indent from current line to end of file
=i( " Re-indent inside parentheses
=at " Re-indent around an HTML/XML tag
== " Re-indent the current line
5== " Re-indent 5 lines
Example
Before (pasted with wrong indentation):
function process() {
const x = 1;
if (x > 0) {
return x;
}
}
Place cursor inside the braces, press =i{:
function process() {
const x = 1;
if (x > 0) {
return x;
}
}
Tips
gg=Gre-indents the entire file — one of Vim's most popular commands- The indent rules depend on your filetype settings:
:set filetype?to check - For C-like languages,
cindenthandles most cases automatically - Use
>and<for manual indent/dedent when smart indent isn't appropriate - Works in visual mode: select lines, press
= - Set
shiftwidthto control the indent step size::set shiftwidth=4