4

I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange.

How can I set up some colors for important Django template tags?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Andrew Johnson
  • 13,108
  • 13
  • 75
  • 116

3 Answers3

6

You could use dedicated modes like django-mode or MuMaMo.

If you want something very basic, and assuming you're editing in html-mode, you could try the following:

(defun django-highlight-comments ()
  (interactive "p")
  (highlight-regexp "{%.*?%}" 'hi-orange))
(add-hook 'html-mode-hook 'django-highlight-comments)

(Just add the above lines to your .emacs or init.el, and eval it or restart emacs).

Ashutosh Mehra
  • 2,582
  • 1
  • 19
  • 15
  • 1
    Be warned though, if you added new tags while editing, you will need to re-evaluate the function (M-x django-highlight-comments) to have the new tags highlighted. Adding font-lock keyword to html-mode seems to be a better choice. – polyglot May 17 '09 at 23:18
  • At least on Emacs 23 pretest (23.0.93.1, which is where I tested the solution), _no_ re-evaluation is needed. Any complete comments like {% ... %} that are enter later are also highlighted immediately. However, I do agree with your point: as a long term solution, it is definitely better to define keywords or use a "proper" mode (django, MuMaMo, etc.) that recognizes the syntax. – Ashutosh Mehra May 17 '09 at 23:32
3

Here's what I do. It's a little more general than the code above, and it uses the built-in font-lock mechanisms.

(defvar django-tag-face (make-face 'django-tag-face))
(defvar django-variable-face (make-face 'django-variable-face))
(set-face-background 'django-tag-face "Aquamarine")
(set-face-foreground 'django-tag-face "Black")
(set-face-background 'django-variable-face "Plum")
(set-face-foreground 'django-variable-face "Black")


(font-lock-add-keywords
 'html-mode
 '(("\\({%[^%]*%}\\)" 1 django-tag-face prepend)
   ("\\({{[^}]*}}\\)" 1 django-variable-face prepend)))
Eddie Sullivan
  • 776
  • 5
  • 9
  • Is defvar necessary? can we use face symbols directly as in http://stackoverflow.com/questions/756666/match-regular-expression-as-keyword-in-define-generic-mode/756927#756927 – Yoo Jul 11 '10 at 13:40
1

Here are some links. I found them on the Google. It seems there is no one fully-complete and "official" solution to this problem, but a number of possibly quite usable substitutes avaliable.

Chris Lutz
  • 73,191
  • 16
  • 130
  • 183