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

she*_*per 12 emacs elisp

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

(global-set-key (kbd "C-c =") 'function-foo)
Run Code Online (Sandbox Code Playgroud)

现在,我想让键绑定工作为:
在我C-c =第一次按下之后,如果我想重复函数foo,我不需要C-c再次按下,而只需重复按下=.然后,在我调用function-foo足够次之后,我可以按除=(或明确按下C-g)以外的键退出.

这该怎么做?

jua*_*eon 14

这可能是你正在寻找的东西:

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


imm*_*rrr 8

有一个smartrep.el包,可以满足您的需求.文档有点稀缺,但你可以通过查看github上发现的众多emacs配置来掌握它应该如何使用.例如(取自这里):

(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))))
Run Code Online (Sandbox Code Playgroud)


jpk*_*tta 6

这就是我用的。我喜欢它,因为您不必指定重复键。

(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")))
Run Code Online (Sandbox Code Playgroud)

  • 我非常喜欢这个,但是请注意,CMD *必须*已经被加载(自动加载不足),否则arglist和交互形式的查询将失败。(实际上,后者*会*触发自动加载,但是以它开头的arglist将是错误的)。 (2认同)