TIL: open file at line in Vim

Most of the time when I edit a file with Vim I just pass it to the vim command. The cursor will be positioned at line 1, column 1 (assuming the previous cursor state isn’t being restored):

> vim file.txt

But every once in a while I’d like to open the file at a specific line number. Here’s how to do that, where {num} is the line number:

> vim +{num} file.txt

# Example:
> vim +12 file.txt

That’s not all. Vim can also open the file and jump to the first occurrence of a search pattern:

> vim +/{pattern} file.txt

# Example:
> vim +/error file.txt

And there’s more still. Vim accepts up to 10 Ex commands to be executed after opening a file:

> vim +{command1} +{command2} file.txt

# This is equivalent to the syntax above
> vim -c {command1} -c {command2} file.txt

# Examples:
> vim +'syntax on' +'set ft=mail' muttrc
> vim -c 'syntax on' -c 'set ft=mail' muttrc

Studying the syntax a little closer reveals what jumping to a line number or to a search pattern really are: nothing more than an Ex command executed after opening the file.

The unfortunate bit is that the default syntax does not understand the way most stack traces and tools report file locations, namely as file.txt:{line} and sometimes with a column number as file.txt:{line}:{col}.

Easy enough, there are plugins that will add support for exactly that. For example this one.

Resources:


More posts here.

Comments