js2-mode-hook 影响到 其他major-mode


#1

我有如下配置, 在保存 .js 文件执行后可以用eslint --fix

(defun eslint-fix-file ()
  (interactive)
  (message "eslint --fixing the file" (buffer-file-name))
  (shell-command (concat "eslint --fix " (buffer-file-name))))

(defun eslint-fix-file-and-revert ()
  (interactive)
  (eslint-fix-file)
  (revert-buffer t t))

(add-hook 'js2-mode-hook
          (lambda ()
            (add-hook 'after-save-hook #'eslint-fix-file-and-revert)))

它在js文件(major mode是js2-mode)运行正常。但是当我打开.el文件(major mode是elisp-mode),修改save后,也会执行eslint --fix。请教下这是为什么?


#2

因为最终使函数 eslint-fix-file-and-revert 生效的钩子是 after-save-hook 而不是 js2-mode-hook。 可以在执行函数 eshlint-fix-file-and-revert 之前判断使用的 Major-mode 是否为 js2-mode, 如果为则执行函数 。代码如下:

(add-hook 'after-save-hook 
          (lambda ()
            (when (eq major-mode 'js2-mode)
                   (eshlint-fix-file-and-revert))))

#4

多谢!It works!


#5

默认情况下是的 . 可以试试

(add-hook 'after-save-hook #'function-a nil t)

因为 add-hook 的用法是:

(add-hook HOOK FUNCTION &optional DEPTH LOCAL)

且对 LOCAL 的描述

The optional fourth argument, LOCAL, if non-nil, says to modify the hook’s buffer-local value rather than its global value. This makes the hook buffer-local, and it makes t a member of the buffer-local value. That acts as a flag to run the hook functions of the global value as well as in the local value.