如何在python模式下自定义emacs以突出显示运算符?

时间:2011-04-29 10:45:27

标签: emacs

我正在设置emacs作为我的python IDE,我在网上发现了很多可以解释自动完成的材料,以及其他各种功能。但是,我无法弄清楚的是如何让语法高亮显示器在操作符上突出显示魔法。

如何在python模式下自定义emacs以制作+ - 不同的颜色?我也喜欢它使整数,浮点数和括号也有不同的颜色。

3 个答案:

答案 0 :(得分:5)

我的编程模式实际上有这样的设置。这定义了两个独立的面,一个用于运算符,一个用于“结束语句”符号(显然在python中不太有用)。您可以修改"\\([][|!.+=&/%*,<>(){}:^~-]+\\)"正则表达式以匹配您感兴趣的运算符,并将面部自定义为您想要的颜色。

(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)))

然后,你只需通过在相关模式中添加一个钩子来启用它(这个例子假设你使用的是“python-mode”):

(add-hook 'python-mode-hook
                  '(lambda ()
                     (font-lock-add-keywords nil font-lock-operator-keywords t))
                  t t)

答案 1 :(得分:3)

将以下内容放在〜/ .emacs文件中:

;
; 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)))

答案 2 :(得分:0)

添加我自己的答案,因为我无法让其他人工作(截至emacs 25.3.1,2017)。

以下elisp可用于突出显示运算符:

;; Operator Fonts
(defface font-lock-operator-face
 '((t (:foreground "#8b8bcd"))) "Basic face for operator." :group 'basic-faces)

;; C-Like
(dolist (mode-iter '(c-mode c++-mode glsl-mode java-mode javascript-mode rust-mode))
  (font-lock-add-keywords mode-iter
   '(("\\([~^&\|!<>=,.\\+*/%-]\\)" 0 'font-lock-operator-face keep))))
;; Scripting
(dolist (mode-iter '(python-mode lua-mode))
  (font-lock-add-keywords mode-iter
   '(("\\([@~^&\|!<>:=,.\\+*/%-]\\)" 0 'font-lock-operator-face keep))))