Search code examples
emacsfunctionmacroselisp

elisp macro to write a function?


I have written a few nearly identical functions, except for their names. For example:

; x is name, such as function/paragraph/line/etc.
(defun my-x-function
 (interactive)
 (mark-x) (do-more-stuff) (modify-x))

Is there a way to automatically generate such functions? I have a feeling this is what macros do, but I am not sure how to use them. Any help, maybe including a small example would be great.

Thanks!


Solution

  • Yep, that's exactly what macros do. Here's a straightforward macro that builds functions according to the pattern you specified:

    (defmacro make-my-function (name)
      (list 'defun (intern (format "my-%s-function" name)) ()
            (list 'interactive)
            (list (intern (format "mark-%s" name)))
            (list 'do-more-stuff)
            (list (intern (format "modify-%s" name)))))
    

    You can copy this macro to a *scratch* buffer in Emacs and evaluate it, and then check that it works like this:

    (make-my-function x) ; type control-J here
    my-x-function ; <-- Emacs's output
    (symbol-function 'my-x-function) ; type control-J here
    (lambda nil (interactive) (mark-x) (do-more-stuff) (modify-x)) ; <-- Emacs's output
    

    More commonly one would use the backquote facility to write macros more concisely, but all macros essentially work in the same manner as the above example.