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

How do I visually select a code block enclosed in curly braces including the braces themselves?

Answer

vaB

Explanation

The aB text object (around Block) selects everything from the matching { to the closing } — including the braces themselves. It is the most natural text object for selecting function bodies, class definitions, if-blocks, and any other {}-delimited structure in code.

How it works

  • v enters Visual mode
  • aB selects around Block — the contents of the nearest enclosing {...} plus the braces
  • iB (inner Block) selects only the contents, excluding the braces themselves
  • B is case-sensitive: uppercase B means {}, while lowercase b means () (parentheses)
  • The cursor can be anywhere inside the block, not just on the brace
  • Works in Normal mode: daB deletes the block, caB changes it, yaB yanks it

Example

function greet(name) {
    console.log('Hello, ' + name);
    return true;
}

With the cursor anywhere inside the function body, vaB selects everything from { to } (inclusive). diB deletes just the body lines, leaving the empty braces.

Tips

  • Use 2vaB (with a count) to select the next outer enclosing block when blocks are nested
  • Combine with : to run an Ex command on the block: after vaB, type :normal I// to prepend // to every selected line
  • =aB (in Normal mode) auto-indents the entire block — handy after pasting code from elsewhere
  • vaB works for any curly-brace language: C, JavaScript, Go, Rust, etc.

Next

How do I run a search and replace only within a visually selected region?