How do I extract the directory, filename, or extension from the current file path inside a Vim command?
Answer
%:h
Explanation
Vim's filename modifiers let you derive path components from the current buffer's filename directly on the command line. The % symbol expands to the current file's path, and chained modifier suffixes extract exactly what you need.
How it works
Modifiers are appended after % (or after any filename expression like # for the alternate file):
| Expression | Meaning | Example result for ~/proj/src/main.go |
|---|---|---|
% |
Relative path | src/main.go |
%:p |
Absolute (full) path | /home/user/proj/src/main.go |
%:h |
Head — parent directory | src |
%:t |
Tail — filename only | main.go |
%:r |
Root — strip one extension | src/main |
%:e |
Extension only | go |
Modifiers chain left to right: %:p:h → absolute parent directory; %:t:r → filename without extension.
Example
Open a test file next to the current file:
:e %:h/main_test.go
Change the working directory to the current file's parent:
:cd %:p:h
Run the current file with a shell command:
:!node %
Tips
- In Vimscript expressions, use
expand('%:h')to get the same result <C-r>%in command-line mode inserts the bare path — then type:h,:t, etc. manually- Modifiers also work on
#(alternate file), making#:hthe parent of the last edited file - Tab-completion after
%:h/works normally, letting you navigate from the current file's directory