Brian Carper
Brian Carper

Reputation: 72926

Preventing automatic change of default-directory

As per the Emacs docs, every time you open a file, Emacs changes default-directory to the directory containing that file.

Then, if the cursor is in that buffer and you (for example) start SLIME, it uses default-directory as the current working directory for SLIME. If you try to open a new file, it opens the file with default-directory as your starting point.

I want to be able to M-x cd or otherwise cd to a directory, and then never have Emacs change my current working directory to anything but that directory until I tell it otherwise. I want this to be global across all buffers, so that any time I'm doing something involving the current working directory, I know what it's set to regardless of where my cursor is at the moment. Is there a way to do this?

Upvotes: 17

Views: 2387

Answers (3)

Brian Carper
Brian Carper

Reputation: 72926

This is the best I've come up with so far, sadly:

(defun find-file-save-directory ()
    (interactive)
    (setq saved-default-directory default-directory)
    (ido-find-file)
    (setq default-directory saved-default-directory))
(global-set-key "\C-x\C-f" 'find-file-save-directory)

This works as long as default-directory is properly set before I C-x C-f. I'm going to Accept jurta's answer for pointing me in a useful direction.

Upvotes: 4

link0ff
link0ff

Reputation: 2774

Another variant is to bind default-directory to the necessary directory in directory-local variables, e.g. in the .dir-locals.el file in one of your parent directories to something like:

((nil . ((default-directory . "~/.emacs.d/"))))

Upvotes: 4

link0ff
link0ff

Reputation: 2774

You could try using something like this:

(add-hook 'find-file-hook
          (lambda ()
            (setq default-directory command-line-default-directory)))

Upvotes: 13

Related Questions