2010-04-29 86 views
59

使用eval-after-load並使用模式掛鉤爲模式設置東西有區別嗎?eval-after-load vs.模式掛鉤

我已經看到一些代碼,其中define-key被用在一個主要的模式鉤子裏面,還有一些代碼被用在eval-after-load的窗體中。


更新:

爲了更好地理解,下面是使用的例子EVAL-後負荷和模式鉤與組織模式。代碼可以在(load "org")(require 'org)(package-initialize)之前運行。包裹在eval-after-load

;; 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))) 
+3

+1 for *「org」,因爲C-h f org-mode RET表示組織模式在org.el *中定義。我正在努力獲得'eval-after-load'來實際評估'nxml-mode',並且這個提示很有用! – 2014-10-12 19:40:08

回答

84

碼將只執行一次,因此它通常被用於執行一次性設置,如設置缺省全局值和行爲。一個例子可能是爲特定模式設置默認的鍵盤映射。在eval-after-load代碼中,沒有「當前緩衝區」的概念。

模式掛鉤爲啓用模式的每個緩衝區執行一次,因此它們用於每個緩衝區的配置。因此,模式掛接比eval-after-load代碼晚;這可以讓他們根據這些信息來採取行動,例如當前緩衝區中是否啓用了其他模式。

+0

在附註(如果我錯了,請糾正我):emacs-lisp-mode和lisp-mode似乎在加載自定義eval-after-load腳本之前被加載。所以在這種情況下,可能確實需要使用模式鉤子。 – balu 2014-01-10 02:35:28

+1

是的:在加載相關庫之後,加載後的eval-block總是'eval''d *。但是請注意,在調用相關庫中的任何函數之前,代碼將始終執行*。因此,如果你('eval-after-load'lisp-mode ...)',那麼這個塊中的'...'代碼將在'lisp-mode.el'中的'lisp-mode'函數之前運行。叫做。 – sanityinc 2014-01-10 11:17:52

+0

對不起。當然,執行** - load之後,庫在eval - **之前加載。但是至於emacs-lisp-mode和lisp-mode,它們似乎並沒有被執行:我試圖修改它們的鍵盤映射,它們在模式鉤子中工作正常,但不是在加載後的eval塊中(沒有任何變化) 。但是,使用python模式和其他模式,一切正常。所以我的猜測是emacs-lisp和lisp模式是異常的,並且在某種程度上是內置的,因爲它們在您的Emacs配置被解析之前加載。 – balu 2014-01-10 16:55:38