2011年10月13日木曜日

同じ単語(シンボル)をハイライト表示する

EmacsのOverlayを使ってみるテスト。カーソル位置にある単語(symbol-at-pointで取得できるもの)と同じ単語をハイライト表示させます。

show-paren-modeみたいにタイマーを使ったほうが良いかも。

(eval-when-compile (require 'cl))

(defvar *hl-same-symbol::text* "")
(defvar *hl-same-symbol::list* nil)
(defvar hl-same-symbol-face 'highlight)

(defun hl-same-symbol::highlight (text)
(setf *hl-same-symbol::text* text)
;; (highlight-regexp (regexp-quote text) hl-same-symbol-face)
(let ((len (length text)))
(save-excursion
(dolist (win (window-list))
(with-current-buffer (window-buffer win)
(goto-char (window-start win))
(while (let ((pos (search-forward text nil t)))
(and pos (< (- pos len) (window-end win))))
(hl-same-symbol::highlight-internal text len)))))))

(defun hl-same-symbol::highlight-internal (text len)
(let ((sym (symbol-at-point)))
(when (and sym (equal (symbol-name sym) text))
(let ((overlay (make-overlay (- (point) len) (point))))
(overlay-put overlay 'face hl-same-symbol-face)
(push overlay *hl-same-symbol::list*)
overlay))))

(defun hl-same-symbol::unhighlight ()
;; (unhighlight-regexp (regexp-quote *hl-same-symbol::text*))
(mapcar 'delete-overlay *hl-same-symbol::list*)
(setf *hl-same-symbol::list* nil))

(defun hl-same-symbol::post-command-hook ()
(let ((sym (symbol-at-point)))
(cond
((and sym (equal (symbol-name sym) *hl-same-symbol::text*))
'nothing-to-do)
(sym
(hl-same-symbol::unhighlight)
(hl-same-symbol::highlight (symbol-name sym)))
(t
(hl-same-symbol::unhighlight)))
t))

(defun hl-same-symbol ()
(interactive)
(if (find 'hl-samey-symbol::post-command-hook post-command-hook)
(remove-hook 'post-command-hook 'hl-same-symbol::post-command-hook)
(add-hook 'post-command-hook 'hl-same-symbol::post-command-hook)))

0 件のコメント:

コメントを投稿