0

When I edit a file, say current-file-path.el

I can have the following code:

(message (format "Here is the path of the current file %s" (buffer-file-name)))

when execting the statement in the buffer of the file when the file is open in a buffer, I got the correct message of the path of the file:

Here is the path of the current file /home/yubrshen/tmp/current-file-path.el

However, if I just load the file, then the message becomes:

Here is the path of the current file nil

What would be the proper way to find out the path of the file where my code is? Actually, I'm interested in knowing the directory of the file of my program so that I can load the other files at the same directory through the program.

Yu Shen
  • 2,770
  • 3
  • 33
  • 48
  • Related: https://stackoverflow.com/questions/4222183/emacs-how-to-jump-to-function-definition-in-el-file – tripleee Oct 20 '19 at 06:34

1 Answers1

1

You seem to be looking for symbol-file.

Of course, not every symbol is defined in Lisp code loaded from a named file; some are defined in the C source code for Emacs, and some are defined interactively by yourself.

There is also no guarantee that your data files will be packaged in the same location as your source code, so what you are describing should probably be implemented with a package variable instead.

(defvar foo-directory (file-name-directory load-file-name)
  "*Directory for data files belonging to package \`foo'.")

This should probably use defcustom actually, but I'd have to guess too many things about your code to create a meaningful example.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • It would work for my use case, but it's not the most straightforward one. Thanks! My preferred solution is ```load-file-name``` as suggested in the above-referred question and answer. – Yu Shen Oct 21 '19 at 01:34
  • 1
    You'll notice that my `defvar` does exactly that. – tripleee Oct 21 '19 at 03:45