在Emacs中有命令的`flet`吗?

时间:2015-04-16 07:13:32

标签: emacs elisp

我想动态地将一个命令重定向到另一个命令 使用around建议的某些功能,如下所示:

(defun f1 (arg)
  (interactive (list (read-from-minibuffer "F1: ")))
  (message "f1: %S" arg)
  arg)
(defun f2 (arg)
  (interactive (list (read-from-minibuffer "F2: ")))
  (message "f2: %S" arg)
  arg)
;; Function that invokes the f1 command
(defun myfunc ()
  (call-interactively 'f1))

;; I want myfunc to invoke f2 instead whenever it would invoke f1
(defadvice myfunc (around f1-to-f2 activate)
  (flet ((f1 (&rest args) (interactive) (call-interactively 'f2)))
    ad-do-it))

(myfunc)

但是,这会产生错误(wrong-type-argument commandp f1), 表示当flet重新定义f1功能时,它没有 处理交互式表单并将其视为命令,因此它无法处理 由call-interactively调用。

是否有flet的变体以这种方式用于命令?

(以下是我想要做的实际重新定义:)

(defadvice org-metaleft (around osx-command activate)
        (flet ((backward-word (&rest args)
                (interactive)
                (call-interactively #'move-beginning-of-line)))
          ad-do-it))

(defadvice org-metaright (around osx-command activate)
        (flet ((forward-word (&rest args)
                (interactive)
                (call-interactively #'move-end-of-line)))
          ad-do-it))

2 个答案:

答案 0 :(得分:4)

你在flet中遇到了一个愚蠢的错误:flet的宏展开将有:(lambda (&rest args) (progn (interactive) (call-interactively 'f2)))。注意那里添加的虚假progn,其中"隐藏" interactive

要获得更多控制权(同时避免cl.el),您可以执行以下操作:

(defadvice myfunc (around f1-to-f2 activate)
  (cl-letf (((symbol-function 'f1)
             (lambda (&rest args)
               (interactive) (call-interactively 'f2))))
    ad-do-it))

答案 1 :(得分:2)

(编辑:cl-letf宏可以在现代emacs中本地执行此操作。以下答案可能对旧版本有用。)

好吧,如果之前没有,现在就有:

(require 'cl)
(require 'cl-lib)
(defmacro command-let (bindings &rest body)
  "Like `flet', but works for interactive commands.

In addition to the standard `(FUNC ARGLIST BODY...)' syntax from
`flet', this also supports `(FUNC NEW-FUNC)' as a shorthand for
remapping command FUNC to another command NEW-FUNC, like this:

  (defun FUNC (&rest ignored)
    (interactive)
    (call-interactively NEW-FUNC))

\(fn ((FUNC ARGLIST BODY...) ...) FORM...)"
  (declare (indent 1))
  (cl-loop for binding in bindings
           collect (list (car binding) nil) into empty-bindings
           collect (if (symbolp (cadr binding))
                       ;; Remap one command to another
                       `(defun ,(car binding) (&rest args)
                          (interactive)
                          (call-interactively ',(cadr binding)))
                     ;; Define command on the fly
                     (cons 'defun binding))
           into defun-forms
           finally return
           `(flet (,@empty-bindings)
              ,@defun-forms
              ,@body)))

行动中:

(defadvice myfunc (around f1-to-f2 activate)
  (command-let ((f1 f2))
    ad-do-it))
(myfunc)

该代码现在根据需要使用f2调用call-interactively命令。

相关问题