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-11 1.1.4 Ken Manheimer:
63 ;; - hookup multishell-list as completion help buffer.
64 ;; Mouse and keyboard selections from help listing properly exits
66 ;; * 2016-02-09 1.1.3 Ken Manheimer:
68 ;; - add some handy operations, like cloning new entry from existing
69 ;; - add optional behaviors to existing operations for returning to
70 ;; stopped shells without restarting them.
71 ;; - solidify maintaining focus on current entry
72 ;; - fix miscellaneous.
73 ;; * 2016-01-31 1.1.2 Ken Manheimer:
74 ;; - Settle puzzling instability of multishell-all-entries
75 ;; - The accumulations was putting items going from more to less active
76 ;; categories to be put at the end, not beginning.
77 ;; - Also, using history for prompting changes history - implement
78 ;; no-record option to avoid this when needed.
79 ;; - Implement simple edit-in-place multishell-replace-entry and use in
80 ;; multishell-list-edit-entry.
81 ;; - Remove now unnecessary multishell-list-revert-buffer-kludge.
82 ;; - Rectify byte compiler offenses, and other fixes - thanks to Stefan
83 ;; Monnier for pointing out many of the corrections.
84 ;; - Avoid directly calling tramp functions unnecessarily.
85 ;; * 2016-01-30 1.1.1 Ken Manheimer:
86 ;; - shake out initial multishell-list glitches:
87 ;; - (Offer to) delete shell buffer, if present, when deleting entry.
88 ;; - Set recency (numeric rank) as initial sort field
89 ;; - Recompute list on most operations that affect the order, and try to
90 ;; preserve stability. (Kludgy solution, needs work.)
91 ;; - Set version to 1.1.1 - multishell-list addition should have been 1.1.0.
92 ;; * 2016-01-30 1.0.9 Ken Manheimer:
93 ;; - Add multishell-list for managing the collection of current and
94 ;; history-registered shells: edit, delete, and switch/pop to entries.
95 ;; Easy access by invoking `multishell-pop-to-shell' from in the
96 ;; `multishell-pop-to-shell' universal arg prompts.
97 ;; - Duplicate existing shell buffer names in completions, for distinction.
98 ;; - Add paths to buffers started without one, when multishell history dir
99 ;; tracking is enabled.
100 ;; - Major code cleanup:
101 ;; - Simplify multishell-start-shell-in-buffer, in particular using
102 ;; shell function, rather than unnecessarily going underneath it.
103 ;; - Establish multishell-name-from-entry as canonical name resolver.
104 ;; - Fallback to eval-after-load in emacs versions that lack
105 ;; with-eval-after-load (eg, emacs 23).
106 ;; - save-match-data, where match-string is used
107 ;; - resituate some helpers
108 ;; * 2016-01-24 1.0.8 Ken Manheimer:
109 ;; - Work around the shell/tramp mishandling of remote+sudo+homedir problem!
110 ;; The work around is clean and simple, basically using high-level `cd'
111 ;; API and not messing with the low-level default-directory setting.
112 ;; (Turns out the problem was not in my local config. Good riddance to the
113 ;; awkward failure handler!)
114 ;; - Clean up code resolving the destination shell, starting to document the
115 ;; decision tree in the process. See getting-to-a-shell.md in the
116 ;; multishell repository, https://github.com/kenmanheimer/EmacsMultishell
117 ;; - There may be some shake-out on resolving the destination shell, but
118 ;; this release gets the fundamental functionality soundly in place.
119 ;; * 2016-01-23 1.0.7 Ken Manheimer:
120 ;; - Remove notes about tramp remote+sudo+homedir problem. Apparently it's
121 ;; due to something in my local site configuration (happens with -q but
123 ;; * 2016-01-22 1.0.6 Ken Manheimer:
124 ;; - Add multishell-version function.
125 ;; - Tweak commentary/comments/docstrings.
126 ;; - Null old multishell-buffer-name-history var, if present.
127 ;; * 2016-01-16 1.0.5 Ken Manheimer:
128 ;; - History now includes paths, when designated.
129 ;; - Actively track current directory in history entries that have a path.
130 ;; Custom control: multishell-history-entry-tracks-current-directory
131 ;; - Offer to remove shell's history entry when buffer is killed.
132 ;; (Currently the only UI mechanism to remove history entries.)
133 ;; - Fix - prevent duplicate entries for same name but different paths
134 ;; - Fix - recognize and respect tramp path syntax to start in home dir
135 ;; - Simplify history var name, migrate existing history if any from old name
136 ;; * 2016-01-04 1.0.4 Ken Manheimer - Released to ELPA
137 ;; * 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
139 ;; TODO and Known Issues:
141 ;; * Add custom shell launch prep actions
142 ;; - for, eg, port knocking, interface activations
143 ;; - shell commands to execute when shell name or path matches a regexp
144 ;; - list of (regexp, which - name, path, or both, command)
145 ;; * Investigate whether we can recognize and provide for failed hops.
146 ;; - Tramp doesn't provide useful reactions for any hop but the first
147 ;; - Might be stuff we can do to detect and convey failures?
148 ;; - Might be no recourse but to seek tramp changes.
149 ;; * Try minibuffer field boundary at beginning of tramp path, to see whether
150 ;; the field boundary magically enables tramp path completion.
157 (require 'multishell-list)
159 (defvar multishell-version "1.1.3")
160 (defun multishell-version (&optional here)
161 "Return string describing the loaded multishell version."
163 (let ((msg (concat "Multishell " multishell-version)))
164 (if here (insert msg)
165 (if (called-interactively-p 'interactive)
169 (defgroup multishell nil
170 "Allout extension that highlights outline structure graphically.
172 Customize `allout-widgets-auto-activation' to activate allout-widgets
176 (defcustom multishell-command-key "\M- "
177 "The key to use if `multishell-activate-command-key' is true.
179 You can instead manually bind `multishell-pop-to-shell` using emacs
180 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
183 (defvar multishell--responsible-for-command-key nil
184 "Coordination for multishell key assignment.")
185 (defun multishell-activate-command-key-setter (symbol setting)
186 "Implement `multishell-activate-command-key' choice."
187 (set-default symbol setting)
188 (when (or setting multishell--responsible-for-command-key)
189 (multishell-implement-command-key-choice (not setting))))
190 (defun multishell-implement-command-key-choice (&optional unbind)
191 "If settings dicate, implement binding of multishell command key.
193 If optional UNBIND is true, globally unbind the key.
195 * `multishell-activate-command-key' - Set this to get the binding or not.
196 * `multishell-command-key' - The key to use for the binding, if appropriate."
198 (when (and (boundp 'multishell-command-key) multishell-command-key)
199 (global-unset-key multishell-command-key)))
200 ((not (and (boundp 'multishell-activate-command-key)
201 (boundp 'multishell-command-key)))
203 ((and multishell-activate-command-key multishell-command-key)
204 (setq multishell--responsible-for-command-key t)
205 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
207 (defcustom multishell-activate-command-key nil
208 "Set this to impose the `multishell-command-key' binding.
210 You can instead manually bind `multishell-pop-to-shell` using emacs
211 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
213 :set 'multishell-activate-command-key-setter)
215 ;; Implement the key customization whenever the package is loaded:
216 (if (fboundp 'with-eval-after-load)
217 (with-eval-after-load "multishell"
218 (multishell-implement-command-key-choice))
219 (eval-after-load "multishell"
220 '(multishell-implement-command-key-choice)))
222 (defcustom multishell-pop-to-frame nil
223 "*If non-nil, jump to a frame already showing the shell, if another one is.
225 Otherwise, disregard already-open windows on the shell if they're
226 in another frame, and open a new window on the shell in the
229 \(Use `pop-up-windows' to change multishell other-window vs
230 current-window behavior.)"
233 (defcustom multishell-history-entry-tracks-current-directory t
234 "Maintain shell's current directory in its multishell history entry.
236 When set, the history entry for shells started with explicit
237 paths will track the shell's current working directory.
239 If `savehist-save-minibuffer-history' is enabled, the current
240 working directory of shells will be conveyed between emacs
244 (defvar multishell-history nil
245 "Name/path entries, most recent first.")
246 ;; Migrate the few pre 1.0.5 users to changed history var:
247 (when (and (not multishell-history)
248 (boundp 'multishell-buffer-name-history)
249 multishell-buffer-name-history)
250 (setq multishell-history multishell-buffer-name-history
251 multishell-buffer-name-history nil))
253 (defvar multishell-primary-name "*shell*"
254 "Default shell name for un-modified multishell-pop-to-shell buffer target.
256 This is set by `multishell-pop-to-shell' as the current default,
257 when invoked with doubled universal argument.
259 If you want the designated primary that you have at the end of
260 one emacs session to be resumed at the next, customize
261 `savehist-additional-variables' to include the
262 `multishell-primary-name'.")
264 (defvar multishell-completing-read nil
265 "Internal use, conveying whether or not we're in the midst of a multishell
268 ;; Multiple entries happen because completion also adds name to history.
269 (defun multishell-register-name-to-path (name path)
270 "Add or replace entry associating NAME with PATH in `multishell-history'.
272 If NAME already had a PATH and new PATH is empty, retain the prior one.
274 Promote added/changed entry to the front of the list."
275 ;; Add or promote to the front, tracking path changes in the process.
276 (let* ((entries (multishell-history-entries name))
278 (dolist (entry entries)
279 (when (string= path "")
280 ;; Retain explicit established path.
281 (setq path (cadr (multishell-split-entry entry))))
282 (setq multishell-history (delete entry multishell-history)))
283 (setq multishell-history (push (concat name path)
284 multishell-history))))
286 (defun multishell-replace-entry (entry revised)
287 "Replace every instance of ENTRY in `multishell-history' with REVISED.
289 Revised entry is situated where former one was.
291 Returns non-nil iff any changes were made."
292 (let ((candidates multishell-history)
294 (while (setq candidates (member entry candidates))
295 (setcar candidates revised)
296 (setq candidates (cdr candidates)
300 (defun multishell-history-entries (name)
301 "Return `multishell-history' entry that starts with NAME, or nil if none."
303 (dolist (entry multishell-history)
304 (when (and (string-equal name (multishell-name-from-entry entry))
305 (not (member entry got)))
310 (defun multishell-pop-to-shell (&optional arg name here)
311 "Easily navigate to and within multiple shell buffers, local and remote.
313 Use a single `universal-argument' (\\[universal-argument]) to launch and choose between
314 nalternate shell buffers, and a doubled universal argument to also set your
315 choice as the ongoing default. Append a path to a new shell name to launch
316 a shell in that directory, and use Emacs tramp syntax to launch a remote
317 shell. There is a shortcut to manage your list of current and
318 historical shells, collectively, using `multishell-list' - see below.
320 Customize-group `multishell' to set up a key binding and tweak behaviors.
322 Manage your collection of current and historical shells by
323 recursively invoking \\[multishell-pop-to-shell] at the
324 `multishell-pop-to-shell' universal argument prompts, eg:
326 \\[universal-argument] \\[multishell-pop-to-shell] \\[multishell-pop-to-shell]
328 \(That will be just a few keys if you do the above
329 customization.) Hit ? in the listing buffer for editing commands.
331 ==== Basic operation:
333 - If the current buffer is shell-mode (or shell-mode derived)
334 buffer then focus is moved to the process input point.
336 \(You can use a universal argument go to a different shell
337 buffer when already in a buffer that has a process - see
340 - If not in a shell buffer (or with universal argument), go to a
341 window that is already showing the (a) shell buffer, if any.
343 In this case, the cursor is left in its prior position in the
344 shell buffer. Repeating the command will then go to the
345 process input point, per the first item in this list.
347 We respect `pop-up-windows', so you can adjust it to set the
348 other-buffer/same-buffer behavior.
350 - Otherwise, start a new shell buffer, using the current
351 directory as the working directory.
353 If a buffer with the resulting name exists and its shell process
354 was disconnected or otherwise stopped, it's resumed.
356 ===== Universal arg to start and select between named shell buffers:
358 You can name alternate shell buffers to create or return to, by
359 prefixing your \\[multishell-pop-to-shell] invocation with single or double
360 `universal-argument', \\[universal-argument]:
362 - With a single universal argument, prompt for the buffer name
363 to use (without the asterisks that shell mode will put around
364 the name), defaulting to 'shell'.
366 Completion is available.
368 This combination makes it easy to start and switch across
369 multiple shell restarts.
371 - A double universal argument will prompt for the name *and* set
372 the default to that name, so the target shell becomes the
375 See `multishell-primary-name' for info about preserving the
376 setting across emacs restarts.
378 - Manage your collection of current and historical shells by
379 recursively invoking \\[multishell-pop-to-shell] at either of the
380 `multishell-pop-to-shell' universal argument prompts, or at any
381 time via \\[multishell-list]. Hit ? in the listing buffer for
384 ===== Select starting directory and remote host:
386 The shell buffer name you give to the prompt for a universal arg
387 can include an appended path. That will be used for the startup
388 directory. You can use tramp remote syntax to specify a remote
389 shell. If there is an element after a final '/', that's used for
390 the buffer name. Otherwise, the host, domain, or path is used.
394 * '#root/sudo:root@localhost:/etc' for a buffer named \"*#root*\" with a
395 root shell starting in /etc.
397 * '/ssh:example.net:' for a shell buffer in your homedir on example.net.
398 The buffer will be named \"*example.net*\".
400 * '#ex/ssh:example.net|sudo:root@example.net:/var/log' for a root shell
401 starting in /var/log on example.net named \"*#ex*\".
403 * 'interior/ssh:gateway.corp.com|ssh:interior.corp.com:' to go
404 via gateway.corp.com to your homedir on interior.corp.com. The
405 buffer will be named \"*interior*\". You could append a sudo
406 hop to the path, combining the previous example, and so on.
408 File visits from the shell, and many common emacs activities like
409 dired, will be on the host where the shell is running, in the
410 auspices of the target account, and relative to the current
413 You can change the startup path for a shell buffer by editing it
414 at the completion prompt. The new path will not take effect for
415 an already-running shell.
417 To remove a shell buffer's history entry, kill the buffer and
418 affirm removal of the entry when prompted.
420 ===== Activate savehist to retain shell buffer names and paths across Emacs restarts:
422 To have emacs maintain your history of shell buffer names and paths,
423 customize the savehist group to activate savehist."
427 (let ((token '(token)))
428 (if (window-minibuffer-p)
429 (throw 'multishell-minibuffer-exit token)
430 (let ((got (catch 'multishell-minibuffer-exit
431 (multishell-pop-to-shell-worker arg name here))))
432 ;; Handle catch or plain fall-through - see cond comments for protocol.
434 ;; Caught token from recursive invocation in minibuffer:
435 ((equal token got) (multishell-list))
436 ;; Caught specifaction of multishell args, eg from multishell-list:
437 ((listp got) (multishell-pop-to-shell-worker (nth 2 got)
440 ;; Regular fallthrough - just relay the result:
443 (defun multishell-pop-to-shell-worker (&optional arg name here)
444 "Do real work of `multishell-pop-to-shell', which see."
445 (let* ((from-buffer (current-buffer))
446 (from-buffer-is-shell (derived-mode-p 'shell-mode))
447 (primary-name-unbracketed (multishell-unbracket
448 multishell-primary-name))
449 (fallthrough-name (if from-buffer-is-shell
450 (buffer-name from-buffer)
451 primary-name-unbracketed))
452 (doublearg (equal arg '(16)))
453 (target-name-and-path
454 (multishell-resolve-target-name-and-path
457 (or (multishell-read-unbracketed-entry
458 (format "Shell buffer name [%s]%s "
459 primary-name-unbracketed
460 (if doublearg " <==" ":")))
461 primary-name-unbracketed))
462 (t fallthrough-name))))
463 (use-path (cadr target-name-and-path))
464 (target-shell-buffer-name (car target-name-and-path))
465 (target-buffer (get-buffer target-shell-buffer-name))
466 (curr-buff-proc (get-buffer-process from-buffer))
470 ;; Register early so the entry is pushed to the front:
471 (multishell-register-name-to-path (multishell-unbracket
472 target-shell-buffer-name)
476 (setq multishell-primary-name target-shell-buffer-name))
482 ((and (or curr-buff-proc from-buffer-is-shell)
484 (eq from-buffer target-buffer)
485 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
486 ;; In a shell buffer, but not named - stay in buffer, but go to end.
487 (setq already-there t))
489 ((string= (buffer-name) target-shell-buffer-name)
490 ;; Already in the specified shell buffer:
491 (setq already-there t))
493 ((or (not target-buffer)
495 (multishell-get-visible-window-for-buffer target-buffer))))
496 ;; No preexisting shell buffer, or not in a visible window:
497 (when (not (get-buffer target-shell-buffer-name))
498 (message "Creating new shell buffer '%s'" target-shell-buffer-name))
500 (switch-to-buffer target-shell-buffer-name)
501 (pop-to-buffer target-shell-buffer-name pop-up-windows)))
503 ;; Buffer exists and already has a window - jump to it:
504 (t (if (and multishell-pop-to-frame
506 (not (equal (window-frame (selected-window))
507 (window-frame inwin))))
508 (select-frame-set-input-focus (window-frame inwin)))
509 (if (not (string= (buffer-name (current-buffer))
510 target-shell-buffer-name))
512 (switch-to-buffer target-shell-buffer-name)
513 (pop-to-buffer target-shell-buffer-name t)))))
515 ;; We're in the buffer. Activate:
517 (if (not (comint-check-proc (current-buffer)))
518 (multishell-start-shell-in-buffer use-path))
520 ;; If the destination buffer has a stopped process, resume it:
521 (let ((process (get-buffer-process (current-buffer))))
522 (if (and process (equal 'stop (process-status process)))
523 (continue-process process)))
525 (when (or already-there
526 (equal (current-buffer) from-buffer))
527 (goto-char (point-max))
528 (and (get-buffer-process from-buffer)
529 (goto-char (process-mark (get-buffer-process from-buffer)))))))
531 (defun multishell-delete-history-name (name &optional ask)
532 "Remove all multishell history entries for NAME.
534 if optional ask is non-nil (default nil), ask before each deletion.
536 Return the last entry deleted."
538 (dolist (entry (multishell-history-entries name) got)
541 (y-or-n-p (format "Remove multishell history entry `%s'? "
544 multishell-history (delete entry multishell-history))))))
546 (defun multishell-kill-buffer-query-function ()
547 "Offer to remove multishell-history entry for buffer."
548 ;; Removal choice is crucial, so users can, eg, kill a shell with huge
549 ;; output backlog, while keeping the history entry to easily restart it.
551 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
553 ;; 1. It enables the user to remove the history without actually killing a
554 ;; running buffer, by not confirming the subsequent running-proc query.
555 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
556 ;; It's probably due to failures in other hooks - beyond our control -
557 ;; and anyway, I like the first reason well enough.
559 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
560 ;; activity. kill-buffer happens behind the scenes a whole lot.)
562 (and (derived-mode-p 'shell-mode)
563 (multishell-delete-history-name
564 (multishell-unbracket (buffer-name))
567 (message "multishell-kill-buffer-query-function error: %s" err)))
569 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
571 (defun multishell-get-visible-window-for-buffer (buffer)
572 "Return visible window containing buffer."
575 (function (lambda (win)
576 (if (and (eq (window-buffer win) buffer)
577 (equal (frame-parameter
578 (selected-frame) 'display)
580 (window-frame win) 'display)))
581 (throw 'got-a-vis win))))
585 (defun multishell-all-entries (&optional active-duplicated)
586 "Return multishell history, with active buffers listed first.
588 Optional ACTIVE-DUPLICATED will return a copy of
589 `multishell-history' with unbracketed names of active buffers,
590 sans paths, appended to the list, so they have short and long
592 ;; Reorder so active lead present lead historical entries:
593 (let (active-entries active-names present past splat name buffer)
594 (dolist (entry multishell-history)
595 (setq splat (multishell-split-entry entry)
597 buffer (and name (get-buffer (multishell-bracket name))))
598 (if (buffer-live-p buffer)
599 (if (comint-check-proc buffer)
600 (setq active-entries (push entry active-entries)
601 active-names (push name active-names))
602 (setq present (push entry present)))
603 (setq past (push entry past))))
604 ;; Reverse present and past lists
605 (setq multishell-history (append (reverse active-entries)
608 (if active-duplicated
609 (append multishell-history active-names)
610 multishell-history)))
612 (defun multishell-read-unbracketed-entry (prompt &optional initial no-record)
613 "PROMPT for shell buffer name, sans asterisks.
615 Optional INITIAL is preliminary value to be edited.
617 Optional NO-RECORD prevents changes to `multishell-history'
620 Input and completion can include associated path, if any.
622 Return what's provided, if anything, else nil."
623 (let* ((was-multishell-history multishell-history)
624 (candidates (multishell-all-entries 'active-duplicated))
625 (multishell-completing-read t)
627 ;; Use `cl-letf' to dynamically bind multishell-list to
628 ;; display-completion-list, so multishell-list is used when doing
629 ;; minibuffer-completion-help.
630 (cl-letf (((symbol-function 'display-completion-list)
632 (completing-read prompt
642 'multishell-history))))
644 (setq multishell-history was-multishell-history))
645 (if (not (string= got ""))
649 (defun multishell-resolve-target-name-and-path (shell-spec)
650 "Given name/tramp-style address shell spec, resolve buffer name and directory.
652 The name is the part of the string up to the first '/' slash, if
653 any. Missing pieces are filled in from remote path elements, if
654 any, and multishell history. Given a tramp-style remote address
655 and no name part, either the user@host is used for the buffer
656 name, if a user is specified, or just the host.
658 Return them as a list: (name path), with name asterisk-bracketed
659 and path nil if none is resolved."
660 (let* ((splat (multishell-split-entry (or shell-spec "")))
662 (name (or (car splat) (multishell-name-from-entry path))))
664 ;; Get path from history, if present.
666 (multishell-history-entries
667 (multishell-unbracket name)))
668 (when (or (not path) (string= path ""))
669 (setq path (cadr (multishell-split-entry entry))))))
670 (list (multishell-bracket name) path)))
672 (defun multishell-name-from-entry (entry)
673 "Derive a name for a shell buffer according to ENTRY."
675 (multishell-unbracket multishell-primary-name)
676 (let* ((splat (multishell-split-entry entry))
680 (if (file-remote-p path)
681 (let ((host (file-remote-p path 'host))
682 (user (file-remote-p path 'user)))
683 (cond ((and host user)
684 (format "%s@%s" user host))
688 (multishell-unbracket multishell-primary-name))))))
690 (declare-function tramp-dissect-file-name "tramp")
691 (declare-function tramp-cleanup-connection "tramp")
693 (defun multishell-start-shell-in-buffer (path)
694 "Start, restart, or continue a shell in BUFFER-NAME on PATH."
695 (let* ((is-active (comint-check-proc (current-buffer))))
697 (when (and path (not is-active))
699 (when (and (derived-mode-p 'shell-mode) (file-remote-p path))
700 ;; Returning to disconnected remote shell - do some tidying.
701 ;; Without this cleanup, occasionally restarting a disconnected
702 ;; remote session, particularly one that includes sudo, results in
703 ;; an untraceable "Args out of range" error. That never happens if
704 ;; we precedeed connection attempts with this cleanup -
706 (tramp-cleanup-connection
707 (tramp-dissect-file-name default-directory 'noexpand)
708 'keep-debug 'keep-password))
710 (when (file-remote-p path) (message "Connecting to %s" path))
713 (shell (current-buffer))))
715 (defun multishell-homedir-shorthand-p (dirpath)
716 "t if dirpath is an unexpanded remote homedir spec."
717 ;; Workaround to recognize tramp-style homedir shorthand, "...:" and "...:~".
718 (let ((localname (file-remote-p dirpath 'localname)))
721 ;; No directory path and no connection to expand homedir:
722 (string= localname "")
723 ;; Original path doesn't equal expanded homedir:
725 (not (string-match (concat (regexp-quote localname) "/?$")
727 ;; (assert (multishell-homedir-shorthand-p "/ssh:myhost.net:")
728 ;; (assert (not (multishell-homedir-shorthand-p "/home/klm")))
729 ;; (assert (not (multishell-homedir-shorthand-p "/ssh:myhost.net:/home/me")))
731 (defun multishell-track-dirchange (name newpath)
732 "Change multishell history entry to track current directory."
733 (let* ((entries (multishell-history-entries name)))
734 (dolist (entry entries)
735 (let* ((name-path (multishell-split-entry entry))
736 (name (car name-path))
737 (path (or (cadr name-path) "")))
739 (let* ((old-localname (or (file-remote-p path 'localname)
742 (if (multishell-homedir-shorthand-p path)
743 (concat entry newpath)
744 (replace-regexp-in-string (concat (regexp-quote
756 (membership (member entry multishell-history)))
758 (setcar membership newentry))))))))
760 (defvar multishell-was-default-directory ()
761 "Provide for tracking directory changes.")
762 (make-variable-buffer-local 'multishell-was-default-directory)
763 (defun multishell-post-command-business ()
764 "Do multishell bookkeeping."
765 ;; Update multishell-history with dir changes.
767 (when (and multishell-history-entry-tracks-current-directory
768 (derived-mode-p 'shell-mode))
769 (let ((curdir (if (file-remote-p default-directory)
770 (file-remote-p default-directory 'localname)
772 (when (not (string= curdir (or multishell-was-default-directory "")))
773 (multishell-track-dirchange (multishell-unbracket (buffer-name))
775 (setq multishell-was-default-directory curdir)))
776 ;; To avoid disruption as a pervasive hook function, swallow all errors:
778 (message "multishell-post-command-business error: %s" err))))
779 (add-hook 'post-command-hook #'multishell-post-command-business)
781 (defun multishell-split-entry (entry)
782 "Given multishell name/path ENTRY, return the separated name and path pair.
784 Returns nil for empty parts, rather than the empty string."
786 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
787 (let ((name (match-string 1 entry))
788 (path (match-string 2 entry)))
789 (and (string= name "") (setq name nil))
790 (and (string= path "") (setq path nil))
792 (defun multishell-bracket (name)
793 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
794 (if (not (string= (substring name 0 1) "*"))
795 (setq name (concat "*" name)))
796 (if (not (string= (substring name -1) "*"))
797 (setq name (concat name "*")))
799 (defun multishell-unbracket (name)
800 "Return a copy of name, removing asterisks, if any, at beginning and end."
801 (if (string= (substring name 0 1) "*")
802 (setq name (substring name 1)))
803 (if (string= (substring name -1) "*")
804 (setq name (substring name 0 -1)))
807 (provide 'multishell)
809 ;;; multishell.el ends here