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

How do I fix the indentation of a code block without affecting surrounding code?

Answer

=i{

Explanation

When editing code with messy indentation — after a paste, a merge conflict, or a refactor — you often need to fix just one block rather than the entire file. The = operator combined with the i{ text object reindents everything inside the current pair of braces, leaving surrounding code untouched.

How it works

  • = is Vim's auto-indent operator, which reformats text according to the current indentexpr or built-in indent rules
  • i{ is the "inner braces" text object, selecting everything between { and } (not including the braces themselves)
  • Combined, =i{ reindents only the contents of the nearest enclosing {} block
  • The cursor can be anywhere inside the block

Example

Before (cursor anywhere inside the function body):

func main() {
fmt.Println("hello")
    if true {
  fmt.Println("world")
        }
}

After pressing =i{:

func main() {
    fmt.Println("hello")
    if true {
        fmt.Println("world")
    }
}

Tips

  • Use =a{ to include the braces themselves in the reindent
  • Works with other block delimiters: =i( for parentheses, =i[ for brackets
  • For HTML/XML, use =it (inner tag) to reindent tag contents
  • Chain with >i{ or <i{ to shift indent level instead of auto-fixing it
  • Set filetype indent on in your vimrc for language-aware indentation rules

Next

How do I ignore whitespace changes when using Vim's diff mode?