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

How do I reference just the filename without its extension in a Vim command?

Answer

%:r

Explanation

The %:r expression expands to the current filename with its extension removed (the "root" of the filename). This is useful when you want to derive related file names or run build commands that transform one file type into another.

How it works

  • % — the current file's path
  • :r — the :r modifier strips the last extension from the path

You can chain modifiers: %:p:r gives the full absolute path without extension, and %:t:r gives just the filename stem (no directory, no extension).

Example

If the current file is src/main.c, then:

%         →  src/main.c
%:r       →  src/main
%:t       →  main.c
%:t:r     →  main
%:e       →  c
%:h       →  src

A practical compile-and-run mapping:

nnoremap <F5> :w \| :!gcc % -o %:r && ./%:r<CR>

This saves the file, compiles it, and immediately runs the resulting binary — all from a single key.

Tips

  • Use in :! shell commands: :!pandoc % -o %:r.pdf
  • Use expand('%:r') in Vimscript to get the same value programmatically
  • Works in command-line mode with any %-like filename reference including # (alternate file)

Next

How do I get just the filename without its path or extension to use in a command?