Does vim allow for searching raw strings?

If what I want to search is in the variable string, does the following code work?

call search('\V' . escape(string, '\'))

Or are there other more direct ways?

  • 3
    No, that is the only possibility. There is no other way to search literally. Sep 24 '18 at 10:24
  • 1
    @ChristianBrabandt care to write an answer?
    – D. Ben Knoble
    Sep 24 '18 at 12:45

Vim does not have an (easy) native way to search for text literally. However, I find that the default of using regular expressions makes the search quite a bit more powerful, if you have grokked at least the basics.

For the few times I have needed to search for text literally, I use basically what you have shown here:

call search('\V' . escape(string, '\'))

which you can wrap into a custom command to make searching text literally more easy:

" Search literally!
com! -nargs=1 Search :let @/='\V'.escape(<q-args>, '\\')| normal! n

So you can search literally by using

:Search my literal text with \\ and . and ^ and more regexpes

to search for the text "my literal text with \ and . and ^ and more regexpes.

This command I have taken from my .vimrc but I can't remember if I ever actually used that command, besides showing how to make searching for a literal text more easily available.


If you want to search multi-line literal text:

call search('\V' . substitute(escape(text, '\'), '\n', '\\n', 'g'))

here is an operator that set up multiline literal search pattern:

nnoremap ,l  :set opfunc=<sid>search_literal<CR>g@
vnoremap ,l  :<c-u>call <sid>search_literal(visualmode(), 1)<cr>

function! s:search_literal(type, ...) abort

  if a:0
    silent exe "normal! gvy"
  elseif a:type ==# 'line'
    silent exe "normal! '[V']y"
    silent exe "normal! `[v`]y"

  let @/ = '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.