Open shell in emacs with a given working directory

4.3k views Asked by At

I want to have a make-shells command in emacs that will open a number of emacs-shell buffers, each with its own working directory. The idea is that for each project I'm working on, I have a shell that starts out in that project's directory, so I can easily switch between them.

Currently I have this code:

(defun shell-dir (name dir)
  (interactive "sShell name: \nDDirectory: ")
  (shell name)
  (switch-to-buffer name)
  (comint-send-string (current-buffer) (concat "cd " dir "\r"))
  (sleep-for 0 10)
  (dirs))

(defun make-shells ()
  (interactive)
  (shell-dir "project1" "~/proj/project1")
  (shell-dir "project2" "~/proj/project2")
  (shell-dir "project3" "~/proj/project3")
  (delete-window))

This is pretty ugly, though, and half the time (dirs) doesn't pick up the correct path, so tab completion breaks until I re-run it manually. Is there a built-in way to set the current working directory of the emacs shell? Or would something like CEDET (plus less reliance on the shell vs. emacs modes) be a much better solution to this?

2

There are 2 answers

0
Trey Jackson On BEST ANSWER

I experienced similar problems with the current directory tracking provided by Emacs, so I wrote one which solves the problem once and forever.

Check it out here.

The short version of what it does is that you modify your shell prompt to include a full path to the current directory (only when running inside Emacs), and the Emacs shell buffer will use that.

This means you never have to do M-x dirs again.

There's also the package dirtrack (shipped with Emacs) which does the same thing.

I like my version better because it removes the path from the prompt. I don't want to see the entire path in my prompt as my current directory is often very long.

Once you use one of the above two solutions, you can simplify your shell-dir routine to be:

(defun shell-dir (name dir)
  (interactive "sShell name: \nDDirectory: ")
  (let ((default-directory dir))
    (shell name)))
0
Alistair Bell On

One more answer... I found there was a way (on Linux) to make Emacs figure out the current directory properly, by using the /proc filesystem.

http://www.emacswiki.org/emacs/ShellDirtrackByProcfs

That way, you just have to start up the shell in whatever directory and Emacs will automatically figure it out and get the tab-completion etc. right.