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

How do I restrict a search to the current function body?

Answer

:[{,]}s/old/new/g

Explanation

By using the range [{,]}, you can limit a substitute command to the lines between the enclosing braces — effectively the current function or block.

How it works

  • [{ is a motion that goes to the enclosing {
  • ]} is a motion that goes to the matching }
  • Using them as a range with : restricts the substitute

Example

function foo() {
    let x = 1;
    let y = x + 1;
}

function bar() {
    let x = 2;
}

With the cursor inside foo, running :[{,]}s/x/z/g replaces x with z only inside foo.

Tips

  • This works with any brace-delimited block
  • For more precision, select the range visually first
  • vi{ selects the inner block content
  • Pair with gd to find and replace local variables

Next

How do you yank a single word into a named register?