Search code examples
vim

How to properly expand <cword> inside an execute command in vim


I am trying to use vim's :exe command to vimgrep the word under cursor, but I am having problems with the command construction:

If my command is

:execute "vimgrep " shellescape(expand("<cword>")) " somedir"

it expands to

execute "vimgrep 'foo' somedir"

But if my command is

execute "vimgrep " .. shellescape(expand("<cword>")) .. " somedir"

it expands to

execute "vimgrep '' somedir"

How do I correctly expand <cword> raw, without single quotes?


Solution

  • Wrapping something in single quotes is the main purpose of shellescape(). If you don't want those quotes, don't use shellescape().

    :help shellescape() is used for preparing commands before they are shelled out. Since :help vimgrep is an internal tool and nothing is sent to a shell, there is no need for quoting.

    This means that the following command should cover most of your needs:

    :execute "vimgrep " .. expand("<cword>") .. " somedir"
    

    Also, :vimgrep searches in files, not directories. Your command should then look more like:

    :execute "vimgrep " .. expand("<cword>") .. " somedir/*"