3

I would like to add a suffix to a message reported by a function called in some source I don't maintain.

Is there a way to locally override the message function so I can manipulate it before it's displayed? (add a prefix or suffix for example).

I know I can read the message log and log new message, but I'd rather avoid flooding the log, or manipulate the message buffer.

Drew
  • 75,699
  • 9
  • 109
  • 225
ideasman42
  • 8,375
  • 1
  • 28
  • 105
  • You can advise the message. `i advice` in the Elisp manual. – Drew Dec 23 '19 at 01:29
  • Can this be done locally though (similar to how `let` can locally override variables) – ideasman42 Dec 23 '19 at 01:30
  • You can certainly turn advice on and off. And you can use `cl-flet` and `cl-letf` to redefine locally. – Drew Dec 23 '19 at 02:06
  • An issue with turning it on and off is there is some risk an error causes it to be left on. cl-letf looks closer to what I'm looking for. – ideasman42 Dec 23 '19 at 02:16
  • An issue with adding/removing advice - is there is some risk an error causes it to be left on. `cl-letf` seems to be what I'm looking for. – ideasman42 Dec 23 '19 at 22:31

1 Answers1

4

This macro adds support for adding a suffix to messages.

Using advice allows this to be nested, so multiple functions can add their own suffixes which accumulate onto the end.

(defmacro with-temp-advice (fn-orig where fn-advice &rest body)
  (declare (indent 3))
  (let ((function-var (gensym)))
    `(let ((,function-var ,fn-advice))
       (unwind-protect
           (progn
             (advice-add ,fn-orig ,where ,function-var)
             ,@body)
         (advice-remove ,fn-orig ,function-var)))))

(defmacro with-message-suffix (suffix &rest body)
  "Add text after the message output.
Argument SUFFIX is the text to add at the start of the message.
Optional argument BODY runs with the message suffix."
  (declare (indent 1))
  `(with-temp-advice
       'message
       :around
       (lambda (fn-orig arg &rest args)
         (apply fn-orig (append (list (concat arg "%s")) args (list ,suffix))))
     ,@body))
Sean Allred
  • 6,861
  • 16
  • 85
ideasman42
  • 8,375
  • 1
  • 28
  • 105