How do I programmatically manipulate register contents using setreg and getreg?
Answer
:call setreg('a', @a . 'text', 'l')
Explanation
How it works
Vim provides two functions for advanced register manipulation: setreg() and getreg(). These let you read, modify, and set register contents programmatically, including controlling the register type (characterwise, linewise, or blockwise).
The setreg() function takes three arguments:
- Register name (a single character as a string)
- The new contents (a string or list of strings)
- The register type:
'c'for characterwise,'l'for linewise,'b'for blockwise
The getreg() function retrieves register contents:
getreg('a')-- get contents as a stringgetreg('a', 1, 1)-- get contents as a list of linesgetregtype('a')-- get the register type
Using @a in expressions is shorthand for getreg('a').
Example
Append text to a register with a separator:
:call setreg('a', @a . "\n---\n" . @b, 'l')
This concatenates register a, a separator line, and register b, then stores the result back in register a as linewise text.
Convert a characterwise register to blockwise:
:call setreg('a', getreg('a'), 'b')
Set a register to a list of lines (creating a linewise register):
:call setreg('a', ['line1', 'line2', 'line3'], 'l')
Modify register contents with a substitution:
:call setreg('a', substitute(@a, 'old', 'new', 'g'))
These functions give you full control over registers that simple yank and paste commands cannot achieve, enabling complex text processing workflows.