39

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?

1
  • 5
    default-directory variable?
    – abo-abo
    Commented Jan 28, 2015 at 15:37

3 Answers 3

52

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

6
  • 1
    Yes, 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
    Commented Nov 19, 2015 at 7:18
  • 2
    buffer-file-name is a function, so this should be (file-name-directory (buffer-file-name)).
    – GManNickG
    Commented Jul 13, 2017 at 20:45
  • 5
    Actually, according to the docs, 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
    Commented Jul 19, 2017 at 3:32
  • Ah, my mistake. :)
    – GManNickG
    Commented Jul 20, 2017 at 15:43
  • 1
    buffer-file-name can be nil, e.g. on the *scratch* buffer. Commented Aug 20, 2019 at 14:59
31

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.

0

You can use the command M-x pwd to see the value of default-directory in the current buffer.

Each buffer has a default directory, stored in the buffer-local variable default-directory. Whenever Emacs reads a file name using the minibuffer, it usually inserts the default directory into the minibuffer as the initial contents. When you visit a file, Emacs sets default-directory in the visiting buffer to the directory of its file.

https://www.gnu.org/software/emacs/manual/html_node/emacs/File-Names.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.