Emacs mode: how to specify that thing in square brackets should be colored
I write a simple emacs mode. How do I explicitly specify that all things in e.g. square brackets should be colored. Must be smth like that:
( (if thing is in square brackets) .开发者_Python百科 font-lock-string-face)
I assume you're writing a major mode, but font-lock-add-keywords
works also in minor
modes. Check out its documentation with C-h f RET font-lock-add-keywords
.
(define-derived-mode my-mode text-mode "mymode"
;; some init code
(font-lock-add-keywords nil '(("\\[\\(.*\\)\\]"
1 font-lock-warning-face prepend)))
;; some more init code
)
So here's a summary: To add new keywords to a mode
(font-lock-add-keywords 'emacs-lisp-mode
'(("foo" . font-lock-keyword-face)))
It can have regexps:
(font-lock-add-keywords 'emacs-lisp-mode '(("\\[\\(.+?\\)\\]" . font-lock-keyword-face)))
(this makes font of everything in square brackets to be of a given color)
For the current mode and current emacs session – you can just evaluate the following:
(font-lock-add-keywords nil '(("\\[\\(.+?\\)\\]" . font-lock-keyword-face)))
(note - You don't specify a mode here)
To make it permanent You can add it as a hook to the mode:
(add-hook 'bk-grmx-mode-hook
(lambda ()
(font-lock-add-keywords nil '(("\\[\\(.+?\\)\\]" . font-lock-keyword-face)))
)
)
You can also add it to a mode specification:
(define-derived-mode bk-grmx-mode fundamental-mode
(setq font-lock-defaults '(bk-grmx-keyWords))
;; the next line is added:
(font-lock-add-keywords nil '(("\\[\\(.+?\\)\\]" . font-lock-keyword-face)))
(setq mode-name "bk-grmx-mode")
You'd either have to extend the mode you're in to incorporate a new syntax rule or you can simply use highlight-regexp
for quick and dirty highlighting.
精彩评论