Search code examples
elispstartuporg-modecustom-functionspacemacs

How can I provide a custom function, depending on major-mode variables, right after the startup of Spacemacs?


I recently started to write some elisp code, mostly to customize my spacemacs -> absolute beginner. Although there are a many different sources of "how to customize..." around, I still am confused about the following.

The situation is that I would like to have a custom function ready at startup of spacemacs, but this function is depending on some major mode variables. What is the best way to achieve that, without having to open a file triggering loading this major mode first?

A specific example: I would like to access (with completion) my org-agenda-files interactively, so I wrote this function

  (defun my/org-agenda-find-file(file-path)
    (interactive (list
                  (completing-read "Choose agenda file: " org-agenda-files)))
    (find-file file-path)
    )

# Binding 
 (spacemacs/set-leader-keys "oof" #'my/org-agenda-find-file)

and put it in an custom my_org_config.el, which gets loaded in .spacemacs/dotspaceamcs/user-conifg(). So far so good, works as expected if org-mode has been loaded at least once before.

In case of a freshly started spacemacs, trying to use my function, I get the error that "org-agenda-files" is not existing. So it seems that "org-agenda-files" is set during the loading of org-mode.

One working solution is to add the "require 'org" statement before my function, but I'm not sure if this is a very good way of handling that.

(require 'org)
(defun my/org-agenda-find-file(file-path)
  (interactive (list
                (completing-read "Choose agenda file: " org-agenda-files)))
  (find-file file-path)
  )

Is there a better way of doing that, maybe through a key-word or a call within the function itself, or is this one of the cases where require and spacemacs go together fine :)?

Any help is appreciated! Thank you.


Solution

  • Putting (require 'org) to the top-level, as you did, is one method to ensure that the org feature is loaded when you call your function. I think there is nothing wrong with it except that the feature will be loaded even though you don't use it, unnecessarily delaying the startup.

    You can alternatively put (require 'org) inside your function to prevent the feature from being loaded if not needed, as shown in the Emacs manual.

    (defun my/org-agenda-find-file (file-path)
      (require 'org)
      ...)