Karl
Karl

Reputation: 1153

Emacs: 'Find file' without changing working directory

My c/c++ projects tend to have fairly straightforward directory structures which separate out src, include, bin, etc. I also tend to have a master makefile in the uppermost directory. When working like this in Emacs, I always have to issue M-x cd uppermost-dir in order for my compilation shortcuts to work as expected.

Is there a way to keep the current directory the same as the one from which I launch Emacs? That is, can I stop Emacs from changing it's working directory when I open a file?

Alternatively, is there something crucial I'm missing about the typical workflow with a directory hierarchiy like this exclusively in Emacs?

Upvotes: 4

Views: 1684

Answers (5)

justinhj
justinhj

Reputation: 11306

One way you can do this:

Make a file in the root directory of your project call .dir-locals.el

This will be read whenever you open a file in the directory or it's sub-directories.

In order to back up to the root folder and run make as your compile command, just put this in the .dir-locals.el file.

((nil . ((compile-command . "cd ~/mycode/c/; make"))))

nil is the mode to set local variables for (nil means any), so to do this for only C++ mode you could do this instead ...

((c++-mode . ((compile-command . "cd ~/mycode/c/; make"))))

Obviously you can set up a list with more options, say running ant for java files and so on.

emacs manual entry for directory locals

Upvotes: 7

pmr
pmr

Reputation: 59811

I used to M-x compile <RET> cd /path/to/project && make -j8 but prefer the method by Ben nowadays.

Upvotes: 1

The current directory associated with a buffer that's associated with a file is normally the directory containing the file. You can change it, but it's not necessary for what you want to do.

Set the variable compilation-directory through a file-local variable (typically relative to the current file, e.g. "../..") or through .dir-locals.el.

Upvotes: 1

Ben
Ben

Reputation: 1359

Invoke make with the --directory argument to force it to change to that directory before doing anything:

make --directory /path/to/your/project

Upvotes: 5

J&#252;rgen H&#246;tzel
J&#252;rgen H&#246;tzel

Reputation: 19727

Change to the project directory (where the Makefile is located) and call compile:

(defun my-compile ()
  (interactive)
  (when-let (default-directory (locate-dominating-file default-directory "Makefile"))
    (call-interactively 'compile)))

Upvotes: 4

Related Questions