6

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?

2
  • 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. Commented Aug 26, 2015 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. Commented Aug 26, 2015 at 22:17

1 Answer 1

5

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)

1
  • Perfect. I was screwing up by using \n interactively rather than C-q C-j to insert the literal. Commented Aug 26, 2015 at 13:48

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.