In emacs there is buffer-file-name that gives the full path to a file. But is there a way to get only the directory of the file loaded in the current buffer?
-
5`default-directory` variable? – abo-abo Jan 28 '15 at 15:37
2 Answers
Sometimes default-directory
for the current buffer may be set to something other than the current directory of the file the buffer is currently visiting, in which case the solution above wouldn't give what the asker was looking for.
In such cases, you can use the file-name-directory
method, like so: (file-name-directory buffer-file-name)
Here is a link to the docs:
http://www.gnu.org/software/emacs/manual/html_node/elisp/File-Name-Components.html

- 799
- 8
- 12
-
1Yes, abo-abo's answer addresses the question in the *title*, but Sandy's answer is what I'd recommend if you're specifically dealing with `buffer-file-name` (although the chances of it ever making a difference are slim). – phils Nov 19 '15 at 07:18
-
2`buffer-file-name` is a function, so this should be `(file-name-directory (buffer-file-name))`. – GManNickG Jul 13 '17 at 20:45
-
5Actually, according to the [docs](https://www.gnu.org/software/emacs/manual/html_node/elisp/Buffer-File-Name.html), `buffer-file-name` is both a function and a buffer-local variable, so both `(file-name-directory buffer-file-name)` and `(file-name-directory (buffer-file-name))` should work. – Sandy Jul 19 '17 at 03:32
-
-
-
1`buffer-file-name` can be `nil`, e.g. on the `*scratch*` buffer. – Andre Holzner Aug 20 '19 at 14:59
You can use the default-directory
variable.
Documentation: Name of default directory of current buffer. Should end with slash. To interactively change the default directory, use command `cd'.
Note that expand-file-name
will use default-directory
by default, so sometimes
you don't even need to mention it.

- 20,038
- 3
- 50
- 71