How do I extract just the parent directory name (not the full path) of the current file in Vim?
Answer
expand('%:p:h:t')
Explanation
Vim's filename modifiers can be chained to transform paths step by step. expand('%:p:h:t') combines four modifiers to extract the immediate parent directory name as a bare string — without the leading path.
This is useful in statuslines, window titles, functions, or any context where you want to display or operate on the current file's containing directory.
How it works
%— the current file path (relative):p— expand to the full absolute path:h— head: strip the last component (file → parent directory path):t— tail: strip all but the last component (full path → just the directory name)
Example
For a file at /home/user/projects/myapp/src/main.py:
expand('%') → src/main.py
expand('%:p') → /home/user/projects/myapp/src/main.py
expand('%:p:h') → /home/user/projects/myapp/src
expand('%:p:h:t') → src
Practical uses:
" Show parent dir name in the statusline
set statusline+=%{expand('%:p:h:t')}/
" Get the project root (grandparent) name
:echo expand('%:p:h:h:t')
Tips
- Chain
:h:h:tto get the grandparent directory name,:h:h:h:tfor great-grandparent, etc. - Use
fnamemodify(path, ':h:t')to apply the same transform to an arbitrary path string in Vimscript - The
:~modifier makes a path relative to$HOME:expand('%:p:~')→~/projects/myapp/src/main.py - For changing to the file's directory, combine
:p:hdirectly::lcd %:p:h