Suppose I have \label{some text} somewhere in my file and I want to store some text into a variable.

Right now what I am doing to achieve this is to first visually select some text and then store it in a register, say "p. Then I run let g:var = @p

This does not feel right. What is a better way to do it.

If it was just one word that I wanted to store in a variable then let g:var = expand('<cword>') does the job once the cursor is on that word. So I am able to avoid going to visual mode. But when there is a bunch of words involved I am looking for avoiding visual mode.

1 Answer 1


Using yank commands from normal mode is actually a common practice.

The alternative is to use getline() to get the contents of a line and then parse it, possibly using regex matches or other Vimscript string functions.

But it's often easier to use normal mode commands, especially when you're matching around the cursor position or when the text you're trying to capture may span multiple lines. (This is not that surprising, considering Vim is a text editor! So its normal mode commands are very efficient for that purpose.)

What you can do is save/restore the default register before executing a yank operation, that way you don't leave undesirable side effects from the operation capturing the text you're interested in.

For example:

function! GetLabelName() abort
    let save_reg = @"
    let save_regtype = getregtype('"')
    normal! yiB
    let label_name = @"
    call setreg('"', save_reg, save_regtype)
    return label_name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.