10

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?

2 Answers2

13

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.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
3

\V is ideal when you can use it. But on some occasions you might want to escape a string, and then include it inside a regular expression that does use magic characters.

In such situations (1), I have been using a function like this:

function! EscapeForVimRegexp(str)
  return escape(a:str, '^$.*?/\[]~')
endfunction

I'm not sure if that has escaped everything it needs to, so please let me know if you find any example which fails!

Note that if your regular expression is going to be used by GNU grep, rather than as a Vim regular expression, then you may need to escape some different things:

function! EscapeForGNURegexp(str)
  return escape(a:str, '^$.*?/\[]()' . '"' . "'")
endfunction

" Example usage
command! FndFunc exec 'grep "\<' . EscapeForGNURegexp(expand('<cword>')) . '(" . -r' | cope
joeytwiddle
  • 29,306
  • 13
  • 121
  • 110