12

When I am editing a LaTeX document in vim, often times I want to search for a phrase. Because I have LaTeX setup to wrap lines, sometimes half of the phrase will be on one line while the other half is on the next. In such a case, the search does not find what I'm looking for. So for example

blah blah blah hello
world blah blah blah

when searching using /hello world, I don't find what I'm looking for. Is there a quick and easy way to modify this search to get me where I want to be? Or better yet, a way to tell vim to match any white space (space, tab, new line) with a space in the search string?

14

After more searching, it looks like the easiest way to do this is with \_s. So for example:

/hello\_sworld
  • 4
    You might want hello\_s\+world if there could be more than one whitespace character between them, of course. – Wodin Feb 18 '11 at 22:30
5

This problem was addressed at http://vim.wikia.com/wiki/Search_across_multiple_lines. Included is a function that can do what I need.

function! SearchMultiLine(bang, ...)
  if a:0 > 0
    let sep = (a:bang) ? '\_W\+' : '\_s\+'
    let @/ = join(a:000, sep)
  endif
endfunction
command! -bang -nargs=* -complete=tag S call SearchMultiLine(<bang>0, <f-args>)|normal! /<C-R>/<CR>

Then you can do a multi-line search using :S hello world and it will convert that to hello\s\+world and search for it. Another nice feature is that this will also add this new search to the search history. This allows you to go back and modify the search using q/ if you need. It can also be used to do substitution with :%s//new thing/g. The downside to this is that it doesn't use incsearch if you have it enabled.

3

The way I know of is not hard, but it's a little tedious. Replace every space in your search query with the following:

[ \t\n]\+

(Note the space after the [.) This is regular expression matching syntax. Broken down, it means:

  • [...] means match any one of the list of characters inside the brackets.
  • \t is Tab
  • \n is Newline
  • ...\+ means match one or more of the preceding.

For more info on regular expressions, you can ask vim:

:help regexp
:help usr_27
1

I personally would use [ \t\n]* instead of spaces. This will match on zero or more of ' ', tab, and newline. This way if one instance of your search pattern spans a line break, but another doesn't, both will be matched.

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.