Emacs mode to edit JSON

后端 未结 12 1742
面向向阳花
面向向阳花 2021-01-30 12:15

Does anybody know a good Emacs mode to edit JSON? An app I am working on uses a JSON based communication protocol and having the data nicely indented and syntax-highlighted woul

12条回答
  •  执笔经年
    2021-01-30 13:03

    I've expanded on Mariusz Nowak's workaround, to make it usable as a major mode in its own right. Little modification was required beyond simply deriving the mode; the only change Nowak's work actually needed was the ability to recognize buffers not associated with files, or associated with files whose names don't end in .json, as JSON, which we accomplish with a buffer-local variable.

    Here's the augmented workaround:

    (make-variable-buffer-local 'js2-parse-as-json)
    
    (defadvice js2-reparse (before json)
        (setq js2-buffer-file-name buffer-file-name))
    (ad-activate 'js2-reparse)
    
    (defadvice js2-parse-statement (around json)
        (if (and (= tt js2-LC)
               js2-buffer-file-name
               (or js2-parse-as-json
                   (string-equal (substring js2-buffer-file-name -5) ".json"))
               (eq (+ (save-excursion
                        (goto-char (point-min))
                        (back-to-indentation)
                        (while (eolp)
                          (next-line)
                          (back-to-indentation))
                        (point)) 1) js2-ts-cursor))
          (setq ad-return-value (js2-parse-assign-expr))
            ad-do-it))
    (ad-activate 'js2-parse-statement)
    
    (define-derived-mode json-mode js2-mode "JSON"
      "Major mode for editing JSON data."
      :group 'json
      (setq js2-parse-as-json t)
      (js2-reparse t))
    
    (add-to-list 'auto-mode-alist '("\\.json$" . json-mode))
    

    If you already use js2-mode, this may be a better option than js-mode plus flymake-json because you need not install anything new (js2-mode already does syntax checking, no need for an external tool), and because this mode will inherit your js2-mode configuration, which js-mode will not.

提交回复
热议问题