help-gnu-emacs
[Top][All Lists]
Advanced

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

Inserting before-match, matched-text, after-match to coloursize matched-


From: Heime
Subject: Inserting before-match, matched-text, after-match to coloursize matched-text
Date: Sun, 08 Sep 2024 01:23:53 +0000

Is it better to insert the whole match by first inserting the context 
before the match, then the highlighted match itself, followed by the 
context after the match ?

Or as I am doing, inserting the whole context using re-search-forward
and then applying the overlay ?



(defun xiakos-context (search-text &optional n)
  (setq n (or n 8))

  (save-excursion

    (goto-char (point-min)) ;; Start from the beginning of the buffer

    (let ( (search-regexp
               (replace-regexp-in-string " " "[ \n]*"
                 (regexp-quote search-text))))

      (if (re-search-forward search-regexp nil t)

          (let* ( (match-start (match-beginning 0))

                  (match-end (match-end 0))

                  ;; Calculate the line numbers for context
                  (start-line (max 1 (- (line-number-at-pos match-start) n)))

                  (end-line (+ (line-number-at-pos match-end) n))

                  (context-start (progn (goto-line start-line) (point)))

                  (context-end (progn (goto-line end-line) (line-end-position)))

                  (context (buffer-substring-no-properties context-start 
context-end))

                  (context-buffer (get-buffer-create "*Search Context*")) )

            (with-current-buffer context-buffer
              (erase-buffer)

              (insert context)
              (goto-char (point-min))

              (font-lock-mode 1)
              (while (re-search-forward search-regexp nil t)
                (let ( (overlay (make-overlay (match-beginning 0) (match-end 
0))) )
                        (overlay-put overlay 'face '(:foreground "yellow")))) )

              (goto-char (point-min)))

            (display-buffer context-buffer))) )) )




reply via email to

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