There are two primary ways to prompt the user for input. You can either use confirm to display a multiple choice dialog (such as yes/no/cancel), or input to process a more complex input.
The confirm function prompts the user with a dialog and a multiple answers a user can select from. Let's try a simple example:
let answer = confirm('Is cat your favorite animal?', "&yes &no")
echo answer
If you execute the script, you'll get the following prompt:
Hitting y or n will select an option. Let's hit y:
The result of this is 1. Now, what if we replay it and choose no?
We get a 2. As you can see, confirm returns an integer with the number of the selected choice.
Oh, and if you're running from a GUI, you'll get a dialog window pop up:
Now, let's get back to our original example:
let answer = confirm('Is cat your favorite animal?', "&yes &no")
echo answer
Here, you can see that confirm takes two arguments: a prompt to be displayed, and a newline-separated ( ) list of options to select from. In the previous example, an option string is non-literal, since we want the newlines to be processed.
A set of ampersand & symbols are used to denote the letters representing each option (in the previous example, y and n become the available options). Here's another example:
let answer = confirm(
'Is cat your favorite animal?', "absolutely &yes hell &no")
This would display the following prompt:
Note that y and n are still the letters a user can press to reply to the prompt.
Lastly, input lets you work with free-form text input. Its use is fairly straightforward:
let animal = input('What is your favorite animal? ')
echo " "
echo 'What a coincidence! My favorite animal is a ' . animal . ' too!'
And this is how the prompt looks when executed:
And this is what it looks like after we enter our string:
However, a word of warning. If you're using input from inside a mapping, you must prefix it with inputsave() and follow it with inputrestore(). Otherwise, the rest of the characters in a mapping will be consumed into input. In fact, you should always use inputsave() and inputrestore() in case your function is ever used in a mapping. Here's an example of how to use them:
function AskAnimalName()
call inputsave()
let name = input('What is the animal"'s name? ')
call inputrestore()
return name
endfunction
nnoremap <leader>a = :let name = AskAnimalName()<cr>:echo name<cr>