简体   繁体   中英

Emacs executes `c-mode-hook` twice

Here's my emacs config

(require 'cc-mode)

(defun ffy-c-mode-hook ()
  "This is settings for the C/C++ mode"
  (message "ffy-c-mode-hook executed")
  (electric-pair-mode +1)
  (electric-indent-local-mode +1)
  (if electric-indent-mode
      (let ((binding (key-binding (kbd "RET"))))
        (local-set-key (kbd "RET") (key-binding (kbd "C-j")))
        (local-set-key (kbd "C-j") binding)))
  (c-toggle-hungry-state +1)
  (c-set-style "gnu")
  (setq c-basic-offset 4))

(add-hook 'c-mode-hook #'ffy-c-mode-hook)

Apparently c-mode-hook is executed twice, because when I open a C file I see:

user-error: Beginning of history; no preceding item
ffy-c-mode-hook executed [2 times]

Is it a feature or a bug ? No other hooks are executed multiple times AFAIK. Plus it seems that now I can't toggle features in the hook.

I looked at the variable c-mode-hook and it its value is (ffy-c-mode-hook)

The versions of Emacs and CC-mode are

GNU Emacs 24.5.1 (i686-pc-mingw32) of 2015-04-11 on LEG570
Using CC Mode version 5.32.5

Stacktrace on ffy-c-mode-hook

ffy-c-mode-hook()
run-hooks(change-major-mode-after-body-hook prog-mode-hook c-mode-common-hook c-mode-hook c-mode-hook)
apply(run-hooks (change-major-mode-after-body-hook prog-mode-hook c-mode-common-hook c-mode-hook c-mode-hook))
run-mode-hooks(c-mode-hook)
c-mode()
set-auto-mode-0(c-mode nil)
set-auto-mode()

Following my comment about the bug report http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16759 I don't think that language hooks are guaranteed to be executed once for a number of language modes. I suspect the issue is due to using define-derived-mode which is a lisp macro for defining a mode that already includes calls to hooks, this means the hooks called in the mode will be an additional execution.

You might want to try the initialization hook. The manual says:

Variable: c-initialization-hook

Hook run only once per Emacs session, when CC Mode is initialized. This is a good place to change key bindings (or add new ones) in any of the CC Mode key maps. See Sample Init File.

The sample it gives is here: https://www.gnu.org/software/emacs/manual/html_node/ccmode/Sample-Init-File.html#Sample-Init-File

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM