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
where init.el
is:
(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?
Update:
I also tried to replace my-json-mode-hook
with:
(defun my-json-mode-hook ()
(modify-syntax-entry ?# "< b")
(modify-syntax-entry ?\n "> b"))
But then nothing is highlighted.
json-mode
package is that — there's only ajson
in the default package list? If I copy yourinit.el
then buffers for.json
files are still in Javascript mode as they are by default. If I use yourmodify-syntax-entry
-based hook and add it tojs-mode-hook
, the#…
comment is highlighted as expected.json-mode
from the Emacs package manager. The GitHub page of the mode is github.com/joshwnj/json-mode.