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