help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: symbols, operators highlighting (+, -, =, <, >, etc)


From: Anselm Helbig
Subject: Re: symbols, operators highlighting (+, -, =, <, >, etc)
Date: Sat, 02 May 2009 12:58:57 +0200
User-agent: SEMI/1.14.6 (Maruoka) FLIM/1.14.8 (Shij┼Ź) APEL/10.7 Emacs/22.3 (i686-pc-linux-gnu) MULE/5.0 (SAKAKI)

Hi Laurens!

> ;;------------------------------------------------------------------------------
> ;; Highlight operators
> (font-lock-add-keywords 'python-mode
>   '(("\\." . font-lock-warning-face)
>     ("else:" . font-lock-keyword-face)
>     ("\\+" . font-lock-warning-face)
>     ("\\-" . font-lock-warning-face)
>     ("\=" . font-lock-warning-face)
>     (":" . font-lock-warning-face)
>     ("\\[" . font-lock-warning-face)
>     ("\\]" . font-lock-warning-face)
>     ("," . font-lock-warning-face)
>     ("!" . font-lock-warning-face)
>     ("(" . font-lock-warning-face)
>     (")" . font-lock-warning-face)
>     ("\<" . font-lock-warning-face)
>     ("\>" . font-lock-warning-face)))

Well, that doesn't look too bad. You can condense this code a bit:

(font-lock-add-keywords 
 'python-mode
 (cons 
  (regexp-opt '("." "else:" "+" "-" "=" ":" "[" "]" "," "!" "(" ")" "<" ">")) 
  'font-lock-warning-face))

> the problem is that this only works for python, and I don't want to
> copy/paste this to other modes, there must be a more elegant
> solution...

You can not copy this for other modes, anyway, as other modes have
different keywords. But of course, it can be done:
font-lock-add-keywords can take nil as the first argument which causes
it to add the keywords for the current buffer. We only need to make
sure it runs every time you open a file, this can be done with the
find-file-hook: 

(defun my-font-lock-keywords-hook ()
  (font-lock-add-keywords 
   nil
   (cons 
    (regexp-opt '("." "else:" "+" "-" "=" ":" "[" "]" "," "!" "(" ")" "<" ">")) 
    'font-lock-warning-face)))
(add-hook 'find-file-hook 'my-font-lock-keywords-hook)

> the other problem is that I'm abusing the warning face (because I
> don't know how to create a face)

Using something like font-lock-warning-face has the benefit that it
works with different color themes. You can define your own faces with
"defface", look it up in the elisp manual: (info "(elisp)Defining Faces")

Happy hacking!


-- 
Anselm Helbig 
mailto:address@hidden


reply via email to

[Prev in Thread] Current Thread [Next in Thread]