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

How do I reindent a block of code using a visual selection?

Answer

= (in visual mode)

Explanation

After making a visual selection, pressing = applies Vim's auto-indent to every selected line at once. This is the most precise way to fix indentation for a specific region without touching the rest of the file — no need to select the whole buffer or manually adjust each line.

How it works

  • = is the indent operator in normal mode; in visual mode it becomes an immediate action on the selection
  • Vim uses the indentexpr (language-aware) or cindent/autoindent rules depending on your filetype settings
  • The selection can be character-wise (v), line-wise (V), or block-wise (<C-v>) — in practice V (linewise) is most useful here
  • The cursor returns to the first line of the selection after the operation

Example

Starting with badly indented Python:

def greet(name):
print(f"Hello, {name}")
        return None

Select all three lines with Vjj, then press =:

def greet(name):
    print(f"Hello, {name}")
    return None

Tips

  • Use =ip (no visual needed) to reindent the current paragraph — the = operator accepts any motion
  • == reindents just the current line
  • gg=G reindents the entire file (equivalent to selecting all and pressing =)
  • If the result looks wrong, Vim may be using the wrong filetype — run :set filetype=python (or your language) to correct it

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?