简体   繁体   中英

How to not highlight values in comments in Emacs?

I want to highlight true and false values in some configuration files. I've done it this way:

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

But it also highlight those values in comments:

在此处输入图片说明

Is there a way to exclude those highlightings?

UPDATE -- highlight-regexp is an alias for 'hi-lock-face-buffer' in 'hi-lock.el'. And string-match-p is a compiled Lisp function in 'subr.el'.

You can just add the regexps via font-lock-add-keywords , which will already account for the comment syntax in the buffer, eg.

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

And call (font-lock-refresh-defaults) to revert back to OG settings.

Sticking to a purely regexp solution with highlight-regexp will undoubtebly produce some mistakes in odd cases, but, I think just customizing your regex to check for a comment prefix would probably work well enough as well,

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

A way would be to simply add a $ at the end of your regex to not match the comments, as the true/false are always at the end, while those in comments are always situated in the middle of a sentence

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM