简体   繁体   中英

Highlight whole line (from left border to right border) in Emacs' regexp mechanism

I'm using

(highlight-regexp ".*data id=\"[^\"]*\".*" 'hi-green)

to highlight lines containing some regexp ( data id="..." ), but it only does so from the left window border to the last char in the line .

How to get the whole line highlighted, up to the right window border ?

UPDATE -- I do need to have some highlights on the whole line, others not:

;; whole line
(highlight-regexp ".*data id=\"[^\"]*\".*" 'hi-green)
(highlight-lines-matching-regexp ".*panel.* id=\"[^\"]*\".*" 'hi-blue)

;; part of the line
(highlight-regexp "data=\"[^\"]*\"" 'hi-green)
(highlight-regexp "action id=\"[^\"]*\"" 'hi-pink)

I don't think this is possible using the font-lock mechanism, which highlight-regexp uses when font-lock-mode is active. However, highlight-regexp falls back to using overlays otherwise, and the region of the overlays can be modified to include the whole visible line.

This behaviour can be forced around calls to hi-lock-set-pattern with the following advice,

(define-advice hi-lock-set-pattern (:around (orig &rest args) "whole-line")
  (let (font-lock-mode)
    (cl-letf* ((orig-make-overlay (symbol-function 'make-overlay))
               ((symbol-function 'make-overlay)
                (lambda (&rest _args)
                  (funcall orig-make-overlay
                           (line-beginning-position) ; could start from match
                           (line-beginning-position 2)))))
      (apply orig args))))

Comment follow-up: to only highlight entire visible lines when calling highlight-regexp and the regexp ends with .* , you could use the following (don't use the previous advice)

(define-advice highlight-regexp (:around (orig regexp &rest args) "maybe-whole-line")
  (if (string-suffix-p ".*" regexp)
      ;; use modified overlay bounds
      (let (font-lock-mode)
        (cl-letf* ((orig-make-overlay (symbol-function 'make-overlay))
                   ((symbol-function 'make-overlay)
                    (lambda (&rest _args)
                      (funcall orig-make-overlay
                               (line-beginning-position) ; could start from match
                               (line-beginning-position 2)))))
          (apply orig regexp args)))
    (apply orig regexp args)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM