如何在emacs中编写密钥绑定以便轻松重复?

时间:2013-06-19 21:31:24

标签: emacs elisp

假设我将密钥绑定到某个函数,如下所示:

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

现在,我希望键绑定能够起作用:
在我第一次按C-c =后,如果我想重复函数foo,我不需要再次按C-c,而只需重复按=。然后,在我调用function-foo足够次之后,我只需按=以外的其他键(或明确按C-g)即可退出。

怎么做?

5 个答案:

答案 0 :(得分:13)

这可能是你要找的东西:

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

答案 1 :(得分: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))))

答案 2 :(得分: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")))

答案 3 :(得分:1)

您希望function-foo使用set-temporary-overlay-map

答案 4 :(得分:0)

除了使用set-temporary-overlay-map的@juanleon所建议的内容之外,这里还有一个我用得很多的替代方案。它使用标准库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