Xun
Xun

Reputation: 79

How to define a function to run multiple shells on Emacs?

As I known, "C-u M-x shell" can be used to run multiple shells. But how to define a function to do the same thing as "C-u M-x shell" do ?

Upvotes: 1

Views: 206

Answers (1)

phils
phils

Reputation: 73334

(defun my-named-shell ()
  "Equivalent to C-u M-x shell RET"
  (interactive)
  (shell (get-buffer
          (read-buffer
           "Shell buffer: "
           (generate-new-buffer-name "*shell*")))))

I used describe-function and find-function to examine the behaviour of shell, and its interactive declaration in particular, and then I just copied the necessary code to turn that into an argument for a non-interactive call to the shell function (but wrapping it in get-buffer so as to provide a buffer argument).

I've actually left out some code which dealt with remote files, because the comments in that code seemed a bit confused. If you weren't in the habit of using C-u M-x shell in buffers accessing remote files via Tramp, that omission won't affect you.

That all said, an even simpler (and more complete) approach is simply:

(defun my-named-shell ()
  "Equivalent to C-u M-x shell RET"
  (interactive)
  (let ((current-prefix-arg '(4)))
    (call-interactively 'shell)))

For more information, refer to https://stackoverflow.com/a/9388058/324105

In this instance current-prefix-arg could be any non-nil value, but I think it's a good habit to use a value that C-u actually generates.

Upvotes: 2

Related Questions