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

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 indentexpr or cindent rules 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=G re-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, cindent handles most cases automatically
  • Use > and < for manual indent/dedent when smart indent isn't appropriate
  • Works in visual mode: select lines, press =
  • Set shiftwidth to control the indent step size: :set shiftwidth=4

Next

How do I run the same command across all windows, buffers, or tabs?