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

How do I quickly select an entire function body using visual mode?

Answer

Va{ or Vi{

Explanation

The a{ (around braces) and i{ (inside braces) text objects combined with visual mode let you instantly select an entire function body or code block, regardless of how large it is.

How it works

With your cursor anywhere inside a function:

Vi{    " Linewise select everything inside the nearest { }
Va{    " Linewise select including the { } delimiters
vi{    " Characterwise select inside braces
va{    " Characterwise select including braces

Example

func processData(input []byte) error {
    decoded := decode(input)
    if decoded == nil {
        return fmt.Errorf("invalid input")
    }
    return save(decoded)
}

With cursor on decoded, pressing Vi{ selects:

    decoded := decode(input)
    if decoded == nil {
        return fmt.Errorf("invalid input")
    }
    return save(decoded)

Expanding the selection

You can keep pressing a{ to expand to outer blocks:

vi{       " Select inside inner braces (if block)
v2i{      " Select inside outer braces (function body)
a{        " While in visual mode, expand to include the braces

Works with all block types

Vi(    " Select inside parentheses (function arguments)
Vi[    " Select inside square brackets (array contents)
Vi<    " Select inside angle brackets (template parameters)
Vit    " Select inside HTML/XML tags

Tips

  • V before the text object forces linewise selection — usually what you want for code blocks
  • After selecting, use y to yank, d to delete, = to re-indent, or > to indent
  • va{V selects around braces and switches to linewise mode to include the closing brace line
  • This works with any brace-based language: C, Go, JavaScript, Rust, Java, etc.

Next

How do I run the same command across all windows, buffers, or tabs?