According to the Emacs documentation, Directory Variables apply to all files below a directory that contains an .dir-locals.el
file.
How can I, in that file, set a variable to the full path that contains the file? For example:
((nil . ((indent-tabs-mode . t) (my-project-path **THIS_DIRECTORY**))))
The answer is the pwd command, which stands for print working directory. The word print in print working directory means “print to the screen,” not “send to printer.” The pwd command displays the full, absolute path of the current, or working, directory.
M-x cd command does change the current working directory.
Visiting a file means reading its contents into an Emacs buffer so you can edit them. Emacs makes a new buffer for each file that you visit. To visit a file, type C-x C-f ( find-file ) and use the minibuffer to enter the name of the desired file. While in the minibuffer, you can abort the command by typing C-g .
Starting with “/” returns to the root directory and starts there. Starting with “../” moves one directory backwards and starts there. Starting with “../../” moves two directories backwards and starts there (and so on…) To move forward, just start with the first subdirectory and keep moving forward.
I asked myself the same question and found no solution on the web, so I think this answer may help. Actually, it turns out we can reuse dir-locals-find-file
to get the directory containing the .dir-locals.el
file. So here's what I found for, e.g, setting up an aspell personal dictionary dedicated to a whole directory:
((nil . ((eval . (setq ispell-personal-dictionary (expand-file-name ".aspell_words" (file-name-directory (let ((d (dir-locals-find-file "."))) (if (stringp d) d (car d))))))))))
Also, it seems entries are evaluated in the order they are specified, so the following code should work:
((nil . ((eval . (set (make-local-variable 'my-project-path) (file-name-directory (let ((d (dir-locals-find-file "."))) (if (stringp d) d (car d)))))) (eval . (message "Project directory set to `%s'." my-project-path)))))
Emacs will complain about unsafe local variables (due to the eval
construct), yet one can still permanently mark it safe.
Update: Since Emacs ≥ 26.3 (and maybe older versions as well), it appears that one needs to use (dir-locals-find-file "./")
instead of (dir-locals-find-file ".")
.
I think (file-name-directory (or load-file-name buffer-file-name))
should give you the directory path.
See http://xahlee.org/emacs/elisp_idioms_batch.html
Edit: Except it won't, because any eval
expressions are evaluated in the context of the buffer whose variables are being hacked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With