How do I open a file path that appears in my code without manually typing it?
Answer
gf
Explanation
The gf command ("go to file") opens the file whose path is under the cursor. Vim intelligently detects file paths in your text — including relative paths, absolute paths, and paths with line numbers — and opens them in the current window. This is incredibly useful for navigating codebases where files reference each other by path.
How it works
- Place your cursor on or near a file path in the buffer
- Press
gfin normal mode - Vim resolves the path and opens the file in the current window
- Vim searches for the file using the
pathoption (:set path?to see it) - If the file doesn't exist, Vim reports an error
Example
Given a source file with an import statement:
#include "utils/helpers.h"
With the cursor anywhere on utils/helpers.h, pressing gf opens that file. Press <C-o> to jump back to the original file.
Or in a configuration file:
source: /etc/nginx/sites-available/default
Cursor on the path, press gf, and you're editing the Nginx config.
Tips
- Use
<C-w>fto open the file in a horizontal split instead of the current window - Use
<C-w>gfto open the file in a new tab - Set
suffixesaddto let Vim try file extensions automatically::set suffixesadd=.js,.ts,.pysogfonutils/helpersfindshelpers.js - Expand the search path with
:set path+=src/**to recursively search insidesrc/ gF(uppercase F) opens the file and jumps to the line number if the path includes one, e.g.,helpers.h:42opens line 42- Press
<C-o>to jump back to where you were beforegf— Vim adds the jump to the jump list - In Node.js projects, set
:set path+=node_modulesto resolverequireandimportpaths