vimtricks.wiki Concise Vim tricks, one at a time.

How do I transform register contents using Vimscript functions?

Answer

:put =map(getreg('a', 1, 1), 'toupper(v:val)')

Explanation

By using getreg() with the list flag and applying map(), you can transform register contents with any Vimscript function before pasting. This enables operations like uppercasing, filtering, sorting, or reformatting register text programmatically.

How it works

  • getreg('a', 1, 1) — get register a as a list of lines
  • map(list, 'expr') — apply an expression to each element
  • v:val — refers to the current element in map()
  • :put = — paste the expression result below the current line

Example

" Uppercase all text in register a
:put =map(getreg('a', 1, 1), 'toupper(v:val)')

" Add line numbers to register contents
:put =map(getreg('a', 1, 1), '(v:key+1).". ".v:val')

" Filter register to only lines containing 'error'
:put =filter(getreg('a', 1, 1), 'v:val =~ "error"')
Register a contains:
hello world
foo bar

After :put =map(...):
HELLO WORLD
FOO BAR

Tips

  • v:key gives the 0-based index in map() and filter()
  • Use join() and split() for string-level transformations
  • Combine filter() and map(): filter first, then transform
  • Store the result back: :call setreg('a', map(...), 'l')

Next

How do I return to normal mode from absolutely any mode in Vim?