1 ;;; multishell.el --- Easily use multiple shell buffers, local and remote.
3 ;; Copyright (C) 1999-2016 Free Software Foundation, Inc.
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 any of your shell buffers, from anywhere inside emacs.
20 ;; * Use universal arguments to launch and choose among alternate shell buffers,
21 ;; ... and change which is the current default.
23 ;; * Easily restart disconnected shells, or shells from prior sessions
24 ;; ... the latter from Emacs builtin savehist minibuf history persistence
26 ;; * Append a path to a new shell name to launch a shell in that directory,
27 ;; ... and use a path with Emacs tramp syntax to launch a remote shell -
30 ;; * `#root/sudo:root@localhost:/etc` for a buffer named "*#root*" with a
31 ;; root shell starting in /etc.
33 ;; * `/ssh:example.net:` for a shell buffer in your homedir on example.net.
34 ;; The buffer will be named "*example.net*".
36 ;; * `#ex/ssh:example.net|sudo:root@example.net:/var/log` for a root shell
37 ;; starting in /var/log on example.net named "*#ex*".
39 ;; * 'interior/ssh:gateway.corp.com|ssh:interior.corp.com:' to go via
40 ;; gateway.corp.com to your homedir on interior.corp.com. The buffer
41 ;; will be named "*interior*". You could append a sudo hop, and so on.
43 ;; * Thanks to tramp, file visits from the shell will seamlessly be in
44 ;; the auspices of the target account, and relative to the current
45 ;; directory, on the host where the shell is running.
47 ;; * Manage your list of shells, current and past, as a collection.
49 ;; See the `multishell-pop-to-shell` docstring for details.
51 ;; Customize-group `multishell' to select and activate a keybinding and set
52 ;; various behaviors. Customize-group `savehist' to preserve buffer
53 ;; names/paths across emacs restarts.
56 ;; [the multishell repository](https://github.com/kenmanheimer/EmacsMultishell)
57 ;; issue tracker to report problems, suggestions, etc, and see that
58 ;; repository for a bit more documentation.
62 ;; * 2016-02-10 1.1.4 Ken Manheimer:
63 ;; - hookup multishell-list as completion help buffer.
64 ;; * 2016-02-09 1.1.3 Ken Manheimer:
66 ;; - add some handy operations, like cloning new entry from existing
67 ;; - add optional behaviors to existing operations for returning to
68 ;; stopped shells without restarting them.
69 ;; - solidify maintaining focus on current entry
70 ;; - fix miscellaneous.
71 ;; * 2016-01-31 1.1.2 Ken Manheimer:
72 ;; - Settle puzzling instability of multishell-all-entries
73 ;; - The accumulations was putting items going from more to less active
74 ;; categories to be put at the end, not beginning.
75 ;; - Also, using history for prompting changes history - implement
76 ;; no-record option to avoid this when needed.
77 ;; - Implement simple edit-in-place multishell-replace-entry and use in
78 ;; multishell-list-edit-entry.
79 ;; - Remove now unnecessary multishell-list-revert-buffer-kludge.
80 ;; - Rectify byte compiler offenses, and other fixes - thanks to Stefan
81 ;; Monnier for pointing out many of the corrections.
82 ;; - Avoid directly calling tramp functions unnecessarily.
83 ;; * 2016-01-30 1.1.1 Ken Manheimer:
84 ;; - shake out initial multishell-list glitches:
85 ;; - (Offer to) delete shell buffer, if present, when deleting entry.
86 ;; - Set recency (numeric rank) as initial sort field
87 ;; - Recompute list on most operations that affect the order, and try to
88 ;; preserve stability. (Kludgy solution, needs work.)
89 ;; - Set version to 1.1.1 - multishell-list addition should have been 1.1.0.
90 ;; * 2016-01-30 1.0.9 Ken Manheimer:
91 ;; - Add multishell-list for managing the collection of current and
92 ;; history-registered shells: edit, delete, and switch/pop to entries.
93 ;; Easy access by invoking `multishell-pop-to-shell' from in the
94 ;; `multishell-pop-to-shell' universal arg prompts.
95 ;; - Duplicate existing shell buffer names in completions, for distinction.
96 ;; - Add paths to buffers started without one, when multishell history dir
97 ;; tracking is enabled.
98 ;; - Major code cleanup:
99 ;; - Simplify multishell-start-shell-in-buffer, in particular using
100 ;; shell function, rather than unnecessarily going underneath it.
101 ;; - Establish multishell-name-from-entry as canonical name resolver.
102 ;; - Fallback to eval-after-load in emacs versions that lack
103 ;; with-eval-after-load (eg, emacs 23).
104 ;; - save-match-data, where match-string is used
105 ;; - resituate some helpers
106 ;; * 2016-01-24 1.0.8 Ken Manheimer:
107 ;; - Work around the shell/tramp mishandling of remote+sudo+homedir problem!
108 ;; The work around is clean and simple, basically using high-level `cd'
109 ;; API and not messing with the low-level default-directory setting.
110 ;; (Turns out the problem was not in my local config. Good riddance to the
111 ;; awkward failure handler!)
112 ;; - Clean up code resolving the destination shell, starting to document the
113 ;; decision tree in the process. See getting-to-a-shell.md in the
114 ;; multishell repository, https://github.com/kenmanheimer/EmacsMultishell
115 ;; - There may be some shake-out on resolving the destination shell, but
116 ;; this release gets the fundamental functionality soundly in place.
117 ;; * 2016-01-23 1.0.7 Ken Manheimer:
118 ;; - Remove notes about tramp remote+sudo+homedir problem. Apparently it's
119 ;; due to something in my local site configuration (happens with -q but
121 ;; * 2016-01-22 1.0.6 Ken Manheimer:
122 ;; - Add multishell-version function.
123 ;; - Tweak commentary/comments/docstrings.
124 ;; - Null old multishell-buffer-name-history var, if present.
125 ;; * 2016-01-16 1.0.5 Ken Manheimer:
126 ;; - History now includes paths, when designated.
127 ;; - Actively track current directory in history entries that have a path.
128 ;; Custom control: multishell-history-entry-tracks-current-directory
129 ;; - Offer to remove shell's history entry when buffer is killed.
130 ;; (Currently the only UI mechanism to remove history entries.)
131 ;; - Fix - prevent duplicate entries for same name but different paths
132 ;; - Fix - recognize and respect tramp path syntax to start in home dir
133 ;; - Simplify history var name, migrate existing history if any from old name
134 ;; * 2016-01-04 1.0.4 Ken Manheimer - Released to ELPA
135 ;; * 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
137 ;; TODO and Known Issues:
139 ;; * Add mouse actions - buttons - to multishell-list entries
140 ;; - see buf-menu.el, eg Buffer-menu-mouse-select
141 ;; * Resolve multishell-list sort glitches:
142 ;; - Fix config so multishell-list-revert-buffer-kludge is not needed
143 ;; - Make multishell-list-edit-entry in-place, so changed entries recency
145 ;; - Fill in kill-buffer prompting gaps, eg if default live-process
146 ;; prompts are inhibited.
147 ;; * Add custom shell launch prep actions
148 ;; - for, eg, port knocking, interface activations
149 ;; - shell commands to execute when shell name or path matches a regexp
150 ;; - list of (regexp, which - name, path, or both, command)
151 ;; * Adapt multishell-list facilities for all-completions
152 ;; - See info on minibuffer-completion-help, display-completion-list
153 ;; * Investigate whether we can recognize and provide for failed hops.
154 ;; - Tramp doesn't provide useful reactions for any hop but the first
155 ;; - Might be stuff we can do to detect and convey failures?
156 ;; - Might be no recourse but to seek tramp changes.
157 ;; * Try minibuffer field boundary at beginning of tramp path, to see whether
158 ;; the field boundary magically enables tramp path completion.
165 (require 'multishell-list)
167 (defvar multishell-version "1.1.3")
168 (defun multishell-version (&optional here)
169 "Return string describing the loaded multishell version."
171 (let ((msg (concat "Multishell " multishell-version)))
172 (if here (insert msg)
173 (if (called-interactively-p 'interactive)
177 (defgroup multishell nil
178 "Allout extension that highlights outline structure graphically.
180 Customize `allout-widgets-auto-activation' to activate allout-widgets
184 (defcustom multishell-command-key "\M- "
185 "The key to use if `multishell-activate-command-key' is true.
187 You can instead manually bind `multishell-pop-to-shell` using emacs
188 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
191 (defvar multishell--responsible-for-command-key nil
192 "Coordination for multishell key assignment.")
193 (defun multishell-activate-command-key-setter (symbol setting)
194 "Implement `multishell-activate-command-key' choice."
195 (set-default symbol setting)
196 (when (or setting multishell--responsible-for-command-key)
197 (multishell-implement-command-key-choice (not setting))))
198 (defun multishell-implement-command-key-choice (&optional unbind)
199 "If settings dicate, implement binding of multishell command key.
201 If optional UNBIND is true, globally unbind the key.
203 * `multishell-activate-command-key' - Set this to get the binding or not.
204 * `multishell-command-key' - The key to use for the binding, if appropriate."
206 (when (and (boundp 'multishell-command-key) multishell-command-key)
207 (global-unset-key multishell-command-key)))
208 ((not (and (boundp 'multishell-activate-command-key)
209 (boundp 'multishell-command-key)))
211 ((and multishell-activate-command-key multishell-command-key)
212 (setq multishell--responsible-for-command-key t)
213 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
215 (defcustom multishell-activate-command-key nil
216 "Set this to impose the `multishell-command-key' binding.
218 You can instead manually bind `multishell-pop-to-shell` using emacs
219 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
221 :set 'multishell-activate-command-key-setter)
223 ;; Implement the key customization whenever the package is loaded:
224 (if (fboundp 'with-eval-after-load)
225 (with-eval-after-load "multishell"
226 (multishell-implement-command-key-choice))
227 (eval-after-load "multishell"
228 '(multishell-implement-command-key-choice)))
230 (defcustom multishell-pop-to-frame nil
231 "*If non-nil, jump to a frame already showing the shell, if another one is.
233 Otherwise, disregard already-open windows on the shell if they're
234 in another frame, and open a new window on the shell in the
237 \(Use `pop-up-windows' to change multishell other-window vs
238 current-window behavior.)"
241 (defcustom multishell-history-entry-tracks-current-directory t
242 "Maintain shell's current directory in its multishell history entry.
244 When set, the history entry for shells started with explicit
245 paths will track the shell's current working directory.
247 If `savehist-save-minibuffer-history' is enabled, the current
248 working directory of shells will be conveyed between emacs
252 (defvar multishell-history nil
253 "Name/path entries, most recent first.")
254 ;; Migrate the few pre 1.0.5 users to changed history var:
255 (when (and (not multishell-history)
256 (boundp 'multishell-buffer-name-history)
257 multishell-buffer-name-history)
258 (setq multishell-history multishell-buffer-name-history
259 multishell-buffer-name-history nil))
261 (defvar multishell-primary-name "*shell*"
262 "Default shell name for un-modified multishell-pop-to-shell buffer target.
264 This is set by `multishell-pop-to-shell' as the current default,
265 when invoked with doubled universal argument.
267 If you want the designated primary that you have at the end of
268 one emacs session to be resumed at the next, customize
269 `savehist-additional-variables' to include the
270 `multishell-primary-name'.")
272 (defvar multishell-completing-read nil
273 "Internal use, conveying whether or not we're in the midst of a multishell
276 ;; Multiple entries happen because completion also adds name to history.
277 (defun multishell-register-name-to-path (name path)
278 "Add or replace entry associating NAME with PATH in `multishell-history'.
280 If NAME already had a PATH and new PATH is empty, retain the prior one.
282 Promote added/changed entry to the front of the list."
283 ;; Add or promote to the front, tracking path changes in the process.
284 (let* ((entries (multishell-history-entries name))
286 (dolist (entry entries)
287 (when (string= path "")
288 ;; Retain explicit established path.
289 (setq path (cadr (multishell-split-entry entry))))
290 (setq multishell-history (delete entry multishell-history)))
291 (setq multishell-history (push (concat name path)
292 multishell-history))))
294 (defun multishell-replace-entry (entry revised)
295 "Replace every instance of ENTRY in `multishell-history' with REVISED.
297 Revised entry is situated where former one was.
299 Returns non-nil iff any changes were made."
300 (let ((candidates multishell-history)
302 (while (setq candidates (member entry candidates))
303 (setcar candidates revised)
304 (setq candidates (cdr candidates)
308 (defun multishell-history-entries (name)
309 "Return `multishell-history' entry that starts with NAME, or nil if none."
311 (dolist (entry multishell-history)
312 (when (and (string-equal name (multishell-name-from-entry entry))
313 (not (member entry got)))
318 (defun multishell-pop-to-shell (&optional arg name here)
319 "Easily navigate to and within multiple shell buffers, local and remote.
321 Use a single `universal-argument' (\\[universal-argument]) to launch and choose between
322 nalternate shell buffers, and a doubled universal argument to also set your
323 choice as the ongoing default. Append a path to a new shell name to launch
324 a shell in that directory, and use Emacs tramp syntax to launch a remote
325 shell. There is a shortcut to manage your list of current and
326 historical shells, collectively, using `multishell-list' - see below.
328 Customize-group `multishell' to set up a key binding and tweak behaviors.
330 Manage your collection of current and historical shells by
331 recursively invoking \\[multishell-pop-to-shell] at the
332 `multishell-pop-to-shell' universal argument prompts, eg:
334 \\[universal-argument] \\[multishell-pop-to-shell] \\[multishell-pop-to-shell]
336 \(That will be just a few keys if you do the above
337 customization.) Hit ? in the listing buffer for editing commands.
339 ==== Basic operation:
341 - If the current buffer is shell-mode (or shell-mode derived)
342 buffer then focus is moved to the process input point.
344 \(You can use a universal argument go to a different shell
345 buffer when already in a buffer that has a process - see
348 - If not in a shell buffer (or with universal argument), go to a
349 window that is already showing the (a) shell buffer, if any.
351 In this case, the cursor is left in its prior position in the
352 shell buffer. Repeating the command will then go to the
353 process input point, per the first item in this list.
355 We respect `pop-up-windows', so you can adjust it to set the
356 other-buffer/same-buffer behavior.
358 - Otherwise, start a new shell buffer, using the current
359 directory as the working directory.
361 If a buffer with the resulting name exists and its shell process
362 was disconnected or otherwise stopped, it's resumed.
364 ===== Universal arg to start and select between named shell buffers:
366 You can name alternate shell buffers to create or return to, by
367 prefixing your \\[multishell-pop-to-shell] invocation with single or double
368 `universal-argument', \\[universal-argument]:
370 - With a single universal argument, prompt for the buffer name
371 to use (without the asterisks that shell mode will put around
372 the name), defaulting to 'shell'.
374 Completion is available.
376 This combination makes it easy to start and switch across
377 multiple shell restarts.
379 - A double universal argument will prompt for the name *and* set
380 the default to that name, so the target shell becomes the
383 See `multishell-primary-name' for info about preserving the
384 setting across emacs restarts.
386 - Manage your collection of current and historical shells by
387 recursively invoking \\[multishell-pop-to-shell] at either of the
388 `multishell-pop-to-shell' universal argument prompts, or at any
389 time via \\[multishell-list]. Hit ? in the listing buffer for
392 ===== Select starting directory and remote host:
394 The shell buffer name you give to the prompt for a universal arg
395 can include an appended path. That will be used for the startup
396 directory. You can use tramp remote syntax to specify a remote
397 shell. If there is an element after a final '/', that's used for
398 the buffer name. Otherwise, the host, domain, or path is used.
402 * '#root/sudo:root@localhost:/etc' for a buffer named \"*#root*\" with a
403 root shell starting in /etc.
405 * '/ssh:example.net:' for a shell buffer in your homedir on example.net.
406 The buffer will be named \"*example.net*\".
408 * '#ex/ssh:example.net|sudo:root@example.net:/var/log' for a root shell
409 starting in /var/log on example.net named \"*#ex*\".
411 * 'interior/ssh:gateway.corp.com|ssh:interior.corp.com:' to go
412 via gateway.corp.com to your homedir on interior.corp.com. The
413 buffer will be named \"*interior*\". You could append a sudo
414 hop to the path, combining the previous example, and so on.
416 File visits from the shell, and many common emacs activities like
417 dired, will be on the host where the shell is running, in the
418 auspices of the target account, and relative to the current
421 You can change the startup path for a shell buffer by editing it
422 at the completion prompt. The new path will not take effect for
423 an already-running shell.
425 To remove a shell buffer's history entry, kill the buffer and
426 affirm removal of the entry when prompted.
428 ===== Activate savehist to retain shell buffer names and paths across Emacs restarts:
430 To have emacs maintain your history of shell buffer names and paths,
431 customize the savehist group to activate savehist."
435 (let ((token '(token)))
436 (if (window-minibuffer-p)
437 (throw 'multishell-minibuffer-exit token)
438 (let ((got (catch 'multishell-minibuffer-exit
439 (multishell-pop-to-shell-worker arg name here))))
440 ;; Handle catch or plain fall-through - see cond comments for protocol.
442 ;; Caught token from recursive invocation in minibuffer:
443 ((equal token got) (multishell-list))
444 ;; Caught specifaction of multishell args, eg from multishell-list:
445 ((listp got) (multishell-pop-to-shell-worker (nth 2 got)
448 ;; Regular fallthrough - just relay the result:
451 (defun multishell-pop-to-shell-worker (&optional arg name here)
452 "Do real work of `multishell-pop-to-shell', which see."
453 (let* ((from-buffer (current-buffer))
454 (from-buffer-is-shell (derived-mode-p 'shell-mode))
455 (primary-name-unbracketed (multishell-unbracket
456 multishell-primary-name))
457 (fallthrough-name (if from-buffer-is-shell
458 (buffer-name from-buffer)
459 primary-name-unbracketed))
460 (doublearg (equal arg '(16)))
461 (target-name-and-path
462 (multishell-resolve-target-name-and-path
465 (or (multishell-read-unbracketed-entry
466 (format "Shell buffer name [%s]%s "
467 primary-name-unbracketed
468 (if doublearg " <==" ":")))
469 primary-name-unbracketed))
470 (t fallthrough-name))))
471 (use-path (cadr target-name-and-path))
472 (target-shell-buffer-name (car target-name-and-path))
473 (target-buffer (get-buffer target-shell-buffer-name))
474 (curr-buff-proc (get-buffer-process from-buffer))
478 ;; Register early so the entry is pushed to the front:
479 (multishell-register-name-to-path (multishell-unbracket
480 target-shell-buffer-name)
484 (setq multishell-primary-name target-shell-buffer-name))
490 ((and (or curr-buff-proc from-buffer-is-shell)
492 (eq from-buffer target-buffer)
493 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
494 ;; In a shell buffer, but not named - stay in buffer, but go to end.
495 (setq already-there t))
497 ((string= (buffer-name) target-shell-buffer-name)
498 ;; Already in the specified shell buffer:
499 (setq already-there t))
501 ((or (not target-buffer)
503 (multishell-get-visible-window-for-buffer target-buffer))))
504 ;; No preexisting shell buffer, or not in a visible window:
505 (when (not (get-buffer target-shell-buffer-name))
506 (message "Creating new shell buffer '%s'" target-shell-buffer-name))
508 (switch-to-buffer target-shell-buffer-name)
509 (pop-to-buffer target-shell-buffer-name pop-up-windows)))
511 ;; Buffer exists and already has a window - jump to it:
512 (t (if (and multishell-pop-to-frame
514 (not (equal (window-frame (selected-window))
515 (window-frame inwin))))
516 (select-frame-set-input-focus (window-frame inwin)))
517 (if (not (string= (buffer-name (current-buffer))
518 target-shell-buffer-name))
520 (switch-to-buffer target-shell-buffer-name)
521 (pop-to-buffer target-shell-buffer-name t)))))
523 ;; We're in the buffer. Activate:
525 (if (not (comint-check-proc (current-buffer)))
526 (multishell-start-shell-in-buffer use-path))
528 ;; If the destination buffer has a stopped process, resume it:
529 (let ((process (get-buffer-process (current-buffer))))
530 (if (and process (equal 'stop (process-status process)))
531 (continue-process process)))
533 (when (or already-there
534 (equal (current-buffer) from-buffer))
535 (goto-char (point-max))
536 (and (get-buffer-process from-buffer)
537 (goto-char (process-mark (get-buffer-process from-buffer)))))))
539 (defun multishell-delete-history-name (name &optional ask)
540 "Remove all multishell history entries for NAME.
542 if optional ask is non-nil (default nil), ask before each deletion.
544 Return the last entry deleted."
546 (dolist (entry (multishell-history-entries name) got)
549 (y-or-n-p (format "Remove multishell history entry `%s'? "
552 multishell-history (delete entry multishell-history))))))
554 (defun multishell-kill-buffer-query-function ()
555 "Offer to remove multishell-history entry for buffer."
556 ;; Removal choice is crucial, so users can, eg, kill a shell with huge
557 ;; output backlog, while keeping the history entry to easily restart it.
559 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
561 ;; 1. It enables the user to remove the history without actually killing a
562 ;; running buffer, by not confirming the subsequent running-proc query.
563 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
564 ;; It's probably due to failures in other hooks - beyond our control -
565 ;; and anyway, I like the first reason well enough.
567 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
568 ;; activity. kill-buffer happens behind the scenes a whole lot.)
570 (and (derived-mode-p 'shell-mode)
571 (multishell-delete-history-name
572 (multishell-unbracket (buffer-name))
575 (message "multishell-kill-buffer-query-function error: %s" err)))
577 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
579 (defun multishell-get-visible-window-for-buffer (buffer)
580 "Return visible window containing buffer."
583 (function (lambda (win)
584 (if (and (eq (window-buffer win) buffer)
585 (equal (frame-parameter
586 (selected-frame) 'display)
588 (window-frame win) 'display)))
589 (throw 'got-a-vis win))))
593 (defun multishell-all-entries (&optional active-duplicated)
594 "Return multishell history, with active buffers listed first.
596 Optional ACTIVE-DUPLICATED will return a copy of
597 `multishell-history' with unbracketed names of active buffers,
598 sans paths, appended to the list, so they have short and long
600 ;; Reorder so active lead present lead historical entries:
601 (let (active-entries active-names present past splat name buffer)
602 (dolist (entry multishell-history)
603 (setq splat (multishell-split-entry entry)
605 buffer (and name (get-buffer (multishell-bracket name))))
606 (if (buffer-live-p buffer)
607 (if (comint-check-proc buffer)
608 (setq active-entries (push entry active-entries)
609 active-names (push name active-names))
610 (setq present (push entry present)))
611 (setq past (push entry past))))
612 ;; Reverse present and past lists
613 (setq multishell-history (append (reverse active-entries)
616 (if active-duplicated
617 (append multishell-history active-names)
618 multishell-history)))
620 (defun multishell-read-unbracketed-entry (prompt &optional initial no-record)
621 "PROMPT for shell buffer name, sans asterisks.
623 Optional INITIAL is preliminary value to be edited.
625 Optional NO-RECORD prevents changes to `multishell-history'
628 Input and completion can include associated path, if any.
630 Return what's provided, if anything, else nil."
631 (let* ((was-multishell-history multishell-history)
632 (candidates (multishell-all-entries 'active-duplicated))
633 (multishell-completing-read t)
635 ;; Use `cl-letf' to dynamically bind multishell-list to
636 ;; display-completion-list, so multishell-list is used when doing
637 ;; minibuffer-completion-help.
638 (cl-letf (((symbol-function 'display-completion-list)
640 (completing-read prompt
650 'multishell-history))))
652 (setq multishell-history was-multishell-history))
653 (if (not (string= got ""))
657 (defun multishell-resolve-target-name-and-path (shell-spec)
658 "Given name/tramp-style address shell spec, resolve buffer name and directory.
660 The name is the part of the string up to the first '/' slash, if
661 any. Missing pieces are filled in from remote path elements, if
662 any, and multishell history. Given a tramp-style remote address
663 and no name part, either the user@host is used for the buffer
664 name, if a user is specified, or just the host.
666 Return them as a list: (name path), with name asterisk-bracketed
667 and path nil if none is resolved."
668 (let* ((splat (multishell-split-entry (or shell-spec "")))
670 (name (or (car splat) (multishell-name-from-entry path))))
672 ;; Get path from history, if present.
674 (multishell-history-entries
675 (multishell-unbracket name)))
676 (when (or (not path) (string= path ""))
677 (setq path (cadr (multishell-split-entry entry))))))
678 (list (multishell-bracket name) path)))
680 (defun multishell-name-from-entry (entry)
681 "Derive a name for a shell buffer according to ENTRY."
683 (multishell-unbracket multishell-primary-name)
684 (let* ((splat (multishell-split-entry entry))
688 (if (file-remote-p path)
689 (let ((host (file-remote-p path 'host))
690 (user (file-remote-p path 'user)))
691 (cond ((and host user)
692 (format "%s@%s" user host))
696 (multishell-unbracket multishell-primary-name))))))
698 (declare-function tramp-dissect-file-name "tramp")
699 (declare-function tramp-cleanup-connection "tramp")
701 (defun multishell-start-shell-in-buffer (path)
702 "Start, restart, or continue a shell in BUFFER-NAME on PATH."
703 (let* ((is-active (comint-check-proc (current-buffer))))
705 (when (and path (not is-active))
707 (when (and (derived-mode-p 'shell-mode) (file-remote-p path))
708 ;; Returning to disconnected remote shell - do some tidying.
709 ;; Without this cleanup, occasionally restarting a disconnected
710 ;; remote session, particularly one that includes sudo, results in
711 ;; an untraceable "Args out of range" error. That never happens if
712 ;; we precedeed connection attempts with this cleanup -
714 (tramp-cleanup-connection
715 (tramp-dissect-file-name default-directory 'noexpand)
716 'keep-debug 'keep-password))
718 (when (file-remote-p path) (message "Connecting to %s" path))
721 (shell (current-buffer))))
723 (defun multishell-homedir-shorthand-p (dirpath)
724 "t if dirpath is an unexpanded remote homedir spec."
725 ;; Workaround to recognize tramp-style homedir shorthand, "...:" and "...:~".
726 (let ((localname (file-remote-p dirpath 'localname)))
729 ;; No directory path and no connection to expand homedir:
730 (string= localname "")
731 ;; Original path doesn't equal expanded homedir:
733 (not (string-match (concat (regexp-quote localname) "/?$")
735 ;; (assert (multishell-homedir-shorthand-p "/ssh:myhost.net:")
736 ;; (assert (not (multishell-homedir-shorthand-p "/home/klm")))
737 ;; (assert (not (multishell-homedir-shorthand-p "/ssh:myhost.net:/home/me")))
739 (defun multishell-track-dirchange (name newpath)
740 "Change multishell history entry to track current directory."
741 (let* ((entries (multishell-history-entries name)))
742 (dolist (entry entries)
743 (let* ((name-path (multishell-split-entry entry))
744 (name (car name-path))
745 (path (or (cadr name-path) "")))
747 (let* ((old-localname (or (file-remote-p path 'localname)
750 (if (multishell-homedir-shorthand-p path)
751 (concat entry newpath)
752 (replace-regexp-in-string (concat (regexp-quote
764 (membership (member entry multishell-history)))
766 (setcar membership newentry))))))))
768 (defvar multishell-was-default-directory ()
769 "Provide for tracking directory changes.")
770 (make-variable-buffer-local 'multishell-was-default-directory)
771 (defun multishell-post-command-business ()
772 "Do multishell bookkeeping."
773 ;; Update multishell-history with dir changes.
775 (when (and multishell-history-entry-tracks-current-directory
776 (derived-mode-p 'shell-mode))
777 (let ((curdir (if (file-remote-p default-directory)
778 (file-remote-p default-directory 'localname)
780 (when (not (string= curdir (or multishell-was-default-directory "")))
781 (multishell-track-dirchange (multishell-unbracket (buffer-name))
783 (setq multishell-was-default-directory curdir)))
784 ;; To avoid disruption as a pervasive hook function, swallow all errors:
786 (message "multishell-post-command-business error: %s" err))))
787 (add-hook 'post-command-hook #'multishell-post-command-business)
789 (defun multishell-split-entry (entry)
790 "Given multishell name/path ENTRY, return the separated name and path pair.
792 Returns nil for empty parts, rather than the empty string."
794 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
795 (let ((name (match-string 1 entry))
796 (path (match-string 2 entry)))
797 (and (string= name "") (setq name nil))
798 (and (string= path "") (setq path nil))
800 (defun multishell-bracket (name)
801 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
802 (if (not (string= (substring name 0 1) "*"))
803 (setq name (concat "*" name)))
804 (if (not (string= (substring name -1) "*"))
805 (setq name (concat name "*")))
807 (defun multishell-unbracket (name)
808 "Return a copy of name, removing asterisks, if any, at beginning and end."
809 (if (string= (substring name 0 1) "*")
810 (setq name (substring name 1)))
811 (if (string= (substring name -1) "*")
812 (setq name (substring name 0 -1)))
815 (provide 'multishell)
817 ;;; multishell.el ends here