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

How do I paste or use the current filename inside Vim without typing it out?

Answer

"% or % or @%

Explanation

The percent register (%) always contains the name of the current file. You can paste it, use it in expressions, or reference it in Ex commands — without ever typing the filename manually.

Ways to use it

In Insert mode

<C-r>%

Inserts the current filename at the cursor position.

In Normal mode

"%p

Pastes the current filename below the cursor.

In Ex commands

:echo @%

Prints the filename in the command line.

:!wc -l %

Runs a shell command on the current file (here % is expanded by Vim, not the register syntax).

What it contains

  • Relative path from Vim's working directory: e.g., src/main.py
  • Use expand('%:p') for the full absolute path: /home/user/project/src/main.py
  • Use expand('%:t') for just the tail (filename only): main.py
  • Use expand('%:h') for the head (directory only): src/
  • Use expand('%:e') for the extension only: py

Example

Insert a file header comment with the filename:

i// File: <C-r>%<CR>// Author: ...<Esc>

Copy the full path to the system clipboard:

:let @+ = expand('%:p')

Tips

  • The # register contains the alternate file (the previously edited file) — useful for referencing both files
  • In command mode, % expands to the filename without needing @: :!cat % works directly
  • <C-r>% in the command line (: mode) also works — inserts the filename into your Ex command as you type it

Next

How do I run a search and replace only within a visually selected region?