scratch buffer 的 hook

elisp

#1

我想给scrach-buffer加一个hook函数。就在lisp-interaction-mode-hook里加了一个函数。

结果发现并没有运行。emacs -q 也能复现。 我估计是因为单纯打开scratch-buffer没有更改major-mode

怎么能给scrach-buffer加hook函数?就是只有打开scratch-buffer才会运行。


#2

在 after-init-hook 或者加个延时的定时器吧

(when (get-buffer "*scratch*")
  (with-current-buffer "*scratch*"
    (set-visited-file-name nil)
    (buffer-local-set-key (kbd "s-s") #'ignore)))

#3

应该没有专门的 Hook。


#5

*scratch* 比较特别,启动的时候好像并没有运行 lisp-interaction-mode-hook

但是可以手动运行 hook,或者创建一个新的 *scratch* 应用 lisp-interaction-mode 它也会运行 hook:

$ cat /path/to/test-hook-of-scratch-buffer.el
;; Usage: emacs -Q -nw -l /path/to/test-hook-of-scratch-buffer.el
;;        emacs -Q --batch -l /path/to/test-hook-of-scratch-buffer.el

(defun switch-to-scratch-buffer ()
  "Switch to *scratch* buffer."
  (interactive)
  (switch-to-buffer "*scratch*")
  (if (eq major-mode 'lisp-interaction-mode)
      (run-hooks 'lisp-interaction-mode-hook)
    (lisp-interaction-mode)))

(add-hook 'lisp-interaction-mode-hook
          (lambda ()
            (message ">>> foo")))

(add-hook 'after-init-hook 'switch-to-scratch-buffer)
(run-hooks 'after-init-hook)

;; test-hook-of-scratch-buffer.el ends here

$ emacs -Q --batch -l /path/to/test-hook-of-scratch-buffer.el
>>> foo