准备工作
格式化是借助web-beautify来完成的, 所以需要emacs先安装web-beautify web-beautify又是借助外部工具js-beautify,所以也需要安装一下 npm install js-beautify -g
##添加配置
(require 'web-beautify)
(defun web-beautify-when-enter (&optional)
" eval web-beautify when type enter "
(interactive)
(newline-and-indent)
(save-excursion
(line-move -1)
(web-beautify-format-region web-beautify-js-program (line-beginning-position) (line-end-position))))
(defun web-beautify-when-branck (&optional)
"eval web-beautify when region"
(interactive)
(insert-char 125)
(save-excursion
(web-beautify-format-region
web-beautify-js-program
(scan-lists (point) -1 0)
(point)))
(forward-list))
然后绑定两个快捷键
; 用js2-mode的同学可以按照下面方法绑定
(add-hook 'js2-mode-hook (lambda ()
(local-set-key (kbd "RET") 'web-beautify-when-enter)
(local-set-key (kbd "}") 'web-beautify-when-branck) ))
这样在我们js2-mode中当按下enter, 或者输入 } 就可以触发自动格式化代码了.