How do I quickly insert the current file's directory into a command-line prompt without typing the full path?
Answer
:cnoremap %% <C-r>=expand('%:h').'/'<CR>
Explanation
By mapping %% in command-line mode, you can type %% wherever you would normally type a path and have Vim automatically expand it to the directory of the current file. This is a widely-used vimrc pattern made popular by Gary Bernhardt and the "Practical Vim" book.
How it works
Add this to your ~/.vimrc or init.vim:
cnoremap %% <C-r>=expand('%:h').'/'<CR>
cnoremapcreates a mapping that only fires in command-line mode (:,/,?prompts)<C-r>=opens the expression register inlineexpand('%:h')returns the directory of the current file (%= current file path,:h= head/directory modifier).'/'appends a trailing slash so you can type filenames immediately after
Example
Editing /home/user/projects/myapp/src/main.lua, typing %% in command mode expands to:
:e /home/user/projects/myapp/src/
You can then continue typing:
:e /home/user/projects/myapp/src/utils.lua
This works everywhere a path is expected — :e, :w, :sp, :vs, etc.
Tips
- The native
%:hmodifier also works directly in one-off commands::e %:h/utils.lua :cd %:hchanges your working directory to the current file's directory without a mapping- For a temporary directory change per-window, use
:lcd %:h