1 ;;; multishell.el --- facilitate multiple local and remote shell buffers
3 ;; Copyright (C) 1999-2016 Free Software Foundation, Inc. and Ken Manheimer
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 elsewhere 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 ;; * `/ssh:example.net:/` for a shell buffer in / on example.net.
31 ;; The buffer will be named "*example.net*".
33 ;; * `#ex/ssh:example.net|sudo:root@example.net:/etc` for a root shell
34 ;; starting in /etc on example.net named "*#ex*".
36 ;; * '\#intrn/ssh:corp.com|ssh:intern.corp.com|sudo:root@intern.corp.com:/etc'
37 ;; to go via corp.com to intern.corp.com, sudood to root, in /etc. Whee! (-:
38 ;; The buffer will be named "*#intrn*".
40 ;; * File visits will all be under the auspices of the account, and relative to
41 ;; the current directory, on the remote host.
43 ;; See the `multishell-pop-to-shell` docstring for details.
45 ;; Customize-group `multishell' to select and activate a keybinding and set
46 ;; various behaviors. Customize-group `savehist' to preserve buffer
47 ;; names/paths across emacs sessions.
50 ;; [the multishell repository](https://github.com/kenmanheimer/EmacsMultishell)
51 ;; issue tracker to report problems, suggestions, etc.
53 ;; (NOTE - tramp sometimes has a problem opening a remote shell pointed at
54 ;; a homedir, eg `/ssh:example.net:` or `/ssh:example.net:~`. When it
55 ;; fails, it won't work for the rest of the session. Non-homedir remote
56 ;; access isn't disrupted. Until this is fixed, you may need to start
57 ;; remote shells with an explicit path, then cd ~.)
61 ;; * 2016-01-16 1.0.5 Ken Manheimer:
62 ;; - History now includes paths, when designated
63 ;; - Actively track current directory in history entries that have a path.
64 ;; Custom control: multishell-history-entry-tracks-current-directory
65 ;; - Offer to remove shell's history entry when buffer is killed.
66 ;; (Currently the only UI mechanism to remove history entries.)
67 ;; - Fix - prevent duplicate entries for same name but different paths
68 ;; - Fix - recognize and respect tramp path syntax to start in home dir
69 ;; - But tramp bug, remote w/empty path (homedir) often fails, gets wedged.
70 ;; - Simplify history var name, migrate existing history if any from old name
71 ;; * 2016-01-04 1.0.4 Ken Manheimer - Released to ELPA
72 ;; * 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
76 ;; * Isolate tramp sporadic failure to connect to remote+homedir (empty path)
78 ;; (eg, /ssh:xyz.com|sudo:root@xyz.com: or /ssh:xyz.com|sudo:root@xyz.com:~)
79 ;; * Find suitable, internally consistent ways to sort tidy completions, eg:
80 ;; - first list completions for active shells, then present but inactive,
82 ;; - some way for user to toggle between presenting just buffer names vs
84 ;; - without cutting user off from easy editing of path
85 ;; * Find proper method for setting field boundary at beginning of tramp path
86 ;; in the minibuffer, in order to see whether the field boundary magically
87 ;; enables tramp completion of the path.
88 ;; * Assess whether option to delete history entry on kill-buffer is
96 (defgroup multishell nil
97 "Allout extension that highlights outline structure graphically.
99 Customize `allout-widgets-auto-activation' to activate allout-widgets
103 (defcustom multishell-command-key "\M- "
104 "The key to use if `multishell-activate-command-key' is true.
106 You can instead manually bind `multishell-pop-to-shell` using emacs
107 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
111 (defvar multishell--responsible-for-command-key nil
112 "Coordination for multishell key assignment.")
113 (defun multishell-activate-command-key-setter (symbol setting)
114 "Implement `multishell-activate-command-key' choice."
115 (set-default 'multishell-activate-command-key setting)
116 (when (or setting multishell--responsible-for-command-key)
117 (multishell-implement-command-key-choice (not setting))))
118 (defun multishell-implement-command-key-choice (&optional unbind)
119 "If settings dicate, implement binding of multishell command key.
121 If optional UNBIND is true, globally unbind the key.
123 * `multishell-activate-command-key' - Set this to get the binding or not.
124 * `multishell-command-key' - The key to use for the binding, if appropriate."
126 (when (and (boundp 'multishell-command-key) multishell-command-key)
127 (global-unset-key multishell-command-key)))
128 ((not (and (boundp 'multishell-activate-command-key)
129 (boundp 'multishell-command-key)))
131 ((and multishell-activate-command-key multishell-command-key)
132 (setq multishell--responsible-for-command-key t)
133 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
135 (defcustom multishell-activate-command-key nil
136 "Set this to impose the `multishell-command-key' binding.
138 You can instead manually bind `multishell-pop-to-shell` using emacs
139 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
141 :set 'multishell-activate-command-key-setter
144 ;; Assert the customizations whenever the package is loaded:
145 (with-eval-after-load "multishell"
146 (multishell-implement-command-key-choice))
148 (defcustom multishell-pop-to-frame nil
149 "*If non-nil, jump to a frame already showing the shell, if another is.
151 Otherwise, disregard already-open windows on the shell if they're
152 in another frame, and open a new window on the shell in the
155 \(Use `pop-up-windows' to change multishell other-buffer vs
156 current-buffer behavior.)"
160 (defcustom multishell-history-entry-tracks-current-directory t
161 "Modify shell buffer's multishell entry to track the current directory.
163 When set, the path part of the name/path entry for each shell
164 will track the current directory of the shell with emacs. If
165 `savehist' is active, the directory tracking will extend across
170 (defvar multishell-history nil
171 "Name/path entries, most recent first.")
172 (when (and (not multishell-history)
173 (boundp 'multishell-buffer-name-history)
174 multishell-buffer-name-history)
175 ;; Migrate few users who had old var to new.
176 (setq multishell-history multishell-buffer-name-history)
179 (defvar multishell-primary-name "*shell*"
180 "Shell name to use for un-modified multishell-pop-to-shell buffer target.")
182 ;; Multiple entries happen because completion also adds name to history.
183 (defun multishell-register-name-to-path (name path)
184 "Add or replace entry associating NAME with PATH in `multishell-history'.
186 If NAME already had a PATH and new PATH is empty, retain the prior one.
188 Promote added/changed entry to the front of the list."
189 ;; Add or promote to the front, tracking path changes in the process.
190 (let* ((entries (multishell-history-entries name))
192 (dolist (entry entries)
193 (when (string= path "")
194 ;; Retain explicit established path.
195 (setq path (cadr (multishell-split-entry-name-and-tramp entry))))
196 (setq multishell-history (delete entry multishell-history)))
197 (setq multishell-history (push (concat name path)
198 multishell-history))))
200 (defun multishell-history-entries (name)
201 "Return `multishell-history' entry that starts with NAME, or nil if none."
202 (let ((match-expr (concat "^" name "\\\(/.*$\\\)?"))
204 (dolist (entry multishell-history)
205 (when (and (string-match match-expr entry)
206 (not (member entry got)))
207 (setq got (cons entry got))))
210 (defun multishell-pop-to-shell (&optional arg)
211 "Easily navigate to and within multiple shell buffers, local and remote.
213 Use universal arguments to launch and choose between alternate
214 shell buffers and to select which is default. Append a path to
215 a new shell name to launch a shell in that directory, and use
216 Emacs tramp syntax to launch a remote shell.
218 Customize-group `multishell' to set up a key binding and tweak behaviors.
220 ==== Basic operation:
222 - If the current buffer is shell-mode (or shell-mode derived)
223 buffer then focus is moved to the process input point.
225 \(You can use a universal argument go to a different shell
226 buffer when already in a buffer that has a process - see
229 - If not in a shell buffer (or with universal argument), go to a
230 window that is already showing the (a) shell buffer, if any.
232 In this case, the cursor is left in its prior position in the
233 shell buffer. Repeating the command will then go to the
234 process input point, per the first item in this list.
236 We respect `pop-up-windows', so you can adjust it to set the
237 other-buffer/same-buffer behavior.
239 - Otherwise, start a new shell buffer, using the current
240 directory as the working directory.
242 If a buffer with the resulting name exists and its shell process
243 was disconnected or otherwise stopped, it's resumed.
245 ===== Universal arg to start and select between named shell buffers:
247 You can name alternate shell buffers to create or return to using
248 single or doubled universal arguments:
250 - With a single universal argument, prompt for the buffer name
251 to use (without the asterisks that shell mode will put around
252 the name), defaulting to 'shell'.
254 Completion is available.
256 This combination makes it easy to start and switch between
257 multiple shell buffers.
259 - A double universal argument will prompt for the name *and* set
260 the default to that name, so the target shell becomes the
263 ===== Select starting directory and remote host:
265 The shell buffer name you give to the prompt for a universal arg
266 can include an appended path. That will be used for the startup
267 directory. You can use tramp remote syntax to specify a remote
268 shell. If there is an element after a final '/', that's used for
269 the buffer name. Otherwise, the host, domain, or path is used.
273 * Use '/ssh:example.net:/home/myaccount' for a shell buffer in
274 /home/myaccount on example.net; the buffer will be named
276 * '\#ex/ssh:example.net|sudo:root@example.net:/etc' for a root
277 shell in /etc on example.net named \"*#ex*\".
278 * '\#in/ssh:corp.com|ssh:internal.corp.com|sudo:root@internal.corp.com:/etc'
279 for a root shell name \"*in*\" in /etc on internal.corp.com, via host
282 \(NOTE that there is a problem with specifying a remote homedir using
283 tramp syntax, eg '/ssh:example.net:'. That sometimes fails on an obscure
284 bug - particularly for remote with empty path (homedir) syntax. Until fixed,
285 you may need to start remote shells with an explicit path, then cd ~.)
287 You can change the startup path for a shell buffer by editing it
288 at the completion prompt. The new path will be preserved in
289 history but will not take effect for an already-running shell.
291 To remove a shell buffer's history entry, kill the buffer and
292 affirm removal of the entry when prompted.
294 ===== Activate savehist to retain shell buffer names and paths across Emacs sessions:
296 To have emacs maintain your history of shell buffer names and paths,
297 customize the savehist group to activate savehist."
301 (let* ((from-buffer (current-buffer))
302 (from-buffer-is-shell (derived-mode-p 'shell-mode))
303 (doublearg (equal arg '(16)))
304 (target-name-and-path
305 (multishell-derive-target-name-and-path
307 (multishell-read-bare-shell-buffer-name
308 (format "Shell buffer name [%s]%s "
309 (substring-no-properties
310 multishell-primary-name
311 1 (- (length multishell-primary-name) 1))
312 (if doublearg " <==" ":"))
313 multishell-primary-name)
314 multishell-primary-name)))
315 (use-default-dir (cadr target-name-and-path))
316 (target-shell-buffer-name (car target-name-and-path))
317 (curr-buff-proc (get-buffer-process from-buffer))
318 (target-buffer (if from-buffer-is-shell
320 (let ((got (get-buffer target-shell-buffer-name)))
321 (if (buffer-live-p got)
324 (get-buffer target-shell-buffer-name)))))
329 (setq multishell-primary-name target-shell-buffer-name))
335 ((and (or curr-buff-proc from-buffer-is-shell)
337 (eq from-buffer target-buffer)
338 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
339 ;; In a shell buffer, but not named - stay in buffer, but go to end.
340 (setq already-there t))
342 ((string= (buffer-name) target-shell-buffer-name)
343 ;; Already in the specified shell buffer:
344 (setq already-there t))
346 ((or (not target-buffer)
348 (multishell-get-visible-window-for-buffer target-buffer))))
349 ;; No preexisting shell buffer, or not in a visible window:
350 (pop-to-buffer target-shell-buffer-name pop-up-windows))
352 ;; Buffer exists and already has a window - jump to it:
353 (t (if (and multishell-pop-to-frame
355 (not (equal (window-frame (selected-window))
356 (window-frame inwin))))
357 (select-frame-set-input-focus (window-frame inwin)))
358 (if (not (string= (buffer-name (current-buffer))
359 target-shell-buffer-name))
360 (pop-to-buffer target-shell-buffer-name t))))
362 ;; We're in the buffer. Activate:
364 (if (not (comint-check-proc (current-buffer)))
365 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
368 ;; If the destination buffer has a stopped process, resume it:
369 (let ((process (get-buffer-process (current-buffer))))
370 (if (and process (equal 'stop (process-status process)))
371 (continue-process process)))
372 (multishell-register-name-to-path (multishell-unbracket-asterisks
373 target-shell-buffer-name)
375 (when (or already-there
376 (equal (current-buffer) from-buffer))
377 (goto-char (point-max))
378 (and (get-buffer-process from-buffer)
379 (goto-char (process-mark (get-buffer-process from-buffer)))))))
381 (defun multishell-kill-buffer-query-function ()
382 "Offer to remove multishell-history entry for buffer."
383 ;; Removal choice is crucial, so users can, eg, kill and a runaway shell
384 ;; and keep the history entry to easily restart it.
386 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
388 ;; 1. It enables the user to remove the history without killing the buffer,
389 ;; by cancelling the kill-buffer process after affirming history removal.
390 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
391 ;; I've failed to resolve that, and like the first reason well enough.
393 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
394 ;; activity. kill-buffer happens behind the scenes a whole lot.)
395 (condition-case anyerr
396 (let ((entries (and (derived-mode-p 'shell-mode)
397 (multishell-history-entries
398 (multishell-unbracket-asterisks (buffer-name))))))
399 (dolist (entry entries)
401 (y-or-n-p (format "Remove multishell history entry `%s'? "
403 (setq multishell-history
404 (delete entry multishell-history)))))
407 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
409 (defun multishell-get-visible-window-for-buffer (buffer)
410 "Return visible window containing buffer."
413 (function (lambda (win)
414 (if (and (eq (window-buffer win) buffer)
415 (equal (frame-parameter
416 (selected-frame) 'display)
418 (window-frame win) 'display)))
419 (throw 'got-a-vis win))))
423 (defun multishell-read-bare-shell-buffer-name (prompt default)
424 "PROMPT for shell buffer name, sans asterisks.
426 Return the supplied name bracketed with the asterisks, or specified DEFAULT
430 ;; Plain shell buffer names appended with names from name/path hist:
432 (mapcar (lambda (buffer)
433 (let* ((name (multishell-unbracket-asterisks
434 (buffer-name buffer))))
435 (and (buffer-live-p buffer)
436 (with-current-buffer buffer
437 ;; Shell mode buffers.
438 (derived-mode-p 'shell-mode))
439 (not (multishell-history-entries name))
443 (got (completing-read prompt
453 'multishell-history)))
454 (if (not (string= got ""))
455 (multishell-bracket-asterisks got)
458 (defun multishell-derive-target-name-and-path (path-ish)
459 "Give tramp-style PATH-ISH, determine target name and default directory.
461 The name is the part of the string before the initial '/' slash,
462 if any. Otherwise, it's either the host-name, domain-name, final
463 directory name, or local host name. The path is everything
464 besides the string before the initial '/' slash.
466 Return them as a list (name dir), with dir nil if none given."
467 (let (name (path "") dir)
468 (cond ((string= path-ish "") (setq dir multishell-primary-name))
469 ((string-match "^\\*\\([^/]*\\)\\(/.*\\)\\*" path-ish)
470 ;; We have a path, use it
471 (let ((overt-name (match-string 1 path-ish)))
472 (setq path (match-string 2 path-ish))
473 (if (string= overt-name "") (setq overt-name nil))
474 (if (string= path "") (setq path nil))
476 (multishell-bracket-asterisks
478 (if (file-remote-p path)
479 (let ((vec (tramp-dissect-file-name path)))
480 (or (tramp-file-name-host vec)
481 (tramp-file-name-domain vec)
482 (tramp-file-name-localname vec)
484 (multishell-unbracket-asterisks
485 multishell-primary-name)))))))
486 (t (setq name (multishell-bracket-asterisks path-ish))))
489 (defun multishell-bracket-asterisks (name)
490 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
491 (if (not (string= (substring name 0 1) "*"))
492 (setq name (concat "*" name)))
493 (if (not (string= (substring name -1) "*"))
494 (setq name (concat name "*")))
496 (defun multishell-unbracket-asterisks (name)
497 "Return a copy of name, removing asterisks, if any, at beginning and end."
498 (if (string= (substring name 0 1) "*")
499 (setq name (substring name 1)))
500 (if (string= (substring name -1) "*")
501 (setq name (substring name 0 -1)))
504 (defun multishell-start-shell-in-buffer (buffer-name path)
505 "Ensure a shell is started, with name NAME and PATH."
506 ;; We work around shell-mode's bracketing of the buffer name, and do
507 ;; some tramp-mode hygiene for remote connections.
509 (let* ((buffer buffer-name)
510 (prog (or explicit-shell-file-name
514 (name (file-name-nondirectory prog))
515 (startfile (concat "~/.emacs_" name))
516 (xargs-name (intern-soft (concat "explicit-" name "-args")))
518 (set-buffer buffer-name)
519 (if (and path (not (string= path "")))
520 (setq default-directory path))
521 (setq is-remote (file-remote-p default-directory))
523 (derived-mode-p 'shell-mode)
524 (not (comint-check-proc (current-buffer))))
525 ;; We're returning to an already established but disconnected remote
527 (tramp-cleanup-connection
528 (tramp-dissect-file-name default-directory 'noexpand)
529 'keep-debug 'keep-password))
530 ;; (cd default-directory) will connect if remote:
532 (message "Connecting to %s" default-directory))
534 (cd default-directory)
536 ;; Aargh. Need to isolate this tramp bug.
537 (when (and (stringp (cadr err))
538 (string-equal (cadr err)
539 "Selecting deleted buffer"))
542 (format "%s, %s (\"%s\")"
543 "Tramp shell can fail on empty (homedir) path"
544 "please try again with an explicit path"
546 (setq buffer (set-buffer (apply 'make-comint
547 (multishell-unbracket-asterisks buffer-name)
549 (if (file-exists-p startfile)
553 (symbol-value xargs-name)
557 (defun multishell-track-dirchange (name newpath)
558 "Change multishell history entry to track current directory."
559 (let* ((entries (multishell-history-entries name)))
560 (dolist (entry entries)
561 (let* ((name-path (multishell-split-entry-name-and-tramp entry))
562 (name (car name-path))
563 (path (cadr name-path)))
565 (let* ((is-remote (file-remote-p path))
566 (vec (and is-remote (tramp-dissect-file-name path nil)))
567 (localname (if is-remote
568 (tramp-file-name-localname vec)
571 (replace-regexp-in-string (if (string= localname "")
573 (regexp-quote localname))
583 (newpath (if is-remote
584 (tramp-make-tramp-file-name (aref vec 0)
590 (newentry (concat name newpath))
591 (membership (member entry multishell-history)))
593 (setcar membership newentry))))))))
594 (defvar multishell-was-default-directory ()
595 "Provide for tracking directory changes.")
596 (make-variable-buffer-local 'multishell-was-default-directory)
597 (defun multishell-post-command-business ()
598 "Do multishell bookkeeping."
599 ;; Update multishell-history with dir changes.
601 (when (and multishell-history-entry-tracks-current-directory
602 (derived-mode-p 'shell-mode))
603 (let ((curdir (if (file-remote-p default-directory)
604 (tramp-file-name-localname
605 (tramp-dissect-file-name default-directory))
607 (when (and multishell-was-default-directory
608 (not (string= curdir multishell-was-default-directory)))
609 (multishell-track-dirchange (multishell-unbracket-asterisks
612 (setq multishell-was-default-directory curdir)))
613 ;; To avoid disruption as a pervasive hook function, swallow all errors:
615 (add-hook 'post-command-hook 'multishell-post-command-business)
617 (defun multishell-split-entry-name-and-tramp (entry)
618 "Given multishell name/path ENTRY, return the separated name and path pair.
620 Returns nil for empty parts, rather than the empty string."
621 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
622 (let ((name (match-string 1 entry))
623 (path (match-string 2 entry)))
624 (and (string= name "") (setq name nil))
625 (and (string= path "") (setq path nil))
628 (provide 'multishell)
630 ;;; multishell.el ends here