【问题标题】:How to not highlight values in comments in Emacs?如何在 Emacs 的注释中不突出显示值?
【发布时间】:2020-06-23 12:15:46
【问题描述】:

我想在某些配置文件中突出显示真假值。我有 这样做:

(defun my/highlight-in-properties-files ()
  "Highlight regexps in PROPERTIES files."
  (when (string-match-p ".properties" (file-name-nondirectory buffer-file-name))
    (highlight-regexp "true" 'hi-green)
    (highlight-regexp "false" 'hi-pink)))

但它也突出了 cmets 中的那些值:

有没有办法排除这些突出显示?

UPDATE -- highlight-regexp 是“hi-lock.el”中“hi-lock-face-buffer”的别名。而string-match-p是‘subr.el’中编译的Lisp函数。

【问题讨论】:

  • 能否将highlight-regexp 的值添加到问题中?
  • 另外,添加string-match-p

标签: regex emacs comments syntax-highlighting


【解决方案1】:

您可以通过font-lock-add-keywords 添加正则表达式,这已经说明了缓冲区中的注释语法,例如。

(defun my-font-lock-additions ()
  (require 'hi-lock)                    ; fonts
  (font-lock-add-keywords
   nil
   '(("\\btrue\\b"  . 'hi-green)
     ("\\bfalse\\b" . 'hi-pink)))
  (font-lock-flush))

并致电(font-lock-refresh-defaults) 以恢复到 OG 设置。

坚持使用highlight-regexp 的纯正则表达式解决方案无疑会在奇怪的情况下产生一些错误,但是,我认为仅自定义您的正则表达式以检查注释前缀可能也足够好,

(defun my/highlight-in-properties-files ()
  "Highlight regexps in PROPERTIES files."
  (when (string-match-p ".properties" (file-name-nondirectory buffer-file-name))
    (comment-normalize-vars)            ; ensure comment variables are setup
    (let ((cmt-re (format "^[^%s]*" (regexp-quote (string-trim comment-start)))))
      (highlight-regexp (format "%s\\(\\_<true\\_>\\)" cmt-re) 'hi-green 1)
      (highlight-regexp (format "%s\\(\\_<false\\_>\\)" cmt-re) 'hi-pink 1))))

【讨论】:

    【解决方案2】:

    一种方法是在您的正则表达式末尾添加一个$ 以不匹配 cmets,因为真/假总是在末尾,而 cmets 中的那些总是位于句子的中间

    (defun my/highlight-in-properties-files ()
      "Highlight regexps in PROPERTIES files."
      (when (string-match-p ".properties" (file-name-nondirectory buffer-file-name))
        (highlight-regexp "true$" 'hi-green)
        (highlight-regexp "false$" 'hi-pink)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-07
      • 2010-10-08
      • 1970-01-01
      • 2019-12-25
      • 2013-02-10
      • 2012-05-15
      • 2016-04-29
      • 1970-01-01
      相关资源
      最近更新 更多