1 ;;; multishell.el --- facilitate multiple local and remote shell buffers
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 - there's a sporadic problem when opening a shell pointed at a
33 ;; remote homedir, eg `/ssh:example.net:` or `/ssh:example.net:~`. It
34 ;; sometimes fails, particularly for remotes with empty fs path syntax. Until
35 ;; fixed, you may need to start remote shells with an explicit path, then
36 ;; cd ~. If you set up `multishell`s persistent dir-tracking history,
37 ;; you'll be able to use completion to start that shell in the right place,
38 ;; 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.
48 ;; Please use [the repository](https://github.com/kenmanheimer/EmacsMultishell)
49 ;; issue tracker to report problems, suggestions, etc.
53 ;; * 2016-01-16 1.0.5 Ken Manheimer:
54 ;; - History now includes paths, when designated
55 ;; - Actively track current directory in history entries that have a path.
56 ;; Custom control: multishell-history-entry-tracks-current-directory
57 ;; - Offer to remove shell's history entry when buffer is killed.
58 ;; (Currently the only UI mechanism to remove history entries.)
59 ;; - Fix - prevent duplicate entries for same name but different paths
60 ;; - Fix - recognize and respect tramp path syntax to start in home dir
61 ;; - But tramp bug, remote w/empty path (homedir) often fails, gets wedged.
62 ;; - Simplify history var name, migrate existing history if any from old name
63 ;; * 2016-01-04 1.0.4 Ken Manheimer - Released to ELPA
64 ;; * 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
68 ;; * Isolate tramp sporadic failure to connect to remote+homedir (empty path)
70 ;; (eg, /ssh:xyz.com|sudo:root@xyz.com: or /ssh:xyz.com|sudo:root@xyz.com:~)
71 ;; * Find suitable, internally consistent ways to sort tidy completions, eg:
72 ;; - first list completions for active shells, then present but inactive,
74 ;; - some way for user to toggle between presenting just buffer names vs
76 ;; - without cutting user off from easy editing of path
77 ;; * Find proper method for setting field boundary at beginning of tramp path
78 ;; in the minibuffer, in order to see whether the field boundary magically
79 ;; enables tramp completion of the path.
80 ;; * Assess whether option to delete history entry on kill-buffer is
88 (defgroup multishell nil
89 "Allout extension that highlights outline structure graphically.
91 Customize `allout-widgets-auto-activation' to activate allout-widgets
95 (defcustom multishell-command-key "\M- "
96 "The key to use if `multishell-activate-command-key' is true.
98 You can instead manually bind `multishell-pop-to-shell` using emacs
99 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
103 (defvar multishell--responsible-for-command-key nil
104 "Coordination for multishell key assignment.")
105 (defun multishell-activate-command-key-setter (symbol setting)
106 "Implement `multishell-activate-command-key' choice."
107 (set-default 'multishell-activate-command-key setting)
108 (when (or setting multishell--responsible-for-command-key)
109 (multishell-implement-command-key-choice (not setting))))
110 (defun multishell-implement-command-key-choice (&optional unbind)
111 "If settings dicate, implement binding of multishell command key.
113 If optional UNBIND is true, globally unbind the key.
115 * `multishell-activate-command-key' - Set this to get the binding or not.
116 * `multishell-command-key' - The key to use for the binding, if appropriate."
118 (when (and (boundp 'multishell-command-key) multishell-command-key)
119 (global-unset-key multishell-command-key)))
120 ((not (and (boundp 'multishell-activate-command-key)
121 (boundp 'multishell-command-key)))
123 ((and multishell-activate-command-key multishell-command-key)
124 (setq multishell--responsible-for-command-key t)
125 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
127 (defcustom multishell-activate-command-key nil
128 "Set this to impose the `multishell-command-key' binding.
130 You can instead manually bind `multishell-pop-to-shell` using emacs
131 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
133 :set 'multishell-activate-command-key-setter
136 ;; Assert the customizations whenever the package is loaded:
137 (with-eval-after-load "multishell"
138 (multishell-implement-command-key-choice))
140 (defcustom multishell-pop-to-frame nil
141 "*If non-nil, jump to a frame already showing the shell, if another is.
143 Otherwise, disregard already-open windows on the shell if they're
144 in another frame, and open a new window on the shell in the
147 \(Use `pop-up-windows' to change multishell other-buffer vs
148 current-buffer behavior.)"
152 (defcustom multishell-history-entry-tracks-current-directory t
153 "Modify shell buffer's multishell entry to track the current directory.
155 When set, the path part of the name/path entry for each shell
156 will track the current directory of the shell with emacs. If
157 `savehist' is active, the directory tracking will extend across
162 (defvar multishell-history nil
163 "Name/path entries, most recent first.")
164 (when (and (not multishell-history)
165 (boundp 'multishell-buffer-name-history)
166 multishell-buffer-name-history)
167 ;; Migrate few users who had old var to new.
168 (setq multishell-history multishell-buffer-name-history)
171 (defvar multishell-primary-name "*shell*"
172 "Shell name to use for un-modified multishell-pop-to-shell buffer target.")
174 ;; There is usually only one entry per name, but disruptions happen.
175 (defun multishell-register-name-to-path (name path)
176 "Add or replace entry associating NAME with PATH in `multishell-history'.
178 If NAME already had a PATH and new PATH is empty, retain old one.
180 Promote added/changed entry to the front of the list."
181 ;; Add or promote to the front, tracking path changes in the process.
182 (let* ((entries (multishell-history-entries name))
183 (becomes (concat name path))
185 (dolist (entry entries)
186 (when (or (not path) (string= path ""))
187 ;; Retain explicit established path.
188 (setq path (cadr (multishell-split-entry-name-and-tramp entry))
189 becomes (concat name path)))
190 (setq multishell-history (delete entry multishell-history)))
191 (setq multishell-history (push becomes multishell-history))))
193 (defun multishell-history-entries (name)
194 "Return `multishell-history' entry that starts with NAME, or nil if none."
195 (let ((match-expr (concat "^" name "\\\(/.*$\\\)?"))
197 (dolist (entry multishell-history)
198 (when (and (string-match match-expr entry)
199 (not (member entry got)))
200 (setq got (cons entry got))))
203 (defun multishell-pop-to-shell (&optional arg)
204 "Easily navigate to and within multiple shell buffers, local and remote.
206 Use universal arguments to launch and choose between alternate
207 shell buffers and to select which is default. Append a path to
208 a new shell name to launch a shell in that directory, and use
209 Emacs tramp syntax to launch a remote shell.
211 Customize-group `multishell' to set up a key binding and tweak behaviors.
213 ==== Basic operation:
215 - If the current buffer is shell-mode (or shell-mode derived)
216 buffer then focus is moved to the process input point.
218 \(You can use a universal argument go to a different shell
219 buffer when already in a buffer that has a process - see
222 - If not in a shell buffer (or with universal argument), go to a
223 window that is already showing the (a) shell buffer, if any.
225 In this case, the cursor is left in its prior position in the
226 shell buffer. Repeating the command will then go to the
227 process input point, per the first item in this list.
229 We respect `pop-up-windows', so you can adjust it to set the
230 other-buffer/same-buffer behavior.
232 - Otherwise, start a new shell buffer, using the current
233 directory as the working directory.
235 If a buffer with the resulting name exists and its shell process
236 was disconnected or otherwise stopped, it's resumed.
238 ===== Universal arg to start and select between named shell buffers:
240 You can name alternate shell buffers to create or return to using
241 single or doubled universal arguments:
243 - With a single universal argument, prompt for the buffer name
244 to use (without the asterisks that shell mode will put around
245 the name), defaulting to 'shell'.
247 Completion is available.
249 This combination makes it easy to start and switch between
250 multiple shell buffers.
252 - A double universal argument will prompt for the name *and* set
253 the default to that name, so the target shell becomes the
256 ===== Select starting directory and remote host:
258 The shell buffer name you give to the prompt for a universal arg
259 can include an appended path. That will be used for the startup
260 directory. You can use tramp remote syntax to specify a remote
261 shell. If there is an element after a final '/', that's used for
262 the buffer name. Otherwise, the host, domain, or path is used.
266 * Use '/ssh:example.net:/home/myaccount' for a shell buffer in
267 /home/myaccount on example.net; the buffer will be named
269 * '\#ex/ssh:example.net|sudo:root@example.net:/etc' for a root
270 shell in /etc on example.net named \"*#ex*\".
272 \(NOTE that there is a problem with specifying a remote homedir using
273 tramp syntax, eg '/ssh:example.net:'. That sometimes fails on an obscure
274 bug - particularly for remote with empty path (homedir) syntax. Until fixed,
275 you may need to start remote shells with an explicit path, then cd ~.)
277 You can change the startup path for a shell buffer by editing it
278 at the completion prompt. The new path will be preserved in
279 history but will not take effect for an already-running shell.
281 To remove a shell buffer's history entry, kill the buffer and
282 affirm removal of the entry when prompted.
284 ===== Activate savehist to persisting your shell buffer names and paths:
286 To have emacs maintain your history of shell buffer names and paths,
287 customize the savehist group to activate savehist."
291 (let* ((from-buffer (current-buffer))
292 (from-buffer-is-shell (derived-mode-p 'shell-mode))
293 (doublearg (equal arg '(16)))
294 (target-name-and-path
295 (multishell-derive-target-name-and-path
297 (multishell-read-bare-shell-buffer-name
298 (format "Shell buffer name [%s]%s "
299 (substring-no-properties
300 multishell-primary-name
301 1 (- (length multishell-primary-name) 1))
302 (if doublearg " <==" ":"))
303 multishell-primary-name)
304 multishell-primary-name)))
305 (use-default-dir (cadr target-name-and-path))
306 (target-shell-buffer-name (car target-name-and-path))
307 (curr-buff-proc (get-buffer-process from-buffer))
308 (target-buffer (if from-buffer-is-shell
310 (let ((got (get-buffer target-shell-buffer-name)))
311 (if (buffer-live-p got)
314 (get-buffer target-shell-buffer-name)))))
319 (setq multishell-primary-name target-shell-buffer-name))
325 ((and (or curr-buff-proc from-buffer-is-shell)
327 (eq from-buffer target-buffer)
328 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
329 ;; In a shell buffer, but not named - stay in buffer, but go to end.
330 (setq already-there t))
332 ((string= (buffer-name) target-shell-buffer-name)
333 ;; Already in the specified shell buffer:
334 (setq already-there t))
336 ((or (not target-buffer)
338 (multishell-get-visible-window-for-buffer target-buffer))))
339 ;; No preexisting shell buffer, or not in a visible window:
340 (pop-to-buffer target-shell-buffer-name pop-up-windows))
342 ;; Buffer exists and already has a window - jump to it:
343 (t (if (and multishell-pop-to-frame
345 (not (equal (window-frame (selected-window))
346 (window-frame inwin))))
347 (select-frame-set-input-focus (window-frame inwin)))
348 (if (not (string= (buffer-name (current-buffer))
349 target-shell-buffer-name))
350 (pop-to-buffer target-shell-buffer-name t))))
352 ;; We're in the buffer. Activate:
354 (if (not (comint-check-proc (current-buffer)))
355 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
358 ;; If the destination buffer has a stopped process, resume it:
359 (let ((process (get-buffer-process (current-buffer))))
360 (if (and process (equal 'stop (process-status process)))
361 (continue-process process)))
362 (multishell-register-name-to-path (multishell-unbracket-asterisks
363 target-shell-buffer-name)
365 (when (or already-there
366 (equal (current-buffer) from-buffer))
367 (goto-char (point-max))
368 (and (get-buffer-process from-buffer)
369 (goto-char (process-mark (get-buffer-process from-buffer)))))))
371 (defun multishell-kill-buffer-query-function ()
372 "Offer to remove multishell-history entry for buffer."
373 ;; Removal choice is crucial, so users can, eg, kill and a runaway shell
374 ;; and keep the history entry to easily restart it.
376 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
378 ;; 1. It enables the user to remove the history without killing the buffer,
379 ;; by cancelling the kill-buffer process after affirming history removal.
380 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
381 ;; I've failed to resolve that, and like the first reason well enough.
383 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
384 ;; activity. kill-buffer happens behind the scenes a whole lot.)
385 (condition-case anyerr
386 (let ((entries (and (derived-mode-p 'shell-mode)
387 (multishell-history-entries
388 (multishell-unbracket-asterisks (buffer-name))))))
389 (dolist (entry entries)
391 (y-or-n-p (format "Remove multishell history entry `%s'? "
393 (setq multishell-history
394 (delete entry multishell-history)))))
397 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
399 (defun multishell-get-visible-window-for-buffer (buffer)
400 "Return visible window containing buffer."
403 (function (lambda (win)
404 (if (and (eq (window-buffer win) buffer)
405 (equal (frame-parameter
406 (selected-frame) 'display)
408 (window-frame win) 'display)))
409 (throw 'got-a-vis win))))
413 (defun multishell-read-bare-shell-buffer-name (prompt default)
414 "PROMPT for shell buffer name, sans asterisks.
416 Return the supplied name bracketed with the asterisks, or specified DEFAULT
420 ;; Plain shell buffer names appended with names from name/path hist:
422 (mapcar (lambda (buffer)
423 (let* ((name (multishell-unbracket-asterisks
424 (buffer-name buffer))))
425 (and (buffer-live-p buffer)
426 (with-current-buffer buffer
427 ;; Shell mode buffers.
428 (derived-mode-p 'shell-mode))
429 (not (multishell-history-entries name))
433 (got (completing-read prompt
443 'multishell-history)))
444 (if (not (string= got ""))
445 (multishell-bracket-asterisks got)
448 (defun multishell-derive-target-name-and-path (path-ish)
449 "Give tramp-style PATH-ISH, determine target name and default directory.
451 The name is the part of the string before the initial '/' slash,
452 if any. Otherwise, it's either the host-name, domain-name, final
453 directory name, or local host name. The path is everything
454 besides the string before the initial '/' slash.
456 Return them as a list (name dir), with dir nil if none given."
457 (let (name (path "") dir)
458 (cond ((string= path-ish "") (setq dir multishell-primary-name))
459 ((string-match "^\\*\\([^/]*\\)\\(/.*\\)\\*" path-ish)
460 ;; We have a path, use it
461 (let ((overt-name (match-string 1 path-ish)))
462 (setq path (match-string 2 path-ish))
463 (if (string= overt-name "") (setq overt-name nil))
464 (if (string= path "") (setq path nil))
466 (multishell-bracket-asterisks
468 (if (file-remote-p path)
469 (let ((vec (tramp-dissect-file-name path)))
470 (or (tramp-file-name-host vec)
471 (tramp-file-name-domain vec)
472 (tramp-file-name-localname vec)
474 (multishell-unbracket-asterisks
475 multishell-primary-name)))))))
476 (t (setq name (multishell-bracket-asterisks path-ish))))
479 (defun multishell-bracket-asterisks (name)
480 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
481 (if (not (string= (substring name 0 1) "*"))
482 (setq name (concat "*" name)))
483 (if (not (string= (substring name -1) "*"))
484 (setq name (concat name "*")))
486 (defun multishell-unbracket-asterisks (name)
487 "Return a copy of name, removing asterisks, if any, at beginning and end."
488 (if (string= (substring name 0 1) "*")
489 (setq name (substring name 1)))
490 (if (string= (substring name -1) "*")
491 (setq name (substring name 0 -1)))
494 (defun multishell-start-shell-in-buffer (buffer-name path)
495 "Ensure a shell is started, with name NAME and PATH."
496 ;; We work around shell-mode's bracketing of the buffer name, and do
497 ;; some tramp-mode hygiene for remote connections.
499 (let* ((buffer buffer-name)
500 (prog (or explicit-shell-file-name
504 (name (file-name-nondirectory prog))
505 (startfile (concat "~/.emacs_" name))
506 (xargs-name (intern-soft (concat "explicit-" name "-args")))
508 (set-buffer buffer-name)
509 (if (and path (not (string= path "")))
510 (setq default-directory path))
511 (setq is-remote (file-remote-p default-directory))
513 (derived-mode-p 'shell-mode)
514 (not (comint-check-proc (current-buffer))))
515 ;; We're returning to an already established but disconnected remote
517 (tramp-cleanup-connection
518 (tramp-dissect-file-name default-directory 'noexpand)
519 'keep-debug 'keep-password))
520 ;; (cd default-directory) will connect if remote:
522 (message "Connecting to %s" default-directory))
524 (cd default-directory)
526 ;; Aargh. Need to isolate this tramp bug.
527 (when (and (stringp (cadr err))
528 (string-equal (cadr err)
529 "Selecting deleted buffer"))
532 (format "%s, %s (\"%s\")"
533 "Tramp shell can fail on empty (homedir) path"
534 "please try again with an explicit path"
536 (setq buffer (set-buffer (apply 'make-comint
537 (multishell-unbracket-asterisks buffer-name)
539 (if (file-exists-p startfile)
543 (symbol-value xargs-name)
547 (defun multishell-track-dirchange (name newpath)
548 "Change multishell history entry to track current directory."
549 (let* ((entries (multishell-history-entries name)))
550 (dolist (entry entries)
551 (let* ((name-path (multishell-split-entry-name-and-tramp entry))
552 (name (car name-path))
553 (path (cadr name-path)))
555 (let* ((is-remote (file-remote-p path))
556 (vec (and is-remote (tramp-dissect-file-name path nil)))
557 (localname (if is-remote
558 (tramp-file-name-localname vec)
561 (replace-regexp-in-string (if (string= localname "")
563 (regexp-quote localname))
573 (newpath (if is-remote
574 (tramp-make-tramp-file-name (aref vec 0)
580 (newentry (concat name newpath))
581 (membership (member entry multishell-history)))
583 (setcar membership newentry))))))))
584 (defvar multishell-was-default-directory ()
585 "Provide for tracking directory changes.")
586 (make-variable-buffer-local 'multishell-was-default-directory)
587 (defun multishell-post-command-business ()
588 "Do multishell bookkeeping."
589 ;; Update multishell-history with dir changes.
591 (when (and multishell-history-entry-tracks-current-directory
592 (derived-mode-p 'shell-mode))
593 (let ((curdir (if (file-remote-p default-directory)
594 (tramp-file-name-localname
595 (tramp-dissect-file-name default-directory))
597 (when (and multishell-was-default-directory
598 (not (string= curdir multishell-was-default-directory)))
599 (multishell-track-dirchange (multishell-unbracket-asterisks
602 (setq multishell-was-default-directory curdir)))
603 ;; To avoid disruption as a pervasive hook function, swallow all errors:
605 (add-hook 'post-command-hook 'multishell-post-command-business)
607 (defun multishell-split-entry-name-and-tramp (entry)
608 "Given multishell name/path ENTRY, return the separated name and path pair.
610 Returns nil for empty parts, rather than the empty string."
611 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
612 (let ((name (match-string 1 entry))
613 (path (match-string 2 entry)))
614 (and (string= name "") (setq name nil))
615 (and (string= path "") (setq path nil))
618 (provide 'multishell)
620 ;;; multishell.el ends here