I've executed the following lines in my scratch buffer

(require 'expand-region)
(global-set-key (kbd "C-=") 'er/expand-region)

and everything worked without any problems, but if I add those same lines to my init.el file I just get the following error

File error: Cannot open load file, no such file or directory, expand-region

What have I done wrong?

  • Have you misplaced the code before a change to the load-path? – Andrew Swann Mar 15 at 9:28
  • Assuming you installed expand-region via package.el, you should not need (require 'expand-region) which only slows down Emacs's startup. – Stefan Mar 15 at 11:52

If you have installed expand-region via melpa you can just remove (require 'expand-region) from your init file because er/expand-region is autoloaded.

A bit of background:

global-set-key does not access the function value of 'er/expand-region so one can use global-set-key even if 'er/expand-region is not yet defined.

When package-initialize runs at the end of the initialization (by default) or maybe in the users init file the function er/expand-region is registered as autoloaded.

Thus when the user opens a file in LaTeX-mode and inputs the key sequence bound to er/expand-region the package expand-region is automagically loaded and er/expand-region is defined on demand.

  • 1
    BTW, in Emacs-27. installed packages get activated before loading ~/.emacs rather than after. – Stefan Mar 15 at 15:20
  • @Stefan I know. That is the reason for the early initialization stuff: reddit.com/r/emacs/comments/7yns85/… (configuration that must run before the activation of packages) Nevertheless, it is very good that you mention it here. – Tobias Mar 15 at 15:26

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.