这是让事情顺利进行的最小片段:
(define-prefix-command 'foo)
(define-key foo "a" 'bar)
(define-key foo "b" 'baz)
(global-set-key (kbd "C-M-r") 'foo)
现在我可以“调用”
foo
当我按 C-M-r 时的键盘映射。但我想知道如何从代码中做到这一点,例如就像是:
(funcall (lambda-from-keymap 'foo))
在这次通话之后,我希望焦点在小缓冲区中,期望
a, 或 b 或 C-h 被输入。
这样的事情可能吗?
最佳答案
您可以使用 read-key-sequence
和 lookup-key
实现这一点:
(defun call-keymap (map &optional prompt)
"Read a key sequence and call the command it's bound to in MAP."
;; Note: MAP must be a symbol so we can trick `describe-bindings' into giving
;; us a nice help text.
(let* ((overriding-local-map `(keymap (,map . ,map)))
(help-form `(describe-bindings ,(vector map)))
(key (read-key-sequence prompt))
(cmd (lookup-key map key t)))
(if (functionp cmd) (call-interactively cmd)
(user-error "%s is undefined" key))))
如果你按 C-h
read-key-sequence
仍然等待您完成序列。我认为您可以通过循环使用 read-key
来模拟 Emacs 的正常行为。相反,它更复杂一些。像这样使用它:
(defun bar () (interactive) (message "you called bar"))
(defun baz () (interactive) (message "you called baz"))
(define-prefix-command 'foo)
(define-key foo "a" 'bar)
(define-key foo "b" 'baz)
(global-set-key (kbd "C-M-r") 'foo)
(defun call-foo ()
(interactive)
;; Note: pass the symbol form of the keymap so we can give nice help
(call-keymap 'foo "enter a foo command: "))
(global-set-key (kbd "C-c f") 'call-foo)
关于emacs - Elisp:从代码中调用键盘映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24914202/