I realise this might be impossible, but thought it might be worth asking anyway.
In vim, the typical way I map keys to functions is using *noremap
commands. However the downside of this is the fact that the mapping is not a call to the function. Instead, it automatically literally types out the characters needed to invoke said function; getting a command prompt with :
, typing call
and the function name, hitting return, etc. Is there a way I can bind a key to a function directly without this intermediary step, much like how hjkl
immediately invoke internal functions that actually do the work of changing the cursor position? Or is this kind of functionality not exposed to the user by vim?
1 Answer
Essentially, the answer is no, :call
is the mechanism for invoking functions starting from normal mode, but there are at least two mechanisms I can think of that you could theoretically use if you needed to call a function from a normal-mode mapping but the colon key had been stolen from your keyboard:
Expression mappings
Expression mappings work by evaluating an expression and then mapping to the result. A function call is a valid expression, thus:
nnoremap <expr> <f2> Function()
However, there are several limitations to what you can actually do during that function: e.g. you can move the cursor but it will be moved back afterwards. See :help map-expr
for the full set of limitations and other details.
The expression register
Vim has a register called the “expression register” which you can use to evaluate expressions in certain circumstances. This could be used to run a function from a normal mode mapping by e.g. entering insert mode first:
nnoremap <f2> i<C-R>=Function()<CR><Esc>
In case it’s not already clear, this would be an asinine thing to do, but the expression register is very useful in other contexts. See :help "=
for more details.