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

How do I use the expression register in a mapping to insert dynamic values?

Answer

:nnoremap <leader>d "=strftime('%Y-%m-%d')<CR>p

Explanation

The expression register (=) evaluates Vimscript expressions and uses the result as register content. When combined with mappings, it creates powerful shortcuts that insert dynamic values like dates, calculations, or formatted text with a single keystroke.

How it works

  • "= — access the expression register
  • expression<CR> — evaluate the expression
  • p — paste the result
  • In a mapping, the entire sequence runs with one keypress

Example

" Insert today's date
nnoremap <leader>d "=strftime('%Y-%m-%d')<CR>p

" Insert a UUID-like string
nnoremap <leader>u "=system('uuidgen')[:-2]<CR>p

" Insert current line number as text
nnoremap <leader>l "=line('.')<CR>p
Press <leader>d:
2024-01-15 (inserted at cursor)

Press <leader>l:
42 (current line number inserted)

Tips

  • Use P instead of p to insert before the cursor
  • In insert mode, use <C-r>=expression<CR> for inline insertion
  • system() runs shell commands — trim trailing newline with [:-2]
  • strftime() supports all standard format specifiers: %H:%M, %A, etc.

Next

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