python语法高亮问题

python-mode有些地方高亮不正常,如图。而且revert-buffer-quick(C-x x g)和font-lock-update(C-x x f)还会无规律地改变。目前在用28.1,不过感觉这个问题存在好久了。

再补一张看上去很诡异的高亮

对高亮很在意的话,可以试试tree-sitter-hl-mode

使用前:

使用后:

emacs -Q 能复现吗?

可以zsbd

放一段 emacs -Q 有问题的python代码片段上来吧,这样别人也可以帮忙看看能否有此问题

import argparse

LIST = 'list'
DICT = 'dict'
SET = 'set'
STR = 'str'
BYTES = 'bytes'
BOOL = 'bool'
INT = 'int'
FLOAT = 'float'

types = {
    LIST: list,
    DICT: dict,
    SET: set,
    STR: str,
    BYTES: bytes,
    BOOL: bool,
    INT: int,
    FLOAT: float,
}

parser = argparse.ArgumentParser()
parser.add_argument('type')
parser.add_argument('value')
args = parser.parse_args()

_type = args.type
_value = args.value

print(repr(types[_type](_value)))

Emacs Python 语法高亮一直有问题

class Test:
    def __init__():
        self.var1 = 123
        self.var2 = self.var1

这个是你代码写的问题吧 :rofl:

defpython里是关键字,不可以用作变量名,所以这里emacs采用的是关键字的高亮

是的,我刚刚想找个更小的案例随手写的,没注意🤣,改了改了

不开tree-sitter的确有些问题

下面是开了tree-sitter的

我这里好像没问题唉, Emacs 29

用的这个 74ff6acdd36bd005fd2b5585768122ef15d047ed commit 的 Emacs.


看了一会儿,发现问题了。 args.typeargs.value 颜色不一致

python-mode.el 里的变量 python-font-lock-keywords-level-2:

(rx symbol-start
          (or
           "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
           "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
           "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
           "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
           "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
           "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
           "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
           "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
           "__import__"
           ;; Python 2:
           "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
           "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
           "intern"
           ;; Python 3:
           "ascii" "breakpoint" "bytearray" "bytes" "exec"
           ;; Special attributes:
           ;; https://docs.python.org/3/reference/datamodel.html
           "__annotations__" "__closure__" "__code__"
           "__defaults__" "__dict__" "__doc__" "__globals__"
           "__kwdefaults__" "__name__" "__module__" "__package__"
           "__qualname__"
           ;; Extras:
           "__all__")
          symbol-end) . font-lock-builtin-face)

type() 属于python builtin方法,渲染为font-lock-builtin-face

理论上说应该渲染的是 type() 之类的。但是 xx.type 也被错误的渲染了。还是说regex没法区分?

这个高亮是正确的。type被高亮是因为关键字,这是另一个问题。我从emacs-mirror上copy了最新的python.el并手动load,问题解决了。