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

How do I jump to the start of the previous method or function in code?

Answer

[m

Explanation

The [m motion jumps backward to the start of the nearest enclosing or preceding method definition. It is especially effective in Java, C++, and Go where methods are delimited by curly braces, letting you navigate class files without counting lines or using search.

How it works

  • [m — jump to the start of the previous method (the opening {)
  • ]m — jump to the start of the next method
  • [M — jump to the end of the previous method (the closing })
  • ]M — jump to the end of the next method

Vim recognizes a "method start" as the first { that begins a block in a Java/C-style file. The detection is filetype-aware and relies on the 'matchpairs' and syntax context.

Example

Given a Go file with:

func Foo() {
    // cursor is here
}

func Bar() {
    doSomething()
}

With the cursor inside Bar, pressing [m jumps to the { on the func Bar() line. Pressing [m again jumps to the { on the func Foo() line.

Tips

  • Combine with an operator: d]M deletes from the cursor to the end of the current method body
  • Works in visual mode to extend selection to a method boundary: v]M selects to end of method
  • Use :help [m to see the full list of bracket motions for code navigation
  • For languages without C-style braces, consider [[ / ]] which jump to { in column 1

Next

How do I pipe a visual selection through an external shell command and replace it with the output?