How do I read the contents of a Vim register into a variable or expression using Vimscript?
Answer
getreg()
Explanation
The getreg({name}) function returns the content of any register as a string. Unlike pasting with "ap or <C-r>a, getreg() lets you use register content inside expressions, conditions, and substitutions without touching the buffer. This is essential for writing robust Vimscript functions and advanced mappings that need to inspect or transform register values.
How it works
getreg('{reg}') " returns content as a string
getreg('{reg}', 1) " include special chars (e.g. newlines as \n)
getreg('{reg}', 1, 1) " returns content as a List (one item per line)
Common registers to read:
| Register | Contents |
|---|---|
" |
Unnamed (default yank/delete) |
0 |
Most recent yank |
/ |
Current search pattern |
: |
Last Ex command |
* / + |
System clipboard |
Example
Use the content of register a as the replacement in a substitute, without retyping it:
:s/old_name/\=getreg('a')/g
The \= in the replacement field evaluates a Vimscript expression, so getreg('a') is expanded at runtime.
Inspect what is currently in the unnamed register before pasting:
:echo getreg('"')
Store a register's content for safe-keeping before a destructive operation:
let saved = getreg('"')
" ... do stuff ...
call setreg('"', saved)
Tips
- Pair with
setreg()to save and restore register state around operations that clobber registers. - Use
getreg('/', 1)to read the raw search pattern including special atoms. getreg('{reg}', 1, 1)returns a list — ideal for iterating over linewise yank content in aforloop.getreg('')(empty string) reads the unnamed register, same asgetreg('"').