In emacs, how can I add a function to a hook when the function hasn't yet been defined?

StackOverflow https://stackoverflow.com/questions/11646150

  •  23-06-2021
  •  | 
  •  

Question

I've installed some things from ELPA, namely evil and rainbow-delimiters.

In order to have them run whenever emacs loads, I would put something like:

(evil-mode)
(global-rainbow-delimiters-mode)

In my init.el file.

However, because I installed them from ELPA, they're not loaded until after my init.el has been loaded, and so both symbols are undefined.

As far as I understand, this also prevents me from doing something like

(add-hook 'after-init-hook 'global-rainbow-delimiters-mode)

How can I work around this?

Postscript: This problem was actually caused by me not calling (package-initialize) at the start of my init.el, which would have loaded all of the things installed using packages (evilmode and rainbow-delimiters being just two of them) at the correct time

Was it helpful?

Solution

Your add-hook solution will work.

There, 'global-rainbow-delimiters-mode is just a name, it will be resolved to the function later, when add-hook is called, and the function will exist by that time.

The ELPA documentation does mention this method, although it seems to consider it as a last resort.

OTHER TIPS

AFAIU compiling the init file is not a good idea - but not related so far.

Your hook fails, as it runs after reading the init, but before stuff gets loaded. You need a function to run after load from ELPA.

Try eval-after-load

You can also initialize your packages early with (package-initialize). This will allow you to not put all that code in one hook.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top