How do I open a related file with a different extension using the current filename?
Answer
:e %:r.html
Explanation
In Vim's command line, % expands to the current buffer's filename. You can append filename modifiers to transform it — making it easy to open related files, split into a sibling directory, or construct paths without typing filenames manually.
How it works
Modifiers are appended after % with a colon:
%:r— root: strip the last extension (src/foo.c→src/foo)%:e— extension only (src/foo.c→c)%:t— tail (basename, no directory) (src/foo.c→foo.c)%:h— head (directory only) (src/foo.c→src)%:p— full absolute path%:p:h— directory of the current file (modifiers chain)
Example
Editing src/components/Button.tsx and you want to open its CSS module:
:e %:r.css
This expands to :e src/components/Button.css. Or to browse the same directory:
:e %:p:h/
This opens netrw in the current file's directory. Or to open the test file:
:e %:r.test.ts
Tips
- Use
<Tab>to complete after the modifier (e.g.,:e %:p:h/<Tab>) - These modifiers also work in
:read,:write,:split,:vsplit %:t:rchains modifiers: basename without extension (src/foo.c→foo)- The
#register holds the alternate filename and supports the same modifiers:#:r,#:hetc. - Preview the expansion without opening:
:echo expand('%:p:h')