2013-06-19 16 views
11

比方說,我綁定的關鍵是一定的功能如下:如何在emacs中編寫一個鍵綁定以方便重複?

(global-set-key (kbd "C-c =") 'function-foo) 

現在,我想重點結合作爲工作:
我按C-c =後的第一次,如果我想重複function-foo,我不需要再次按C-c,而只需重複按=即可。然後,在我調用function-foo足夠多的時間之後,我只需按除=以外的其他鍵(或明確按下C-g)即可退出。

如何做到這一點?

+1

您是否熟悉'repeat'命令?它綁定到'C-x z',你可以用它來重複前面的命令。它每次按'z'時重複該命令。 – mk1

+1

@ mk1我知道C-x z,我只是想知道我是否可以讓自己的鍵綁定以這種方式工作......無論如何,感謝您的評論 – shelper

+0

用於執行鍵盤宏的'C-x e'具有所需的行爲。如果該綁定的實現位於某個地方的elisp中,那麼這可能是您編寫自己的綁定的開始。 – pcurry

回答

12

這可能是你正在尋找的東西:

(defun function-foo() 
    (interactive) 
    (do-your-thing) 
    (set-temporary-overlay-map 
    (let ((map (make-sparse-keymap))) 
     (define-key map (kbd "=") 'function-foo) 
     map))) 
1

你想要你的function-foo使用set-temporary-overlay-map

7

有一個smartrep.el包,不正是你所需要的。這個文檔有點稀少,但是你可以通過研究github上的許多emacs配置來掌握它應該如何使用。例如(取自here):

(require 'smartrep) 
(smartrep-define-key 
    global-map "C-q" '(("n" . (scroll-other-window 1)) 
         ("p" . (scroll-other-window -1)) 
         ("N" . 'scroll-other-window) 
         ("P" . (scroll-other-window '-)) 
         ("a" . (beginning-of-buffer-other-window 0)) 
         ("e" . (end-of-buffer-other-window 0)))) 
+0

它似乎沒有明確說明,但我發現'C-g'退出重複模式。 –

4

這就是我使用的。我喜歡它,因爲您不必指定重複鍵。

(require 'repeat) 
(defun make-repeatable-command (cmd) 
    "Returns a new command that is a repeatable version of CMD. 
The new command is named CMD-repeat. CMD should be a quoted 
command. 

This allows you to bind the command to a compound keystroke and 
repeat it with just the final key. For example: 

    (global-set-key (kbd \"C-c a\") (make-repeatable-command 'foo)) 

will create a new command called foo-repeat. Typing C-c a will 
just invoke foo. Typing C-c a a a will invoke foo three times, 
and so on." 
    (fset (intern (concat (symbol-name cmd) "-repeat")) 
     `(lambda ,(help-function-arglist cmd) ;; arg list 
      ,(format "A repeatable version of `%s'." (symbol-name cmd)) ;; doc string 
      ,(interactive-form cmd) ;; interactive form 
      ;; see also repeat-message-function 
      (setq last-repeatable-command ',cmd) 
      (repeat nil))) 
    (intern (concat (symbol-name cmd) "-repeat"))) 
+1

我非常喜歡這個,但是請注意,CMD *必須*已經被加載(自動加載不足),否則arglist和交互式形式的詢問將失敗。 (實際上後者*會觸發自動加載,但在它之前的arglist將是錯誤的)。 – phils

0

除了什麼@juanleon建議,它採用set-temporary-overlay-map,這裏是我用相當多的選擇。它使用標準庫repeat.el

;; This function builds a repeatable version of its argument COMMAND. 
(defun repeat-command (command) 
    "Repeat COMMAND." 
(interactive) 
(let ((repeat-previous-repeated-command command) 
     (last-repeatable-command   'repeat)) 
    (repeat nil))) 

使用它來定義不同的可重複命令。例如,

(defun backward-char-repeat() 
    "Like `backward-char', but repeatable even on a prefix key." 
    (interactive) 
    (repeat-command 'backward-char)) 

這樣的命令然後結合至與可重複的後綴的鍵,例如,C-c =(對於C-c = = = = ...)

更多信息參見this SO post