What are Vim's read-only special registers and how do I use them?
Answer
". / "% / ": / "# registers
Explanation
Vim has four read-only special registers that automatically contain useful contextual information. You can paste from them but never write to them directly.
The four read-only registers
| Register | Contents | Example |
|---|---|---|
". |
Last inserted text | "Hello World" |
"% |
Current filename | src/main.go |
": |
Last Ex command | %s/old/new/g |
"# |
Alternate filename | src/utils.go |
Accessing them
" In normal mode — paste
".p " Paste last inserted text
"%p " Paste current filename
":p " Paste last Ex command
"#p " Paste alternate filename
" In insert mode — insert inline
<C-r>. " Insert last inserted text
<C-r>% " Insert current filename
<C-r>: " Insert last Ex command
<C-r># " Insert alternate filename
" In Vimscript
:echo @% " Print current filename
:echo @: " Print last Ex command
Practical examples
" Add a file header with the current filename
ggO// File: <C-r>%<Esc>
" Re-run the last Ex command with modifications
":p " Paste it, edit, then yank and execute with @"
" Duplicate the text you just typed
<Esc>".p " Paste last inserted text
" Reference the current file in a shell command
:!wc -l %
Tips
".is incredibly useful for repeating an insertion at a different location":pairs well with@:(which executes the last Ex command) — paste it to see/edit before re-running"%and"#are buffer-local — they update as you switch files- These registers are read-only:
:let @% = 'test'will fail - Use
:reg .%:#to see all four at once