Search code examples
emacsflycheckjs2-mode

Use flycheck for indent settings in js2-mode


I'm on Emacs 25.2 with js2-mode and flycheck/eslint enabled.

Currenty pressing tab (or newline) will indent as per js2-mode-js-indent-level.

I would like for it to be dynamic to match flycheck/eslint settings

Is there a way to do this ?


Solution

  • Emacs has already facilities to parse json (eslint config in this case).

    Parse config and setting indent config as js-indent-level:

    (defun js2-mode-use-eslint-indent ()
      (let ((json-object-type 'hash-table)
        (json-config (shell-command-to-string (format  "eslint --print-config %s"
                                   (shell-quote-argument
                                (buffer-file-name))))))
        (ignore-errors
          (setq js-indent-level
            (aref (gethash "indent" (gethash  "rules" (json-read-from-string json-config))) 1)))))
    
    (add-hook 'js2-mode-hook #'js2-mode-use-eslint-indent)