How do I paste the current filename into the buffer?
Answer
"%p
Explanation
The % register in Vim always contains the name of the current file. You can paste it into your buffer with "%p in normal mode, or insert it while typing with <C-r>% in insert mode. This is invaluable for writing headers, comments, or log statements that reference the current filename.
How it works
"tells Vim you're about to specify a register%is the special read-only register that holds the current file's path (as it was opened or as shown in the status line)ppastes the register contents after the cursor
The % register reflects how the file was opened. If you ran vim src/app.js, it contains src/app.js. If you used an absolute path, it contains the absolute path.
Example
You're editing src/utils/helpers.py and want to add a module docstring:
# File: |
In insert mode, press <C-r>% to insert the filename:
# File: src/utils/helpers.py
Or in normal mode with the cursor at the end of File: , press "%p:
# File: src/utils/helpers.py
Tips
- Use
<C-r>%in insert mode to insert the filename without leaving insert mode - The
#register contains the alternate file (the previously edited file) — paste it with"#p - Use
:echo expand('%:t')to see just the filename without the path, orexpand('%:p')for the full absolute path - Insert the tail (filename only) in insert mode with
<C-r>=expand('%:t')<CR> - Insert the directory only with
<C-r>=expand('%:h')<CR> - The
%:emodifier gives the file extension,%:rgives the path without extension - Use
1<C-g>to display the full path in the status line, or:echo @%to echo the register contents