4

I frequently search in my files using /, and \c is really helpful in these situations. Is there any similar way to ignore white space and line breaks? It would really be nice to be able to add something, like \<something>, to the search

/the words I am looking for

so that it would match this, even if there where multiple white spaces and line breaks in-between the words. It is a bit tedious to have to write

/the\_\s*words\_\s*I\_\s*am\_\s*looking\_\s*for

every time I want to search. In this example I somehow indicated that it was the spaces that represented the places where the extra white space or line breaks could occur, however, it would not bother me if it also matched something like

t h e   wo r d sI a   m l o o k i ngfor

as there will usually not be any "silly" matches of this sort (or at least few) in the searches I make.

I am not in very high hopes that this is possible, and, in case there is nothing like this, is there other ways to obtain something similar, with a function maybe. However, it is only relevant, it if makes it easier than typing

/the\_\s*words\_\s*I\_\s*am\_\s*looking\_\s*for
5

You can use a mapping and replace all spaces by e.g. \_s* which would match linebreaks as well. Something like this should work:

:func! ReplaceSearch()
if getcmdtype() =~# '[?/]'
    return substitute(getcmdline(), ' \+', '\\_s*', 'g')
else
    return getcmdline()
endif
:endfunc
:cmap <F7> <C-\>eReplaceSearch()<CR>

This maps F7 in command line mode, so hit F7 when entering a search pattern to have it transformed.

Theoretically, you could use the enter key for mapping, but if your function makes an error you will never get out of the command line again. Therefor I usually don't advise to map that key.

  • That was way better than I had actually hoped for, and it tough me a few new things above Vim. Thanks. Could I get you to mention briefly that you have to press <kbd>F7</kbd> before "executing" the search. I had myself never used/seen cmap before, or, if not, would it be all right if I did it? The Vim help files did not really help me out when I tried to understand how to use your solution. – Kristian Jul 18 '16 at 20:04
  • @Kristian yes, you need to press f7 when entering the search – Christian Brabandt Jul 19 '16 at 17:14
  • Yes, I found out, but I wanted to know if I might ad it as a note to your answer. – Kristian Jul 20 '16 at 14:15

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.