How do I reference just the extension, stem, or directory of the current file in a Vim command?
Answer
%:e
Explanation
Vim exposes the current filename as % in Ex commands, and you can apply modifiers to extract specific parts of the path. These filename modifiers are indispensable when writing commands that need to work with related files — opening a test file for the current source file, compiling the current file, or switching between header and implementation files.
How it works
Modifiers are appended to % with a colon:
%— full path as opened (e.g.,src/utils/parser.py)%:p— absolute path (e.g.,/home/user/project/src/utils/parser.py)%:h— head (directory only):src/utils%:t— tail (filename only):parser.py%:r— root (filename without extension):src/utils/parser%:e— extension only:py%:t:r— filename without extension and without directory:parser
Modifiers can be chained: %:p:h gives the absolute directory of the current file.
Example
Open the corresponding test file in a split:
:vsplit %:r_test.%:e
For src/parser.py, this opens src/parser_test.py. Compile the current C file:
:!gcc % -o %:r
Insert the current filename into the buffer while in insert mode:
<C-r>%
Tips
- Use
expand('%:p:h')in Vimscript to get the absolute directory programmatically #refers to the alternate (previously edited) file and accepts the same modifiers:#:t- In the command line,
<C-r>%pastes the current filename at the cursor :lcd %:hchanges the local working directory to the current file's directory