22

I am looking to include a reference to a non-elisp file (a small Python program), and would like to be able to say "it is in the same directory as the current file, but with a different file name." In many scripting languages, there are things like __FILE__ (in PHP) for getting an absolute path to the current file.

If the file to be included is in the load-path, then I can find it with (locate-library "file.py" t), but I'm kind of stuck if the file is not in the load path.

So is there a way for an Emacs Lisp file to find out its own absolute path (when being loaded, not visited)?

Trey Jackson
  • 73,529
  • 11
  • 197
  • 229
haxney
  • 3,358
  • 4
  • 30
  • 31
  • 1
    Changed the title to reflect the question asked. The original title to the question would lead me to want to answer "the variable `buffer-file-name`" which isn't what you asked. – Trey Jackson Aug 28 '09 at 03:48

1 Answers1

32

M-x describe-variable load-file-name

load-file-name is a variable defined in `C source code'.

Documentation:
Full name of file being loaded by `load'.

You might also be interested in the symbol-file function, which will tell you the absolute filename in which a specified function or variable was defined.

If you want to get fancy, you can check the load-in-progress variable. If that's nil, then no load is in progress (and you're presumably being eval'd in a buffer). In that case, you could try (buffer-file-name) to get the filename.

cjm
  • 61,471
  • 9
  • 126
  • 175
  • 6
    Simpler fancyness: `(or load-file-name (buffer-file-name))` – dbr Oct 03 '12 at 12:39
  • 1
    Upvote for `symbol-file`, for allowing self-referential code. Currently using a variant on `(defvar my-locn nil) (setq my-locn (symbol-file 'my-locn))`. – Paul Whittaker Sep 11 '13 at 16:15