I see both of these styles for inserting the contents of an expression in a map. For example:
imap ,9 <c-r>=1+1<cr>
imap <expr> ,9 1+1
Both of these do the same thing as far as I can tell: they insert 2
if you type ,9
in insert mode.
I see some scripts use the first style and others the second. Are there any differences? It seems to me that the <expr>
style is clearer, but are there use-cases where the <c-r>=
style can accomplish something that <expr>
can't?
Your two examples are equivalent. You should prefer the second style as <c-r>=
behaves differently in some case. One recent example would be <Plug> function failing, inserting as literal "<t_ý>S", where using <c-r>=<Plug>Func()<CR>
did something different and unexpected compared to <Plug>Func()
in an expression mapping.
Most of the uses for <c-r>=
should be when you want to insert the result of the expression in the middle of your mapping (or just using the expression register manually). A trivial example would be you want to include the contents of the g:some_var
variable in between parentheses when you hit ,8
imap ,8 (<c-r>=g:some_var<cr>)
My biggest issues with :map-<expr>
are the one explained in the documentation:
:normal
:normal
...Moreover, i_CTRL-R
has been around for a much longer time. As a consequence I haven't even try to migrate my old, and intensively tested and used, mappings to i(nore)map <expr>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With