Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<c-r>= versus <expr> in mappings

Tags:

vim

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?

like image 301
Jonah Avatar asked Jan 15 '16 18:01

Jonah


2 Answers

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>)
like image 197
FDinoff Avatar answered Oct 05 '22 17:10

FDinoff


My biggest issues with :map-<expr> are the one explained in the documentation:

  • We cannot modify the buffer, nor play with other buffers
  • We cannot use :normal
  • We cannot move the cursor around (as an observable property of the mapping) -- which I sometime do with :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>.

like image 22
Luc Hermitte Avatar answered Oct 05 '22 16:10

Luc Hermitte