6

I want to write a function which copies, say, the last word of the next line which contains keyword into a variable say var or any named register say l.

I did something inelegant:

function! CopyIntoVar()
          "go to the next line which contains keyword
    /keyword

          "go to the last word and copy it like one does using normal mode
    normal $vb"ly
    let var=@l
endfunction

Is there a better way?

(I am not particularly interested in the last word. Just want to see how to copy a desired string into a register or variable).

Thanks.

6

I think you're looking for the expand() function:

Expand wildcards and the following special keywords in `{expr}`.

with the <cword> or <cWORD> special keywords:

<cword>     word under the cursor
<cWORD>     WORD under the cursor

Your function would then look like:

function! CopyIntoVar()
    " Go to the next line which contains keyword
    /keyword

    " Go to the last word
    normal $

    " Get the value of the word under the cursor
    let var = expand('<cword>')
endfunction

This still has 2 side-effects though:

  • It will move the cursor
  • Using / will set the "/ register (and pressing n now searches for that pattern).

This may or may not be what you want.

We can use the search() function to avoid setting "/, and use getpos() and setpos() to set & restore the cursor position:

Another advantage of search() it's not affected by settings such as wrapscan or magic; it always behaves the same.

function! CopyIntoVar()
    " Save cursor position
    let l:save_cursor = getpos(".")   

    " Go to the next line which contains keyword
    call search('keyword')

    " Go to the last word
    normal $

    " Get the value of the word under the cursor
    let var = expand('<cword>')

    " Restore cursor position
    call setpos('.', l:save_cursor)   
endfunction
  • Very helpful. Can you tell me just one thing though. Is it necessary use a variable of the type l:save_cursor. Woudn't just save_cursor suffice? – caffeinemachine Jun 7 '15 at 2:41
  • 2
    @caffeinemachine Yeah, the l: is mostly optional, I like typing it anyway, but you don't have to ;-) Just remember that if a special (v:) variable exists it takes precedence. – Martin Tournoij Jun 7 '15 at 2:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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