In Emacs24 python mode, how to customize each syntax's color?

2k views Asked by At

For example, I want "while" to be blue, "for" to be green, how to do that? Beyond colors, can I make syntax bold or italic? Thank you so much in advance.

3

There are 3 answers

0
choroba On

The easiest way is to put the cursor into a string of the given colour and type M-xset-face-foregroundEnter. Then just confirm the face name and specify the colour. To set the face to bold or italic, use set-face-font in a similar way.

You can save the settings into your .emacs file:

(set-face-foreground 'font-lock-comment-face "gray")

This doesn't work in recent Emacs versions when hl-line-mode is enabled. You need to get the face name from C-uC-x=, as the set-face-foreground doesn't auto-complete the face name, but the hl-line face.

4
lawlist On

Because ALL of the following keywords are defined within python.el as python-font-lock-keywords, you would need to trump some of them with a different font face or hack the source for these same keywords to have different font faces:

"and" "del" "from" "not" "while" "as" "elif" "global" "or" "with" "assert" "else" "if" "pass" "yield" "break" "except" "import" "class" "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda" "try" "print" "exec" "nonlocal" "self".

The following code is an example of how to trump python-font-lock-keywords for some of the keywords that have already been defined within python.el -- in this example, while is blue with bold; and, for is green with bold and italics.   python-font-lock-keywords that are not trumped by specially defined font faces will default to font-lock-keyword-face -- I have included a sample modification of that face as well:

(custom-set-faces
  '(font-lock-keyword-face
     ((t (:background "white" :foreground "red" :bold t))))
  )

(defvar lawlist-blue (make-face 'lawlist-blue))
(set-face-attribute 'lawlist-blue nil
  :background "white" :foreground "blue" :bold t)

(defvar lawlist-green (make-face 'lawlist-green))
(set-face-attribute 'lawlist-green nil
  :background "white" :foreground "green" :bold t :italic t)

(defvar lawlist-keywords-01
  (concat "\\b\\(?:"
    (regexp-opt (list "hello" "world" "while" ))
  "\\)\\b"))

(defvar lawlist-keywords-02
  (concat "\\b\\(?:"
    (regexp-opt (list "foo" "bar" "for" ))
  "\\)\\b"))

(font-lock-add-keywords 'python-mode (list

  (list (concat
    "\\("lawlist-keywords-01"\\)") 1 'lawlist-blue t)

  (list (concat
    "\\("lawlist-keywords-02"\\)") 1 'lawlist-green t)

   ))
0
b10n1k On

Another approach is to make the change permanent

M-x customize-face RET font-lock TAB

This will give you a list to choose the face that you want to change. from the buffer that opens it shows you the current variable and you can enter the [ Choose ] link and pick from the color variables of your emacs.