]> code.delx.au - gnu-emacs-elpa/blob - multishell.el
a0783ee5b07705879ca4ea923756125a1e9b5b22
[gnu-emacs-elpa] / multishell.el
1 ;;; multishell.el --- Easily use multiple shell buffers, local and remote.
2
3 ;; Copyright (C) 1999-2016 Free Software Foundation, Inc.
4
5 ;; Author: Ken Manheimer <ken.manheimer@gmail.com>
6 ;; Version: 1.1.4
7 ;; Created: 1999 -- first public availability
8 ;; Keywords: processes
9 ;; URL: https://github.com/kenmanheimer/EmacsMultishell
10 ;;
11 ;;; Commentary:
12 ;;
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:
16 ;;
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.
19 ;;
20 ;; * Use universal arguments to launch and choose among alternate shell buffers,
21 ;; ... and change which is the current default.
22 ;;
23 ;; * Easily restart disconnected shells, or shells from prior sessions
24 ;; ... the latter from Emacs builtin savehist minibuf history persistence
25 ;;
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 -
28 ;; for example:
29 ;;
30 ;; * `#root/sudo:root@localhost:/etc` for a buffer named "*#root*" with a
31 ;; root shell starting in /etc.
32 ;;
33 ;; * `/ssh:example.net:` for a shell buffer in your homedir on example.net.
34 ;; The buffer will be named "*example.net*".
35 ;;
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*".
38 ;;
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.
42 ;;
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.
46 ;;
47 ;; * Manage your list of shells, current and past, as a collection.
48 ;;
49 ;; See the `multishell-pop-to-shell` docstring for details.
50 ;;
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.
54 ;;
55 ;; Please use
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.
59 ;;
60 ;; Change Log:
61 ;;
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:
65 ;; multishell-list:
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
120 ;; not -Q).
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.
136 ;;
137 ;; TODO and Known Issues:
138 ;;
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
144 ;; doesn't change.
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.
159
160 ;;; Code:
161
162 (require 'comint)
163 (require 'shell)
164 (require 'savehist)
165 (require 'multishell-list)
166
167 (defvar multishell-version "1.1.3")
168 (defun multishell-version (&optional here)
169 "Return string describing the loaded multishell version."
170 (interactive "P")
171 (let ((msg (concat "Multishell " multishell-version)))
172 (if here (insert msg)
173 (if (called-interactively-p 'interactive)
174 (message "%s" msg)
175 msg))))
176
177 (defgroup multishell nil
178 "Allout extension that highlights outline structure graphically.
179
180 Customize `allout-widgets-auto-activation' to activate allout-widgets
181 with allout-mode."
182 :group 'shell)
183
184 (defcustom multishell-command-key "\M- "
185 "The key to use if `multishell-activate-command-key' is true.
186
187 You can instead manually bind `multishell-pop-to-shell` using emacs
188 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
189 :type 'key-sequence)
190
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.
200
201 If optional UNBIND is true, globally unbind the key.
202
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."
205 (cond (unbind
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)))
210 nil)
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))))
214
215 (defcustom multishell-activate-command-key nil
216 "Set this to impose the `multishell-command-key' binding.
217
218 You can instead manually bind `multishell-pop-to-shell` using emacs
219 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
220 :type 'boolean
221 :set 'multishell-activate-command-key-setter)
222
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)))
229
230 (defcustom multishell-pop-to-frame nil
231 "*If non-nil, jump to a frame already showing the shell, if another one is.
232
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
235 current frame.
236
237 \(Use `pop-up-windows' to change multishell other-window vs
238 current-window behavior.)"
239 :type 'boolean)
240
241 (defcustom multishell-history-entry-tracks-current-directory t
242 "Maintain shell's current directory in its multishell history entry.
243
244 When set, the history entry for shells started with explicit
245 paths will track the shell's current working directory.
246
247 If `savehist-save-minibuffer-history' is enabled, the current
248 working directory of shells will be conveyed between emacs
249 sessions."
250 :type 'boolean)
251
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))
260
261 (defvar multishell-primary-name "*shell*"
262 "Default shell name for un-modified multishell-pop-to-shell buffer target.
263
264 This is set by `multishell-pop-to-shell' as the current default,
265 when invoked with doubled universal argument.
266
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'.")
271
272 ;; Multiple entries happen because completion also adds name to history.
273 (defun multishell-register-name-to-path (name path)
274 "Add or replace entry associating NAME with PATH in `multishell-history'.
275
276 If NAME already had a PATH and new PATH is empty, retain the prior one.
277
278 Promote added/changed entry to the front of the list."
279 ;; Add or promote to the front, tracking path changes in the process.
280 (let* ((entries (multishell-history-entries name))
281 (path (or path "")))
282 (dolist (entry entries)
283 (when (string= path "")
284 ;; Retain explicit established path.
285 (setq path (cadr (multishell-split-entry entry))))
286 (setq multishell-history (delete entry multishell-history)))
287 (setq multishell-history (push (concat name path)
288 multishell-history))))
289
290 (defun multishell-replace-entry (entry revised)
291 "Replace every instance of ENTRY in `multishell-history' with REVISED.
292
293 Revised entry is situated where former one was.
294
295 Returns non-nil iff any changes were made."
296 (let ((candidates multishell-history)
297 did-revisions)
298 (while (setq candidates (member entry candidates))
299 (setcar candidates revised)
300 (setq candidates (cdr candidates)
301 did-revisions t))
302 did-revisions))
303
304 (defun multishell-history-entries (name)
305 "Return `multishell-history' entry that starts with NAME, or nil if none."
306 (let (got)
307 (dolist (entry multishell-history)
308 (when (and (string-equal name (multishell-name-from-entry entry))
309 (not (member entry got)))
310 (push entry got)))
311 got))
312
313 ;;;###autoload
314 (defun multishell-pop-to-shell (&optional arg name here)
315 "Easily navigate to and within multiple shell buffers, local and remote.
316
317 Use a single `universal-argument' (\\[universal-argument]) to launch and choose between
318 nalternate shell buffers, and a doubled universal argument to also set your
319 choice as the ongoing default. Append a path to a new shell name to launch
320 a shell in that directory, and use Emacs tramp syntax to launch a remote
321 shell. There is a shortcut to manage your list of current and
322 historical shells, collectively, using `multishell-list' - see below.
323
324 Customize-group `multishell' to set up a key binding and tweak behaviors.
325
326 Manage your collection of current and historical shells by
327 recursively invoking \\[multishell-pop-to-shell] at the
328 `multishell-pop-to-shell' universal argument prompts, eg:
329
330 \\[universal-argument] \\[multishell-pop-to-shell] \\[multishell-pop-to-shell]
331
332 \(That will be just a few keys if you do the above
333 customization.) Hit ? in the listing buffer for editing commands.
334
335 ==== Basic operation:
336
337 - If the current buffer is shell-mode (or shell-mode derived)
338 buffer then focus is moved to the process input point.
339
340 \(You can use a universal argument go to a different shell
341 buffer when already in a buffer that has a process - see
342 below.)
343
344 - If not in a shell buffer (or with universal argument), go to a
345 window that is already showing the (a) shell buffer, if any.
346
347 In this case, the cursor is left in its prior position in the
348 shell buffer. Repeating the command will then go to the
349 process input point, per the first item in this list.
350
351 We respect `pop-up-windows', so you can adjust it to set the
352 other-buffer/same-buffer behavior.
353
354 - Otherwise, start a new shell buffer, using the current
355 directory as the working directory.
356
357 If a buffer with the resulting name exists and its shell process
358 was disconnected or otherwise stopped, it's resumed.
359
360 ===== Universal arg to start and select between named shell buffers:
361
362 You can name alternate shell buffers to create or return to, by
363 prefixing your \\[multishell-pop-to-shell] invocation with single or double
364 `universal-argument', \\[universal-argument]:
365
366 - With a single universal argument, prompt for the buffer name
367 to use (without the asterisks that shell mode will put around
368 the name), defaulting to 'shell'.
369
370 Completion is available.
371
372 This combination makes it easy to start and switch across
373 multiple shell restarts.
374
375 - A double universal argument will prompt for the name *and* set
376 the default to that name, so the target shell becomes the
377 primary.
378
379 See `multishell-primary-name' for info about preserving the
380 setting across emacs restarts.
381
382 - Manage your collection of current and historical shells by
383 recursively invoking \\[multishell-pop-to-shell] at either of the
384 `multishell-pop-to-shell' universal argument prompts, or at any
385 time via \\[multishell-list]. Hit ? in the listing buffer for
386 editing commands.
387
388 ===== Select starting directory and remote host:
389
390 The shell buffer name you give to the prompt for a universal arg
391 can include an appended path. That will be used for the startup
392 directory. You can use tramp remote syntax to specify a remote
393 shell. If there is an element after a final '/', that's used for
394 the buffer name. Otherwise, the host, domain, or path is used.
395
396 For example:
397
398 * '#root/sudo:root@localhost:/etc' for a buffer named \"*#root*\" with a
399 root shell starting in /etc.
400
401 * '/ssh:example.net:' for a shell buffer in your homedir on example.net.
402 The buffer will be named \"*example.net*\".
403
404 * '#ex/ssh:example.net|sudo:root@example.net:/var/log' for a root shell
405 starting in /var/log on example.net named \"*#ex*\".
406
407 * 'interior/ssh:gateway.corp.com|ssh:interior.corp.com:' to go
408 via gateway.corp.com to your homedir on interior.corp.com. The
409 buffer will be named \"*interior*\". You could append a sudo
410 hop to the path, combining the previous example, and so on.
411
412 File visits from the shell, and many common emacs activities like
413 dired, will be on the host where the shell is running, in the
414 auspices of the target account, and relative to the current
415 directory.
416
417 You can change the startup path for a shell buffer by editing it
418 at the completion prompt. The new path will not take effect for
419 an already-running shell.
420
421 To remove a shell buffer's history entry, kill the buffer and
422 affirm removal of the entry when prompted.
423
424 ===== Activate savehist to retain shell buffer names and paths across Emacs restarts:
425
426 To have emacs maintain your history of shell buffer names and paths,
427 customize the savehist group to activate savehist."
428
429 (interactive "P")
430
431 (let ((token '(token)))
432 (if (window-minibuffer-p)
433 (throw 'multishell-do-list token)
434 (if (equal token
435 (catch 'multishell-do-list
436 (multishell-pop-to-shell-worker arg name here)))
437 (multishell-list)))))
438
439 (defun multishell-pop-to-shell-worker (&optional arg name here)
440 "Do real work of `multishell-pop-to-shell', which see."
441 (let* ((from-buffer (current-buffer))
442 (from-buffer-is-shell (derived-mode-p 'shell-mode))
443 (primary-name-unbracketed (multishell-unbracket
444 multishell-primary-name))
445 (fallthrough-name (if from-buffer-is-shell
446 (buffer-name from-buffer)
447 primary-name-unbracketed))
448 (doublearg (equal arg '(16)))
449 (target-name-and-path
450 (multishell-resolve-target-name-and-path
451 (cond (name name)
452 (arg
453 (or (multishell-read-unbracketed-entry
454 (format "Shell buffer name [%s]%s "
455 primary-name-unbracketed
456 (if doublearg " <==" ":")))
457 primary-name-unbracketed))
458 (t fallthrough-name))))
459 (use-path (cadr target-name-and-path))
460 (target-shell-buffer-name (car target-name-and-path))
461 (target-buffer (get-buffer target-shell-buffer-name))
462 (curr-buff-proc (get-buffer-process from-buffer))
463 inwin
464 already-there)
465
466 ;; Register early so the entry is pushed to the front:
467 (multishell-register-name-to-path (multishell-unbracket
468 target-shell-buffer-name)
469 use-path)
470
471 (when doublearg
472 (setq multishell-primary-name target-shell-buffer-name))
473
474 ;; Situate:
475
476 (cond
477
478 ((and (or curr-buff-proc from-buffer-is-shell)
479 (not arg)
480 (eq from-buffer target-buffer)
481 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
482 ;; In a shell buffer, but not named - stay in buffer, but go to end.
483 (setq already-there t))
484
485 ((string= (buffer-name) target-shell-buffer-name)
486 ;; Already in the specified shell buffer:
487 (setq already-there t))
488
489 ((or (not target-buffer)
490 (not (setq inwin
491 (multishell-get-visible-window-for-buffer target-buffer))))
492 ;; No preexisting shell buffer, or not in a visible window:
493 (when (not (get-buffer target-shell-buffer-name))
494 (message "Creating new shell buffer '%s'" target-shell-buffer-name))
495 (if here
496 (switch-to-buffer target-shell-buffer-name)
497 (pop-to-buffer target-shell-buffer-name pop-up-windows)))
498
499 ;; Buffer exists and already has a window - jump to it:
500 (t (if (and multishell-pop-to-frame
501 inwin
502 (not (equal (window-frame (selected-window))
503 (window-frame inwin))))
504 (select-frame-set-input-focus (window-frame inwin)))
505 (if (not (string= (buffer-name (current-buffer))
506 target-shell-buffer-name))
507 (if here
508 (switch-to-buffer target-shell-buffer-name)
509 (pop-to-buffer target-shell-buffer-name t)))))
510
511 ;; We're in the buffer. Activate:
512
513 (if (not (comint-check-proc (current-buffer)))
514 (multishell-start-shell-in-buffer use-path))
515
516 ;; If the destination buffer has a stopped process, resume it:
517 (let ((process (get-buffer-process (current-buffer))))
518 (if (and process (equal 'stop (process-status process)))
519 (continue-process process)))
520
521 (when (or already-there
522 (equal (current-buffer) from-buffer))
523 (goto-char (point-max))
524 (and (get-buffer-process from-buffer)
525 (goto-char (process-mark (get-buffer-process from-buffer)))))))
526
527 (defun multishell-delete-history-name (name &optional ask)
528 "Remove all multishell history entries for NAME.
529
530 if optional ask is non-nil (default nil), ask before each deletion.
531
532 Return the last entry deleted."
533 (let (got)
534 (dolist (entry (multishell-history-entries name) got)
535 (when (and entry
536 (or (not ask)
537 (y-or-n-p (format "Remove multishell history entry `%s'? "
538 entry))))
539 (setq got entry
540 multishell-history (delete entry multishell-history))))))
541
542 (defun multishell-kill-buffer-query-function ()
543 "Offer to remove multishell-history entry for buffer."
544 ;; Removal choice is crucial, so users can, eg, kill a shell with huge
545 ;; output backlog, while keeping the history entry to easily restart it.
546 ;;
547 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
548 ;;
549 ;; 1. It enables the user to remove the history without actually killing a
550 ;; running buffer, by not confirming the subsequent running-proc query.
551 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
552 ;; It's probably due to failures in other hooks - beyond our control -
553 ;; and anyway, I like the first reason well enough.
554
555 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
556 ;; activity. kill-buffer happens behind the scenes a whole lot.)
557 (condition-case err
558 (and (derived-mode-p 'shell-mode)
559 (multishell-delete-history-name
560 (multishell-unbracket (buffer-name))
561 t))
562 (error
563 (message "multishell-kill-buffer-query-function error: %s" err)))
564 t)
565 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
566
567 (defun multishell-get-visible-window-for-buffer (buffer)
568 "Return visible window containing buffer."
569 (catch 'got-a-vis
570 (walk-windows
571 (function (lambda (win)
572 (if (and (eq (window-buffer win) buffer)
573 (equal (frame-parameter
574 (selected-frame) 'display)
575 (frame-parameter
576 (window-frame win) 'display)))
577 (throw 'got-a-vis win))))
578 nil 'visible)
579 nil))
580
581 (defun multishell-all-entries (&optional active-duplicated)
582 "Return multishell history, with active buffers listed first.
583
584 Optional ACTIVE-DUPLICATED will return a copy of
585 `multishell-history' with unbracketed names of active buffers,
586 sans paths, appended to the list, so they have short and long
587 completions."
588 ;; Reorder so active lead present lead historical entries:
589 (let (active-entries active-names present past splat name buffer)
590 (dolist (entry multishell-history)
591 (setq splat (multishell-split-entry entry)
592 name (car splat)
593 buffer (and name (get-buffer (multishell-bracket name))))
594 (if (buffer-live-p buffer)
595 (if (comint-check-proc buffer)
596 (setq active-entries (push entry active-entries)
597 active-names (push name active-names))
598 (setq present (push entry present)))
599 (setq past (push entry past))))
600 ;; Reverse present and past lists
601 (setq multishell-history (append (reverse active-entries)
602 (reverse present)
603 (reverse past)))
604 (if active-duplicated
605 (append multishell-history active-names)
606 multishell-history)))
607
608 (defun multishell-display-completion-list (completions)
609 "Present COMPLETIONS using multishell-list for `display-completion-list'."
610 (let ((multishell-history (mapcar 'substring-no-properties completions)))
611 (multishell-list "*Completions*")))
612
613 (defun multishell-read-unbracketed-entry (prompt &optional initial no-record)
614 "PROMPT for shell buffer name, sans asterisks.
615
616 Optional INITIAL is preliminary value to be edited.
617
618 Optional NO-RECORD prevents changes to `multishell-history'
619 across the activity.
620
621 Input and completion can include associated path, if any.
622
623 Return what's provided, if anything, else nil."
624 (let* ((was-multishell-history multishell-history)
625 (candidates (multishell-all-entries 'active-duplicated))
626 (got (cl-letf
627 ;; Engage our custom display-completion-list, for
628 ;; minibuffer-completion-help. `cl-letf' for dynamic
629 ;; binding; cl-flet's lexical doesn't do what's needed.
630 (((symbol-function 'display-completion-list)
631 #'multishell-display-completion-list))
632 (completing-read prompt
633 ;; COLLECTION:
634 (reverse candidates)
635 ;; PREDICATE:
636 nil
637 ;; REQUIRE-MATCH:
638 'confirm
639 ;; INITIAL-INPUT
640 initial
641 ;; HIST:
642 'multishell-history))))
643 (when no-record
644 (setq multishell-history was-multishell-history))
645 (if (not (string= got ""))
646 got
647 nil)))
648
649 (defun multishell-resolve-target-name-and-path (shell-spec)
650 "Given name/tramp-style address shell spec, resolve buffer name and directory.
651
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.
657
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 "")))
661 (path (cadr splat))
662 (name (or (car splat) (multishell-name-from-entry path))))
663 (when (not path)
664 ;; Get path from history, if present.
665 (dolist (entry
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)))
671
672 (defun multishell-name-from-entry (entry)
673 "Derive a name for a shell buffer according to ENTRY."
674 (if (not entry)
675 (multishell-unbracket multishell-primary-name)
676 (let* ((splat (multishell-split-entry entry))
677 (name (car splat))
678 (path (cadr splat)))
679 (or name
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))
685 (host host)
686 (user user)
687 ((system-name))))
688 (multishell-unbracket multishell-primary-name))))))
689
690 (declare-function tramp-dissect-file-name "tramp")
691 (declare-function tramp-cleanup-connection "tramp")
692
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))))
696
697 (when (and path (not is-active))
698
699 (when (and (derived-mode-p 'shell-mode) (file-remote-p path))
700 ;; Returning to disconnected remote shell - do some tidying.
701 ;; (Prevents the "Args out of range" failure when reconnecting.)
702 (tramp-cleanup-connection
703 (tramp-dissect-file-name default-directory 'noexpand)
704 'keep-debug 'keep-password))
705
706 (when (file-remote-p path) (message "Connecting to %s" path))
707 (cd path))
708
709 (shell (current-buffer))))
710
711 (defun multishell-homedir-shorthand-p (dirpath)
712 "t if dirpath is an unexpanded remote homedir spec."
713 ;; Workaround to recognize tramp-style homedir shorthand, "...:" and "...:~".
714 (let ((localname (file-remote-p dirpath 'localname)))
715 (and localname
716 (or
717 ;; No directory path and no connection to expand homedir:
718 (string= localname "")
719 ;; Original path doesn't equal expanded homedir:
720 (save-match-data
721 (not (string-match (concat (regexp-quote localname) "/?$")
722 dirpath)))))))
723 ;; (assert (multishell-homedir-shorthand-p "/ssh:myhost.net:")
724 ;; (assert (not (multishell-homedir-shorthand-p "/home/klm")))
725 ;; (assert (not (multishell-homedir-shorthand-p "/ssh:myhost.net:/home/me")))
726
727 (defun multishell-track-dirchange (name newpath)
728 "Change multishell history entry to track current directory."
729 (let* ((entries (multishell-history-entries name)))
730 (dolist (entry entries)
731 (let* ((name-path (multishell-split-entry entry))
732 (name (car name-path))
733 (path (or (cadr name-path) "")))
734 (when path
735 (let* ((old-localname (or (file-remote-p path 'localname)
736 path))
737 (newentry
738 (if (multishell-homedir-shorthand-p path)
739 (concat entry newpath)
740 (replace-regexp-in-string (concat (regexp-quote
741 old-localname)
742 "$")
743 ;; REPLACEMENT
744 newpath
745 ;; STRING
746 entry
747 ;; FIXEDCASE
748 t
749 ;; LITERAL
750 t
751 )))
752 (membership (member entry multishell-history)))
753 (when membership
754 (setcar membership newentry))))))))
755
756 (defvar multishell-was-default-directory ()
757 "Provide for tracking directory changes.")
758 (make-variable-buffer-local 'multishell-was-default-directory)
759 (defun multishell-post-command-business ()
760 "Do multishell bookkeeping."
761 ;; Update multishell-history with dir changes.
762 (condition-case err
763 (when (and multishell-history-entry-tracks-current-directory
764 (derived-mode-p 'shell-mode))
765 (let ((curdir (if (file-remote-p default-directory)
766 (file-remote-p default-directory 'localname)
767 default-directory)))
768 (when (not (string= curdir (or multishell-was-default-directory "")))
769 (multishell-track-dirchange (multishell-unbracket (buffer-name))
770 curdir))
771 (setq multishell-was-default-directory curdir)))
772 ;; To avoid disruption as a pervasive hook function, swallow all errors:
773 (error
774 (message "multishell-post-command-business error: %s" err))))
775 (add-hook 'post-command-hook #'multishell-post-command-business)
776
777 (defun multishell-split-entry (entry)
778 "Given multishell name/path ENTRY, return the separated name and path pair.
779
780 Returns nil for empty parts, rather than the empty string."
781 (save-match-data
782 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
783 (let ((name (match-string 1 entry))
784 (path (match-string 2 entry)))
785 (and (string= name "") (setq name nil))
786 (and (string= path "") (setq path nil))
787 (list name path))))
788 (defun multishell-bracket (name)
789 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
790 (if (not (string= (substring name 0 1) "*"))
791 (setq name (concat "*" name)))
792 (if (not (string= (substring name -1) "*"))
793 (setq name (concat name "*")))
794 name)
795 (defun multishell-unbracket (name)
796 "Return a copy of name, removing asterisks, if any, at beginning and end."
797 (if (string= (substring name 0 1) "*")
798 (setq name (substring name 1)))
799 (if (string= (substring name -1) "*")
800 (setq name (substring name 0 -1)))
801 name)
802
803 (provide 'multishell)
804
805 ;;; multishell.el ends here