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