3

Is it possible to use word under cursor in shell command? Say:

Elvis
^ cursor here

then
:r! echo <word_under_cursor> 

and get "Elvis" read in.

2 Answers 2

7

If you are typing interactively in the vim command line you can hit CtrlrCtrlw to include the current word or CtrlrCtrla to include the current WORD.

If you are writing a function or a command you can use expand('<cword>') or expand('<cWORD>') for the current WORD version.

Like in:

function! Hello()
  echo 'The current word is: ' . expand('<cword>')
  echo 'The current WORD is: ' . expand('<cWORD>')
endfunction
2
  • 2
    Yes, using <C-r>_<C-w> solves it. Using expand() is not possible in command line mode as far as I see.
    – l00p
    Commented Jun 17, 2022 at 13:11
  • 1
    expand() is works in a "command line" context like this: :cexpr(system("find somedir -name \\*.py | xargs grep -nsi '" . expand('<cword>') . "'")) Commented Aug 13 at 20:21
1

There is something to remember: Vim treats the commands differently. Some of them accept literals and cmdline-specials, so you can do

:r !echo <cword>

(or maybe :.!echo <cword>)

While others accept VimScript expressions, so it could look as, for example,

:put=expand('<cword>')

(or maybe :put=system('echo ' .. expand('<cword>'))

So the syntax of VimScript is heavily context-dependent.

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.