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
ggmoves the cursor to the first line of the file=is the indent operator — it adjusts indentation based on filetype rulesGis 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, andexpandtabsettings - Use
==to auto-indent just the current line - Use
=apto 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 onfor best results