I am trying to add a comment feature to
json-mode. A comment starts with
a hash sign and ends at the end of the line. However, if the hash sign is inside a string it should not count as the start of the comment. For example:
I am using Emacs 24.4, and installed
json-mode from the package manager in Emacs.
Here is a minimal example:
$ emacs -Q -l init.el test.json
(setq package-load-list '((json-mode t) (json-reformat t) (json-snatcher t))) (require 'package) (package-initialize) (setq package-enable-at-startup nil) (defun my-json-mode-comment-highlighter (limit) "When this function is called, it receives one argument `limit', the limit of the search; it should begin searching at point, and not search beyond the limit. It should return non-nil if it succeeds, and set the match data to describe the match that was found. Returning nil indicates failure of the search. Fontification will call function repeatedly with the same limit, and with point where the previous invocation left it, until function fails. On failure, this function need not reset point in any particular way." (let ((repeat 1) (noerror t)) (re-search-forward "\\(#.*\\)$" limit noerror repeat))) (defun my-json-mode-hook () (let* ( ;; `sub-expression', specifies which subexpression of matcher should ;; be highlighted (instead of the entire text that matcher matched) (sub-expression 1) ;; If `override' is t, override existing fontification made by previous ;; elements of `font-lock-keywords' (override t) ;; If `mode' is nil, adds keywords to `font-lock-keywords' in the current buffer. (mode nil) (keywords `((my-json-mode-comment-highlighter ,sub-expression font-lock-comment-face ,override)))) (font-lock-add-keywords mode keywords))) (add-hook 'json-mode-hook #'my-json-mode-hook)
This will highlight comments correctly, but also incorrectly assume that a hash sign inside a string starts a comment.
How can I extend the function
my-json-mode-comment-highlighter so it works as desired?
I also tried to replace
(defun my-json-mode-hook () (modify-syntax-entry ?# "< b") (modify-syntax-entry ?\n "> b"))
But then nothing is highlighted.
json-modepackage is that — there's only a
jsonin the default package list? If I copy your
init.elthen buffers for
modify-syntax-entry-based hook and add it to
#…comment is highlighted as expected.
json-modefrom the Emacs package manager. The GitHub page of the mode is github.com/joshwnj/json-mode.