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

How do I select an entire code block from opening brace to closing brace in visual mode?

Answer

V%

Explanation

Pressing V% enters visual line mode on the current line and immediately extends the selection to the line containing the matching bracket or brace. This lets you select a whole function body, if block, or any bracket-delimited structure with just two keystrokes.

How it works

  • V — enters visual line mode, selecting the current line
  • % — the match-bracket motion: jumps to the matching (, ), {, }, [, or ]
  • Combined, the visual selection grows from the current line to the line with the matching delimiter

The cursor must be on a line that contains an opening (or closing) bracket for % to find its pair. If the line has multiple brackets, % matches the first one it finds under or after the cursor.

Example

With the cursor on the func line:

func calculate(x int) int {
    if x > 0 {
        return x * 2
    }
    return 0
}

Press V% to select all six lines (from func through the closing }).

Tips

  • After selecting, you can d to delete, y to yank, > to indent, or gc to comment (with vim-commentary)
  • If the cursor is on the closing brace, V% selects backwards to the opening brace
  • % is also a valid standalone motion: use d% to delete from cursor to the matching bracket
  • To select only what is inside the braces (excluding the brace lines), use vi{ instead

Next

How do I run a shell command on a range of lines in normal mode and replace them with the output?