Search code examples
regexsearchescapingvim

How to escape search patterns or regular expressions in vimscript?


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?


Solution

  • 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 via escape(). And, since this regexp is delimited by /.../, the forward slash must be escaped, too.

    exec 'vimgrep /\V' . escape(expand('<cword>'), '/\') . '/g filename'
    

    If you want to make the search case-sensitive regardless of the 'ignorecase' setting, add the \C atom: /\V\C...

    PS: If filename can contain special characters (like %), you should fnameescape() it, too.