Frank Cheng
Frank Cheng

Reputation: 6206

How to open terminal in current directory?

When i use M-x shell to open a new terminal, it will sometimes set the current directory to the file in. But sometimes it won't. So is there a function to always open a new terminal in current directory?

Upvotes: 7

Views: 3643

Answers (2)

Ehvince
Ehvince

Reputation: 18415

There's the package shell-here available in ELPA: M-x list-packages, look for shell-here, mark for install (i) and execute (x).

An excerpt of the readme:

Open a shell buffer in (or relative to) default-directory,
e.g. whatever directory the current buffer is in. If you have
find-file-in-project installed, you can also move around relative
to the root of the current project.

I use Emacs shell buffers for everything, and shell-here is great
for getting where you need to quickly. The =find-file-in-project=
integration makes it very easy to manage multiple shells and
maintain your path / history / scrollback when switching between
projects.

github home: https://github.com/ieure/shell-here

And I like shell-pop too, to pop up and pop out a shell buffer window with one easily. And there's maybe more in ELPA !

Upvotes: 5

Chris Barrett
Chris Barrett

Reputation: 3385

M-x shell will switch to an existing shell if there's already one running, which may be your problem. If you don't mind creating lots of shell buffers, the command below will generate new buffers whenever it can't find one visiting the given directory:

(require 'cl-lib)

(defun shell-at-dir (dir)
  "Open a shell at DIR.
If a shell buffer visiting DIR already exists, show that one."
  (interactive (list default-directory))
  (let ((buf (car (cl-remove-if-not
                   (lambda (it)
                     (with-current-buffer it
                       (and (derived-mode-p 'shell-mode)
                            (equal default-directory dir))))
                   (buffer-list)))))
    (if buf
        (switch-to-buffer buf)
      (shell (generate-new-buffer-name "*shell*")))))

Upvotes: 3

Related Questions