11

I'm working on an Emacs Lisp package and one particular feature I would like to add is ability to define functions on the fly - they would follow the same naming convention, but it would help me not having to declare every single one of them manually.

To give an example, I have a basic function called exec, which takes an argument that is the name of executable to launch:

(def exec (cmd)
    (async-shell-command cmd "buffer"))

At the same time, in this particular case, I know the list of the executables that I will want to use - or more precisely, I know how to get a list of them, as it can change over time. So what I would like to do, given the following list of executables:

("a" "b" "c")

is to iterate over them and for each one to create a function with a name exec-[executable] - exec-a, exec-b, exec-c.

Unfortunately, defun does not evaluate the NAME argument so I cannot create the function name dynamically.

PS. The exec command is good enough in itself - it uses completing-read with the list of executables supplied, but I thought the above would be nice addition.

1 Answer 1

13

How 'bout

(dolist (name name-list)
  (defalias (intern (concat "exec-" name))
   `(lambda () ,(format "Run %s via `exec'." name) (interactive) (exec ,name))))
Sign up to request clarification or add additional context in comments.

6 Comments

This is absolutely fantastic, thank you so much :D. Need to study more Emacs Lisp I think :).
You could also use a macro to generate the functions, but this defalias/lambda pairing is very succinct!
@Stefan, what considerations did you make in choosing defalias+lambda over a macro?
@event_jr: The fact that life is better when you can avoid macros (but don't get me wrong: when you do need macros, life is much better if you can use macros).
@Stefan any chance you can clarify what this is doing? particularly the back tick in front of the lambda and the comma's
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.