Leo Ufimtsev
Leo Ufimtsev

Reputation: 6512

Emacs, how to get directory of current buffer?

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?

Upvotes: 43

Views: 26885

Answers (3)

Wr0NG
Wr0NG

Reputation: 46

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

Upvotes: 0

Sandy
Sandy

Reputation: 839

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

Upvotes: 56

abo-abo
abo-abo

Reputation: 20362

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.

Upvotes: 32

Related Questions