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

How do I access the current and alternate filename registers in Vim?

Answer

:echo @%

Explanation

Vim provides special read-only registers that hold the current and alternate filenames. The % register contains the current file's name, while # holds the alternate (previous) file. These are useful in scripts, mappings, and command-line operations.

How it works

  • @% — the current filename register
  • @# — the alternate filename register (previous buffer)
  • <C-r>% — insert current filename in insert/command mode
  • These registers update automatically as you switch buffers

Example

:echo @%
" Output: src/main.go

:echo @#
" Output: src/utils.go (previous file)

" Copy current filepath to system clipboard
:let @+ = expand('%:p')
Useful expansions:
%     → src/main.go (relative path)
%:p   → /home/user/project/src/main.go (absolute)
%:t   → main.go (filename only)
%:r   → src/main (without extension)
%:e   → go (extension only)

Tips

  • Use expand('%:p:h') to get the directory of the current file
  • In command mode: :edit %:h/ opens a new file in the same directory
  • <C-r># inserts the alternate filename in insert mode
  • Combine with :!: :!go run % runs the current file

Next

How do I return to normal mode from absolutely any mode in Vim?