How do I use the filename under the cursor as a value in a Vim mapping or command?
Answer
expand('<cfile>')
Explanation
The expand('<cfile>') function returns the filename that Vim sees under the cursor — the same file that gf would open. Unlike the % register (which gives the current buffer's path), <cfile> extracts a path-like string from the text at the cursor position. This makes it useful for building mappings that act on file references embedded in your code or documentation.
How it works
expand('<cfile>')— returns the filename under the cursor as a stringexpand('<cWORD>')— returns the full WORD under the cursor (less intelligent)expand('<cfile>:p')— applies filename modifiers;:pexpands to the full absolute path- Vim uses
'path'and'suffixesadd'when resolving<cfile>, just likegf
Example
Map a key to open a vertical split for the file under the cursor:
nnoremap <leader>gv :vsplit <C-r>=expand('<cfile>')<CR><CR>
Or search for a file across your project using the name under the cursor:
nnoremap <leader>ff :find <C-r>=expand('<cfile>')<CR><CR>
Tips
<C-r>=expand('<cfile>')<CR>inserts the result into the command line interactively, letting you edit it before executing- Combine with
fnamemodify()for more complex path transformations:fnamemodify(expand('<cfile>'), ':r')strips the extension <cfile>respects'iskeyword'and path separators, so it picks up../foo/bar.luaas a whole unit- Unlike
%,<cfile>works correctly even when the cursor is not in the current file's path