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

359 views Asked by At

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

3

There are 3 answers

1
Frédéric Hamidi On BEST ANSWER

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.

2
Andreas Röhler On

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

0
Nicolas Dudebout On

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