14

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?

Hotschke
  • 4,740
  • 26
  • 37
doraemon
  • 1,667
  • 11
  • 27

2 Answers2

9

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.

Christian Brabandt
  • 25,820
  • 1
  • 52
  • 77
2

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"
  else
    silent exe "normal! `[v`]y"
  endif

  let @/ = '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')
endfunction
dedowsdi
  • 6,248
  • 1
  • 18
  • 31