]> code.delx.au - gnu-emacs-elpa/blob - packages/multishell/multishell.el
Merge commit 'f2458211bc25749f07e0d70addde7c7745dcc79d'
[gnu-emacs-elpa] / packages / multishell / 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-11 1.1.4 Ken Manheimer:
63 ;; - hookup multishell-list as completion help buffer.
64 ;; Mouse and keyboard selections from help listing properly exits
65 ;; minibuffer.
66 ;; * 2016-02-09 1.1.3 Ken Manheimer:
67 ;; multishell-list:
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
122 ;; not -Q).
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.
138 ;;
139 ;; TODO and Known Issues:
140 ;;
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.
151
152 ;;; Code:
153
154 (require 'comint)
155 (require 'shell)
156 (require 'savehist)
157 (require 'multishell-list)
158
159 (defvar multishell-version "1.1.3")
160 (defun multishell-version (&optional here)
161 "Return string describing the loaded multishell version."
162 (interactive "P")
163 (let ((msg (concat "Multishell " multishell-version)))
164 (if here (insert msg)
165 (if (called-interactively-p 'interactive)
166 (message "%s" msg)
167 msg))))
168
169 (defgroup multishell nil
170 "Allout extension that highlights outline structure graphically.
171
172 Customize `allout-widgets-auto-activation' to activate allout-widgets
173 with allout-mode."
174 :group 'shell)
175
176 (defcustom multishell-command-key "\M- "
177 "The key to use if `multishell-activate-command-key' is true.
178
179 You can instead manually bind `multishell-pop-to-shell` using emacs
180 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
181 :type 'key-sequence)
182
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.
192
193 If optional UNBIND is true, globally unbind the key.
194
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."
197 (cond (unbind
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)))
202 nil)
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))))
206
207 (defcustom multishell-activate-command-key nil
208 "Set this to impose the `multishell-command-key' binding.
209
210 You can instead manually bind `multishell-pop-to-shell` using emacs
211 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
212 :type 'boolean
213 :set 'multishell-activate-command-key-setter)
214
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)))
221
222 (defcustom multishell-pop-to-frame nil
223 "*If non-nil, jump to a frame already showing the shell, if another one is.
224
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
227 current frame.
228
229 \(Use `pop-up-windows' to change multishell other-window vs
230 current-window behavior.)"
231 :type 'boolean)
232
233 (defcustom multishell-history-entry-tracks-current-directory t
234 "Maintain shell's current directory in its multishell history entry.
235
236 When set, the history entry for shells started with explicit
237 paths will track the shell's current working directory.
238
239 If `savehist-save-minibuffer-history' is enabled, the current
240 working directory of shells will be conveyed between emacs
241 sessions."
242 :type 'boolean)
243
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))
252
253 (defvar multishell-primary-name "*shell*"
254 "Default shell name for un-modified multishell-pop-to-shell buffer target.
255
256 This is set by `multishell-pop-to-shell' as the current default,
257 when invoked with doubled universal argument.
258
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'.")
263
264 (defvar multishell-completing-read nil
265 "Internal use, conveying whether or not we're in the midst of a multishell
266 completing-read.")
267
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'.
271
272 If NAME already had a PATH and new PATH is empty, retain the prior one.
273
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))
277 (path (or path "")))
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))))
285
286 (defun multishell-replace-entry (entry revised)
287 "Replace every instance of ENTRY in `multishell-history' with REVISED.
288
289 Revised entry is situated where former one was.
290
291 Returns non-nil iff any changes were made."
292 (let ((candidates multishell-history)
293 did-revisions)
294 (while (setq candidates (member entry candidates))
295 (setcar candidates revised)
296 (setq candidates (cdr candidates)
297 did-revisions t))
298 did-revisions))
299
300 (defun multishell-history-entries (name)
301 "Return `multishell-history' entry that starts with NAME, or nil if none."
302 (let (got)
303 (dolist (entry multishell-history)
304 (when (and (string-equal name (multishell-name-from-entry entry))
305 (not (member entry got)))
306 (push entry got)))
307 got))
308
309 ;;;###autoload
310 (defun multishell-pop-to-shell (&optional arg name here)
311 "Easily navigate to and within multiple shell buffers, local and remote.
312
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.
319
320 Customize-group `multishell' to set up a key binding and tweak behaviors.
321
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:
325
326 \\[universal-argument] \\[multishell-pop-to-shell] \\[multishell-pop-to-shell]
327
328 \(That will be just a few keys if you do the above
329 customization.) Hit ? in the listing buffer for editing commands.
330
331 ==== Basic operation:
332
333 - If the current buffer is shell-mode (or shell-mode derived)
334 buffer then focus is moved to the process input point.
335
336 \(You can use a universal argument go to a different shell
337 buffer when already in a buffer that has a process - see
338 below.)
339
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.
342
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.
346
347 We respect `pop-up-windows', so you can adjust it to set the
348 other-buffer/same-buffer behavior.
349
350 - Otherwise, start a new shell buffer, using the current
351 directory as the working directory.
352
353 If a buffer with the resulting name exists and its shell process
354 was disconnected or otherwise stopped, it's resumed.
355
356 ===== Universal arg to start and select between named shell buffers:
357
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]:
361
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'.
365
366 Completion is available.
367
368 This combination makes it easy to start and switch across
369 multiple shell restarts.
370
371 - A double universal argument will prompt for the name *and* set
372 the default to that name, so the target shell becomes the
373 primary.
374
375 See `multishell-primary-name' for info about preserving the
376 setting across emacs restarts.
377
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
382 editing commands.
383
384 ===== Select starting directory and remote host:
385
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.
391
392 For example:
393
394 * '#root/sudo:root@localhost:/etc' for a buffer named \"*#root*\" with a
395 root shell starting in /etc.
396
397 * '/ssh:example.net:' for a shell buffer in your homedir on example.net.
398 The buffer will be named \"*example.net*\".
399
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*\".
402
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.
407
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
411 directory.
412
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.
416
417 To remove a shell buffer's history entry, kill the buffer and
418 affirm removal of the entry when prompted.
419
420 ===== Activate savehist to retain shell buffer names and paths across Emacs restarts:
421
422 To have emacs maintain your history of shell buffer names and paths,
423 customize the savehist group to activate savehist."
424
425 (interactive "P")
426
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.
433 (cond
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)
438 (nth 0 got)
439 (nth 1 got)))
440 ;; Regular fallthrough - just relay the result:
441 (t got))))))
442
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
455 (cond (name name)
456 (arg
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))
467 inwin
468 already-there)
469
470 ;; Register early so the entry is pushed to the front:
471 (multishell-register-name-to-path (multishell-unbracket
472 target-shell-buffer-name)
473 use-path)
474
475 (when doublearg
476 (setq multishell-primary-name target-shell-buffer-name))
477
478 ;; Situate:
479
480 (cond
481
482 ((and (or curr-buff-proc from-buffer-is-shell)
483 (not arg)
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))
488
489 ((string= (buffer-name) target-shell-buffer-name)
490 ;; Already in the specified shell buffer:
491 (setq already-there t))
492
493 ((or (not target-buffer)
494 (not (setq inwin
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))
499 (if here
500 (switch-to-buffer target-shell-buffer-name)
501 (pop-to-buffer target-shell-buffer-name pop-up-windows)))
502
503 ;; Buffer exists and already has a window - jump to it:
504 (t (if (and multishell-pop-to-frame
505 inwin
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))
511 (if here
512 (switch-to-buffer target-shell-buffer-name)
513 (pop-to-buffer target-shell-buffer-name t)))))
514
515 ;; We're in the buffer. Activate:
516
517 (if (not (comint-check-proc (current-buffer)))
518 (multishell-start-shell-in-buffer use-path))
519
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)))
524
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)))))))
530
531 (defun multishell-delete-history-name (name &optional ask)
532 "Remove all multishell history entries for NAME.
533
534 if optional ask is non-nil (default nil), ask before each deletion.
535
536 Return the last entry deleted."
537 (let (got)
538 (dolist (entry (multishell-history-entries name) got)
539 (when (and entry
540 (or (not ask)
541 (y-or-n-p (format "Remove multishell history entry `%s'? "
542 entry))))
543 (setq got entry
544 multishell-history (delete entry multishell-history))))))
545
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.
550 ;;
551 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
552 ;;
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.
558
559 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
560 ;; activity. kill-buffer happens behind the scenes a whole lot.)
561 (condition-case err
562 (and (derived-mode-p 'shell-mode)
563 (multishell-delete-history-name
564 (multishell-unbracket (buffer-name))
565 t))
566 (error
567 (message "multishell-kill-buffer-query-function error: %s" err)))
568 t)
569 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
570
571 (defun multishell-get-visible-window-for-buffer (buffer)
572 "Return visible window containing buffer."
573 (catch 'got-a-vis
574 (walk-windows
575 (function (lambda (win)
576 (if (and (eq (window-buffer win) buffer)
577 (equal (frame-parameter
578 (selected-frame) 'display)
579 (frame-parameter
580 (window-frame win) 'display)))
581 (throw 'got-a-vis win))))
582 nil 'visible)
583 nil))
584
585 (defun multishell-all-entries (&optional active-duplicated)
586 "Return multishell history, with active buffers listed first.
587
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
591 completions."
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)
596 name (car splat)
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)
606 (reverse present)
607 (reverse past)))
608 (if active-duplicated
609 (append multishell-history active-names)
610 multishell-history)))
611
612 (defun multishell-read-unbracketed-entry (prompt &optional initial no-record)
613 "PROMPT for shell buffer name, sans asterisks.
614
615 Optional INITIAL is preliminary value to be edited.
616
617 Optional NO-RECORD prevents changes to `multishell-history'
618 across the activity.
619
620 Input and completion can include associated path, if any.
621
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)
626 (got
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)
631 #'multishell-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 ;; 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 -
705 ;; prophylactic.
706 (tramp-cleanup-connection
707 (tramp-dissect-file-name default-directory 'noexpand)
708 'keep-debug 'keep-password))
709
710 (when (file-remote-p path) (message "Connecting to %s" path))
711 (cd path))
712
713 (shell (current-buffer))))
714
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)))
719 (and localname
720 (or
721 ;; No directory path and no connection to expand homedir:
722 (string= localname "")
723 ;; Original path doesn't equal expanded homedir:
724 (save-match-data
725 (not (string-match (concat (regexp-quote localname) "/?$")
726 dirpath)))))))
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")))
730
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) "")))
738 (when path
739 (let* ((old-localname (or (file-remote-p path 'localname)
740 path))
741 (newentry
742 (if (multishell-homedir-shorthand-p path)
743 (concat entry newpath)
744 (replace-regexp-in-string (concat (regexp-quote
745 old-localname)
746 "$")
747 ;; REPLACEMENT
748 newpath
749 ;; STRING
750 entry
751 ;; FIXEDCASE
752 t
753 ;; LITERAL
754 t
755 )))
756 (membership (member entry multishell-history)))
757 (when membership
758 (setcar membership newentry))))))))
759
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.
766 (condition-case err
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)
771 default-directory)))
772 (when (not (string= curdir (or multishell-was-default-directory "")))
773 (multishell-track-dirchange (multishell-unbracket (buffer-name))
774 curdir))
775 (setq multishell-was-default-directory curdir)))
776 ;; To avoid disruption as a pervasive hook function, swallow all errors:
777 (error
778 (message "multishell-post-command-business error: %s" err))))
779 (add-hook 'post-command-hook #'multishell-post-command-business)
780
781 (defun multishell-split-entry (entry)
782 "Given multishell name/path ENTRY, return the separated name and path pair.
783
784 Returns nil for empty parts, rather than the empty string."
785 (save-match-data
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))
791 (list name path))))
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 "*")))
798 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)))
805 name)
806
807 (provide 'multishell)
808
809 ;;; multishell.el ends here