]> code.delx.au - gnu-emacs-elpa/blob - multishell.el
multishell - Be more specific about why we use tramp-cleanup-connection.
[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 (defvar multishell-completing-read nil
273 "Internal use, conveying whether or not we're in the midst of a multishell
274 completing-read.")
275
276 ;; Multiple entries happen because completion also adds name to history.
277 (defun multishell-register-name-to-path (name path)
278 "Add or replace entry associating NAME with PATH in `multishell-history'.
279
280 If NAME already had a PATH and new PATH is empty, retain the prior one.
281
282 Promote added/changed entry to the front of the list."
283 ;; Add or promote to the front, tracking path changes in the process.
284 (let* ((entries (multishell-history-entries name))
285 (path (or path "")))
286 (dolist (entry entries)
287 (when (string= path "")
288 ;; Retain explicit established path.
289 (setq path (cadr (multishell-split-entry entry))))
290 (setq multishell-history (delete entry multishell-history)))
291 (setq multishell-history (push (concat name path)
292 multishell-history))))
293
294 (defun multishell-replace-entry (entry revised)
295 "Replace every instance of ENTRY in `multishell-history' with REVISED.
296
297 Revised entry is situated where former one was.
298
299 Returns non-nil iff any changes were made."
300 (let ((candidates multishell-history)
301 did-revisions)
302 (while (setq candidates (member entry candidates))
303 (setcar candidates revised)
304 (setq candidates (cdr candidates)
305 did-revisions t))
306 did-revisions))
307
308 (defun multishell-history-entries (name)
309 "Return `multishell-history' entry that starts with NAME, or nil if none."
310 (let (got)
311 (dolist (entry multishell-history)
312 (when (and (string-equal name (multishell-name-from-entry entry))
313 (not (member entry got)))
314 (push entry got)))
315 got))
316
317 ;;;###autoload
318 (defun multishell-pop-to-shell (&optional arg name here)
319 "Easily navigate to and within multiple shell buffers, local and remote.
320
321 Use a single `universal-argument' (\\[universal-argument]) to launch and choose between
322 nalternate shell buffers, and a doubled universal argument to also set your
323 choice as the ongoing default. Append a path to a new shell name to launch
324 a shell in that directory, and use Emacs tramp syntax to launch a remote
325 shell. There is a shortcut to manage your list of current and
326 historical shells, collectively, using `multishell-list' - see below.
327
328 Customize-group `multishell' to set up a key binding and tweak behaviors.
329
330 Manage your collection of current and historical shells by
331 recursively invoking \\[multishell-pop-to-shell] at the
332 `multishell-pop-to-shell' universal argument prompts, eg:
333
334 \\[universal-argument] \\[multishell-pop-to-shell] \\[multishell-pop-to-shell]
335
336 \(That will be just a few keys if you do the above
337 customization.) Hit ? in the listing buffer for editing commands.
338
339 ==== Basic operation:
340
341 - If the current buffer is shell-mode (or shell-mode derived)
342 buffer then focus is moved to the process input point.
343
344 \(You can use a universal argument go to a different shell
345 buffer when already in a buffer that has a process - see
346 below.)
347
348 - If not in a shell buffer (or with universal argument), go to a
349 window that is already showing the (a) shell buffer, if any.
350
351 In this case, the cursor is left in its prior position in the
352 shell buffer. Repeating the command will then go to the
353 process input point, per the first item in this list.
354
355 We respect `pop-up-windows', so you can adjust it to set the
356 other-buffer/same-buffer behavior.
357
358 - Otherwise, start a new shell buffer, using the current
359 directory as the working directory.
360
361 If a buffer with the resulting name exists and its shell process
362 was disconnected or otherwise stopped, it's resumed.
363
364 ===== Universal arg to start and select between named shell buffers:
365
366 You can name alternate shell buffers to create or return to, by
367 prefixing your \\[multishell-pop-to-shell] invocation with single or double
368 `universal-argument', \\[universal-argument]:
369
370 - With a single universal argument, prompt for the buffer name
371 to use (without the asterisks that shell mode will put around
372 the name), defaulting to 'shell'.
373
374 Completion is available.
375
376 This combination makes it easy to start and switch across
377 multiple shell restarts.
378
379 - A double universal argument will prompt for the name *and* set
380 the default to that name, so the target shell becomes the
381 primary.
382
383 See `multishell-primary-name' for info about preserving the
384 setting across emacs restarts.
385
386 - Manage your collection of current and historical shells by
387 recursively invoking \\[multishell-pop-to-shell] at either of the
388 `multishell-pop-to-shell' universal argument prompts, or at any
389 time via \\[multishell-list]. Hit ? in the listing buffer for
390 editing commands.
391
392 ===== Select starting directory and remote host:
393
394 The shell buffer name you give to the prompt for a universal arg
395 can include an appended path. That will be used for the startup
396 directory. You can use tramp remote syntax to specify a remote
397 shell. If there is an element after a final '/', that's used for
398 the buffer name. Otherwise, the host, domain, or path is used.
399
400 For example:
401
402 * '#root/sudo:root@localhost:/etc' for a buffer named \"*#root*\" with a
403 root shell starting in /etc.
404
405 * '/ssh:example.net:' for a shell buffer in your homedir on example.net.
406 The buffer will be named \"*example.net*\".
407
408 * '#ex/ssh:example.net|sudo:root@example.net:/var/log' for a root shell
409 starting in /var/log on example.net named \"*#ex*\".
410
411 * 'interior/ssh:gateway.corp.com|ssh:interior.corp.com:' to go
412 via gateway.corp.com to your homedir on interior.corp.com. The
413 buffer will be named \"*interior*\". You could append a sudo
414 hop to the path, combining the previous example, and so on.
415
416 File visits from the shell, and many common emacs activities like
417 dired, will be on the host where the shell is running, in the
418 auspices of the target account, and relative to the current
419 directory.
420
421 You can change the startup path for a shell buffer by editing it
422 at the completion prompt. The new path will not take effect for
423 an already-running shell.
424
425 To remove a shell buffer's history entry, kill the buffer and
426 affirm removal of the entry when prompted.
427
428 ===== Activate savehist to retain shell buffer names and paths across Emacs restarts:
429
430 To have emacs maintain your history of shell buffer names and paths,
431 customize the savehist group to activate savehist."
432
433 (interactive "P")
434
435 (let ((token '(token)))
436 (if (window-minibuffer-p)
437 (throw 'multishell-minibuffer-exit token)
438 (let ((got (catch 'multishell-minibuffer-exit
439 (multishell-pop-to-shell-worker arg name here))))
440 ;; Handle catch or plain fall-through - see cond comments for protocol.
441 (cond
442 ;; Caught token from recursive invocation in minibuffer:
443 ((equal token got) (multishell-list))
444 ;; Caught specifaction of multishell args, eg from multishell-list:
445 ((listp got) (multishell-pop-to-shell-worker (nth 2 got)
446 (nth 0 got)
447 (nth 1 got)))
448 ;; Regular fallthrough - just relay the result:
449 (t got))))))
450
451 (defun multishell-pop-to-shell-worker (&optional arg name here)
452 "Do real work of `multishell-pop-to-shell', which see."
453 (let* ((from-buffer (current-buffer))
454 (from-buffer-is-shell (derived-mode-p 'shell-mode))
455 (primary-name-unbracketed (multishell-unbracket
456 multishell-primary-name))
457 (fallthrough-name (if from-buffer-is-shell
458 (buffer-name from-buffer)
459 primary-name-unbracketed))
460 (doublearg (equal arg '(16)))
461 (target-name-and-path
462 (multishell-resolve-target-name-and-path
463 (cond (name name)
464 (arg
465 (or (multishell-read-unbracketed-entry
466 (format "Shell buffer name [%s]%s "
467 primary-name-unbracketed
468 (if doublearg " <==" ":")))
469 primary-name-unbracketed))
470 (t fallthrough-name))))
471 (use-path (cadr target-name-and-path))
472 (target-shell-buffer-name (car target-name-and-path))
473 (target-buffer (get-buffer target-shell-buffer-name))
474 (curr-buff-proc (get-buffer-process from-buffer))
475 inwin
476 already-there)
477
478 ;; Register early so the entry is pushed to the front:
479 (multishell-register-name-to-path (multishell-unbracket
480 target-shell-buffer-name)
481 use-path)
482
483 (when doublearg
484 (setq multishell-primary-name target-shell-buffer-name))
485
486 ;; Situate:
487
488 (cond
489
490 ((and (or curr-buff-proc from-buffer-is-shell)
491 (not arg)
492 (eq from-buffer target-buffer)
493 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
494 ;; In a shell buffer, but not named - stay in buffer, but go to end.
495 (setq already-there t))
496
497 ((string= (buffer-name) target-shell-buffer-name)
498 ;; Already in the specified shell buffer:
499 (setq already-there t))
500
501 ((or (not target-buffer)
502 (not (setq inwin
503 (multishell-get-visible-window-for-buffer target-buffer))))
504 ;; No preexisting shell buffer, or not in a visible window:
505 (when (not (get-buffer target-shell-buffer-name))
506 (message "Creating new shell buffer '%s'" target-shell-buffer-name))
507 (if here
508 (switch-to-buffer target-shell-buffer-name)
509 (pop-to-buffer target-shell-buffer-name pop-up-windows)))
510
511 ;; Buffer exists and already has a window - jump to it:
512 (t (if (and multishell-pop-to-frame
513 inwin
514 (not (equal (window-frame (selected-window))
515 (window-frame inwin))))
516 (select-frame-set-input-focus (window-frame inwin)))
517 (if (not (string= (buffer-name (current-buffer))
518 target-shell-buffer-name))
519 (if here
520 (switch-to-buffer target-shell-buffer-name)
521 (pop-to-buffer target-shell-buffer-name t)))))
522
523 ;; We're in the buffer. Activate:
524
525 (if (not (comint-check-proc (current-buffer)))
526 (multishell-start-shell-in-buffer use-path))
527
528 ;; If the destination buffer has a stopped process, resume it:
529 (let ((process (get-buffer-process (current-buffer))))
530 (if (and process (equal 'stop (process-status process)))
531 (continue-process process)))
532
533 (when (or already-there
534 (equal (current-buffer) from-buffer))
535 (goto-char (point-max))
536 (and (get-buffer-process from-buffer)
537 (goto-char (process-mark (get-buffer-process from-buffer)))))))
538
539 (defun multishell-delete-history-name (name &optional ask)
540 "Remove all multishell history entries for NAME.
541
542 if optional ask is non-nil (default nil), ask before each deletion.
543
544 Return the last entry deleted."
545 (let (got)
546 (dolist (entry (multishell-history-entries name) got)
547 (when (and entry
548 (or (not ask)
549 (y-or-n-p (format "Remove multishell history entry `%s'? "
550 entry))))
551 (setq got entry
552 multishell-history (delete entry multishell-history))))))
553
554 (defun multishell-kill-buffer-query-function ()
555 "Offer to remove multishell-history entry for buffer."
556 ;; Removal choice is crucial, so users can, eg, kill a shell with huge
557 ;; output backlog, while keeping the history entry to easily restart it.
558 ;;
559 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
560 ;;
561 ;; 1. It enables the user to remove the history without actually killing a
562 ;; running buffer, by not confirming the subsequent running-proc query.
563 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
564 ;; It's probably due to failures in other hooks - beyond our control -
565 ;; and anyway, I like the first reason well enough.
566
567 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
568 ;; activity. kill-buffer happens behind the scenes a whole lot.)
569 (condition-case err
570 (and (derived-mode-p 'shell-mode)
571 (multishell-delete-history-name
572 (multishell-unbracket (buffer-name))
573 t))
574 (error
575 (message "multishell-kill-buffer-query-function error: %s" err)))
576 t)
577 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
578
579 (defun multishell-get-visible-window-for-buffer (buffer)
580 "Return visible window containing buffer."
581 (catch 'got-a-vis
582 (walk-windows
583 (function (lambda (win)
584 (if (and (eq (window-buffer win) buffer)
585 (equal (frame-parameter
586 (selected-frame) 'display)
587 (frame-parameter
588 (window-frame win) 'display)))
589 (throw 'got-a-vis win))))
590 nil 'visible)
591 nil))
592
593 (defun multishell-all-entries (&optional active-duplicated)
594 "Return multishell history, with active buffers listed first.
595
596 Optional ACTIVE-DUPLICATED will return a copy of
597 `multishell-history' with unbracketed names of active buffers,
598 sans paths, appended to the list, so they have short and long
599 completions."
600 ;; Reorder so active lead present lead historical entries:
601 (let (active-entries active-names present past splat name buffer)
602 (dolist (entry multishell-history)
603 (setq splat (multishell-split-entry entry)
604 name (car splat)
605 buffer (and name (get-buffer (multishell-bracket name))))
606 (if (buffer-live-p buffer)
607 (if (comint-check-proc buffer)
608 (setq active-entries (push entry active-entries)
609 active-names (push name active-names))
610 (setq present (push entry present)))
611 (setq past (push entry past))))
612 ;; Reverse present and past lists
613 (setq multishell-history (append (reverse active-entries)
614 (reverse present)
615 (reverse past)))
616 (if active-duplicated
617 (append multishell-history active-names)
618 multishell-history)))
619
620 (defun multishell-read-unbracketed-entry (prompt &optional initial no-record)
621 "PROMPT for shell buffer name, sans asterisks.
622
623 Optional INITIAL is preliminary value to be edited.
624
625 Optional NO-RECORD prevents changes to `multishell-history'
626 across the activity.
627
628 Input and completion can include associated path, if any.
629
630 Return what's provided, if anything, else nil."
631 (let* ((was-multishell-history multishell-history)
632 (candidates (multishell-all-entries 'active-duplicated))
633 (multishell-completing-read t)
634 (got
635 ;; Use `cl-letf' to dynamically bind multishell-list to
636 ;; display-completion-list, so multishell-list is used when doing
637 ;; minibuffer-completion-help.
638 (cl-letf (((symbol-function 'display-completion-list)
639 #'multishell-list))
640 (completing-read prompt
641 ;; COLLECTION:
642 (reverse candidates)
643 ;; PREDICATE:
644 nil
645 ;; REQUIRE-MATCH:
646 'confirm
647 ;; INITIAL-INPUT
648 initial
649 ;; HIST:
650 'multishell-history))))
651 (when no-record
652 (setq multishell-history was-multishell-history))
653 (if (not (string= got ""))
654 got
655 nil)))
656
657 (defun multishell-resolve-target-name-and-path (shell-spec)
658 "Given name/tramp-style address shell spec, resolve buffer name and directory.
659
660 The name is the part of the string up to the first '/' slash, if
661 any. Missing pieces are filled in from remote path elements, if
662 any, and multishell history. Given a tramp-style remote address
663 and no name part, either the user@host is used for the buffer
664 name, if a user is specified, or just the host.
665
666 Return them as a list: (name path), with name asterisk-bracketed
667 and path nil if none is resolved."
668 (let* ((splat (multishell-split-entry (or shell-spec "")))
669 (path (cadr splat))
670 (name (or (car splat) (multishell-name-from-entry path))))
671 (when (not path)
672 ;; Get path from history, if present.
673 (dolist (entry
674 (multishell-history-entries
675 (multishell-unbracket name)))
676 (when (or (not path) (string= path ""))
677 (setq path (cadr (multishell-split-entry entry))))))
678 (list (multishell-bracket name) path)))
679
680 (defun multishell-name-from-entry (entry)
681 "Derive a name for a shell buffer according to ENTRY."
682 (if (not entry)
683 (multishell-unbracket multishell-primary-name)
684 (let* ((splat (multishell-split-entry entry))
685 (name (car splat))
686 (path (cadr splat)))
687 (or name
688 (if (file-remote-p path)
689 (let ((host (file-remote-p path 'host))
690 (user (file-remote-p path 'user)))
691 (cond ((and host user)
692 (format "%s@%s" user host))
693 (host host)
694 (user user)
695 ((system-name))))
696 (multishell-unbracket multishell-primary-name))))))
697
698 (declare-function tramp-dissect-file-name "tramp")
699 (declare-function tramp-cleanup-connection "tramp")
700
701 (defun multishell-start-shell-in-buffer (path)
702 "Start, restart, or continue a shell in BUFFER-NAME on PATH."
703 (let* ((is-active (comint-check-proc (current-buffer))))
704
705 (when (and path (not is-active))
706
707 (when (and (derived-mode-p 'shell-mode) (file-remote-p path))
708 ;; Returning to disconnected remote shell - do some tidying.
709 ;; Without this cleanup, occasionally restarting a disconnected
710 ;; remote session, particularly one that includes sudo, results in
711 ;; an untraceable "Args out of range" error. That never happens if
712 ;; we precedeed connection attempts with this cleanup -
713 ;; prophylactic.
714 (tramp-cleanup-connection
715 (tramp-dissect-file-name default-directory 'noexpand)
716 'keep-debug 'keep-password))
717
718 (when (file-remote-p path) (message "Connecting to %s" path))
719 (cd path))
720
721 (shell (current-buffer))))
722
723 (defun multishell-homedir-shorthand-p (dirpath)
724 "t if dirpath is an unexpanded remote homedir spec."
725 ;; Workaround to recognize tramp-style homedir shorthand, "...:" and "...:~".
726 (let ((localname (file-remote-p dirpath 'localname)))
727 (and localname
728 (or
729 ;; No directory path and no connection to expand homedir:
730 (string= localname "")
731 ;; Original path doesn't equal expanded homedir:
732 (save-match-data
733 (not (string-match (concat (regexp-quote localname) "/?$")
734 dirpath)))))))
735 ;; (assert (multishell-homedir-shorthand-p "/ssh:myhost.net:")
736 ;; (assert (not (multishell-homedir-shorthand-p "/home/klm")))
737 ;; (assert (not (multishell-homedir-shorthand-p "/ssh:myhost.net:/home/me")))
738
739 (defun multishell-track-dirchange (name newpath)
740 "Change multishell history entry to track current directory."
741 (let* ((entries (multishell-history-entries name)))
742 (dolist (entry entries)
743 (let* ((name-path (multishell-split-entry entry))
744 (name (car name-path))
745 (path (or (cadr name-path) "")))
746 (when path
747 (let* ((old-localname (or (file-remote-p path 'localname)
748 path))
749 (newentry
750 (if (multishell-homedir-shorthand-p path)
751 (concat entry newpath)
752 (replace-regexp-in-string (concat (regexp-quote
753 old-localname)
754 "$")
755 ;; REPLACEMENT
756 newpath
757 ;; STRING
758 entry
759 ;; FIXEDCASE
760 t
761 ;; LITERAL
762 t
763 )))
764 (membership (member entry multishell-history)))
765 (when membership
766 (setcar membership newentry))))))))
767
768 (defvar multishell-was-default-directory ()
769 "Provide for tracking directory changes.")
770 (make-variable-buffer-local 'multishell-was-default-directory)
771 (defun multishell-post-command-business ()
772 "Do multishell bookkeeping."
773 ;; Update multishell-history with dir changes.
774 (condition-case err
775 (when (and multishell-history-entry-tracks-current-directory
776 (derived-mode-p 'shell-mode))
777 (let ((curdir (if (file-remote-p default-directory)
778 (file-remote-p default-directory 'localname)
779 default-directory)))
780 (when (not (string= curdir (or multishell-was-default-directory "")))
781 (multishell-track-dirchange (multishell-unbracket (buffer-name))
782 curdir))
783 (setq multishell-was-default-directory curdir)))
784 ;; To avoid disruption as a pervasive hook function, swallow all errors:
785 (error
786 (message "multishell-post-command-business error: %s" err))))
787 (add-hook 'post-command-hook #'multishell-post-command-business)
788
789 (defun multishell-split-entry (entry)
790 "Given multishell name/path ENTRY, return the separated name and path pair.
791
792 Returns nil for empty parts, rather than the empty string."
793 (save-match-data
794 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
795 (let ((name (match-string 1 entry))
796 (path (match-string 2 entry)))
797 (and (string= name "") (setq name nil))
798 (and (string= path "") (setq path nil))
799 (list name path))))
800 (defun multishell-bracket (name)
801 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
802 (if (not (string= (substring name 0 1) "*"))
803 (setq name (concat "*" name)))
804 (if (not (string= (substring name -1) "*"))
805 (setq name (concat name "*")))
806 name)
807 (defun multishell-unbracket (name)
808 "Return a copy of name, removing asterisks, if any, at beginning and end."
809 (if (string= (substring name 0 1) "*")
810 (setq name (substring name 1)))
811 (if (string= (substring name -1) "*")
812 (setq name (substring name 0 -1)))
813 name)
814
815 (provide 'multishell)
816
817 ;;; multishell.el ends here