加载后评估与模式挂钩 [英] eval-after-load vs. mode hook

查看:16
本文介绍了加载后评估与模式挂钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 eval-after-load 和使用模式钩子设置模式有区别吗?

Is there a difference between setting things for a mode using eval-after-load and using the mode hook?

我看过一些代码,其中 define-key 用于主模式钩子中,还有一些其他代码 define-key 用于 eval-after-load 表单.

I've seen some code where define-key is used inside a major mode hook, and some other code where define-key is used in eval-after-load form.

更新:

为了更好地理解,这里有一个在 org-mode 中使用 eval-after-load 和 mode 钩子的例子.代码可以运行 before (load "org")(require 'org)(package-initialize).

For better understanding, here is an example of using eval-after-load and mode hooks with org-mode. The code can run before (load "org") or (require 'org) or (package-initialize).

;; The following two lines of code set some org-mode options.
;; Usually, these can be outside (eval-after-load ...) and work.
;; In cases that doesn't work, try using setq-default or set-variable
;; and putting them in (eval-after-load ...), if the
;; doc for the variables don't say what to do.
;; Or use Customize interface.
(setq org-hide-leading-stars t)
(setq org-return-follows-link t)

;; "org" because C-h f org-mode RET says that org-mode is defined in org.el
(eval-after-load "org"
  '(progn
     ;; Establishing your own keybindings for org-mode.
     ;; Variable org-mode-map is available only after org.el or org.elc is loaded.
     (define-key org-mode-map (kbd "<C-M-return>") 'org-insert-heading-respect-content)
     (define-key org-mode-map (kbd "<M-right>") nil) ; erasing a keybinding.
     (define-key org-mode-map (kbd "<M-left>") nil) ; erasing a keybinding.

     (defun my-org-mode-hook ()
       ;; The following two lines of code is run from the mode hook.
       ;; These are for buffer-specific things.
       ;; In this setup, you want to enable flyspell-mode
       ;; and run org-reveal for every org buffer.
       (flyspell-mode 1)
       (org-reveal))
     (add-hook 'org-mode-hook 'my-org-mode-hook)))

推荐答案

包裹在 eval-after-load 中的代码只会被执行一次,所以它通常用于执行一次性设置,例如作为设置默认全局值和行为.一个例子可能是为特定模式设置默认键盘映射.在eval-after-load 代码中,没有当前缓冲区"的概念.

Code wrapped in eval-after-load will be executed only once, so it is typically used to perform one-time setup such as setting default global values and behaviour. An example might be setting up a default keymap for a particular mode. In eval-after-load code, there's no notion of the "current buffer".

模式挂钩对启用模式的每个缓冲区执行一次,因此它们用于每个缓冲区的配置.因此,模式挂钩的运行时间晚于 eval-after-load 代码;这让他们可以根据当前缓冲区中是否启用其他模式等信息采取行动.

Mode hooks execute once for every buffer in which the mode is enabled, so they're used for per-buffer configuration. Mode hooks are therefore run later than eval-after-load code; this lets them take actions based upon such information as whether other modes are enabled in the current buffer.

这篇关于加载后评估与模式挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆