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 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-01-31 1.1.2 Ken Manheimer:
63 ;; - Settle puzzling instability of multishell-all-entries
64 ;; - The accumulations was putting items going from more to less active
65 ;; categories to be put at the end, not beginning.
66 ;; - Also, using history for prompting changes history - implement
67 ;; no-record option to avoid this when needed.
68 ;; - Implement simple edit-in-place multishell-replace-entry and use in
69 ;; multishell-list-edit-entry.
70 ;; - Remove now (hopefully) unnecessary multishell-list-revert-buffer-kludge.
71 ;; * 2016-01-30 1.1.1 Ken Manheimer:
72 ;; - shake out initial multishell-list glitches:
73 ;; - (Offer to) delete shell buffer, if present, when deleting entry.
74 ;; - Set recency (numeric rank) as initial sort field
75 ;; - Recompute list on most operations that affect the order, and try to
76 ;; preserve stability. (Kludgy solution, needs work.)
77 ;; - Set version to 1.1.1 - multishell-list addition should have been 1.1.0.
78 ;; * 2016-01-30 1.0.9 Ken Manheimer:
79 ;; - Add multishell-list for managing the collection of current and
80 ;; history-registered shells: edit, delete, and switch/pop to entries.
81 ;; Easy access by invoking `multishell-pop-to-shell' from in the
82 ;; `multishell-pop-to-shell' universal arg prompts.
83 ;; - Duplicate existing shell buffer names in completions, for distinction.
84 ;; - Add paths to buffers started without one, when multishell history dir
85 ;; tracking is enabled.
86 ;; - Major code cleanup:
87 ;; - Simplify multishell-start-shell-in-buffer, in particular using
88 ;; shell function, rather than unnecessarily going underneath it.
89 ;; - Establish multishell-name-from-entry as canonical name resolver.
90 ;; - Fallback to eval-after-load in emacs versions that lack
91 ;; with-eval-after-load (eg, emacs 23).
92 ;; - save-match-data, where match-string is used
93 ;; - resituate some helpers
94 ;; * 2016-01-24 1.0.8 Ken Manheimer:
95 ;; - Work around the shell/tramp mishandling of remote+sudo+homedir problem!
96 ;; The work around is clean and simple, basically using high-level `cd'
97 ;; API and not messing with the low-level default-directory setting.
98 ;; (Turns out the problem was not in my local config. Good riddance to the
99 ;; awkward failure handler!)
100 ;; - Clean up code resolving the destination shell, starting to document the
101 ;; decision tree in the process. See getting-to-a-shell.md in the
102 ;; multishell repository, https://github.com/kenmanheimer/EmacsMultishell
103 ;; - There may be some shake-out on resolving the destination shell, but
104 ;; this release gets the fundamental functionality soundly in place.
105 ;; * 2016-01-23 1.0.7 Ken Manheimer:
106 ;; - Remove notes about tramp remote+sudo+homedir problem. Apparently it's
107 ;; due to something in my local site configuration (happens with -q but
109 ;; * 2016-01-22 1.0.6 Ken Manheimer:
110 ;; - Add multishell-version function.
111 ;; - Tweak commentary/comments/docstrings.
112 ;; - Null old multishell-buffer-name-history var, if present.
113 ;; * 2016-01-16 1.0.5 Ken Manheimer:
114 ;; - History now includes paths, when designated.
115 ;; - Actively track current directory in history entries that have a path.
116 ;; Custom control: multishell-history-entry-tracks-current-directory
117 ;; - Offer to remove shell's history entry when buffer is killed.
118 ;; (Currently the only UI mechanism to remove history entries.)
119 ;; - Fix - prevent duplicate entries for same name but different paths
120 ;; - Fix - recognize and respect tramp path syntax to start in home dir
121 ;; - Simplify history var name, migrate existing history if any from old name
122 ;; * 2016-01-04 1.0.4 Ken Manheimer - Released to ELPA
123 ;; * 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
125 ;; TODO and Known Issues:
127 ;; * Add mouse actions - buttons - to multishell-list entries
128 ;; - see buf-menu.el, eg Buffer-menu-mouse-select
129 ;; * Resolve multishell-list sort glitches:
130 ;; - Fix config so multishell-list-revert-buffer-kludge is not needed
131 ;; - Make multishell-list-edit-entry in-place, so changed entries recency
133 ;; - Fill in kill-buffer prompting gaps, eg if default live-process
134 ;; prompts are inhibited.
135 ;; * Add custom shell launch prep actions
136 ;; - for, eg, port knocking, interface activations
137 ;; - shell commands to execute when shell name or path matches a regexp
138 ;; - list of (regexp, which - name, path, or both, command)
139 ;; * Adapt multishell-list facilities for all-completions
140 ;; - See info on minibuffer-completion-help, display-completion-list
141 ;; * Investigate whether we can recognize and provide for failed hops.
142 ;; - Tramp doesn't provide useful reactions for any hop but the first
143 ;; - Might be stuff we can do to detect and convey failures?
144 ;; - Might be no recourse but to seek tramp changes.
145 ;; * Try minibuffer field boundary at beginning of tramp path, to see whether
146 ;; the field boundary magically enables tramp path completion.
153 (require 'multishell-list)
155 (defvar multishell-version "1.1.2")
156 (defun multishell-version (&optional here)
157 "Return string describing the loaded multishell version."
159 (let ((msg (concat "Multishell " multishell-version)))
160 (if here (insert msg)
161 (if (called-interactively-p 'interactive)
165 (defgroup multishell nil
166 "Allout extension that highlights outline structure graphically.
168 Customize `allout-widgets-auto-activation' to activate allout-widgets
172 (defcustom multishell-command-key "\M- "
173 "The key to use if `multishell-activate-command-key' is true.
175 You can instead manually bind `multishell-pop-to-shell` using emacs
176 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
180 (defvar multishell--responsible-for-command-key nil
181 "Coordination for multishell key assignment.")
182 (defun multishell-activate-command-key-setter (symbol setting)
183 "Implement `multishell-activate-command-key' choice."
184 (set-default 'multishell-activate-command-key setting)
185 (when (or setting multishell--responsible-for-command-key)
186 (multishell-implement-command-key-choice (not setting))))
187 (defun multishell-implement-command-key-choice (&optional unbind)
188 "If settings dicate, implement binding of multishell command key.
190 If optional UNBIND is true, globally unbind the key.
192 * `multishell-activate-command-key' - Set this to get the binding or not.
193 * `multishell-command-key' - The key to use for the binding, if appropriate."
195 (when (and (boundp 'multishell-command-key) multishell-command-key)
196 (global-unset-key multishell-command-key)))
197 ((not (and (boundp 'multishell-activate-command-key)
198 (boundp 'multishell-command-key)))
200 ((and multishell-activate-command-key multishell-command-key)
201 (setq multishell--responsible-for-command-key t)
202 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
204 (defcustom multishell-activate-command-key nil
205 "Set this to impose the `multishell-command-key' binding.
207 You can instead manually bind `multishell-pop-to-shell` using emacs
208 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
210 :set 'multishell-activate-command-key-setter
213 ;; Implement the key customization whenever the package is loaded:
214 (if (fboundp 'with-eval-after-load)
215 (with-eval-after-load "multishell"
216 (multishell-implement-command-key-choice))
217 (eval-after-load "multishell"
218 (multishell-implement-command-key-choice)))
220 (defcustom multishell-pop-to-frame nil
221 "*If non-nil, jump to a frame already showing the shell, if another one is.
223 Otherwise, disregard already-open windows on the shell if they're
224 in another frame, and open a new window on the shell in the
227 \(Use `pop-up-windows' to change multishell other-window vs
228 current-window behavior.)"
232 (defcustom multishell-history-entry-tracks-current-directory t
233 "Maintain shell's current directory in its multishell history entry.
235 When set, the history entry for shells started with explicit
236 paths will track the shell's current working directory. (Explicit
237 paths will not be added to local shells started without one,
240 If `savehist-save-minibuffer-history' is enabled, the current
241 working directory of shells \(that were started with an explicit
242 path) will be conveyed between emacs sessions."
246 (defvar multishell-history nil
247 "Name/path entries, most recent first.")
248 ;; Migrate the few pre 1.0.5 users to changed history var:
249 (when (and (not multishell-history)
250 (boundp 'multishell-buffer-name-history)
251 multishell-buffer-name-history)
252 (setq multishell-history multishell-buffer-name-history
253 multishell-buffer-name-history nil))
255 (defvar multishell-primary-name "*shell*"
256 "Default shell name for un-modified multishell-pop-to-shell buffer target.
258 This is set by `multishell-pop-to-shell' as the current default,
259 when invoked with doubled universal argument.
261 If you want the designated primary that you have at the end of
262 one emacs session to be resumed at the next, customize
263 `savehist-additional-variables' to include the
264 `multishell-primary-name'.")
266 ;; Multiple entries happen because completion also adds name to history.
267 (defun multishell-register-name-to-path (name path)
268 "Add or replace entry associating NAME with PATH in `multishell-history'.
270 If NAME already had a PATH and new PATH is empty, retain the prior one.
272 Promote added/changed entry to the front of the list."
273 ;; Add or promote to the front, tracking path changes in the process.
274 (let* ((entries (multishell-history-entries name))
276 (dolist (entry entries)
277 (when (string= path "")
278 ;; Retain explicit established path.
279 (setq path (cadr (multishell-split-entry entry))))
280 (setq multishell-history (delete entry multishell-history)))
281 (setq multishell-history (push (concat name path)
282 multishell-history))))
284 (defun multishell-replace-entry (entry revised)
285 "Replace every instance of ENTRY in `multishell-history' with REVISED.
287 Revised entry is situated where former one was.
289 Returns non-nil iff any changes were made."
290 (let ((candidates multishell-history)
292 (while (setq candidates (member entry candidates))
293 (setcar candidates revised
295 (setq candidates (cdr candidates)))
298 (defun multishell-history-entries (name)
299 "Return `multishell-history' entry that starts with NAME, or nil if none."
301 (dolist (entry multishell-history)
302 (when (and (string-equal name (multishell-name-from-entry entry))
303 (not (member entry got)))
304 (setq got (cons entry got))))
308 (defun multishell-pop-to-shell (&optional arg name here)
309 "Easily navigate to and within multiple shell buffers, local and remote.
311 Use a single `universal-argument' (\\[universal-argument]) to launch and choose between
312 nalternate shell buffers, and a doubled universal argument to also set your
313 choice as the ongoing default. Append a path to a new shell name to launch
314 a shell in that directory, and use Emacs tramp syntax to launch a remote
315 shell. There is a shortcut to manage your list of current and
316 historical shells, collectively, using `multishell-list' - see below.
318 Customize-group `multishell' to set up a key binding and tweak behaviors.
320 Manage your collection of current and historical shells by
321 recursively invoking \\[multishell-pop-to-shell] at the
322 `multishell-pop-to-shell' universal argument prompts, eg:
324 \\[universal-argument] \\[multishell-pop-to-shell] \\[multishell-pop-to-shell]
326 \(That will be just a few keys if you do the above
327 customization.) Hit ? in the listing buffer for editing commands.
329 ==== Basic operation:
331 - If the current buffer is shell-mode (or shell-mode derived)
332 buffer then focus is moved to the process input point.
334 \(You can use a universal argument go to a different shell
335 buffer when already in a buffer that has a process - see
338 - If not in a shell buffer (or with universal argument), go to a
339 window that is already showing the (a) shell buffer, if any.
341 In this case, the cursor is left in its prior position in the
342 shell buffer. Repeating the command will then go to the
343 process input point, per the first item in this list.
345 We respect `pop-up-windows', so you can adjust it to set the
346 other-buffer/same-buffer behavior.
348 - Otherwise, start a new shell buffer, using the current
349 directory as the working directory.
351 If a buffer with the resulting name exists and its shell process
352 was disconnected or otherwise stopped, it's resumed.
354 ===== Universal arg to start and select between named shell buffers:
356 You can name alternate shell buffers to create or return to, by
357 prefixing your \\[multishell-pop-to-shell] invocation with single or double
358 `universal-argument', \\[universal-argument]:
360 - With a single universal argument, prompt for the buffer name
361 to use (without the asterisks that shell mode will put around
362 the name), defaulting to 'shell'.
364 Completion is available.
366 This combination makes it easy to start and switch across
367 multiple shell restarts.
369 - A double universal argument will prompt for the name *and* set
370 the default to that name, so the target shell becomes the
373 See `multishell-primary-name' for info about preserving the
374 setting across emacs restarts.
376 - Manage your collection of current and historical shells by
377 recursively invoking \\[multishell-pop-to-shell] at either of the
378 `multishell-pop-to-shell' universal argument prompts, or at any
379 time via \\[multishell-list]. Hit ? in the listing buffer for
382 ===== Select starting directory and remote host:
384 The shell buffer name you give to the prompt for a universal arg
385 can include an appended path. That will be used for the startup
386 directory. You can use tramp remote syntax to specify a remote
387 shell. If there is an element after a final '/', that's used for
388 the buffer name. Otherwise, the host, domain, or path is used.
392 * '#root/sudo:root@localhost:/etc' for a buffer named \"*#root*\" with a
393 root shell starting in /etc.
395 * '/ssh:example.net:' for a shell buffer in your homedir on example.net.
396 The buffer will be named \"*example.net*\".
398 * '#ex/ssh:example.net|sudo:root@example.net:/var/log' for a root shell
399 starting in /var/log on example.net named \"*#ex*\".
401 * 'interior/ssh:gateway.corp.com|ssh:interior.corp.com:' to go
402 via gateway.corp.com to your homedir on interior.corp.com. The
403 buffer will be named \"*interior*\". You could append a sudo
404 hop to the path, combining the previous example, and so on.
406 File visits from the shell, and many common emacs activities like
407 dired, will be on the host where the shell is running, in the
408 auspices of the target account, and relative to the current
411 You can change the startup path for a shell buffer by editing it
412 at the completion prompt. The new path will not take effect for
413 an already-running shell.
415 To remove a shell buffer's history entry, kill the buffer and
416 affirm removal of the entry when prompted.
418 ===== Activate savehist to retain shell buffer names and paths across Emacs restarts:
420 To have emacs maintain your history of shell buffer names and paths,
421 customize the savehist group to activate savehist."
425 (let ((token '(token)))
426 (if (window-minibuffer-p)
427 (throw 'multishell-do-list token)
429 (catch 'multishell-do-list
430 (multishell-pop-to-shell-worker arg name here)))
431 (multishell-list)))))
433 (defun multishell-pop-to-shell-worker (&optional arg name here)
434 "Do real work of `multishell-pop-to-shell', which see."
435 (let* ((from-buffer (current-buffer))
436 (from-buffer-is-shell (derived-mode-p 'shell-mode))
437 (primary-name-unbracketed (multishell-unbracket
438 multishell-primary-name))
439 (fallthrough-name (if from-buffer-is-shell
440 (buffer-name from-buffer)
441 primary-name-unbracketed))
442 (doublearg (equal arg '(16)))
443 (target-name-and-path
444 (multishell-resolve-target-name-and-path
447 (or (multishell-read-unbracketed-entry
448 (format "Shell buffer name [%s]%s "
449 primary-name-unbracketed
450 (if doublearg " <==" ":"))
451 primary-name-unbracketed)
452 primary-name-unbracketed))
453 (t fallthrough-name))))
454 (use-path (cadr target-name-and-path))
455 (target-shell-buffer-name (car target-name-and-path))
456 (target-buffer (get-buffer target-shell-buffer-name))
457 (curr-buff-proc (get-buffer-process from-buffer))
461 ;; Register early so the entry is pushed to the front:
462 (multishell-register-name-to-path (multishell-unbracket
463 target-shell-buffer-name)
467 (setq multishell-primary-name target-shell-buffer-name))
473 ((and (or curr-buff-proc from-buffer-is-shell)
475 (eq from-buffer target-buffer)
476 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
477 ;; In a shell buffer, but not named - stay in buffer, but go to end.
478 (setq already-there t))
480 ((string= (buffer-name) target-shell-buffer-name)
481 ;; Already in the specified shell buffer:
482 (setq already-there t))
484 ((or (not target-buffer)
486 (multishell-get-visible-window-for-buffer target-buffer))))
487 ;; No preexisting shell buffer, or not in a visible window:
488 (when (not (get-buffer target-shell-buffer-name))
489 (message "Creating new shell buffer '%s'" target-shell-buffer-name))
491 (switch-to-buffer target-shell-buffer-name)
492 (pop-to-buffer target-shell-buffer-name pop-up-windows)))
494 ;; Buffer exists and already has a window - jump to it:
495 (t (if (and multishell-pop-to-frame
497 (not (equal (window-frame (selected-window))
498 (window-frame inwin))))
499 (select-frame-set-input-focus (window-frame inwin)))
500 (if (not (string= (buffer-name (current-buffer))
501 target-shell-buffer-name))
503 (switch-to-buffer target-shell-buffer-name)
504 (pop-to-buffer target-shell-buffer-name t)))))
506 ;; We're in the buffer. Activate:
508 (if (not (comint-check-proc (current-buffer)))
509 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
512 ;; If the destination buffer has a stopped process, resume it:
513 (let ((process (get-buffer-process (current-buffer))))
514 (if (and process (equal 'stop (process-status process)))
515 (continue-process process)))
517 (when (or already-there
518 (equal (current-buffer) from-buffer))
519 (goto-char (point-max))
520 (and (get-buffer-process from-buffer)
521 (goto-char (process-mark (get-buffer-process from-buffer)))))))
523 (defun multishell-delete-history-name (name &optional ask)
524 "Remove all multishell history entries for NAME.
526 if optional ask is non-nil (default nil), ask before each deletion.
528 Return the last entry deleted."
530 (dolist (entry (multishell-history-entries name) got)
533 (y-or-n-p (format "Remove multishell history entry `%s'? "
536 multishell-history (delete entry multishell-history))))))
538 (defun multishell-kill-buffer-query-function ()
539 "Offer to remove multishell-history entry for buffer."
540 ;; Removal choice is crucial, so users can, eg, kill a shell with huge
541 ;; output backlog, while keeping the history entry to easily restart it.
543 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
545 ;; 1. It enables the user to remove the history without actually killing a
546 ;; running buffer, by not confirming the subsequent running-proc query.
547 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
548 ;; It's probably due to failures in other hooks - beyond our control -
549 ;; and anyway, I like the first reason well enough.
551 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
552 ;; activity. kill-buffer happens behind the scenes a whole lot.)
554 (and (derived-mode-p 'shell-mode)
555 (multishell-delete-history-name
556 (multishell-unbracket (buffer-name))
559 (message "multishell-kill-buffer-query-function error: %s" err)))
561 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
563 (defun multishell-get-visible-window-for-buffer (buffer)
564 "Return visible window containing buffer."
567 (function (lambda (win)
568 (if (and (eq (window-buffer win) buffer)
569 (equal (frame-parameter
570 (selected-frame) 'display)
572 (window-frame win) 'display)))
573 (throw 'got-a-vis win))))
577 (defun multishell-all-entries (&optional active-duplicated)
578 "Return multishell history, with active buffers listed first.
580 Optional ACTIVE-DUPLICATED will return a copy of
581 `multishell-history' with unbracketed names of active buffers,
582 sans paths, appended to the list, so they have short and long
584 ;; Reorder so active lead present lead historical entries:
585 (let (active-entries active-names present past splat name path buffer)
586 (dolist (entry multishell-history)
587 (setq splat (multishell-split-entry entry)
590 buffer (and name (get-buffer (multishell-bracket name))))
591 (if (buffer-live-p buffer)
592 (if (comint-check-proc buffer)
593 (setq active-entries (push entry active-entries)
594 active-names (push name active-names))
595 (setq present (push entry present)))
596 (setq past (push entry past))))
597 ;; Reverse present and past lists
598 (setq multishell-history (append (reverse active-entries)
601 (if active-duplicated
602 (append multishell-history active-names)
603 multishell-history)))
605 (defun multishell-read-unbracketed-entry (prompt default
606 &optional initial no-record)
607 "PROMPT for shell buffer name, sans asterisks. Indicate DEFAULT in prompt.
609 Optional INITIAL is preliminary value to be edited.
611 Optional NO-RECORD prevents changes to `multishell-history'
614 Input and completion can include associated path, if any.
616 Return what's provided, if anything, else nil."
617 (let* ((was-multishell-history multishell-history)
618 (candidates (multishell-all-entries 'active-duplicated))
619 (got (completing-read prompt
629 'multishell-history)))
631 (setq multishell-history was-multishell-history))
632 (if (not (string= got ""))
636 (defun multishell-resolve-target-name-and-path (path-ish)
637 "Given name/tramp-path PATH-ISH, resolve buffer name and initial directory.
639 The name is the part of the string up to the first '/' slash, if
640 any. Missing pieces are filled in from remote path elements, if
641 any, and multishell history. Given a path and no name, either the
642 host-name, domain-name, final directory name, or local host name
645 Return them as a list (name path), with name asterisk-bracketed
646 and path nil if none resolved."
647 (let* ((splat (multishell-split-entry (or path-ish "")))
649 (name (or (car splat) (multishell-name-from-entry path))))
651 ;; Get path from history, if present.
652 (mapcar #'(lambda (entry)
653 (when (or (not path) (string= path ""))
654 (setq path (cadr (multishell-split-entry entry)))))
655 (multishell-history-entries
656 (multishell-unbracket name))))
657 (list (multishell-bracket name) path)))
659 (defun multishell-name-from-entry (entry)
660 "Derive a name for a shell buffer according to ENTRY."
662 (multishell-unbracket multishell-primary-name)
663 (let* ((splat (multishell-split-entry entry))
667 (if (file-remote-p path)
668 (let ((vec (tramp-dissect-file-name path)))
669 (or (tramp-file-name-host vec)
670 (tramp-file-name-domain vec)
671 (tramp-file-name-localname vec)
673 (multishell-unbracket multishell-primary-name))))))
675 (defun multishell-start-shell-in-buffer (buffer-name path)
676 "Start, restart, or continue a shell in BUFFER-NAME on PATH."
677 (let* ((buffer (get-buffer buffer-name))
681 (setq is-active (comint-check-proc buffer))
683 (when (and path (not is-active))
685 (when (and (derived-mode-p 'shell-mode) (file-remote-p path))
686 ;; Returning to disconnected remote shell - do some tidying:
687 (tramp-cleanup-connection
688 (tramp-dissect-file-name default-directory 'noexpand)
689 'keep-debug 'keep-password))
691 (when (file-remote-p path) (message "Connecting to %s" path))
696 (defun multishell-track-dirchange (name newpath)
697 "Change multishell history entry to track current directory."
698 (let* ((entries (multishell-history-entries name)))
699 (dolist (entry entries)
700 (let* ((name-path (multishell-split-entry entry))
701 (name (car name-path))
702 (path (or (cadr name-path) "")))
704 (let* ((is-remote (file-remote-p path))
705 (vec (and is-remote (tramp-dissect-file-name path nil)))
706 (localname (if is-remote
707 (tramp-file-name-localname vec)
710 (replace-regexp-in-string (if (string= localname "")
712 (regexp-quote localname))
722 (newpath (if is-remote
723 (tramp-make-tramp-file-name (aref vec 0)
729 (newentry (concat name newpath))
730 (membership (member entry multishell-history)))
732 (setcar membership newentry))))))))
733 (defvar multishell-was-default-directory ()
734 "Provide for tracking directory changes.")
735 (make-variable-buffer-local 'multishell-was-default-directory)
736 (defun multishell-post-command-business ()
737 "Do multishell bookkeeping."
738 ;; Update multishell-history with dir changes.
740 (when (and multishell-history-entry-tracks-current-directory
741 (derived-mode-p 'shell-mode))
742 (let ((curdir (if (file-remote-p default-directory)
743 (tramp-file-name-localname
744 (tramp-dissect-file-name default-directory))
746 (when (not (string= curdir (or multishell-was-default-directory "")))
747 (multishell-track-dirchange (multishell-unbracket (buffer-name))
749 (setq multishell-was-default-directory curdir)))
750 ;; To avoid disruption as a pervasive hook function, swallow all errors:
752 (message "multishell-post-command-business error: %s" err))))
753 (add-hook 'post-command-hook 'multishell-post-command-business)
755 (defun multishell-split-entry (entry)
756 "Given multishell name/path ENTRY, return the separated name and path pair.
758 Returns nil for empty parts, rather than the empty string."
760 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
761 (let ((name (match-string 1 entry))
762 (path (match-string 2 entry)))
763 (and (string= name "") (setq name nil))
764 (and (string= path "") (setq path nil))
766 (defun multishell-bracket (name)
767 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
768 (if (not (string= (substring name 0 1) "*"))
769 (setq name (concat "*" name)))
770 (if (not (string= (substring name -1) "*"))
771 (setq name (concat name "*")))
773 (defun multishell-unbracket (name)
774 "Return a copy of name, removing asterisks, if any, at beginning and end."
775 (if (string= (substring name 0 1) "*")
776 (setq name (substring name 1)))
777 (if (string= (substring name -1) "*")
778 (setq name (substring name 0 -1)))
781 (provide 'multishell)
783 ;;; multishell.el ends here