Question

In Emacs I would like quoted symbols in emacs lisp such as: 'blah and display them in a different color. How can I use font-lock mode to do this?

Était-ce utile?

La solution

Try:

(font-lock-add-keywords 'emacs-lisp-mode
                        '(("'[-a-zA-Z_][-a-zA-Z0-9_]*\\>" 0 'font-lock-constant-face)))

Or (if you don't want the quote colored):

(font-lock-add-keywords 'emacs-lisp-mode
                        '(("'\\([-a-zA-Z_][-a-zA-Z0-9_]*\\)\\>" 1 'font-lock-constant-face)))

This will not color things in comments or strings, as they are colored in earlier, and font-lock (by default) doesn't re-color things.

Autres conseils

Following code will enable syntax highlighting for quote itself and the symbol following it with different faces. You can also customize the two faces if you want. You might also want to be able to spot difference between '(hello world) and (hello world) easily. For that, highlighting the quote may not be enough, so the commented out parts of the code are for highlighting open parenthesis following a quote. They are commented out because I don't think it's compatible with other packages that highlight nested parenthesis in different colors and you are very likely to be using one of those packages.

(defface my-lisp-quoted-symbol-face
  '((t :inherit font-lock-constant-face))
  "Face for Lisp quoted symbols.")

(defface my-lisp-quote-face
  '((t :inherit warning))
  "Face for Lisp quotes.")

;; (defface my-lisp-quoted-open-paren-face
;;   '((t :weight bold
;;        :inherit my-lisp-quoted-symbol-face))
;;   "Face for Lisp quoted open paren.")

(defvar my--lisp-quote-regexp
  (rx (group "'")
      (or symbol-start
          (group (syntax open-parenthesis)))))

(defvar my--lisp-quoted-symbol-regexp
  (rx "'" (group (+ (or (syntax symbol)
                        (syntax word))))))

(dolist (mode (list 'emacs-lisp-mode
                    'lisp-mode))
  (font-lock-add-keywords mode
                          `((,my--lisp-quote-regexp
                             (1 'my-lisp-quote-face)
                             ;; (2 'my-lisp-quoted-open-paren-face nil t)
                             )
                            (,my--lisp-quoted-symbol-regexp
                             1 'my-lisp-quoted-symbol-face))))

Use of defface and rx make the code more verbose. Benefit of defface is easy customization of faces. Benefit of rx comes when you try to modify this code for other purposes (for example, if you want to make it also take care of backquotes.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top