Note, that defadvice
has been replaced by advice-add
since Emacs 24.4.
With advice-add
, you could just do the following.
(defun original-function ()
"Some function without `interactive' specification and with no args."
(message "Do something."))
;; Cleaning up the mess when repeatedly advicing:
(advice-mapc `(lambda (fun props) (advice-remove 'original-function fun)) 'original-function)
;; That is the actual advice:
(advice-add 'original-function :around
(lambda (original-fun &optional prefix)
;; We use a lambda rather than a named function
;; since the named function would not be meaningful as command.
"The new function with PREFIX argument replacing ORIGINAL-FUN."
(interactive "P")
(if prefix
(message "Do something else.")
(funcall original-fun))
)
)
That also works when the original function has arguments:
(defun original-function (arg &optional opt-arg)
"Some function without `interactive' specification and with no args."
(message "Do something with arg %s and opt-arg %s." arg opt-arg))
;; Cleaning up the mess when repeatedly advicing:
(advice-mapc `(lambda (fun props) (advice-remove 'original-function fun)) 'original-function)
;; That is the actual advice:
(advice-add 'original-function :around
(lambda (original-fun arg &optional opt-arg prefix)
;; We use a lambda rather than a named function
;; since the named function would not be meaningful as command.
"The new function with PREFIX argument replacing ORIGINAL-FUN."
(interactive "sArg:\nsOptional arg:\nP")
(if prefix
(message "Do something else with arg %s and opt-arg %s." arg opt-arg)
(funcall original-fun arg opt-arg))
)
)
You can also use the variable current-prefix-arg
within the advicing function. Maybe, that is even cleaner because the argument list does not get messed up:
(defun original-function (arg &optional opt-arg)
"Some function without `interactive' specification and with no args."
(message "Do something with arg %s and opt-arg %s." arg opt-arg))
;; Cleaning up the mess when repeatedly advicing:
(advice-mapc `(lambda (fun props) (advice-remove 'original-function fun)) 'original-function)
;; That is the actual advice:
(advice-add 'original-function :around
(lambda (original-fun arg &optional opt-arg)
;; We use a lambda rather than a named function
;; since the named function would not be meaningful as command.
"The new function with PREFIX argument replacing ORIGINAL-FUN."
(interactive "sArg:\nsOptional arg:")
(if current-prefix-arg
(message "Do something else with arg %s and opt-arg %s." arg opt-arg)
(funcall original-fun arg opt-arg))
)
)