Q: (how) can I use occur to match a phrase that stretches over multiple lines?

Consider the following buffer:

Here's a line of text with the phrase "kittens and puppies".
Here's an awkward alternative: the phrase "kittens and
puppies" stretches across two lines.
Here's a false positive: "kittens and otters".

I'd like to identify all the locations in the buffer that contain the phrase "kittens and puppies". If I use occur, however, the following two problems arise:

  • the phrase "kittens and puppies" matches only the first line, and not the second/third where the phrase wraps over a line break.
  • the phrase "kittens" (or "kittens and") also matches the false positive on the last line.

How, if at all, can I use occur to locate the relevant lines in the buffer -- those that contain the entire phrase, or the beginning of one that wraps across lines? If occur can't do it, is there an occur-like alternative that can?

  • The question seems unclear as posed, wrt "line", e.g., matching a line across multiple lines. Perhaps you have visual lines in mind here somewhere? If so, consider clarifying that. – Drew Aug 26 '15 at 14:08
  • If you are feeling adventurous you could try helm-swoop. The prefix argument of it specifies how many lines it matches against. – clemera Aug 26 '15 at 22:17

The easiest might be (occur "kittens[ ]and[ ]puppies" nil)

If you use occur interactively, you can insert the actual newlines with C-q C-j. If you use the above lisp snippet, you can replace the newlines by \n: (occur "kittens[ \n]and[ \n]puppies" nil)

| improve this answer | |
  • Perfect. I was screwing up by using \n interactively rather than C-q C-j to insert the literal. – Dan Aug 26 '15 at 13:48

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.