2011-05-26 33 views
18

我有以下defun定義如何添加一個鉤子才能在特定模式下運行?

(defun a-test-save-hook() 
    "Test of save hook" 
    (message "banana") 
) 

,我通過下鉤

(add-hook 'after-save-hook 'a-test-save-hook) 

可正常工作使用。我想要做的是限制掛鉤到特定的模式,在這種情況下org模式。任何關於如何去做這件事的想法?

在此先感謝。

回答

33

如果你看一看的文檔add-hook(或章添加F-鉤RET) ,你會發現一個可能的解決方案是將鉤子設置爲你想要的主要模式。這是略高於vderyagin的answer更多地參與,並期待這樣的:

(add-hook 'org-mode-hook 
      (lambda() 
      (add-hook 'after-save-hook 'a-test-save-hook nil 'make-it-local))) 

'make-it-local是標誌(可以是任何東西,是不是nil)告訴add-hook僅在當前緩衝區增加了鉤。通過以上操作,您只會在org-mode中添加a-test-save-hook

如果您想在多種模式下使用a-test-save-hook,這很不錯。

的文檔add-hook是:

add-hook is a compiled Lisp function in `subr.el'. 

(add-hook HOOK FUNCTION &optional APPEND LOCAL) 

Add to the value of HOOK the function FUNCTION. 
FUNCTION is not added if already present. 
FUNCTION is added (if necessary) at the beginning of the hook list 
unless the optional argument APPEND is non-nil, in which case 
FUNCTION is added at the end. 

The optional fourth argument, LOCAL, if non-nil, says to modify 
the hook's buffer-local value rather than its default value. 
This makes the hook buffer-local if needed, and it makes t a member 
of the buffer-local value. That acts as a flag to run the hook 
functions in the default value as well as in the local value. 

HOOK should be a symbol, and FUNCTION may be any valid function. If 
HOOK is void, it is first set to nil. If HOOK's value is a single 
function, it is changed to a list of functions. 
+0

是不是應該引用拉姆達? – kindahero 2011-05-26 16:45:50

+2

@ kindahero,'(lambda()...)'無論如何都會評估自己,所以引用並沒有什麼區別。 – 2011-05-26 17:31:06

+0

謝謝,這是我之後的信息。將潛入文檔。 – 2011-05-27 12:24:33

5

簡單的解決方案,我想,是添加的主要模式在鉤本身檢查:

(defun a-test-save-hook() 
    "Test of save hook" 
    (when (eq major-mode 'org-mode) 
    (message "banana"))) 

(add-hook 'after-save-hook 'a-test-save-hook) 
+0

只是測試它,和它的作品。 – 2012-09-13 14:10:41

相關問題