0

I have something like this inside my init file:

(when (file-readable-p "/absolute/path/to/config.org")
      (org-babel-load-file (expand-file-name "/absolute/path/to/config.org")))

Where config.org is in the same directory as init.el. I want to be able to specify a relative path to init.el so that emacs can find the config file no matter where the init file is located on any device. However, when I tried "./config.org" that is interpreted relative to the directory where emacs is opened, not where init.el is located.

How can I specify a path relative to init.el?

I'm using emacs-28, if that matters.

2

When your init file is loaded, the current directory, that is, the value of variable default-directory, is the directory where your init file is, by default. That is, that's the value unless your init file does something that changes default-directory.

So you can just use the value of default-directory.

For example if you use a function that accepts a file name without the directory part, then just use the file name without the directory part, and default-directory will be understood.

Or if you use a function that needs an absolute file name, then use expand-file-name without specifying optional arg DEFAULT-DIRECTORY (or passing it as nil).

E.g.:

(when (file-readable-p "config.org")
  (org-babel-load-file (expand-file-name "config.org")))

which is the same as:

(when (file-readable-p (expand-file-name "config.org"))
  (org-babel-load-file (expand-file-name "config.org")))

which is the same as:

(when (file-readable-p (expand-file-name "config.org" default-directory))
  (org-babel-load-file (expand-file-name "config.org" default-directory)))

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.