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

How do I insert the result of a Vimscript expression as a new line?

Answer

:put ={expr}

Explanation

The :put ={expr} command evaluates a Vimscript expression and inserts the result as a new line below the cursor. Unlike the expression register in insert mode (<C-r>=), this is an Ex command that works from normal mode and is particularly handy in macros, mappings, and scripts where you need to drop calculated content into a buffer without entering insert mode.

How it works

  • :put inserts register contents as a new line below the cursor
  • = tells Vim to use the expression register, which evaluates the following expression as Vimscript
  • {expr} is any valid Vimscript expression — a function call, arithmetic, string operation, etc.
  • :put! ={expr} inserts above the cursor instead of below

Example

Insert the current date as a new line:

:put =strftime('%Y-%m-%d')

Insert a computed value:

:put =line('$') . ' lines total'

Before:

some text

After :put =strftime('%Y-%m-%d'):

some text
2024-06-01

Tips

  • :put =getreg('a') is equivalent to :put a — both insert register a as a new line, but the expression form lets you transform it first: :put =toupper(getreg('a'))
  • Combine with a range to insert at a specific line: :0put =strftime('%Y-%m-%d') inserts at the top of the file
  • Use in a mapping to stamp timestamps: :nnoremap <leader>d :put =strftime('%Y-%m-%d')<CR>
  • Unlike p/P, :put always inserts linewise, so the result always lands on its own line

Next

How do I create my own custom ex commands in Vim?