【问题标题】:Defining second font-lock-comment-face in Emacs在 Emacs 中定义第二个 font-lock-comment-face
【发布时间】:2015-02-06 17:47:09
【问题描述】:

是否可以在 Emacs 中定义第二个注释面和注释开始指示符,这样即使从第一个注释面中调用,第二个注释突出显示也会出现?

我目前有一个自定义 Emacs 模式,具有以下功能:

.emacs 文件:: (set-face-attribute 'font-lock-comment-face nil :foreground "gray70")

custom_mode.el:: (set (make-local-variable 'comment-start) "//")

是否可以添加:

.emacs 文件:: (set-face-attribute 'font-lock-comment-face nil :foreground "gray70") (set-face-attribute 'font-lock-comment2-face nil :foreground "forestgreen")

custom_mode.el:: (set (make-local-variable 'comment-start) "//") (set (make-local-variable 'comment2-start) "||")

这样一行

//测试注释:||第二个测试注释

渲染成两种颜色?

我需要在别处定义“comment2”吗?

谢谢!

【问题讨论】:

    标签: emacs emacs-faces


    【解决方案1】:

    着色 cmets 一般由 font-lock 参考模式的语法表处理,这仅支持 cmets 的一个面。

    但是,您可以为 font-lock 指定一个正则表达式以强制以您想要的任何颜色突出显示,这样我们可以指定一个匹配“//”后跟文本,然后是“||”的正则表达式后跟更多文本,并让字体锁定突出显示“||”以及以下文字。

    这是一个主要模式的基本实现。

    ;; your custom face to color secondary comments blue
    (defface my-second-comment-face '((t (:foreground "blue"))) "its a face")
    
    (define-derived-mode testy-mode fundamental-mode
      "test"
      (modify-syntax-entry ?/ "<1")
      (modify-syntax-entry ?/ "<2")
      (modify-syntax-entry 10 ">")
      (font-lock-add-keywords
       'testy-mode
       ;; this highlights || followed by anything to the end of the line as long as there is
       ;; a // before it on the same line.
       ;; the 2 means only highlight the second regexp group, and the t means highlight it
       ;; even if it has been highlighted already, which is should have been.
       '(("\\(//.*\\)\\(||.*$\\)" 2 'my-second-comment-face t))))
    

    您应该注意,这是一个基本解决方案,不能处理所有情况。像

    这样的正常情况
    foobar // comment || more comments
    

    将被正确处理,但类似

    foobar "string//string" || text 
    

    无法正常工作,|| text 将突出显示,即使 // 出现在字符串中

    如果您希望这些辅助 cmets 的字体化更“智能”,您将需要研究更高级的字体化技术。您使用jit-lock-functions 中的钩子来执行此操作。在您的 jit 锁定功能中,您需要扫描 || 文本模式并根据它是否已经在注释中突出显示它,如果您的语法表设置正确,您可以使用 syntax-ppss 找到它。

    【讨论】:

    • 这很有帮助!我假设这段代码是从 .emacs 文件中实现的?还是将其解析为修改语法条目行与其他语法表调用位于 custom_mode.el 文件中?我无法让它发挥作用,但我认为我把它放在了错误的部分。
    • 你可以在任何你想要的地方评估该代码,然后打开一个新的缓冲区,执行 M-x testy-mode 并输入图片中的文本,它应该会突出显示。如果它没有立即突出显示,请键入 M-o M-o
    • 您需要先评估代码,尝试将其粘贴到您的暂存缓冲区中并运行 M-x eval-buffer
    • 我的错误 - 对不起;当 .emacs.el 文件控制事物时,我意识到我正在修改 .emacs 文件。我在其中添加了代码,然后 M-x testy-mode 将整个文件内容更改为目标 my-second-comment-face 颜色。然而,测试行“//comment1 || comment2”仍然没有调用第二种颜色。将代码放在临时缓冲区中,然后是测试行并执行 M-x eval-buffer 返回“符号的变量值是无效的://注释”。主模式文件包含 (set (make-local-variable 'comment-start) "//") 行是否重要?
    猜你喜欢
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2022-01-17
    • 2018-07-17
    • 1970-01-01
    • 2023-03-11
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多