1 ;;; multishell.el --- Easily use multiple shell buffers, local and remote.
3 ;; Copyright (C) 1999-2016 Free Software Foundation, Inc.
5 ;; Author: Ken Manheimer <ken.manheimer@gmail.com>
7 ;; Created: 1999 -- first public availability
9 ;; URL: https://github.com/kenmanheimer/EmacsMultishell
13 ;; Easily use and navigate multiple shell buffers, including remote shells.
14 ;; Fundamentally, multishell is the function `multishell-pop-to-shell' -
15 ;; a la `pop-to-buffer' - plus a keybinding. Together, they enable you to:
17 ;; * Get to the input point from wherever you are in a shell buffer,
18 ;; ... or to any of your shell buffers, from anywhere inside emacs.
20 ;; * Use universal arguments to launch and choose among alternate shell buffers,
21 ;; ... and change which is the current default.
23 ;; * Easily restart disconnected shells, or shells from prior sessions
24 ;; ... the latter from Emacs builtin savehist minibuf history persistence
26 ;; * Append a path to a new shell name to launch a shell in that directory,
27 ;; ... and use a path with Emacs tramp syntax to launch a remote shell -
30 ;; * `#root/sudo:root@localhost:/etc` for a buffer named "*#root*" with a
31 ;; root shell starting in /etc.
33 ;; * `/ssh:example.net:` for a shell buffer in your homedir on example.net.
34 ;; The buffer will be named "*example.net*".
36 ;; * `#ex/ssh:example.net|sudo:root@example.net:/var/log` for a root shell
37 ;; starting in /var/log on example.net named "*#ex*".
39 ;; * 'interior/ssh:gateway.corp.com|ssh:interior.corp.com:' to go via
40 ;; gateway.corp.com to your homedir on interior.corp.com. The buffer
41 ;; will be named "*interior*". You could append a sudo hop, and so on.
43 ;; * Thanks to tramp, file visits from the shell will seamlessly be in
44 ;; the auspices of the target account, and relative to the current
45 ;; directory, on the host where the shell is running.
47 ;; * Manage your list of shells, current and past, as a collection.
49 ;; See the `multishell-pop-to-shell` docstring for details.
51 ;; Customize-group `multishell' to select and activate a keybinding and set
52 ;; various behaviors. Customize-group `savehist' to preserve buffer
53 ;; names/paths across emacs restarts.
56 ;; [the multishell repository](https://github.com/kenmanheimer/EmacsMultishell)
57 ;; issue tracker to report problems, suggestions, etc, and see that
58 ;; repository for a bit more documentation.
62 ;; * 2016-02-10 1.1.4 Ken Manheimer:
63 ;; - hookup multishell-list as completion help buffer.
64 ;; * 2016-02-09 1.1.3 Ken Manheimer:
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
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.
137 ;; TODO and Known Issues:
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
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.
165 (require 'multishell-list)
167 (defvar multishell-version "1.1.3")
168 (defun multishell-version (&optional here)
169 "Return string describing the loaded multishell version."
171 (let ((msg (concat "Multishell " multishell-version)))
172 (if here (insert msg)
173 (if (called-interactively-p 'interactive)
177 (defgroup multishell nil
178 "Allout extension that highlights outline structure graphically.
180 Customize `allout-widgets-auto-activation' to activate allout-widgets
184 (defcustom multishell-command-key "\M- "
185 "The key to use if `multishell-activate-command-key' is true.
187 You can instead manually bind `multishell-pop-to-shell` using emacs
188 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
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.
201 If optional UNBIND is true, globally unbind the key.
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."
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)))
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))))
215 (defcustom multishell-activate-command-key nil
216 "Set this to impose the `multishell-command-key' binding.
218 You can instead manually bind `multishell-pop-to-shell` using emacs
219 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
221 :set 'multishell-activate-command-key-setter)
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)))
230 (defcustom multishell-pop-to-frame nil
231 "*If non-nil, jump to a frame already showing the shell, if another one is.
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
237 \(Use `pop-up-windows' to change multishell other-window vs
238 current-window behavior.)"
241 (defcustom multishell-history-entry-tracks-current-directory t
242 "Maintain shell's current directory in its multishell history entry.
244 When set, the history entry for shells started with explicit
245 paths will track the shell's current working directory.
247 If `savehist-save-minibuffer-history' is enabled, the current
248 working directory of shells will be conveyed between emacs
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))
261 (defvar multishell-primary-name "*shell*"
262 "Default shell name for un-modified multishell-pop-to-shell buffer target.
264 This is set by `multishell-pop-to-shell' as the current default,
265 when invoked with doubled universal argument.
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'.")
272 ;; Multiple entries happen because completion also adds name to history.
273 (defun multishell-register-name-to-path (name path)
274 "Add or replace entry associating NAME with PATH in `multishell-history'.
276 If NAME already had a PATH and new PATH is empty, retain the prior one.
278 Promote added/changed entry to the front of the list."
279 ;; Add or promote to the front, tracking path changes in the process.
280 (let* ((entries (multishell-history-entries name))
282 (dolist (entry entries)
283 (when (string= path "")
284 ;; Retain explicit established path.
285 (setq path (cadr (multishell-split-entry entry))))
286 (setq multishell-history (delete entry multishell-history)))
287 (setq multishell-history (push (concat name path)
288 multishell-history))))
290 (defun multishell-replace-entry (entry revised)
291 "Replace every instance of ENTRY in `multishell-history' with REVISED.
293 Revised entry is situated where former one was.
295 Returns non-nil iff any changes were made."
296 (let ((candidates multishell-history)
298 (while (setq candidates (member entry candidates))
299 (setcar candidates revised)
300 (setq candidates (cdr candidates)
304 (defun multishell-history-entries (name)
305 "Return `multishell-history' entry that starts with NAME, or nil if none."
307 (dolist (entry multishell-history)
308 (when (and (string-equal name (multishell-name-from-entry entry))
309 (not (member entry got)))
314 (defun multishell-pop-to-shell (&optional arg name here)
315 "Easily navigate to and within multiple shell buffers, local and remote.
317 Use a single `universal-argument' (\\[universal-argument]) to launch and choose between
318 nalternate shell buffers, and a doubled universal argument to also set your
319 choice as the ongoing default. Append a path to a new shell name to launch
320 a shell in that directory, and use Emacs tramp syntax to launch a remote
321 shell. There is a shortcut to manage your list of current and
322 historical shells, collectively, using `multishell-list' - see below.
324 Customize-group `multishell' to set up a key binding and tweak behaviors.
326 Manage your collection of current and historical shells by
327 recursively invoking \\[multishell-pop-to-shell] at the
328 `multishell-pop-to-shell' universal argument prompts, eg:
330 \\[universal-argument] \\[multishell-pop-to-shell] \\[multishell-pop-to-shell]
332 \(That will be just a few keys if you do the above
333 customization.) Hit ? in the listing buffer for editing commands.
335 ==== Basic operation:
337 - If the current buffer is shell-mode (or shell-mode derived)
338 buffer then focus is moved to the process input point.
340 \(You can use a universal argument go to a different shell
341 buffer when already in a buffer that has a process - see
344 - If not in a shell buffer (or with universal argument), go to a
345 window that is already showing the (a) shell buffer, if any.
347 In this case, the cursor is left in its prior position in the
348 shell buffer. Repeating the command will then go to the
349 process input point, per the first item in this list.
351 We respect `pop-up-windows', so you can adjust it to set the
352 other-buffer/same-buffer behavior.
354 - Otherwise, start a new shell buffer, using the current
355 directory as the working directory.
357 If a buffer with the resulting name exists and its shell process
358 was disconnected or otherwise stopped, it's resumed.
360 ===== Universal arg to start and select between named shell buffers:
362 You can name alternate shell buffers to create or return to, by
363 prefixing your \\[multishell-pop-to-shell] invocation with single or double
364 `universal-argument', \\[universal-argument]:
366 - With a single universal argument, prompt for the buffer name
367 to use (without the asterisks that shell mode will put around
368 the name), defaulting to 'shell'.
370 Completion is available.
372 This combination makes it easy to start and switch across
373 multiple shell restarts.
375 - A double universal argument will prompt for the name *and* set
376 the default to that name, so the target shell becomes the
379 See `multishell-primary-name' for info about preserving the
380 setting across emacs restarts.
382 - Manage your collection of current and historical shells by
383 recursively invoking \\[multishell-pop-to-shell] at either of the
384 `multishell-pop-to-shell' universal argument prompts, or at any
385 time via \\[multishell-list]. Hit ? in the listing buffer for
388 ===== Select starting directory and remote host:
390 The shell buffer name you give to the prompt for a universal arg
391 can include an appended path. That will be used for the startup
392 directory. You can use tramp remote syntax to specify a remote
393 shell. If there is an element after a final '/', that's used for
394 the buffer name. Otherwise, the host, domain, or path is used.
398 * '#root/sudo:root@localhost:/etc' for a buffer named \"*#root*\" with a
399 root shell starting in /etc.
401 * '/ssh:example.net:' for a shell buffer in your homedir on example.net.
402 The buffer will be named \"*example.net*\".
404 * '#ex/ssh:example.net|sudo:root@example.net:/var/log' for a root shell
405 starting in /var/log on example.net named \"*#ex*\".
407 * 'interior/ssh:gateway.corp.com|ssh:interior.corp.com:' to go
408 via gateway.corp.com to your homedir on interior.corp.com. The
409 buffer will be named \"*interior*\". You could append a sudo
410 hop to the path, combining the previous example, and so on.
412 File visits from the shell, and many common emacs activities like
413 dired, will be on the host where the shell is running, in the
414 auspices of the target account, and relative to the current
417 You can change the startup path for a shell buffer by editing it
418 at the completion prompt. The new path will not take effect for
419 an already-running shell.
421 To remove a shell buffer's history entry, kill the buffer and
422 affirm removal of the entry when prompted.
424 ===== Activate savehist to retain shell buffer names and paths across Emacs restarts:
426 To have emacs maintain your history of shell buffer names and paths,
427 customize the savehist group to activate savehist."
431 (let ((token '(token)))
432 (if (window-minibuffer-p)
433 (throw 'multishell-do-list token)
435 (catch 'multishell-do-list
436 (multishell-pop-to-shell-worker arg name here)))
437 (multishell-list)))))
439 (defun multishell-pop-to-shell-worker (&optional arg name here)
440 "Do real work of `multishell-pop-to-shell', which see."
441 (let* ((from-buffer (current-buffer))
442 (from-buffer-is-shell (derived-mode-p 'shell-mode))
443 (primary-name-unbracketed (multishell-unbracket
444 multishell-primary-name))
445 (fallthrough-name (if from-buffer-is-shell
446 (buffer-name from-buffer)
447 primary-name-unbracketed))
448 (doublearg (equal arg '(16)))
449 (target-name-and-path
450 (multishell-resolve-target-name-and-path
453 (or (multishell-read-unbracketed-entry
454 (format "Shell buffer name [%s]%s "
455 primary-name-unbracketed
456 (if doublearg " <==" ":")))
457 primary-name-unbracketed))
458 (t fallthrough-name))))
459 (use-path (cadr target-name-and-path))
460 (target-shell-buffer-name (car target-name-and-path))
461 (target-buffer (get-buffer target-shell-buffer-name))
462 (curr-buff-proc (get-buffer-process from-buffer))
466 ;; Register early so the entry is pushed to the front:
467 (multishell-register-name-to-path (multishell-unbracket
468 target-shell-buffer-name)
472 (setq multishell-primary-name target-shell-buffer-name))
478 ((and (or curr-buff-proc from-buffer-is-shell)
480 (eq from-buffer target-buffer)
481 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
482 ;; In a shell buffer, but not named - stay in buffer, but go to end.
483 (setq already-there t))
485 ((string= (buffer-name) target-shell-buffer-name)
486 ;; Already in the specified shell buffer:
487 (setq already-there t))
489 ((or (not target-buffer)
491 (multishell-get-visible-window-for-buffer target-buffer))))
492 ;; No preexisting shell buffer, or not in a visible window:
493 (when (not (get-buffer target-shell-buffer-name))
494 (message "Creating new shell buffer '%s'" target-shell-buffer-name))
496 (switch-to-buffer target-shell-buffer-name)
497 (pop-to-buffer target-shell-buffer-name pop-up-windows)))
499 ;; Buffer exists and already has a window - jump to it:
500 (t (if (and multishell-pop-to-frame
502 (not (equal (window-frame (selected-window))
503 (window-frame inwin))))
504 (select-frame-set-input-focus (window-frame inwin)))
505 (if (not (string= (buffer-name (current-buffer))
506 target-shell-buffer-name))
508 (switch-to-buffer target-shell-buffer-name)
509 (pop-to-buffer target-shell-buffer-name t)))))
511 ;; We're in the buffer. Activate:
513 (if (not (comint-check-proc (current-buffer)))
514 (multishell-start-shell-in-buffer use-path))
516 ;; If the destination buffer has a stopped process, resume it:
517 (let ((process (get-buffer-process (current-buffer))))
518 (if (and process (equal 'stop (process-status process)))
519 (continue-process process)))
521 (when (or already-there
522 (equal (current-buffer) from-buffer))
523 (goto-char (point-max))
524 (and (get-buffer-process from-buffer)
525 (goto-char (process-mark (get-buffer-process from-buffer)))))))
527 (defun multishell-delete-history-name (name &optional ask)
528 "Remove all multishell history entries for NAME.
530 if optional ask is non-nil (default nil), ask before each deletion.
532 Return the last entry deleted."
534 (dolist (entry (multishell-history-entries name) got)
537 (y-or-n-p (format "Remove multishell history entry `%s'? "
540 multishell-history (delete entry multishell-history))))))
542 (defun multishell-kill-buffer-query-function ()
543 "Offer to remove multishell-history entry for buffer."
544 ;; Removal choice is crucial, so users can, eg, kill a shell with huge
545 ;; output backlog, while keeping the history entry to easily restart it.
547 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
549 ;; 1. It enables the user to remove the history without actually killing a
550 ;; running buffer, by not confirming the subsequent running-proc query.
551 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
552 ;; It's probably due to failures in other hooks - beyond our control -
553 ;; and anyway, I like the first reason well enough.
555 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
556 ;; activity. kill-buffer happens behind the scenes a whole lot.)
558 (and (derived-mode-p 'shell-mode)
559 (multishell-delete-history-name
560 (multishell-unbracket (buffer-name))
563 (message "multishell-kill-buffer-query-function error: %s" err)))
565 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
567 (defun multishell-get-visible-window-for-buffer (buffer)
568 "Return visible window containing buffer."
571 (function (lambda (win)
572 (if (and (eq (window-buffer win) buffer)
573 (equal (frame-parameter
574 (selected-frame) 'display)
576 (window-frame win) 'display)))
577 (throw 'got-a-vis win))))
581 (defun multishell-all-entries (&optional active-duplicated)
582 "Return multishell history, with active buffers listed first.
584 Optional ACTIVE-DUPLICATED will return a copy of
585 `multishell-history' with unbracketed names of active buffers,
586 sans paths, appended to the list, so they have short and long
588 ;; Reorder so active lead present lead historical entries:
589 (let (active-entries active-names present past splat name buffer)
590 (dolist (entry multishell-history)
591 (setq splat (multishell-split-entry entry)
593 buffer (and name (get-buffer (multishell-bracket name))))
594 (if (buffer-live-p buffer)
595 (if (comint-check-proc buffer)
596 (setq active-entries (push entry active-entries)
597 active-names (push name active-names))
598 (setq present (push entry present)))
599 (setq past (push entry past))))
600 ;; Reverse present and past lists
601 (setq multishell-history (append (reverse active-entries)
604 (if active-duplicated
605 (append multishell-history active-names)
606 multishell-history)))
608 (defun multishell-display-completion-list (completions)
609 "Present COMPLETIONS using multishell-list for `display-completion-list'."
610 (let ((multishell-history (mapcar 'substring-no-properties completions)))
611 (multishell-list "*Completions*")))
613 (defun multishell-read-unbracketed-entry (prompt &optional initial no-record)
614 "PROMPT for shell buffer name, sans asterisks.
616 Optional INITIAL is preliminary value to be edited.
618 Optional NO-RECORD prevents changes to `multishell-history'
621 Input and completion can include associated path, if any.
623 Return what's provided, if anything, else nil."
624 (let* ((was-multishell-history multishell-history)
625 (candidates (multishell-all-entries 'active-duplicated))
627 ;; Engage our custom display-completion-list, for
628 ;; minibuffer-completion-help. `cl-letf' for dynamic
629 ;; binding; cl-flet's lexical doesn't do what's needed.
630 (((symbol-function 'display-completion-list)
631 #'multishell-display-completion-list))
632 (completing-read prompt
642 'multishell-history))))
644 (setq multishell-history was-multishell-history))
645 (if (not (string= got ""))
649 (defun multishell-resolve-target-name-and-path (shell-spec)
650 "Given name/tramp-style address shell spec, resolve buffer name and directory.
652 The name is the part of the string up to the first '/' slash, if
653 any. Missing pieces are filled in from remote path elements, if
654 any, and multishell history. Given a tramp-style remote address
655 and no name part, either the user@host is used for the buffer
656 name, if a user is specified, or just the host.
658 Return them as a list: (name path), with name asterisk-bracketed
659 and path nil if none is resolved."
660 (let* ((splat (multishell-split-entry (or shell-spec "")))
662 (name (or (car splat) (multishell-name-from-entry path))))
664 ;; Get path from history, if present.
666 (multishell-history-entries
667 (multishell-unbracket name)))
668 (when (or (not path) (string= path ""))
669 (setq path (cadr (multishell-split-entry entry))))))
670 (list (multishell-bracket name) path)))
672 (defun multishell-name-from-entry (entry)
673 "Derive a name for a shell buffer according to ENTRY."
675 (multishell-unbracket multishell-primary-name)
676 (let* ((splat (multishell-split-entry entry))
680 (if (file-remote-p path)
681 (let ((host (file-remote-p path 'host))
682 (user (file-remote-p path 'user)))
683 (cond ((and host user)
684 (format "%s@%s" user host))
688 (multishell-unbracket multishell-primary-name))))))
690 (declare-function tramp-dissect-file-name "tramp")
691 (declare-function tramp-cleanup-connection "tramp")
693 (defun multishell-start-shell-in-buffer (path)
694 "Start, restart, or continue a shell in BUFFER-NAME on PATH."
695 (let* ((is-active (comint-check-proc (current-buffer))))
697 (when (and path (not is-active))
699 (when (and (derived-mode-p 'shell-mode) (file-remote-p path))
700 ;; Returning to disconnected remote shell - do some tidying.
701 ;; (Prevents the "Args out of range" failure when reconnecting.)
702 (tramp-cleanup-connection
703 (tramp-dissect-file-name default-directory 'noexpand)
704 'keep-debug 'keep-password))
706 (when (file-remote-p path) (message "Connecting to %s" path))
709 (shell (current-buffer))))
711 (defun multishell-homedir-shorthand-p (dirpath)
712 "t if dirpath is an unexpanded remote homedir spec."
713 ;; Workaround to recognize tramp-style homedir shorthand, "...:" and "...:~".
714 (let ((localname (file-remote-p dirpath 'localname)))
717 ;; No directory path and no connection to expand homedir:
718 (string= localname "")
719 ;; Original path doesn't equal expanded homedir:
721 (not (string-match (concat (regexp-quote localname) "/?$")
723 ;; (assert (multishell-homedir-shorthand-p "/ssh:myhost.net:")
724 ;; (assert (not (multishell-homedir-shorthand-p "/home/klm")))
725 ;; (assert (not (multishell-homedir-shorthand-p "/ssh:myhost.net:/home/me")))
727 (defun multishell-track-dirchange (name newpath)
728 "Change multishell history entry to track current directory."
729 (let* ((entries (multishell-history-entries name)))
730 (dolist (entry entries)
731 (let* ((name-path (multishell-split-entry entry))
732 (name (car name-path))
733 (path (or (cadr name-path) "")))
735 (let* ((old-localname (or (file-remote-p path 'localname)
738 (if (multishell-homedir-shorthand-p path)
739 (concat entry newpath)
740 (replace-regexp-in-string (concat (regexp-quote
752 (membership (member entry multishell-history)))
754 (setcar membership newentry))))))))
756 (defvar multishell-was-default-directory ()
757 "Provide for tracking directory changes.")
758 (make-variable-buffer-local 'multishell-was-default-directory)
759 (defun multishell-post-command-business ()
760 "Do multishell bookkeeping."
761 ;; Update multishell-history with dir changes.
763 (when (and multishell-history-entry-tracks-current-directory
764 (derived-mode-p 'shell-mode))
765 (let ((curdir (if (file-remote-p default-directory)
766 (file-remote-p default-directory 'localname)
768 (when (not (string= curdir (or multishell-was-default-directory "")))
769 (multishell-track-dirchange (multishell-unbracket (buffer-name))
771 (setq multishell-was-default-directory curdir)))
772 ;; To avoid disruption as a pervasive hook function, swallow all errors:
774 (message "multishell-post-command-business error: %s" err))))
775 (add-hook 'post-command-hook #'multishell-post-command-business)
777 (defun multishell-split-entry (entry)
778 "Given multishell name/path ENTRY, return the separated name and path pair.
780 Returns nil for empty parts, rather than the empty string."
782 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
783 (let ((name (match-string 1 entry))
784 (path (match-string 2 entry)))
785 (and (string= name "") (setq name nil))
786 (and (string= path "") (setq path nil))
788 (defun multishell-bracket (name)
789 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
790 (if (not (string= (substring name 0 1) "*"))
791 (setq name (concat "*" name)))
792 (if (not (string= (substring name -1) "*"))
793 (setq name (concat name "*")))
795 (defun multishell-unbracket (name)
796 "Return a copy of name, removing asterisks, if any, at beginning and end."
797 (if (string= (substring name 0 1) "*")
798 (setq name (substring name 1)))
799 (if (string= (substring name -1) "*")
800 (setq name (substring name 0 -1)))
803 (provide 'multishell)
805 ;;; multishell.el ends here