1

在下面的代码中应该避免 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))))
4

1 回答 1

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))
于 2013-09-21T16:17:44.367 回答