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

How do I auto-indent a block of code in visual selection without specifying a line range?

Answer

vip=

Explanation

Pressing = in visual mode re-indents all selected lines according to the current filetype's indent rules — the same engine used by == for a single line, but applied to the whole selection. The combo vip= selects the current paragraph (a function body, block, etc.) and fixes its indentation in one motion.

How it works

  • v enters character-wise visual mode
  • ip selects the inner paragraph (contiguous lines without blank line gaps)
  • = triggers the indent operator on the visual selection, reindenting all lines according to 'indentexpr', 'cinindent', or 'smartindent' settings

Example

Before (misaligned Python/Lua/JavaScript block):

function greet(name) {
  console.log("hi");
      if (name) {
console.log(name);
    }
}

With cursor anywhere inside the block, press vip=:

function greet(name) {
  console.log("hi");
  if (name) {
    console.log(name);
  }
}

Tips

  • =ap (in normal mode) achieves the same result — a paragraph includes surrounding blank lines
  • gg=G re-indents the entire file from top to bottom
  • =i{ re-indents everything inside the nearest {} block (great for functions)
  • The quality of = depends on the filetype plugin; it is most reliable for C-family languages, Python, Lua, and Vim script
  • Use > and < for manual indent adjustments when = would change semantics (e.g., in languages where indentation is significant like Python with unusual constructs)

Next

How do I search for and highlight text that exceeds a specific column width like 80 or 120?