[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: search across linebreaks

From: Nicolas Richard
Subject: Re: search across linebreaks
Date: Mon, 18 Feb 2013 14:09:53 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.2.92 (gnu/linux)

Eric Abrahamsen <> writes:
> The two solutions I can think of are: 1) break up the characters in the
> search string and insert "\n?" between each one to create regexps to
> search on, and 2) unfill the whole file at the start of the procedure
> and then refill it afterwards. Neither of these seems like a great
> idea -- does anyone have any brighter ideas?

Not bright by any means, but slightly different from your solutions. The idea
is : save newlines as markers (except if two or more consecutive), and
restore afterwards.

(defun yf/test nil ""
  (let* (lom marker
         (dict '(("foo bar" "foo barred")
                 ("foo baz" "foo bazzed")
                 ("foo foo" "foo fooed")))
         (regexp (regexp-opt (mapcar 'car dict))))
    ;; replace single newlines by markers (recorded in a list of markers)
    (while (search-forward "\n" nil t)
      (if (looking-at "\n")
          (skip-chars-forward "\n")
        (replace-match " ")
        (add-to-list 'lom (set-marker (make-marker) (point)))))
    (goto-char (point-min))
    ;; replace matches according to dict
    (while (re-search-forward regexp nil t)
      (replace-match (cadr (assoc (match-string 0) dict)) t t))
    ;; transform markers into newline again
    (while (setq marker (pop lom))
      (goto-char marker)
      (when (looking-at " ")
        (replace-match ""))
      (insert "\n"))))

There are many "areas for improvement" (aka bugs), e.g. it might be
necessary to allow more than just "\n" to be deleted/restored (I
imagine you could make `lom' into an alist of (marker . deleted-text)
and restore deleted-text instead of just inserting \n).

Test it with smth like:
   "One two foo
bar three do
bar baz foo
baz for foo

bar baz foo
bar foo bar
foo bar foo
bar foo bar")
  (goto-char (point-min))


reply via email to

[Prev in Thread] Current Thread [Next in Thread]