eval-after-load
If you'd like to defer the execution of some code until a particular file has been loaded, eval-after-load is the way to do it. For example, suppose you came up with a better definition for dired-sort-toggle than the one that's in dired (Emacs's directory-editing module). You couldn't simply put your version into your .emacs, because the first time you edit a directory, dired will be autoloaded, complete with its definition for dired-sort-toggle, which will wipe out your definition.
What you could do instead is:
(eval-after-load
"dired"
'(defun dired-sort-toggle ()
...))This will execute the defun immediately after dired is loaded, clobbering dired's version of dired-sort-toggle instead of the other way around. Note, however, that this will work only if dired is loaded under precisely the name dired. It won't work if dired is loaded under the name dired.elc or /usr/local/share/emacs/19.34/lisp/dired. The load or autoload or require that causes dired to be loaded must refer to it by exactly the same name used in eval-after-load. This is why, as mentioned earlier, it's best always to load files by just their base name.
Another use for eval-after-load is when you need to refer to a variable, function, or keymap in a package that's not loaded yet, and you don't want to force the package to be loaded:
(eval-after-load "font-lock" '(setq lisp-font-lock-keywords lisp-font-lock-keywords-2))
This refers to the value of lisp-font-lock-keywords-2, a variable defined in font-lock ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access