Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting symbols automatically in Emacs

I am looking for a way to highlight symbols automatically, possibly using the package highlight-symbol.el (link).

I was wondering, is there a way so that, the first argument of all (setq ) will get automatically highlighted?

(setq thisshouldbehighlighted 1)

..and all the subsequent times when that symbol has been used / will be used.

like image 385
PascalVKooten Avatar asked Nov 03 '22 06:11

PascalVKooten


1 Answers

First of all, the following code is based on version 1.2 of highlight-symbol. Older versions lack the function highlight-symbol-add-symbol.

The basic approach is to search the buffer for "(setq ". The actual regular expression is a bit more complex, as it allows whitespace and handles defvar and defcustom.

(defun highlight-all-symbols ()
  (interactive)
  (save-excursion
    (highlight-symbol-mode 1)
    (goto-char (point-min))
    (while (re-search-forward (concat "([ \t\n]*"
                                      "\\_<\\(?:"
                                      "setq\\|defvar\\|defcustom"
                                      "\\)\\_>[ \t\n]*"
                                      "\\(\\_<\\(?:\\sw\\|\\s_\\)+\\_>\\)")
                              nil t)
      (highlight-symbol-add-symbol (concat "\\_<"
                                           (regexp-quote (match-string 1))
                                           "\\_>")))))

You'll probably want to include the code in a mode hook

 (add-hook 'emacs-lisp-mode-hook 'highlight-all-symbols)

Of course, simply highlighting all symbols set with setq can't be a perfect solution, as it ignores variable namespaces. Handling this correctly is a much bigger task, though, as it requires parsing the code. If you want to go down that rabbit hole, this might give you an idea, but I'm afraid it's not particularly documented.

like image 142
nschum Avatar answered Nov 16 '22 13:11

nschum