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

How do I prompt the user for input in the middle of a mapping or Vimscript function?

Answer

input({prompt})

Explanation

The built-in input() function pauses execution, displays a prompt at the bottom of the screen, and returns whatever the user types before pressing Enter. It is the standard way to make a mapping or script interactive without requiring a full plugin.

How it works

  • input({prompt}) displays the prompt string and waits for text + <CR>
  • Returns the entered string; returns '' if the user presses <Esc> without typing
  • A second argument sets a default value: input('Name: ', 'unnamed')
  • A third argument enables completion: input('File: ', '', 'file') gives Tab-completion for filenames. Other types include 'buffer', 'command', 'tag', and 'customlist,FuncName'

Example

A mapping that runs :vimgrep for a user-entered pattern and opens results:

nnoremap <leader>/ :execute 'vimgrep /' . input('Pattern: ') . '/ **' \| copen<CR>

An interactive rename function that asks for the new name:

function! RenameBuffer()
  let l:new = input('Rename to: ', expand('%:t'))
  if l:new !=# ''
    execute 'saveas ' . fnameescape(expand('%:h') . '/' . l:new)
  endif
endfunction

Tips

  • Call inputsave() before input() and inputrestore() after when used in a mapping — this prevents buffered keystrokes from being consumed as the input
  • For a menu-style prompt with numbered choices, use inputlist(['Choose:', '1. Alpha', '2. Beta']) instead
  • For a single keypress (no Enter required), use getchar() or nr2char(getchar())
  • Wrap in a function call so the prompt string is defined in one place and reused safely across mappings

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?