I am writing a vim plugin in vimscript where I need to search another file for the word currently under the cursor using following command:
exec 'vimgrep /' . expand('<cword>') . '/g filename'
I need to ensure that there are no regular expressions or slashes within the search pattern.
How can I escape those characters?
Start the regular expression with
\V, it turns it into “very nomagic” mode; i.e. only atoms starting with a backslash are special. Exactly this backslash is then escaped viaescape(). And, since this regexp is delimited by/.../, the forward slash must be escaped, too.If you want to make the search case-sensitive regardless of the
'ignorecase'setting, add the\Catom:/\V\C...PS: If
filenamecan contain special characters (like%), you shouldfnameescape()it, too.