0

I have an init.el file with the following line: (require 'my-1)

The my-1 package is on the load path.

The my-1 defines this function:

(defun my-f ()
  "Hello."
  (interactive)
  (when (featurep 'my-2) (require 'my-2)
    ... some code here ...)

'my-2' is also on the load path.

Now the problem: calling my-f works (i.e. Emacs evaluates the my-1 package), but the feature my-2 is not loaded. If I manually evaluated (require 'my-2) - everything works (this also proves that my-2 package is on the load path).

How do I require my-2 package from within the defun so it gets evaluated?

4
  • Can you show complete code? As it stands, the when will test if my-2 is a feature (i.e. if the my-2 package is already loaded): If it is, it will require it again (which is a no-op) and do the rest of the code; if it is not, then none of that will be done: not the require and not the some code here either.
    – NickD
    May 26, 2020 at 14:39
  • Maybe you want (when (not (featurep 'my-2)) (require 'my-2) ...)?
    – NickD
    May 26, 2020 at 14:48
  • 1
    @NickD: (require 'my-2) is the same as (when (not (featurep 'my-2)) (require 'my-2)).
    – Drew
    May 26, 2020 at 17:42
  • 1
    Just put (require 'my-2) in your function. Remove the test for its feature. If its feature is present then it's already been loaded, so require would be a no-op.
    – Drew
    May 26, 2020 at 17:43

1 Answer 1

0

featurep is true when the specified feature has already been provided, and so this code doesn't make sense:

(when (featurep 'my-2)
  (require 'my-2)
  ...)

That require and ... can only be evaluated if my-2 had previously been loaded by some other means. So the require either (a) isn't called, or (b) is called redundantly and does nothing.

You most likely want either:

(when (require 'my-2 nil t)
  ...)

Or:

(require 'my-2 nil t)
(when (featurep 'my-2)
  ...)

You might prefer the latter case if my-2 was used pervasively throughout the library and was expected to be present -- in which case the require might be at the beginning of the library, and individual functions would then only need the featurep check.

n.b. I've assumed you don't want require to signal an error if it can't load my-2, as it seems like an optional dependency for your code in general.

Use C-hf to see details of require or featurep, and see C-hig (elisp)Loading for more information.

2
  • Thanks! Indeed, my intention to use when was to avoid: 1) errors if the my-2 was not available and 2) to 'lazy load' the my-2 - to speed-up load time, by not requiring it during the start-up. Any idea how to approach the 2)? May 27, 2020 at 10:24
  • 1
    If you're putting the require in the function(s) which use it, then it's not loaded before it's needed.
    – phils
    May 27, 2020 at 10:58

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.