1

我使用这个命令来启动 emacs

$ emacs -Q c-mode-test.el

然后我使用 C-xC-e 来评估每一行

(require 'cc-mode)

(add-hook 'c-mode-common-hook '(lambda () (print "hello")))

(add-hook 'c-mode-hook '(lambda () (print "hello c")))

(c-mode)

在此之后,迷你缓冲区显示

"hello"

"hello c"

"hello c"
nil

和 c++-mode-hook 运行一样

(add-hook 'c++-mode-hook '(lambda () (print "hello c++")))

(c++-mode)

小缓冲区

"hello"

"hello c++"

"hello c++"
nil

为什么它运行两次或出现问题。

4

3 回答 3

3

您为“C”文件使用了错误的钩子。正确使用的钩子是“c-mode-hook”。

钩子“c-mode-common-hook”在每种 c 风格语言之前运行。也就是说,该钩子适用于多种语言,例如 java、objective-c、awk 等。您可以在此处找到有关这些挂钩的更多信息。

于 2015-08-24T14:22:16.183 回答
1

There is a bug report about this 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

于 2015-09-02T09:40:07.863 回答
0

似乎特定于语言的钩子不止一次运行。(run-hooks c-mode-hook)您可以通过运行or来确认是这种情况(run-hooks c-mode-common-hook),并且您会注意到您的print语句只发生了一次。

使用钩子的一般建议是不要依赖于它们的运行顺序——而不是依赖于它们运行的​​次数,这似乎是一种自然的扩展。

于 2012-08-11T05:12:29.517 回答