[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Colour search-text across multiple lines in the created buffer
From: |
Heime |
Subject: |
Colour search-text across multiple lines in the created buffer |
Date: |
Sat, 07 Sep 2024 18:50:10 +0000 |
Sent with Proton Mail secure email.
On Sunday, September 8th, 2024 at 4:20 AM, Heime <heimeborgia@protonmail.com>
wrote:
> I want to colour the search-text in the created buffer, even when
> the search text spans multiple lines. How can I do it ?
>
> (defun xiakos-context (search-text &optional n)
>
> ;; Set a default value for N if not provided
> (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))
>
> (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))
>
> ;; Create a temporary buffer to display the context
> (context-buffer
> (get-buffer-create "Search Context")) )
>
> (with-current-buffer context-buffer
> (erase-buffer)
> (insert context)
>
> (font-lock-mode 1)
>
> ;; Highlight the search text
> (let ((pos 0))
> (while (setq pos
> (string-match search-regexp context pos))
>
> (let ((overlay (make-overlay
> (+ context-start pos)
> (+ context-start (match-end 0)))))
> (overlay-put overlay 'face '(:background "yellow"))
> (setq pos (match-end 0)))))
>
> (goto-char (point-min)))
>
> (display-buffer context-buffer))) )) )
I see the problem - context-start and context-end refer to the
positions in the original buffer, but the highlighting is supposed
to be applied to the text in the newly created buffer, which doesn't
directly correspond to the same positions.
Is it a good strategy to use an overlay to colour the matched string
in thus case ?