How do I insert the current filename into the buffer or use it in commands?
Answer
"%p
Explanation
Vim has several read-only registers that hold special values. The % register always contains the name of the current file, while # contains the alternate file (the previously edited buffer). You can paste these just like any other register.
How it works
"%p— paste the current filename after the cursor (normal mode)"#p— paste the alternate filename after the cursor<C-r>%— insert the current filename while in insert mode<C-r>#— insert the alternate filename while in insert mode
These registers are read-only — you cannot write to them with "xy.
Example
You are editing src/main.go and want to add a comment referencing the file:
Cursor position: // File: |
In insert mode, press <C-r>%:
// File: src/main.go
Or in a shell command, paste the current path into a :! command:
:!echo "%"
To view the current values:
:echo @%
:echo @#
Tips
@%and@#can be used in Vimscript expressions and mappings- Combine with filename modifiers:
:echo expand('%:p:h')to get the directory - The
:register holds the last Ex command;.holds the last inserted text — all three are useful readonly registers to know - In a mapping:
nnoremap <leader>fn "=%p<CR>inserts the filename with a leader key