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

How do I make a macro prompt for user input at a specific point during its execution?

Answer

<C-r>=input('Enter: ')<CR>

Explanation

By embedding <C-r>=input('prompt: ')<CR> inside a recorded macro, you can pause the macro at any point to ask for user input and insert the result. This turns a static macro into a semi-interactive template, letting you reuse the same keystrokes while customizing one critical value each time you run it.

How it works

  • <C-r> in insert mode opens the register-insertion prompt
  • = selects the expression register, which evaluates a Vimscript expression
  • input('prompt: ') displays a prompt in the command line and waits for you to type a response, returning the string you entered
  • <CR> confirms the expression, inserting the result directly into the buffer

The entire <C-r>=input(...)<CR> sequence is recorded as literal keystrokes in the macro, so every time you run it with @q, Vim pauses and prompts you.

Example

Record a macro that inserts a labelled TODO comment:

qq O// TODO(<C-r>=input('Owner: ')<CR>): <Esc>q

Running @q opens a new line above, types // TODO(, then prompts for the owner name. If you type alice, you get:

// TODO(alice): 

To pre-fill a default value, use input('Owner: ', 'alice') — the second argument initialises the prompt text.

Tips

  • For password-style input (no echo), replace input() with inputsecret()
  • Use inputlist(['Option A', 'Option B']) to present a numbered menu and return the chosen index
  • This technique requires that the macro is run interactively with @q or @@ — it does not work when called via :normal @q, because :normal runs in a non-interactive context
  • Combine with a count prefix (5@q) only if the same input is appropriate for all iterations; the prompt fires once per repetition

Next

How do I add more keystrokes to the end of an existing macro without re-recording the whole thing?