Question

I'm trying to setup an emacs major-mode which essentially just highlights text between lots of different characters, in different colors. I have square brackets working with:

(font-lock-add-keywords nil '(("\\[\\(.*\\)\\]"
                             1 font-lock-keyword-face prepend)))

but when I try replacing the [ and ] with other characters, it stops working. For example, round parentheses '()' does not work:

(font-lock-add-keywords nil '(("\\(\\(.*\\)\\)"
                             1 font-lock-function-name-face prepend)))

Trying single, double, or back-quotes, etc also don't work. I'm completely unfamiliar with lisp-syntax --- what am I doing wrong? Also: is there any way to include the characters bracketing the expression?

Was it helpful?

Solution

You're mixing regular expressions and regular strings.

Try these:

;; square brackets - escape the first one so you don't get a [..] regexp
(font-lock-add-keywords nil '(("\\(\\[.*]\\)"
                         1 font-lock-keyword-face prepend)))

;; parentheses - don't escape the parentheses you want to match!
(font-lock-add-keywords nil '(("\\((.*)\\)"
                         1 font-lock-keyword-face prepend)))

;; quotes - single escape so you don't break your string:
(font-lock-add-keywords nil '(("\\(\".*\"\\)"
                         1 font-lock-keyword-face prepend)))

;; other characters - not regexps, so don't escape them:
(font-lock-add-keywords nil '(("\\('.*'\\)"
                         1 font-lock-keyword-face prepend)))
(font-lock-add-keywords nil '(("\\(<.*>\\)"
                         1 font-lock-keyword-face prepend)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top