vimtricks.wiki Concise Vim tricks, one at a time.

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>
  • cnoremap creates a mapping that only fires in command-line mode (:, /, ? prompts)
  • <C-r>= opens the expression register inline
  • expand('%: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 %:h modifier also works directly in one-off commands: :e %:h/utils.lua
  • :cd %:h changes your working directory to the current file's directory without a mapping
  • For a temporary directory change per-window, use :lcd %:h

Next

How do I rename a variable across all its case variants (camelCase, snake_case, SCREAMING_CASE) in one command?