user1002146
user1002146

Reputation: 11

Find file in source directory in emacs lisp

I have a text file containing a list of words that my elisp code is dependent on. I would like to keep it in the same directory as the source files.

Using a relative path does not seem to work, because when the function that triggers the reading is run the path is relative to what buffer you are currently in.

The code:

(defconst etype-lines-file "etype.lines")

(defun etype-read-file ()
  (with-temp-buffer
    (insert-file-contents (expand-file-name etype-lines-file default-directory))
    (apply
     'vector
     (split-string
      (buffer-substring-no-properties (point-min) (point-max)) "\n"))))

Any way to achieve a path relative to the location of the source code file?

Upvotes: 1

Views: 1150

Answers (2)

Drew
Drew

Reputation: 30718

Yes, it is, because of this code:

(insert-file-contents (expand-file-name etype-lines-file default-directory))`

Instead, either pass the directory you want to your function, as an argument, and use that here, in place of default-directory, or use a global variable (or "constant", via defconst) for the directory (in place of default-directory here).

Upvotes: 0

legoscia
legoscia

Reputation: 41648

You can use load-file-name for this. While an Emacs Lisp file is being compiled or loaded, it's bound to the name of the source file. Here is an example from the elisp manual:

 (defconst superfrobnicator-base (file-name-directory load-file-name))

 (defun superfrobnicator-fetch-image (file)
   (expand-file-name file superfrobnicator-base))

That means that you'll have to load your file by load-file or emacs-lisp-byte-compile-and-load exclusively, instead of evaluating parts of the buffer, since load-file-name is nil in the latter case.

Upvotes: 3

Related Questions