Emacs: 'Find file' without changing working directory

微笑、不失礼 提交于 2019-11-29 22:41:32

问题


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?


回答1:


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




回答2:


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

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




回答3:


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)))



回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/6367743/emacs-find-file-without-changing-working-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!