Search code examples
emacselisp

How to pass &rest arguments to another function in emacs lisp?


I have a convinience defun in my init.el to do some logging

(defvar log4me::loglevel 5
  "Global loglevel.")

(defun log4me (level logmsg)
  "Log message."
  (interactive)
  (when (>= level log4elisp::loglevel)
    (message logmsg))))

It kind of works but somehow i frequently do

  (log4me somelevel (format "mymessage with %d" 1))

So i found the emacs lisp &rest parameters which i thought i might use like this:

(defun log4me (level logmsg &rest formatparams)
  "Log message."
  (interactive)
  (when (<= level log4elisp::loglevel)
    (message (format logmsg formatparams))))

(log4me 3 "Hello %ust!" 1)

which resuslts into "Format specifier doesn't match argument type" error since formatparams is actually (1) and not 1.

Is there a nice way to include format parameters into the log4elisp defun and make them arrive in the format function call as "normal" parameters (not a single list)?


Solution

  • What you need is apply:

    (defun log4me (level logmsg &rest formatparams)
      "Log message."
      (interactive)
      (when (<= level log4elisp::loglevel)
        (apply #'message logmsg formatparams)))