I wrote a minor mode for automatically detecting the language in which the user is typing. For this to work, I have to load some files containing language statistics. These files are in a subdirectory of the (m)elpa package. How can I determine the path to these files? Is there a function that gives me the base directory of a package?
(defvar guess-language-data-dir (expand-file-name "trigrams" (file-name-directory (or load-file-name buffer-file-name))))
load-file-name is set when the elisp file is loading (and requiring),
buffer-file-name is set when user use
M-x eval-buffer to load the file.
Notes that it can't detect directory changes, for example, your package probably stops working after user upgrades it without restart Emacs since upgrading also means deleting old package by default. But I guess it's OK since restarting Emacs is necessary to make the new package takes effect after upgrading(?)
One (imperfect) solution is to use
find-function-library. Given a function, this returns a pair
(ORIG-FUNCTION . LIBRARY). Quote from the documentation:
ORIG-FUNCTION is the original name, after removing all advice and resolving aliases. LIBRARY is an absolute file name, a relative file name inside the C sources directory, or a name of an autoloaded feature.
The benefit of this solution is that it works independently of whether the function is defined in an elpa package or not. However, if the user redefines the function, the path changes. So it would still be desirable to have a way to find the base directory of an elpa package.