在 Emacs 的正则表达式机制中高亮整行(从左边界到右边界)

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

我正在使用

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

突出显示包含一些正则表达式 (data id="...") 的行,但它只从 左 window 边界 这样做行中的最后一个字符.

如何突出显示整行,直到 右 window 边框

更新——我确实需要在整行中添加一些亮点,其他的则不需要:

;; 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)

认为 这可以使用字体锁定机制实现,highlight-regexpfont-lock-mode 处于活动状态时使用。但是,highlight-regexp 退回到使用覆盖,否则可以修改覆盖区域以包括整个可见线。

可以根据以下建议在对 hi-lock-set-pattern 的调用周围强制执行此行为,

(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))))

评论后续:在调用 highlight-regexp 且正则表达式以 .* 结尾时仅突出显示整个可见行,您可以使用以下内容(不要使用之前的建议)

(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)))