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

How do I auto-indent an entire file in Vim?

Answer

gg=G

Explanation

The gg=G command re-indents every line in the current file according to Vim's indentation rules. It is the fastest way to fix inconsistent indentation across an entire file.

How it works

  • gg moves the cursor to the first line of the file
  • = is the indent operator — it adjusts indentation based on filetype rules
  • G is a motion to the last line of the file

Together, gg=G tells Vim: "from the first line to the last line, fix the indentation."

Example

Given the poorly indented code:

function greet() {
const name = "Vim";
    if (name) {
console.log(name);
}
}

Pressing gg=G reformats it to:

function greet() {
    const name = "Vim";
    if (name) {
        console.log(name);
    }
}

Tips

  • The indentation style depends on your filetype, shiftwidth, and expandtab settings
  • Use == to auto-indent just the current line
  • Use =ap to auto-indent the current paragraph
  • In visual mode, select a range of lines and press = to re-indent only the selection
  • Use =i{ to auto-indent everything inside the current curly brace block
  • Make sure filetype detection is enabled with :filetype indent on for best results

Next

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