Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the expression register?

Tags:

vim

Just watched this http://www.derekwyatt.org/vim/vim-tutorial-videos/vim-advanced-tutorial-videos/#expression-register, and I can't see any benefit to using <c-r>= vs <c-o>normal or something like that (although I'm sure that is just because I am not understanding something)

like image 852
Matt Briggs Avatar asked Aug 11 '11 14:08

Matt Briggs


2 Answers

It has many interesting uses, many many. In Derek's video, it was used to call an external script. The point is that you can do that without leaving insert mode. You said you don't see benefits over <c-o>, but how would you to that?

The expression register inserts the result from an expression. You don't need to :call a function for example, as demonstrated in the video. I'll try to show you another two uses that I find interesting, and use frequently.

1.Evaluating Math

The expression 2 evaluates to 2, right (like in VimScript)? So you can use the expression register to insert some numbers as result from a calculation. For example, considering you're in insert mode in this file:

... the total sum is $

Now hit <c-r>= and type

5*6+3.2*8+5.52<enter>

And the result is:

... the total sum is $61.12

Practical, eh?

2.Using Variable Values

Let's say you need to number headings in a text. Headings start with a # like in:

# Heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.

# Another Heading

Consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

Considering it's a long list, you'd need to find a way to do it quickly. Here is one approach:

  1. Create a variable to hold the current value
  2. Find the next heading
  3. Insert the contents of that variable (using the expression register)
  4. Increment the variable

This can be done with by first creating the variable:

:let i=1

And then with a macro:

qa            ; start recording
/^#<CR>       ; find next heading
0w            ; move to the first word
i             ; switch to insert mode
<c-r>=i<CR>   ; insert the number
.<esc>        ; insert a dot and back to normal mode
:let i+=1<CR> ; increment the variable
q             ; stop recording

And now you can press @a and use @@ to subsequently insert the numbers in your headings.

like image 93
sidyll Avatar answered Nov 20 '22 01:11

sidyll


I use the expression register like this: <C-r>=618+27<CR>. It's very useful when doing CSS.

like image 22
romainl Avatar answered Nov 20 '22 00:11

romainl