【问题标题】:Emacs syntax highlighting of optional parts可选部分的 Emacs 语法高亮
【发布时间】:2012-10-24 08:11:44
【问题描述】:

我正在尝试从基本模式编写派生模式。假设我有这个正则表达式:A ((foo)bar)? B,我怎样才能告诉 emacs 使用以下面孔?

  • font-lock-keyword-faceA
  • font-lock-warning-facefoo(但不是 bar
  • font-lock-constant-faceB

我已尝试使用以下代码:

(defvar myregexp
  "\\(A\\) \\(?:\\(foo\\)bar \\)?\\(B\\)")

(setq mylang-font-lock-keywords `(
  (, myregex 1 font-lock-keyword-face)
  (, myregex 2 font-lock-warning-face)
  (, myregex 3 font-lock-constant-face)
))

但它不适用于字符串A B(emacs 报告缺少捕获)。

【问题讨论】:

    标签: emacs elisp font-lock emacs-faces


    【解决方案1】:

    按照指定正则表达式的方式,AB 之间需要两个空格。要么在可选的 foobar 部分中拉出第二个空格,要么在其后使用 *?

    【讨论】:

    • 错字,已修复。丢失的捕获错误仍然存​​在 (Error during redisplay: (error "No match 3 in highlight (1 font-lock-constant-face)"))
    • 您引用的错误(“突出显示中没有匹配 3(1 font-lock-constant-face)”)没有多大意义,也与您的代码不匹配(您的代码有 3与 font-lock-constant-face 相关联,而不是 1)。
    【解决方案2】:

    使用启用了 laxmatch 的 subexp 荧光笔让 font-lock-mode 忽略匹配中缺失的组:

    (setq mylang-font-lock-keywords
          `((,myregexp (1 font-lock-keyword-face)
                  (2 font-lock-warning-face nil t)
                  (3 font-lock-constant-face))))
    

    每个子表达式突出显示的第四个元素是laxmatch 参数。如果tmyregexp的匹配结果中没有找到第一个元素中的对应组,则font-lock-mode忽略此荧光笔。

    有关详细信息,请参阅 Emacs Lisp 手册中的 Search-based Fontification

    【讨论】:

    • 这只是第二场比赛需要的,但在任何地方都可以使用它(我实际上认为默认情况下 font-lock 是 non-lax 是一个错误)。此外,您明智地将规则更改为只使用一次myregex,这将使代码速度提高大约 3。但是您需要将关键字包装到另外一对括号中。
    • @Stefan 感谢您的更正。我已经相应地更新了代码。
    猜你喜欢
    • 2010-10-26
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多