1 ;;; multishell.el --- manage interaction with multiple local and remote shells
3 ;; Copyright (C) 1999-2016 Free Software Foundation, Inc. and Ken Manheimer
5 ;; Author: Ken Manheimer <ken.manheimer@gmail.com>
7 ;; Created: 1999 -- first public availability
9 ;; URL: https://github.com/kenmanheimer/EmacsMultishell
13 ;; Easily use and navigate multiple shell buffers, including remote shells.
14 ;; Fundamentally, multishell is the function `multishell-pop-to-shell' -
15 ;; a la `pop-to-buffer' - plus a keybinding. Together, they enable you to:
17 ;; * Get to the input point from wherever you are in a shell buffer,
18 ;; * ... or to one of your shell buffers if you're not currently in one.
19 ;; * Use universal arguments to launch and choose among alternate shell buffers,
20 ;; * ... and select which is default.
21 ;; * Append a path to a new shell name to launch a shell in that directory,
22 ;; * ... and use a path with Emacs tramp syntax to launch a remote shell.
26 ;; * `/ssh:example.net:/` for a shell buffer in / on
27 ;; example.net; the buffer will be named "*example.net*".
29 ;; * `#ex/ssh:example.net|sudo:root@example.net:/etc` for a root shell
30 ;; starting in /etc on example.net named "*#ex*".
32 ;; (NOTE that there is a frequent problem with specifying a remote homedir
33 ;; using tramp syntax, eg `/ssh:example.net:` or `/ssh:example.net:~`. That
34 ;; sometimes fails on an obscure bug - particularly for remote+sudo with
35 ;; homedir syntax. Until fixed, you may need to start remote+sudo shells with
36 ;; an explicit path, then cd ~. With `multishell`s dir-tracking persistent
37 ;; history, you'll be able to use completion to start that shell in the right
38 ;; place, in your subsequent sessions.)
40 ;; See the `multishell-pop-to-shell` docstring for details.
42 ;; Customize-group `multishell' to select and activate a keybinding and set
43 ;; various behaviors. Customize-group `savehist' to preserve buffer
44 ;; names/paths across emacs sessions.
46 ;; See the `multishell-pop-to-shell' docstring for details.
50 ;; * 2016-01-16 1.0.5 Ken Manheimer:
51 ;; - History now includes paths, when designated
52 ;; - Actively track current directory in history entries that have a path.
53 ;; Custom control: multishell-history-entry-tracks-current-directory
54 ;; - Offer to remove shell's history entry when buffer is killed
55 ;; (For now, the only UI way to remove history entries.)
56 ;; - Fix - prevent duplicate entries for same name but different paths
57 ;; - Fix - recognize and respect tramp path syntax to start in home dir
58 ;; - But tramp bug, remote+sudo hops to a home dir can fail, get wedged.
59 ;; - Simplify history var name, migrate existing history if any from old name
60 ;; * 2016-01-04 Ken Manheimer - Released to ELPA
61 ;; * 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
65 ;; * Isolate tramp sporadic failure to connect to remote+sudo+homedir syntax
66 ;; (eg, /ssh:xyz.com|sudo:root@xyz.com: or /ssh:xyz.com|sudo:root@xyz.com:~)
67 ;; * Find suitable, internally consistent ways to sort tidy completions, eg:
68 ;; - first list completions for active shells, then present but inactive,
70 ;; - some way for user to toggle between presenting just buffer names vs
72 ;; - without cutting user off from easy editing of path
73 ;; * Find proper method for setting field boundary at beginning of tramp path
74 ;; in the minibuffer, in order to see whether the field boundary magically
75 ;; enables tramp completion of the path.
76 ;; * Assess whether option to delete history entry on kill-buffer is
84 (defgroup multishell nil
85 "Allout extension that highlights outline structure graphically.
87 Customize `allout-widgets-auto-activation' to activate allout-widgets
91 (defcustom multishell-command-key "\M- "
92 "The key to use if `multishell-activate-command-key' is true.
94 You can instead manually bind `multishell-pop-to-shell` using emacs
95 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
99 (defvar multishell--responsible-for-command-key nil
100 "Coordination for multishell key assignment.")
101 (defun multishell-activate-command-key-setter (symbol setting)
102 "Implement `multishell-activate-command-key' choice."
103 (set-default 'multishell-activate-command-key setting)
104 (when (or setting multishell--responsible-for-command-key)
105 (multishell-implement-command-key-choice (not setting))))
106 (defun multishell-implement-command-key-choice (&optional unbind)
107 "If settings dicate, implement binding of multishell command key.
109 If optional UNBIND is true, globally unbind the key.
111 * `multishell-activate-command-key' - Set this to get the binding or not.
112 * `multishell-command-key' - The key to use for the binding, if appropriate."
114 (when (and (boundp 'multishell-command-key) multishell-command-key)
115 (global-unset-key multishell-command-key)))
116 ((not (and (boundp 'multishell-activate-command-key)
117 (boundp 'multishell-command-key)))
119 ((and multishell-activate-command-key multishell-command-key)
120 (setq multishell--responsible-for-command-key t)
121 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
123 (defcustom multishell-activate-command-key nil
124 "Set this to impose the `multishell-command-key' binding.
126 You can instead manually bind `multishell-pop-to-shell` using emacs
127 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
129 :set 'multishell-activate-command-key-setter
132 ;; Assert the customizations whenever the package is loaded:
133 (with-eval-after-load "multishell"
134 (multishell-implement-command-key-choice))
136 (defcustom multishell-pop-to-frame nil
137 "*If non-nil, jump to a frame already showing the shell, if another is.
139 Otherwise, disregard already-open windows on the shell if they're
140 in another frame, and open a new window on the shell in the
143 \(Use `pop-up-windows' to change multishell other-buffer vs
144 current-buffer behavior.)"
148 (defcustom multishell-history-entry-tracks-current-directory t
149 "Modify shell buffer's multishell entry to track the current directory.
151 When set, the path part of the name/path entry for each shell
152 will track the current directory of the shell with emacs. If
153 `savehist' is active, the directory tracking will extend across
158 (defvar multishell-history nil
159 "Name/path entries, most recent first.")
160 (when (and (not multishell-history)
161 (boundp 'multishell-buffer-name-history)
162 multishell-buffer-name-history)
163 ;; Migrate few users who had old var to new.
164 (setq multishell-history multishell-buffer-name-history)
167 (defvar multishell-primary-name "*shell*"
168 "Shell name to use for un-modified multishell-pop-to-shell buffer target.")
170 ;; There is usually only one entry per name, but disruptions happen.
171 (defun multishell-register-name-to-path (name path)
172 "Add or replace entry associating NAME with PATH in `multishell-history'.
174 Promote to added/changed entry to the front of the list."
175 ;; Add or promote to the front, tracking path changes in the process.
176 (let* ((entries (multishell-history-entries name))
177 (becomes (concat name path)))
178 (dolist (entry entries)
179 (setq multishell-history (delete entry multishell-history)))
180 (setq multishell-history (push becomes multishell-history))))
182 (defun multishell-history-entries (name)
183 "Return `multishell-history' entry that starts with NAME, or nil if none."
184 (let ((match-expr (concat "^" name "\\\(/.*$\\\)?"))
186 (dolist (entry multishell-history)
187 (when (and (string-match match-expr entry)
188 (not (member entry got)))
189 (setq got (cons entry got))))
192 (defun multishell-pop-to-shell (&optional arg)
193 "Easily navigate to and within multiple shell buffers, local and remote.
195 Use universal arguments to launch and choose between alternate
196 shell buffers and to select which is default. Append a path to
197 a new shell name to launch a shell in that directory, and use
198 Emacs tramp syntax to launch a remote shell.
200 Customize-group `multishell' to set up a key binding and tweak behaviors.
202 ==== Basic operation:
204 - If the current buffer is shell-mode (or shell-mode derived)
205 buffer then focus is moved to the process input point.
207 \(You can use a universal argument go to a different shell
208 buffer when already in a buffer that has a process - see
211 - If not in a shell buffer (or with universal argument), go to a
212 window that is already showing the (a) shell buffer, if any.
214 In this case, the cursor is left in its prior position in the
215 shell buffer. Repeating the command will then go to the
216 process input point, per the first item in this list.
218 We respect `pop-up-windows', so you can adjust it to set the
219 other-buffer/same-buffer behavior.
221 - Otherwise, start a new shell buffer, using the current
222 directory as the working directory.
224 If a buffer with the resulting name exists and its shell process
225 was disconnected or otherwise stopped, it's resumed.
227 ===== Universal arg to start and select between named shell buffers:
229 You can name alternate shell buffers to create or return to using
230 single or doubled universal arguments:
232 - With a single universal argument, prompt for the buffer name
233 to use (without the asterisks that shell mode will put around
234 the name), defaulting to 'shell'.
236 Completion is available.
238 This combination makes it easy to start and switch between
239 multiple shell buffers.
241 - A double universal argument will prompt for the name *and* set
242 the default to that name, so the target shell becomes the
245 ===== Select starting directory and remote host:
247 The shell buffer name you give to the prompt for a universal arg
248 can include an appended path. That will be used for the startup
249 directory. You can use tramp remote syntax to specify a remote
250 shell. If there is an element after a final '/', that's used for
251 the buffer name. Otherwise, the host, domain, or path is used.
255 * Use '/ssh:example.net:/home/myaccount' for a shell buffer in
256 /home/myaccount on example.net; the buffer will be named
258 * '\#ex/ssh:example.net|sudo:root@example.net:/etc' for a root
259 shell in /etc on example.net named \"*#ex*\".
261 \(NOTE that there is a problem with specifying a remote homedir using
262 tramp syntax, eg '/ssh:example.net:'. That sometimes fails on an obscure
263 bug - particularly for remote+sudo with homedir syntax. Until fixed, you
264 may need to start remote+sudo shells with an explicit path, then cd ~.)
266 You can change the startup path for a shell buffer by editing it
267 at the completion prompt. The new path will be preserved in
268 history but will not take effect for an already-running shell.
270 To remove a shell buffer's history entry, kill the buffer and
271 affirm removal of the entry when prompted.
273 ===== Activate savehist to persisting your shell buffer names and paths:
275 To have emacs maintain your history of shell buffer names and paths,
276 customize the savehist group to activate savehist."
280 (let* ((from-buffer (current-buffer))
281 (from-buffer-is-shell (derived-mode-p 'shell-mode))
282 (doublearg (equal arg '(16)))
283 (target-name-and-path
284 (multishell-derive-target-name-and-path
286 (multishell-read-bare-shell-buffer-name
287 (format "Shell buffer name [%s]%s "
288 (substring-no-properties
289 multishell-primary-name
290 1 (- (length multishell-primary-name) 1))
291 (if doublearg " <==" ":"))
292 multishell-primary-name)
293 multishell-primary-name)))
294 (use-default-dir (cadr target-name-and-path))
295 (target-shell-buffer-name (car target-name-and-path))
296 (curr-buff-proc (get-buffer-process from-buffer))
297 (target-buffer (if from-buffer-is-shell
299 (let ((got (get-buffer target-shell-buffer-name)))
300 (if (buffer-live-p got)
303 (get-buffer target-shell-buffer-name)))))
308 (setq multishell-primary-name target-shell-buffer-name))
314 ((and (or curr-buff-proc from-buffer-is-shell)
316 (eq from-buffer target-buffer)
317 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
318 ;; In a shell buffer, but not named - stay in buffer, but go to end.
319 (setq already-there t))
321 ((string= (buffer-name) target-shell-buffer-name)
322 ;; Already in the specified shell buffer:
323 (setq already-there t))
325 ((or (not target-buffer)
327 (multishell-get-visible-window-for-buffer target-buffer))))
328 ;; No preexisting shell buffer, or not in a visible window:
329 (pop-to-buffer target-shell-buffer-name pop-up-windows))
331 ;; Buffer exists and already has a window - jump to it:
332 (t (if (and multishell-pop-to-frame
334 (not (equal (window-frame (selected-window))
335 (window-frame inwin))))
336 (select-frame-set-input-focus (window-frame inwin)))
337 (if (not (string= (buffer-name (current-buffer))
338 target-shell-buffer-name))
339 (pop-to-buffer target-shell-buffer-name t))))
341 ;; We're in the buffer. Activate:
343 (if (not (comint-check-proc (current-buffer)))
344 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
347 ;; If the destination buffer has a stopped process, resume it:
348 (let ((process (get-buffer-process (current-buffer))))
349 (if (and process (equal 'stop (process-status process)))
350 (continue-process process)))
351 (multishell-register-name-to-path (multishell-unbracket-asterisks
352 target-shell-buffer-name)
354 (when (or already-there
355 (equal (current-buffer) from-buffer))
356 (goto-char (point-max))
357 (and (get-buffer-process from-buffer)
358 (goto-char (process-mark (get-buffer-process from-buffer)))))))
360 (defun multishell-kill-buffer-query-function ()
361 "Offer to remove multishell-history entry for buffer."
362 ;; Removal choice is crucial, so users can, eg, kill and a runaway shell
363 ;; and keep the history entry to easily restart it.
365 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
367 ;; 1. It enables the user to remove the history without killing the buffer,
368 ;; by cancelling the kill-buffer process after affirming history removal.
369 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
370 ;; I've failed to resolve that, and like the first reason well enough.
372 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
373 ;; activity. kill-buffer happens behind the scenes a whole lot.)
374 (condition-case anyerr
375 (let ((entries (and (derived-mode-p 'shell-mode)
376 (multishell-history-entries
377 (multishell-unbracket-asterisks (buffer-name))))))
378 (dolist (entry entries)
380 (y-or-n-p (format "Remove multishell history entry `%s'? "
382 (setq multishell-history
383 (delete entry multishell-history)))))
386 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
388 (defun multishell-get-visible-window-for-buffer (buffer)
389 "Return visible window containing buffer."
392 (function (lambda (win)
393 (if (and (eq (window-buffer win) buffer)
394 (equal (frame-parameter
395 (selected-frame) 'display)
397 (window-frame win) 'display)))
398 (throw 'got-a-vis win))))
402 (defun multishell-read-bare-shell-buffer-name (prompt default)
403 "PROMPT for shell buffer name, sans asterisks.
405 Return the supplied name bracketed with the asterisks, or specified DEFAULT
409 ;; Plain shell buffer names appended with names from name/path hist:
411 (mapcar (lambda (buffer)
412 (let* ((name (multishell-unbracket-asterisks
413 (buffer-name buffer))))
414 (and (buffer-live-p buffer)
415 (with-current-buffer buffer
416 ;; Shell mode buffers.
417 (derived-mode-p 'shell-mode))
418 (not (multishell-history-entries name))
422 (got (completing-read prompt
432 'multishell-history)))
433 (if (not (string= got ""))
434 (multishell-bracket-asterisks got)
437 (defun multishell-derive-target-name-and-path (path-ish)
438 "Give tramp-style PATH-ISH, determine target name and default directory.
440 The name is the part of the string before the initial '/' slash,
441 if any. Otherwise, it's either the host-name, domain-name, final
442 directory name, or local host name. The path is everything
443 besides the string before the initial '/' slash.
445 Return them as a list (name dir), with dir nil if none given."
446 (let (name (path "") dir)
447 (cond ((string= path-ish "") (setq dir multishell-primary-name))
448 ((string-match "^\\*\\([^/]*\\)\\(/.*\\)\\*" path-ish)
449 ;; We have a path, use it
450 (let ((overt-name (match-string 1 path-ish)))
451 (setq path (match-string 2 path-ish))
452 (if (string= overt-name "") (setq overt-name nil))
453 (if (string= path "") (setq path nil))
455 (multishell-bracket-asterisks
457 (if (file-remote-p path)
458 (let ((vec (tramp-dissect-file-name path)))
459 (or (tramp-file-name-host vec)
460 (tramp-file-name-domain vec)
461 (tramp-file-name-localname vec)
463 (multishell-unbracket-asterisks
464 multishell-primary-name)))))))
465 (t (setq name (multishell-bracket-asterisks path-ish))))
468 (defun multishell-bracket-asterisks (name)
469 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
470 (if (not (string= (substring name 0 1) "*"))
471 (setq name (concat "*" name)))
472 (if (not (string= (substring name -1) "*"))
473 (setq name (concat name "*")))
475 (defun multishell-unbracket-asterisks (name)
476 "Return a copy of name, removing asterisks, if any, at beginning and end."
477 (if (string= (substring name 0 1) "*")
478 (setq name (substring name 1)))
479 (if (string= (substring name -1) "*")
480 (setq name (substring name 0 -1)))
483 (defun multishell-start-shell-in-buffer (buffer-name path)
484 "Ensure a shell is started, with name NAME and PATH."
485 ;; We work around shell-mode's bracketing of the buffer name, and do
486 ;; some tramp-mode hygiene for remote connections.
488 (let* ((buffer buffer-name)
489 (prog (or explicit-shell-file-name
493 (name (file-name-nondirectory prog))
494 (startfile (concat "~/.emacs_" name))
495 (xargs-name (intern-soft (concat "explicit-" name "-args")))
497 (set-buffer buffer-name)
498 (if (and path (not (string= path "")))
499 (setq default-directory path))
500 (setq is-remote (file-remote-p default-directory))
502 (derived-mode-p 'shell-mode)
503 (not (comint-check-proc (current-buffer))))
504 ;; We're returning to an already established but disconnected remote
506 (tramp-cleanup-connection
507 (tramp-dissect-file-name default-directory 'noexpand)
508 'keep-debug 'keep-password))
509 ;; (cd default-directory) will connect if remote:
511 (message "Connecting to %s" default-directory))
513 (cd default-directory)
515 ;; Aargh. Need to isolate this tramp bug.
516 (when (and (stringp (cadr err))
517 (string-equal (cadr err)
518 "Selecting deleted buffer"))
521 (format "Tramp shell can fail on homedir paths, %s (\"%s\")"
522 "please try with an explicit path"
524 (setq buffer (set-buffer (apply 'make-comint
525 (multishell-unbracket-asterisks buffer-name)
527 (if (file-exists-p startfile)
531 (symbol-value xargs-name)
535 (defun multishell-track-dirchange (name newpath)
536 "Change multishell history entry to track current directory."
537 (let* ((entries (multishell-history-entries name)))
538 (dolist (entry entries)
539 (let* ((name-path (multishell-split-entry-name-and-tramp entry))
540 (name (car name-path))
541 (path (cadr name-path)))
543 (let* ((is-remote (file-remote-p path))
544 (vec (and is-remote (tramp-dissect-file-name path nil)))
545 (localname (if is-remote
546 (tramp-file-name-localname vec)
549 (replace-regexp-in-string (if (string= localname "")
551 (regexp-quote localname))
561 (newpath (if is-remote
562 (tramp-make-tramp-file-name (aref vec 0)
568 (newentry (concat name newpath))
569 (membership (member entry multishell-history)))
571 (setcar membership newentry))))))))
572 (defvar multishell-was-default-directory ()
573 "Provide for tracking directory changes.")
574 (make-variable-buffer-local 'multishell-was-default-directory)
575 (defun multishell-post-command-business ()
576 "Do multishell bookkeeping."
577 ;; Update multishell-history with dir changes.
579 (when (and multishell-history-entry-tracks-current-directory
580 (derived-mode-p 'shell-mode))
581 (let ((curdir (if (file-remote-p default-directory)
582 (tramp-file-name-localname
583 (tramp-dissect-file-name default-directory))
585 (when (and multishell-was-default-directory
586 (not (string= curdir multishell-was-default-directory)))
587 (multishell-track-dirchange (multishell-unbracket-asterisks
590 (setq multishell-was-default-directory curdir)))
591 ;; To avoid disruption as a pervasive hook function, swallow all errors:
593 (add-hook 'post-command-hook 'multishell-post-command-business)
595 (defun multishell-split-entry-name-and-tramp (entry)
596 "Given multishell name/path ENTRY, return the separated name and path pair.
598 Returns nil for empty parts, rather than the empty string."
599 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
600 (let ((name (match-string 1 entry))
601 (path (match-string 2 entry)))
602 (and (string= name "") (setq name nil))
603 (and (string= path "") (setq path nil))
606 (provide 'multishell)
608 ;;; multishell.el ends here