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

How do I open a file in a split window and jump directly to the first match of a pattern?

Answer

:sp +/{pattern} {file}

Explanation

The +{cmd} syntax lets you run an Ex command immediately after a file is opened. Combining it with / makes Vim jump to the first line matching a pattern as soon as the file loads — handy when you know what you're looking for before you even open the file.

How it works

  • :sp opens a new horizontal split (use :vs or :vsp for vertical)
  • +/{pattern} is an Ex "pre-command": after the file is loaded, Vim runs /{pattern} to position the cursor at the first match
  • {file} is the file to open
  • The search pattern follows normal Vim regex rules; spaces in the pattern must be escaped with \

Example

Open config.lua in a split and land on the keymaps section:

:sp +/keymaps config.lua

Open main.go vertically and jump to func main:

:vs +/func\ main main.go

Tips

  • Works with :e (no split), :tabedit, and :pedit too — any command that accepts a filename
  • :e +123 file opens at line 123; :e +$ file opens at the last line
  • Chain with :args: :argdo e +/TODO % to open each argument file at its first TODO
  • The + prefix accepts any Ex command, not just search: :sp +%s/foo/bar/g file opens the file and immediately runs a substitution

Next

How do I create my own custom ex commands in Vim?