Say I have foobar_utility.el that defines an interactive function foobar_utility.

How can I postpone loading foobar_utility.el until foobar_utility is called?

Example usage:

(load (concat user-emacs-directory "foobar_utility.el") :nomessage t)
(global-set-key (kbd "<f1>") 'foobar_utility)

Is there a better way to do this besides moving the load into the key binding? e.g:

 (kbd "<f1>")
 (lambda ()
   (load (concat user-emacs-directory "foobar_utility.el") :nomessage t)
   (call-interactively 'foobar_utility)))
  • Would using ;;;###autoload on the line immediately before the function foobar_utility suffice -- then, eliminate the call to load and let Emacs autoload the library automatically whenever the function is called the first time (either noninteractively or interactively)? – lawlist Mar 24 '20 at 1:37
  • Maybe? I would then need to generate auto-loads I suppose? Probably all of this is easy when you know how - I just never set this up before. – ideasman42 Mar 24 '20 at 1:39
  • Yes, that is my understanding. Here is a little snippet from abo-abo, which I assume works (but I have not tried it out): emacs.stackexchange.com/a/8044/2287 – lawlist Mar 24 '20 at 1:45

Put (autoload 'foobar_utility "foobar_utility" nil t) in your init file, and put foobar_utility.el in a directory in your load-path. Don't load the file explicitly.

See the Elisp manual, node Autoload.

In response to a comment:

This is an explicit sexp that invokes function autoload. You can use it instead of using ;;;###autoload cookies and generating an autoloads file from them (which you then load from your init file). All an ;;;###autoload cookie does is let you generate a file with autoload sexps like the one I showed.

Cookies can be convenient when you write a library that has many function definitions. Individual calls to function autoload can be convenient when you just want to autoload, from your init file, some functions that are defined in other files.

  • Does this require ;;;###autoload above the functions & generating auto-load files? – ideasman42 Mar 24 '20 at 4:29
  • 1
    No. It's instead of using ;;;###autoload and generating and autoloads file. All that cookie does is let you generate a file with sexps like the one I showed. – Drew Mar 24 '20 at 4:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.