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?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityDoes 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?
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"
else
silent exe "normal! `[v`]y"
endif
let @/ = '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')
endfunction