This is a suggestion for a canonical resource. Please review.
I've gone ahead and posted it.
Question: how do I use a variable or return value in option, command, or mapping?
I have a variable
let foo='value', and a function
and I want to use them
- in an option:
:set option=F(); or
- in a command:
:edit F(); or
- in a mapping:
:nnoremap f :foo<CR>,
:nnoremap f :F()<CR>
How can I do this?
variables, options, key-bindings, command-line,
The reason your example attempts don't work is that in many locations text is simply seen as a literal string, rather than VimScript. So functions, variables, and the like don't work.
For example, if you do:
Then Vim will simply set the value of
option to the literal value
var, since it doesn't recognize VimScript in
:set. The same applies to
:map and many other locations.
In general, most colon/Ex/
: commands do not evaluate VimScript.
Not all is lost, since you can still build a string with
:execute ':set option=' . var
:execute command executes the given VimScript expression. In this case, we build a string using the variable, and what
:execute sees is
You can use any Vim expression; some more examples:
" Function return value
:execute 'set option=' . Fun()
" You don't need to use string concatenation; all arguments are
" concatenated automatically. A space is added.
:execute 'edit' var
:execute 'edit' Fun()
map expands special key sequences like
<CR>. To get them in an execute, you need to prepend the
< with a
"\<CR>". You need to use double quotes, single quotes won't work:
:let key = 'h'
:execute 'nnoremap ' . key . " :echo 'hello'\<CR>"
Because you're building VimScript code in a VimScript string things tend to look rather ugly. C'est la vie. Depending on your personal tastes,
printf() can make things a bit easier on the eyes:
:execute printf("nnoremap %s :echo 'hello'\<CR>", key)
Note: it's very common to abbreviate
:help :execute for more information.
Finally, you can use expression mappings to use a Vim expression for the entire right-hand side.
" Execute the contents of the current line as a Vim command.
:nnoremap <expr> f getline('.')
The biggest difference with
:execute is that the expression is run when the key is pressed, and not when the command is defined. So every time you press
f in the above example
getline() gets the value of the current line. If we had used:
:execute ':nnoremap f' getline('.')
Then it would get the value of the line once. So if you had been on the line
gg it would be the same as typing:
:nnoremap f gg
:help :map-<expr> for more information.