I'm setting up emacs to be my python IDE, and I've found plenty of material online that explain auto-completion, among a variety of other features. What I can't figure out, though, is how to get the syntax highlighter to do its highlighting magic on operators.
How can I customize my emacs in python mode to make + - different colors? I'd also like it to make integers, floats, and parentheses different colors as well.
i actually have something like this setup for my programming modes. this defines 2 separate faces, one for operators and one for the "end statement" symbol (not so useful in python, obviously). you can modify the "\\([][|!.+=&/%*,<>(){}:^~-]+\\)"
regex to match the operators you are interested in and customize the faces to be the color you want.
(defvar font-lock-operator-face 'font-lock-operator-face)
(defface font-lock-operator-face
'((((type tty) (class color)) nil)
(((class color) (background light))
(:foreground "dark red"))
(t nil))
"Used for operators."
:group 'font-lock-faces)
(defvar font-lock-end-statement-face 'font-lock-end-statement-face)
(defface font-lock-end-statement-face
'((((type tty) (class color)) nil)
(((class color) (background light))
(:foreground "DarkSlateBlue"))
(t nil))
"Used for end statement symbols."
:group 'font-lock-faces)
(defvar font-lock-operator-keywords
'(("\\([][|!.+=&/%*,<>(){}:^~-]+\\)" 1 font-lock-operator-face)
(";" 0 font-lock-end-statement-face)))
then, you just enable this by adding a hook to the relevant modes (this example assumes you are using "python-mode"):
(add-hook 'python-mode-hook
'(lambda ()
(font-lock-add-keywords nil font-lock-operator-keywords t))
t t)
Put the following in your ~/.emacs file:
;
; Python operator and integer highlighting
; Integers are given font lock's "constant" face since that's unused in python
; Operators, brackets are given "widget-inactive-face" for convenience to end-user
;
(font-lock-add-keywords 'python-mode
'(("\\<\\(object\\|str\\|else\\|except\\|finally\\|try\\|\\)\\>" 0 py-builtins-face) ; adds object and str and fixes it so that keywords that often appear with : are assigned as builtin-face
("\\<[\\+-]?[0-9]+\\(.[0-9]+\\)?\\>" 0 'font-lock-constant-face) ; FIXME: negative or positive prefixes do not highlight to this regexp but does to one below
("\\([][{}()~^<>:=,.\\+*/%-]\\)" 0 'widget-inactive-face)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With