是否以及如何在defadvice循环中避免eval

时间:2013-09-21 14:12:34

标签: emacs elisp eval defadvice advising-functions

是否应该在以下代码中避免使用eval?如果是这样,怎么样?或者这是使用eval更好的特殊情况之一吗?

(dolist (command '(....))
  (eval
   `(defadvice ,command (around blah activate)
      ...)))

关于上述成语的真实例子:

(dolist (command '(paredit-comment-dwim comment-dwim))
  (eval
   `(defadvice ,command (around my-check-parens-and-warn-for-comment activate)
      (if (and (called-interactively-p 'any)
               (use-region-p))
          (progn
            (my-check-parens-and-warn-if-mismatch "You commented out a region and introduced a mismatched paren")
            ad-do-it
            (my-check-parens-and-warn-if-mismatch "You uncommented out a region and introduced a mismatched paren"))
        ad-do-it))))

1 个答案:

答案 0 :(得分:3)

两种解决方案:

  • 使用ad-add-advice代替defadvice
  • 如果您使用的是Emacs中继,则可以使用新的advice-add

使用advice-add看起来像以下代码:

(defun my-check-commented-parens (orig-fun &rest args)
  (if (not (and (called-interactively-p 'any)
                (use-region-p)))
      (apply orig-fun args)
    (my-check-parens-and-warn-if-mismatch "You commented out a region and introduced a mismatched paren")
    (apply orig-fun args)
    (my-check-parens-and-warn-if-mismatch "You uncommented out a region and introduced a mismatched paren")))

(dolist (command '(paredit-comment-dwim comment-dwim))
  (advice-add command :around #'my-check-commented-parens))