Vim Recipes Typing Opening the File Name Beneath the Cursor

Opening the File Name Beneath the Cursor

Problem

You have a file name under your cursor and would like Vim to open it.

For example, program source code often references other files from which it includes functionality. You want to quickly open such a file.

Solution

Position your cursor over a file name then hit gf (mnemonic: go to file or get file) in Normal mode. For example, consider a file like the following:

Edit your ~/.vimrc by opening it with Vim, then...

If your cursor was anywhere over ~/.vimrc, gf would try to open your Vim configuration file. (This assumes that you're using Linux where ~ is shorthand for the user's home directory).

Vim doesn't care if the word under the cursor looks like a filename, so if your cursor was over the word your, instead, it would try to open a file named your in your path.

Your path is a list of directories in which Vim searches for the named file. To see what it's currently set to execute :echo &path. The path is a comma-separated list of directories, some of which have special significance:

.
The directory containing the current file.
;
A path that ends with a semicolon is searched recursively, up the directory hierarchy. For example /usr/share/doc; means to first search in /usr/share/doc, then /usr/share/, then /usr/, then /.
*
A path that ends in an asterisk is searched recursively downwards. For example, /home/kate/* would search all of user kate's home directory.

I like gf to search recursively downwards from the current directory so I append ./** to my path like so: :set path+=./**.

Discussion

This feature has a surprising amount of uses for something so basic. I use it when:

Vim also lets you follow URLs in this way, so you can gf on http://example.com/, to open the HTML in Vim, or sftp://example.com/README to connect to example.com via SFTP, fetch README, then open it for editing in Vim.

By default gf opens the file in the same window. To open it in a new tab use <Ctrl>w+gf. To make this behaviour the default consider a key remap: :nnoremap gf <C-W>gf.

If your filename is followed by a line number, e.g. foo.txt:10 you can jump to the given line with gF.

If the filename you use gf on doesn't exist, Vim complains. I don't use gF so I have remapped it to create the given file: :nnoremap gF :view <cfile><cr>.