Avoid locking fonts inside comments

In mine font-lock-defaultsI have:

("\\(^\\| \\|\t\\)\\(![^\n]+\\)\n" 2 'factor-font-lock-comment)

The comment symbol !, and this makes the comments get the right face. This works mostly, unless there is a competing font-dependent object in the comment, such as a string (separated by double quotes):

! this line is font-locked fine
! this one is "not" because "strings"

How do you get a font lock to understand that a comment is already perfectly covered by the font and doesn’t need to try to block the font with any lines inside it? The obvious way is to add !comments to the starting class in the syntax table:

(modify-syntax-entry ?! "< 2b" table)

This solution is impossible, because function names and other characters containing !are legal, for example map! filter!and foo!bar. And adding !will lead to incorrect selection of code containing such names.

+4
source share
1 answer

This is usually a bad idea to highlight comments using the font-lock keyword. To do this, it is better to use the syntax phase.

, , , . !, . syntax-propertize-function.

. elisp. , .

: , ! , . , - .

(defun exmark-syntax-propertize (start end)
  (funcall (syntax-propertize-rules
            ("[[:alnum:]_]\\(!\\)"
             (1 "_")))
           start
           end))

(defvar exmark-mode-syntax-table
  (let ((table (make-syntax-table)))
    (modify-syntax-entry ?\n ">   " table)
    (modify-syntax-entry ?!  "<   " table)
    table))

(define-derived-mode exmark-mode prog-mode "!-Mark"
  "Major mode for !-mark."
  (set (make-local-variable 'syntax-propertize-function)
       'exmark-syntax-propertize))
+3

All Articles