Felix D.
Felix D.

Reputation: 2220

Launching eshell when starting up emacs from terminal with cwd

I added a hook to my init.el to launch Emacs on eshell.

;;start on eshell
(add-hook 'emacs-startup-hook 'eshell)

The thing is, I often launch Emacs from the terminal and would love to have eshell working directory being the working directory of the terminal from which I launched Emacs.

Let's say I'm in a directory X, and launch Emacs

~/X $ emacs

I want this to happen

Welcome to the Emacs shell
~/X $ 

For now, I have added

(cd "~")

to my init.el, as a temporary solution (changes emacs path to home), but it's not good enough.

Edit

I want to run Emacs in its gui.

Edit 2

Chris's answer worked if not using open -a emacs to launch the application. But just with the executable path instead.

Upvotes: 1

Views: 948

Answers (1)

Chris
Chris

Reputation: 136880

You can detect that Emacs is running in a terminal when the function display-graphic-p returns nil, and you can get the directory from which you invoked Emacs from the default-directory variable.

So something like

(when (not (display-graphic-p))
  (cd default-directory)
  (eshell))

in your init should change to the "current" directory and then launch eshell when Emacs is invoked from the terminal.

If you always wish to invoke eshell you should be able to remove (eshell) from the code and simply keep your emacs-startup-hook.

Edit: Replaced variable window-system with call to function display-graphic-p as recommended in this answer.

Edit 2: If you simply want to modify your emacs-startup-hook to change to whatever directory you invoke Emacs from and then launch eshell (regardless of the windowing system), you can use something like

(add-hook 'emacs-startup-hook
          (lambda ()
            (cd default-directory)
            (eshell)))

Upvotes: 2

Related Questions