Elisp: Get Script Name at Run Time, Call by Relative Path
Get Current Script's Name Programmatically
;; get the current elisp script's name at run time (or load-file-name buffer-file-name)
Explanation: If user ran your script by
eval-buffer
, then
load-file-name's value would be nil. So, using both {load-file-name,
buffer-file-name
} is a good way to get the script name regardless whether the script is executed by load or eval buffer.
If you want the directory, call file-name-directory
on the result.
Get Full Path from Relative Path at Run Time
If you have file A, that calls load
to load a file at B, and B calls load
on file C using a relative path, then Emacs will complain about unable to find C. Because, emacs does not switch current directory with load
.
The following function solves this problem.
(defun xah-get-fullpath (RelativePath) "Return the full path of RelativePath, relative to caller's file location. Created: 2017-07-19 Version: 2021-07-17" (concat (file-name-directory (or load-file-name buffer-file-name)) RelativePath))
See also: What is the difference between load-file, load, require, autoload?.