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

How do I refer to the current filename, extension, or directory in Vim ex commands?

Answer

%:p:h

Explanation

Vim's filename modifiers let you derive path components from the current file's name directly inside ex commands. The special symbol % expands to the current buffer's filename, and chaining : modifiers extracts exactly the part you need — eliminating manual path typing and making commands portable across projects.

How it works

Modifiers are appended to % (current file) or # (alternate file) with colons:

Expression Meaning Example (file: /src/app/main.go)
% Current filename src/app/main.go
%:p Absolute (full) path /src/app/main.go
%:h Head (directory) src/app
%:p:h Absolute directory /src/app
%:t Tail (filename only) main.go
%:r Root (no extension) src/app/main
%:e Extension only go
%:t:r Tail without extension main

Modifiers can be chained left to right.

Example

Open a new file in the same directory as the current buffer:

:e %:h/config.json

Change the working directory to the file's directory:

:cd %:p:h

Write a backup copy with a .bak extension:

:w %:r.bak

Tips

  • Works anywhere a filename is expected: :e, :w, :r, :!, :cd, :lcd, :sp, etc.
  • In insert mode, <C-r>=expand('%:p:h') inserts the expanded path as text.
  • Use %:~ to shorten the path relative to $HOME.
  • %:.:h gives a path relative to the current working directory.

Next

How do I exclude compiled files and dependency folders from Vim's file name completion?