I like to build up a solution to these problems incrementally. If you just want to try my answer, skip to the defun
block of code at the end. I go to the *scratch*
buffer, in lisp-interaction-mode
to try these code snippets out. You can type C-j
after an expression and Emacs will run it and insert the results in the buffer.
The apropos
function searches for symbols matching some pattern, including regular expressions. So we can find all symbols starting with "inspiration-" like so:
(apropos "^inspiration-\*" t)
But that result has a list for each symbol with some other information. We can discard that and just take the symbol name, which comes first, using the first
function:
(mapcar #'first (apropos "^inspiration-\*" t))
Some of those aren't functions, so let's remove any that fail the functionp
test:
(let ((symbols (mapcar #'first (apropos "^inspiration-\*" t))))
(remove-if-not #'functionp symbols))
Now let's randomly choose one of those. I'm switching from let
to let*
because let*
allows me to reference earlier definitions in the same initialization, e.g. using symbols
when defining functions
.
(let* ((symbols (mapcar #'first (apropos "^inspiration-\*" t)))
(functions (remove-if-not #'functionp symbols))
(number (random (length functions))))
(nth number functions))
Now let's turn that into a new lisp function (and let's not have the name start with inspiration-
). I'll mark it as interactive
so that you can run it via M-x use-random-inspiration
in addition to using it in other elisp code. The other big change is to use funcall
to actually run the randomly selected function:
(defun use-random-inspiration ()
(interactive)
(let* ((symbols (mapcar #'first (apropos "^inspiration-\*" t)))
(functions (remove-if-not #'functionp symbols))
(number (random (length functions))))
(funcall (nth number functions))))
So add that to your $HOME/.emacs
file and try it out.
EDIT: Avoid the Apropos buffer popup
(defun use-random-inspiration ()
(interactive)
(let* ((pop-up-windows nil)
(symbols (mapcar #'first (apropos "^inspiration-\*" t)))
(functions (remove-if-not #'functionp symbols))
(number (random (length functions))))
(funcall (nth number functions)))
(kill-buffer (get-buffer "*Apropos*")))