Is there a way to define a macro in an emacs-lisp file in such a way that the macro would not be visible anywhere else once the file is read and evaluated?
Kind of like a temporary macro that goes out of scope at the end of a file?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this communityYou can always unbind the macro when the file ends. As far as I know, Emacs Lisp doesn't have to worry about asynchronous complexities; the flow of execution is purely linear. Therefore, you can do this:
(defmacro my-test-macro (secret sauce recipe)
;; super secret stuff here
;; wouldn't want it to LEAK out
;; and get stolen by some other files
)
;; [...] blabitty blah blah [...]
(fmakunbound 'my-test-macro)
The other solution you should look at (which is less hacky) uses cl-macrolet
, which is basically a let
for macros.
(eval-when-compile (require 'cl-lib))
(cl-macrolet ((my-test-macro (secret sauce recipie)
;; super secret stuff here
;; wouldn't want it to LEAK out
;; and get stolen by some other files
))
;; [...] blabitty blah blah [...]
)
No doubt, this solution is cleaner, although you pay for it by adding another level of indentation. Also, the macro is dynamically bound and could in theory be run asynchronously (although Emacs is a long way from multi-threading).
(defmacro abc () (message "abc")) (abc) (fmakunbound 'abc) (abc)
into *scratch*
and doing M-x
eval-buffer
works for me. You first get "abc" then a symbol's function definition is void abc
Jan 29, 2015 at 23:34
macrolet
, remember that it is often the case that you need a particular macro only at byte-compile time. In that case, byte-compiling a file without the macro definition loaded, or just using that file without compiling it, will mean that the code in that file does not have the macro available at runtime. IOW, it knows nothing about the macro.(eval-when-compile (defmacro ...))
?(eval-when-compile (require 'my-macros))
for the files that you want to see the macro definition.