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/EmacsUtils
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 ;; * ... with just a keystroke.
20 ;; * Use universal arguments to launch and choose among alternate shell buffers,
21 ;; * ... and select which is default.
22 ;; * Append a path to a new shell name to launch a shell in that directory,
23 ;; * ... and use a path with Emacs tramp syntax to launch a remote shell.
27 ;; * '/ssh:example.net:/' for a shell buffer in / on
28 ;; example.net; the buffer will be named "*example.net*".
30 ;; * '#ex/ssh:example.net|sudo:root@example.net:/etc' for a root shell
31 ;; starting in /etc on example.net named "*#ex*".
33 ;; (NOTE that there is a problem with specifying a remote homedir using
34 ;; tramp syntax, eg '/ssh:example.net:'. That sometimes fails on an obscure
35 ;; bug - particularly for remote+sudo with homedir syntax. Until fixed, you
36 ;; may need to start remote+sudo shells with an explicit path, then cd ~.)
38 ;; Customize-group `multishell' to select and activate a keybinding and set
39 ;; various behaviors. Customize-group `savehist' to preserve buffer
40 ;; names/paths across emacs sessions.
42 ;; See the `multishell-pop-to-shell' docstring for details.
46 ;; 2016-01-16 1.0.5 Ken Manheimer:
47 ;; - History now includes paths, when specified.
48 ;; - Actively track current directory in history entry, if it has a path
49 ;; Customize: multishell-history-entry-tracks-current-directory
50 ;; - Offer to user to remove shell's history entry when buffer is killed
51 ;; - Fix - prevent duplicate entries for same name but different paths
52 ;; - Fix - recognize and respect tramp path syntax to start in home dir
53 ;; - But tramp bug, sudo hops to a home dir often fails.
54 ;; - Simplify history var name, migrate existing history if any from old name
55 ;; 2016-01-06 Ken Manheimer - Released
56 ;; 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
60 ;; * Isolate frequent failure with remote tramp home-dir syntax (`/host.dom:')
61 ;; * Find suitable modes for brief and elaborate name/path exposures,
62 ;; e.g. toggle for completions to show just name or name+path
69 (defgroup multishell nil
70 "Allout extension that highlights outline structure graphically.
72 Customize `allout-widgets-auto-activation' to activate allout-widgets
76 (defcustom multishell-command-key "\M- "
77 "The key to use if `multishell-activate-command-key' is true.
79 You can instead manually bind `multishell-pop-to-shell` using emacs
80 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
84 (defvar multishell--responsible-for-command-key nil
85 "Coordination for multishell key assignment.")
86 (defun multishell-activate-command-key-setter (symbol setting)
87 "Implement `multishell-activate-command-key' choice."
88 (set-default 'multishell-activate-command-key setting)
89 (when (or setting multishell--responsible-for-command-key)
90 (multishell-implement-command-key-choice (not setting))))
91 (defun multishell-implement-command-key-choice (&optional unbind)
92 "If settings dicate, implement binding of multishell command key.
94 If optional UNBIND is true, globally unbind the key.
96 * `multishell-activate-command-key' - Set this to get the binding or not.
97 * `multishell-command-key' - The key to use for the binding, if appropriate."
99 (when (and (boundp 'multishell-command-key) multishell-command-key)
100 (global-unset-key multishell-command-key)))
101 ((not (and (boundp 'multishell-activate-command-key)
102 (boundp 'multishell-command-key)))
104 ((and multishell-activate-command-key multishell-command-key)
105 (setq multishell--responsible-for-command-key t)
106 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
108 (defcustom multishell-activate-command-key nil
109 "Set this to impose the `multishell-command-key' binding.
111 You can instead manually bind `multishell-pop-to-shell` using emacs
112 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
114 :set 'multishell-activate-command-key-setter
117 ;; Assert the customizations whenever the package is loaded:
118 (with-eval-after-load "multishell"
119 (multishell-implement-command-key-choice))
121 (defcustom multishell-pop-to-frame nil
122 "*If non-nil, jump to a frame already showing the shell, if another is.
124 Otherwise, disregard already-open windows on the shell if they're
125 in another frame, and open a new window on the shell in the
128 \(Use `pop-up-windows' to change multishell other-buffer vs
129 current-buffer behavior.)"
133 (defcustom multishell-history-entry-tracks-current-directory t
134 "Modify shell buffer's multishell entry to track the current directory.
136 When set, the path part of the name/path entry for each shell
137 will track the current directory of the shell with emacs. If
138 `savehist' is active, the directory tracking will extend across
143 (defvar multishell-history nil
144 "Name/path entries, most recent first.")
145 (when (and (not multishell-history)
146 (boundp 'multishell-buffer-name-history)
147 multishell-buffer-name-history)
148 ;; Migrate few users who had old var to new.
149 (setq multishell-history multishell-buffer-name-history)
152 (defvar multishell-primary-name "*shell*"
153 "Shell name to use for un-modified multishell-pop-to-shell buffer target.")
155 ;; There is usually only one entry per name, but disruptions happen.
156 (defun multishell-register-name-to-path (name path)
157 "Add or replace entry associating NAME with PATH in `multishell-history'.
159 Promote to added/changed entry to the front of the list."
160 ;; Add or promote to the front, tracking path changes in the process.
161 (let* ((entries (multishell-history-entries name))
162 (becomes (concat name path)))
163 (dolist (entry entries)
164 (setq multishell-history (delete entry multishell-history)))
165 (setq multishell-history (push becomes multishell-history))))
167 (defun multishell-history-entries (name)
168 "Return `multishell-history' entry that starts with NAME, or nil if none."
169 (let ((match-expr (concat "^" name "\\\(/.*$\\\)?"))
171 (dolist (entry multishell-history)
172 (when (and (string-match match-expr entry)
173 (not (member entry got)))
174 (setq got (cons entry got))))
177 (defun multishell-pop-to-shell (&optional arg)
178 "Easily navigate to and within multiple shell buffers, local and remote.
180 Use universal arguments to launch and choose between alternate
181 shell buffers and to select which is default. Append a path to
182 a new shell name to launch a shell in that directory, and use
183 Emacs tramp syntax to launch a remote shell.
185 Customize-group `multishell' to set up a key binding and tweak behaviors.
187 ==== Basic operation:
189 - If the current buffer is shell-mode (or shell-mode derived)
190 buffer then focus is moved to the process input point.
192 \(You can use a universal argument go to a different shell
193 buffer when already in a buffer that has a process - see
196 - If not in a shell buffer (or with universal argument), go to a
197 window that is already showing the (a) shell buffer, if any.
199 In this case, the cursor is left in its prior position in the
200 shell buffer. Repeating the command will then go to the
201 process input point, per the first item in this list.
203 We respect `pop-up-windows', so you can adjust it to set the
204 other-buffer/same-buffer behavior.
206 - Otherwise, start a new shell buffer, using the current
207 directory as the working directory.
209 If a buffer with the resulting name exists and its shell process
210 was disconnected or otherwise stopped, it's resumed.
212 ===== Universal arg to start and select between named shell buffers:
214 You can name alternate shell buffers to create or return to using
215 single or doubled universal arguments:
217 - With a single universal argument, prompt for the buffer name
218 to use (without the asterisks that shell mode will put around
219 the name), defaulting to 'shell'.
221 Completion is available.
223 This combination makes it easy to start and switch between
224 multiple shell buffers.
226 - A double universal argument will prompt for the name *and* set
227 the default to that name, so the target shell becomes the
230 ===== Select starting directory and remote host:
232 The shell buffer name you give to the prompt for a universal arg
233 can include an appended path. That will be used for the startup
234 directory. You can use tramp remote syntax to specify a remote
235 shell. If there is an element after a final '/', that's used for
236 the buffer name. Otherwise, the host, domain, or path is used.
240 * Use '/ssh:example.net:/home/myaccount' for a shell buffer in
241 /home/myaccount on example.net; the buffer will be named
243 * '\#ex/ssh:example.net|sudo:root@example.net:/etc' for a root
244 shell in /etc on example.net named \"*#ex*\".
246 \(NOTE that there is a problem with specifying a remote homedir using
247 tramp syntax, eg '/ssh:example.net:'. That sometimes fails on an obscure
248 bug - particularly for remote+sudo with homedir syntax. Until fixed, you
249 may need to start remote+sudo shells with an explicit path, then cd ~.)
251 You can change the startup path for a shell buffer by editing it
252 at the completion prompt. The new path will be preserved in
253 history but will not take effect for an already-running shell.
255 To remove a shell buffer's history entry, kill the buffer and
256 affirm removal of the entry when prompted.
258 ===== Activate savehist to persisting your shell buffer names and paths:
260 To have emacs maintain your history of shell buffer names and paths,
261 customize the savehist group to activate savehist."
265 (let* ((from-buffer (current-buffer))
266 (from-buffer-is-shell (derived-mode-p 'shell-mode))
267 (doublearg (equal arg '(16)))
268 (target-name-and-path
269 (multishell-derive-target-name-and-path
271 (multishell-read-bare-shell-buffer-name
272 (format "Shell buffer name [%s]%s "
273 (substring-no-properties
274 multishell-primary-name
275 1 (- (length multishell-primary-name) 1))
276 (if doublearg " <==" ":"))
277 multishell-primary-name)
278 multishell-primary-name)))
279 (use-default-dir (cadr target-name-and-path))
280 (target-shell-buffer-name (car target-name-and-path))
281 (curr-buff-proc (get-buffer-process from-buffer))
282 (target-buffer (if from-buffer-is-shell
284 (let ((got (get-buffer target-shell-buffer-name)))
285 (if (buffer-live-p got)
288 (get-buffer target-shell-buffer-name)))))
293 (setq multishell-primary-name target-shell-buffer-name))
299 ((and (or curr-buff-proc from-buffer-is-shell)
301 (eq from-buffer target-buffer)
302 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
303 ;; In a shell buffer, but not named - stay in buffer, but go to end.
304 (setq already-there t))
306 ((string= (buffer-name) target-shell-buffer-name)
307 ;; Already in the specified shell buffer:
308 (setq already-there t))
310 ((or (not target-buffer)
312 (multishell-get-visible-window-for-buffer target-buffer))))
313 ;; No preexisting shell buffer, or not in a visible window:
314 (pop-to-buffer target-shell-buffer-name pop-up-windows))
316 ;; Buffer exists and already has a window - jump to it:
317 (t (if (and multishell-pop-to-frame
319 (not (equal (window-frame (selected-window))
320 (window-frame inwin))))
321 (select-frame-set-input-focus (window-frame inwin)))
322 (if (not (string= (buffer-name (current-buffer))
323 target-shell-buffer-name))
324 (pop-to-buffer target-shell-buffer-name t))))
326 ;; We're in the buffer. Activate:
328 (if (not (comint-check-proc (current-buffer)))
329 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
332 ;; If the destination buffer has a stopped process, resume it:
333 (let ((process (get-buffer-process (current-buffer))))
334 (if (and process (equal 'stop (process-status process)))
335 (continue-process process)))
336 (multishell-register-name-to-path (multishell-unbracket-asterisks
337 target-shell-buffer-name)
339 (when (or already-there
340 (equal (current-buffer) from-buffer))
341 (goto-char (point-max))
342 (and (get-buffer-process from-buffer)
343 (goto-char (process-mark (get-buffer-process from-buffer)))))))
345 (defun multishell-kill-buffer-query-function ()
346 "Offer to remove multishell-history entry for buffer."
347 ;; Removal choice is crucial, so users can, eg, kill and a runaway shell
348 ;; and keep the history entry to easily restart it.
350 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
352 ;; 1. It enables the user to remove the history without killing the buffer,
353 ;; by cancelling the kill-buffer process after affirming history removal.
354 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
355 ;; I've failed to resolve that, and like the first reason well enough.
357 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
358 ;; activity. kill-buffer happens behind the scenes a whole lot.)
359 (condition-case anyerr
360 (let ((entries (and (derived-mode-p 'shell-mode)
361 (multishell-history-entries
362 (multishell-unbracket-asterisks (buffer-name))))))
363 (dolist (entry entries)
365 (y-or-n-p (format "Remove multishell history entry `%s'? "
367 (setq multishell-history
368 (delete entry multishell-history)))))
371 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
373 (defun multishell-get-visible-window-for-buffer (buffer)
374 "Return visible window containing buffer."
377 (function (lambda (win)
378 (if (and (eq (window-buffer win) buffer)
379 (equal (frame-parameter
380 (selected-frame) 'display)
382 (window-frame win) 'display)))
383 (throw 'got-a-vis win))))
387 (defun multishell-read-bare-shell-buffer-name (prompt default)
388 "PROMPT for shell buffer name, sans asterisks.
390 Return the supplied name bracketed with the asterisks, or specified DEFAULT
394 ;; Plain shell buffer names appended with names from name/path hist:
396 (mapcar (lambda (buffer)
397 (let* ((name (multishell-unbracket-asterisks
398 (buffer-name buffer))))
399 (and (buffer-live-p buffer)
400 (with-current-buffer buffer
401 ;; Shell mode buffers.
402 (derived-mode-p 'shell-mode))
403 (not (multishell-history-entries name))
407 (got (completing-read prompt
417 'multishell-history)))
418 (if (not (string= got ""))
419 (multishell-bracket-asterisks got)
422 (defun multishell-derive-target-name-and-path (path-ish)
423 "Give tramp-style PATH-ISH, determine target name and default directory.
425 The name is the part of the string before the initial '/' slash,
426 if any. Otherwise, it's either the host-name, domain-name, final
427 directory name, or local host name. The path is everything
428 besides the string before the initial '/' slash.
430 Return them as a list (name dir), with dir nil if none given."
431 (let (name (path "") dir)
432 (cond ((string= path-ish "") (setq dir multishell-primary-name))
433 ((string-match "^\\*\\([^/]*\\)\\(/.*\\)\\*" path-ish)
434 ;; We have a path, use it
435 (let ((overt-name (match-string 1 path-ish)))
436 (setq path (match-string 2 path-ish))
437 (if (string= overt-name "") (setq overt-name nil))
438 (if (string= path "") (setq path nil))
440 (multishell-bracket-asterisks
442 (if (file-remote-p path)
443 (let ((vec (tramp-dissect-file-name path)))
444 (or (tramp-file-name-host vec)
445 (tramp-file-name-domain vec)
446 (tramp-file-name-localname vec)
448 (multishell-unbracket-asterisks
449 multishell-primary-name)))))))
450 (t (setq name (multishell-bracket-asterisks path-ish))))
453 (defun multishell-bracket-asterisks (name)
454 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
455 (if (not (string= (substring name 0 1) "*"))
456 (setq name (concat "*" name)))
457 (if (not (string= (substring name -1) "*"))
458 (setq name (concat name "*")))
460 (defun multishell-unbracket-asterisks (name)
461 "Return a copy of name, removing asterisks, if any, at beginning and end."
462 (if (string= (substring name 0 1) "*")
463 (setq name (substring name 1)))
464 (if (string= (substring name -1) "*")
465 (setq name (substring name 0 -1)))
468 (defun multishell-start-shell-in-buffer (buffer-name path)
469 "Ensure a shell is started, with name NAME and PATH."
470 ;; We work around shell-mode's bracketing of the buffer name, and do
471 ;; some tramp-mode hygiene for remote connections.
473 (let* ((buffer buffer-name)
474 (prog (or explicit-shell-file-name
478 (name (file-name-nondirectory prog))
479 (startfile (concat "~/.emacs_" name))
480 (xargs-name (intern-soft (concat "explicit-" name "-args")))
482 (set-buffer buffer-name)
483 (if (and path (not (string= path "")))
484 (setq default-directory path))
485 (setq is-remote (file-remote-p default-directory))
487 (derived-mode-p 'shell-mode)
488 (not (comint-check-proc (current-buffer))))
489 ;; We're returning to an already established but disconnected remote
491 (tramp-cleanup-connection
492 (tramp-dissect-file-name default-directory 'noexpand)
493 'keep-debug 'keep-password))
494 ;; (cd default-directory) will connect if remote:
496 (message "Connecting to %s" default-directory))
498 (cd default-directory)
500 ;; Aargh. Need to isolate this tramp bug.
501 (when (and (stringp (cadr err))
502 (string-equal (cadr err)
503 "Selecting deleted buffer"))
506 (format "Tramp shell can fail on homedir paths, %s (\"%s\")"
507 "please try with an explicit path"
509 (setq buffer (set-buffer (apply 'make-comint
510 (multishell-unbracket-asterisks buffer-name)
512 (if (file-exists-p startfile)
516 (symbol-value xargs-name)
520 (defun multishell-track-dirchange (name newpath)
521 "Change multishell history entry to track current directory."
522 (let* ((entries (multishell-history-entries name)))
523 (dolist (entry entries)
524 (let* ((name-path (multishell-split-entry-name-and-tramp entry))
525 (name (car name-path))
526 (path (cadr name-path)))
528 (let* ((is-remote (file-remote-p path))
529 (vec (and is-remote (tramp-dissect-file-name path nil)))
530 (localname (if is-remote
531 (tramp-file-name-localname vec)
534 (replace-regexp-in-string (if (string= localname "")
536 (regexp-quote localname))
546 (newpath (if is-remote
547 (tramp-make-tramp-file-name (aref vec 0)
553 (newentry (concat name newpath))
554 (membership (member entry multishell-history)))
556 (setcar membership newentry))))))))
557 (defvar multishell-was-default-directory ()
558 "Provide for tracking directory changes.")
559 (make-variable-buffer-local 'multishell-was-default-directory)
560 (defun multishell-post-command-business ()
561 "Do multishell bookkeeping."
562 ;; Update multishell-history with dir changes.
564 (when (and multishell-history-entry-tracks-current-directory
565 (derived-mode-p 'shell-mode))
566 (let ((curdir (if (file-remote-p default-directory)
567 (tramp-file-name-localname
568 (tramp-dissect-file-name default-directory))
570 (when (and multishell-was-default-directory
571 (not (string= curdir multishell-was-default-directory)))
572 (multishell-track-dirchange (multishell-unbracket-asterisks
575 (setq multishell-was-default-directory curdir)))
576 ;; To avoid disruption as a pervasive hook function, swallow all errors:
578 (add-hook 'post-command-hook 'multishell-post-command-business)
580 (defun multishell-split-entry-name-and-tramp (entry)
581 "Given multishell name/path ENTRY, return the separated name and path pair.
583 Returns nil for empty parts, rather than the empty string."
584 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
585 (let ((name (match-string 1 entry))
586 (path (match-string 2 entry)))
587 (and (string= name "") (setq name nil))
588 (and (string= path "") (setq path nil))
591 (provide 'multishell)
593 ;;; multishell.el ends here