如何让 emacs 光标与背景文字同色?

如题,我记得有一个package,可以使光标与它下面被高亮的文字保持同一种颜色(效果如图)

2022-05-08-154420_476x229_scrot

有哪位大佬知道是什么吗?

建议修改标题,使其成为完整的句子:

- emacs 光标与背景文字同色
+ 如何让 emacs 光标与背景文字同色?
1 个赞

我自己实现了一下

(defvar last-post-command-position 0
  "Holds the cursor position from the last run of post-command-hooks.")

(make-variable-buffer-local 'last-post-command-position)

(defun real-time-cursor-color ()
  (unless (equal (point) last-post-command-position)
    (set-cursor-color (foreground-color-at-point)))
  (setq last-post-command-position (point)))

(add-to-list 'post-command-hook #'real-time-cursor-color)

不过似乎在hl-line-mode的情况下. (foreground-color-at-point)只能获取到hl-line的foreground

我找到了一个package应该符合你的要求: smart-cursor-color.el, 不过同样的, 它也会与hl-mode产生冲突, README 里面说:

But when global-hl-line-mode is on, smart-cursor-color-mode is work.

而我实际使用的时候仍然会产生冲突

text-properties-at 读取 face 然后得到正确的 foreground:

$ emacs -Q -f hl-line-mode --eval "
  (run-with-idle-timer
   0 nil
   (lambda ()
     (goto-char (point-min))
     (let ((face (cadr (memq 'face (text-properties-at (point))))))
       (when face
         (message (face-foreground (if (consp face) (car face) face) nil t))))))
  "

image


smart-cursor-color 把问题搞复杂了。我用 emacs-29 -Q 试了一下,global-hl-line-mode 的时候,只有上下移动光标的时候背景色是正确的。估计是它里边几个状态 last/default/saved 没管理好。

2 个赞

对, text-properties-at确实可以获取正确的内容, 我写了个简单的minor-mode代替了smart-cursor-color:

(defvar rtcc--default-cursor-color nil
  "Default cursor color.  When picked foreground color is nil, use this.")

(defvar rtcc--last-post-command-position 0
  "Holds the cursor position from the last run of post-command-hooks.")

(make-variable-buffer-local 'rtcc--last-post-command-position)

(defgroup real-time-cursor-color nil
  "real time cursor group"
  :group 'cursor)

(defun rtcc--set-cursor-color ()
  "Change cursor color dynamically."
  (unless (equal (point) rtcc--last-post-command-position)
    (let ((face (cadr (memq 'face (text-properties-at (point))))))
      (if face
          (set-cursor-color (face-attribute face :foreground))
	(set-cursor-color rtcc--default-cursor-color))))
  (setq rtcc--last-post-command-position (point)))

(define-minor-mode real-time-cursor-color-mode
  "Dynamically changed cursor color at point's color."
  :lighter " rtcc"
  :global t
  :group 'real-time-cursor-color
  :require 'real-time-cursor-color
  (if real-time-cursor-color-mode
      (progn
        (setq rtcc--default-cursor-color (face-attribute 'default :foreground))
        (add-hook 'post-command-hook 'rtcc--set-cursor-color))
    (remove-hook 'post-command-hook 'rtcc--set-cursor-color)))

(provide 'real-time-cursor-color)
1 个赞

这个思路是正确的,只要读取到当前字符的颜色就行了。