1 ;;; multishell.el --- manage interaction with multiple local and remote shells
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/EmacsUtils
13 ;; Easily use and manage multiple shell buffers, including remote shells.
14 ;; Fundamentally, multishell is the function `multishell:pop-to-shell - like
15 ;; 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 a shell buffer if you're not currently in one.
19 ;; * Use universal arguments to launch and choose among alternate shell buffers,
20 ;; * ... and select which is default.
21 ;; * Prepend a path to a new shell name to launch a shell in that directory,
22 ;; * ... and use a path with Emacs tramp syntax to launch a remote shell.
24 ;; Customize-group `multishell` to select and activate a keybinding and set
27 ;; See the pop-to-shell docstring for details.
31 ;; 2016-01-02 Ken Manheimer - initial release
35 ;; * Fix operation given local path without specified name
36 ;; * Preserveable (savehist) history that associates names with paths
37 ;; - Using an association list between names and paths
38 ;; - Searched for search backwards/forwards on isearch-like M-r/M-s bindings
39 ;; - *Not* searched for regular completion
41 ;; - During confirmation for new buffers - to use historical one
42 ;; - Or with minibuffer setup created key binding (isearch-like) M-e
43 ;; - M-e in empty initial provides completion on historicals
44 ;; - User can edit the entire path, changing the association
45 ;; - New association overrides previous
46 ;; - Deleting path removes association and history entry
47 ;; - Tracks buffer name changes
48 ;; - Using buffer-list-update-hook
49 ;; * Customize activation of savehist
50 ;; - Customize entry has warning about activating savehist
51 ;; - Adds the name/path association list to savehist-additional-variables
52 ;; - Activates savehist, if inactive
56 (defvar non-interactive-process-buffers '("*compilation*" "*grep*"))
61 (defgroup multishell nil
62 "Allout extension that highlights outline structure graphically.
64 Customize `allout-widgets-auto-activation' to activate allout-widgets
68 (defcustom multishell:non-interactive-process-buffers
69 '("*compilation*" "*grep*")
70 "Names of buffers that have processes but are not for interaction.
71 Add names of buffers that you don't want pop-to-shell to stick around in."
72 :type '(repeat string)
74 (defcustom multishell:command-key "\M- "
75 "The key to use if `multishell:activate-command-key' is true.
77 You can instead bind `pop-to-shell` to your preferred key using emacs
78 lisp, eg: (global-set-key \"\\M- \" 'pop-to-shell)."
82 (defvar multishell:responsible-for-command-key nil
83 "Multishell internal.")
84 (defun multishell:activate-command-key-setter (symbol setting)
85 "Implement `multishell:activate-command-key' choice."
86 (set-default 'multishell:activate-command-key setting)
87 (when (or setting multishell:responsible-for-command-key)
88 (multishell:implement-command-key-choice (not setting))))
89 (defun multishell:implement-command-key-choice (&optional unbind)
90 "If settings dicate, implement binding of multishell command key.
92 If optional UNBIND is true, globally unbind the key.
94 * `multishell:activate-command-key' - Set this to get the binding or not.
95 * `multishell:command-key' - The key to use for the binding, if appropriate."
97 (when (and (boundp 'multishell:command-key) multishell:command-key)
98 (global-unset-key multishell:command-key)))
99 ((not (and (boundp 'multishell:activate-command-key)
100 (boundp 'multishell:command-key)))
102 ((and multishell:activate-command-key multishell:command-key)
103 (setq multishell:responsible-for-command-key t)
104 (global-set-key multishell:command-key 'pop-to-shell))))
106 (defcustom multishell:activate-command-key nil
107 "Set this to impose the `multishell:command-key' binding.
109 You can instead bind `pop-to-shell` to your preferred key using emacs
110 lisp, eg: (global-set-key \"\\M- \" 'pop-to-shell)."
112 :set 'multishell:activate-command-key-setter
115 ;; Assert the customizations whenever the package is loaded:
116 (with-eval-after-load "multishell"
117 (multishell:implement-command-key-choice))
119 (defcustom multishell:pop-to-frame nil
120 "*If non-nil, jump to a frame already showing the shell, if another is.
122 Otherwise, open a new window in the current frame.
124 \(Adjust `pop-up-windows' to change other-buffer vs current-buffer behavior.)"
128 ;; (defcustom multishell:persist-shell-names nil
129 ;; "Remember shell name/path associations across sessions. Note well:
130 ;; This will activate minibuffer history persistence, in general, if it's not
135 (defvar multishell:name-path-assoc nil
136 "Assoc list from name to path")
138 (defvar multishell:primary-name "*shell*"
139 "Shell name to use for un-modified pop-to-shell buffer target.")
140 (defvar multishell:buffer-name-history nil
141 "Distinct pop-to-shell completion history container.")
142 (defvar multishell:buffer-name-path-history nil
143 "Another pop-to-shell completion history container, including paths.")
145 (defun pop-to-shell (&optional arg)
146 "Easily navigate to and within multiple shell buffers, local and remote.
148 Use universal arguments to launch and choose between alternate
149 shell buffers and to select which is default. Prepend a path to
150 a new shell name to launch a shell in that directory, and use
151 Emacs tramp syntax to launch a remote shell.
153 Customize-group `multishell' to set up a key binding and tweak behaviors.
155 ==== Basic operation:
157 - If the current buffer is associated with a subprocess (that is
158 not among those named on `non-interactive-process-buffers'),
159 then focus is moved to the process input point.
161 \(You can use a universal argument go to a different shell
162 buffer when already in a buffer that has a process - see
165 - If not in a shell buffer (or with universal argument), go to a
166 window that is already showing the (a) shell buffer, if any.
168 In this case, the cursor is left in its prior position in the
169 shell buffer. Repeating the command will then go to the
170 process input point, per the first item in this list.
172 We respect `pop-up-windows', so you can adjust it to set the
173 other-buffer/same-buffer behavior.
175 - Otherwise, start a new shell buffer, using the current
176 directory as the working directory.
178 If a buffer with the resulting name exists and its shell process
179 was disconnected or otherwise stopped, it's resumed.
181 ===== Universal arg to start and select between named shell buffers:
183 You can name alternate shell buffers to create or return to using
184 single or doubled universal arguments:
186 - With a single universal argument, prompt for the buffer name
187 to use (without the asterisks that shell mode will put around
188 the name), defaulting to 'shell'.
190 Completion is available.
192 This combination makes it easy to start and switch between
193 multiple shell buffers.
195 - A double universal argument will prompt for the name *and* set
196 the default to that name, so the target shell becomes the
199 ===== Select starting directory and remote host:
201 The shell buffer name you give to the prompt for a universal arg
202 can include a preceding path. That will be used for the startup
203 directory. You can use tramp remote syntax to specify a remote
204 shell. If there is an element after a final '/', that's used for
205 the buffer name. Otherwise, the host, domain, or path is used.
209 * Use '/ssh:example.net:/' for a shell buffer on example.net named
211 * '/ssh:example.net|sudo:root@example.net:/\#ex' for a root shell on
212 example.net named \"#ex\"."
214 ;; I'm leaving the following out of the docstring for now because just
215 ;; saving the buffer names, and not the paths, yields sometimes unwanted
218 ;; ===== Persisting your alternate shell buffer names and paths:
220 ;; You can use emacs builtin SaveHist to preserve your alternate
221 ;; shell buffer names and paths across emacs sessions. To do so,
222 ;; customize the `savehist' group, and:
224 ;; 1. Add `multishell:pop-to-shell-buffer-name-history' to Savehist Additional
226 ;; 2. Activate Savehist Mode, if not already activated.
231 (let* ((from-buffer (current-buffer))
232 (from-buffer-is-shell (eq major-mode 'shell-mode))
233 (doublearg (equal arg '(16)))
234 (target-name-and-path
235 (multishell:derive-target-name-and-path
237 (multishell:read-bare-shell-buffer-name
238 (format "Shell buffer name [%s]%s "
239 (substring-no-properties
240 multishell:primary-name
241 1 (- (length multishell:primary-name) 1))
242 (if doublearg " <==" ":"))
243 multishell:primary-name)
244 multishell:primary-name)))
245 (use-default-dir (cadr target-name-and-path))
246 (target-shell-buffer-name (car target-name-and-path))
247 (curr-buff-proc (get-buffer-process from-buffer))
248 (target-buffer (if (and (or curr-buff-proc from-buffer-is-shell)
249 (not (member (buffer-name from-buffer)
250 non-interactive-process-buffers)))
252 (get-buffer target-shell-buffer-name)))
257 (setq multishell:primary-name target-shell-buffer-name))
263 ((and (or curr-buff-proc from-buffer-is-shell)
265 (eq from-buffer target-buffer)
266 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
267 ;; In a shell buffer, but not named - stay in buffer, but go to end.
268 (setq already-there t))
270 ((string= (buffer-name) target-shell-buffer-name)
271 ;; Already in the specified shell buffer:
272 (setq already-there t))
274 ((or (not target-buffer)
276 (multishell:get-visible-window-for-buffer target-buffer))))
277 ;; No preexisting shell buffer, or not in a visible window:
278 (pop-to-buffer target-shell-buffer-name pop-up-windows))
280 ;; Buffer exists and already has a window - jump to it:
281 (t (if (and multishell:pop-to-frame
283 (not (equal (window-frame (selected-window))
284 (window-frame inwin))))
285 (select-frame-set-input-focus (window-frame inwin)))
286 (if (not (string= (buffer-name (current-buffer))
287 target-shell-buffer-name))
288 (pop-to-buffer target-shell-buffer-name t))))
290 ;; We're in the buffer. Activate:
292 (cond ((not (comint-check-proc (current-buffer)))
293 (multishell:start-shell-in-buffer (buffer-name (current-buffer))
296 (cd use-default-dir)))
298 ;; If the destination buffer has a stopped process, resume it:
299 (let ((process (get-buffer-process (current-buffer))))
300 (if (and process (equal 'stop (process-status process)))
301 (continue-process process)))
302 (when (or already-there
303 (equal (current-buffer) from-buffer))
304 (goto-char (point-max))
305 (and (get-buffer-process from-buffer)
306 (goto-char (process-mark (get-buffer-process from-buffer)))))))
308 (defun multishell:get-visible-window-for-buffer (buffer)
309 "Return visible window containing buffer."
312 (function (lambda (win)
313 (if (and (eq (window-buffer win) buffer)
314 (equal (frame-parameter
315 (selected-frame) 'display)
317 (window-frame win) 'display)))
318 (throw 'got-a-vis win))))
322 (defun multishell:read-bare-shell-buffer-name (prompt default)
323 "PROMPT for shell buffer name, sans asterisks.
325 Return the supplied name bracketed with the asterisks, or specified DEFAULT
327 (let* ((candidates (append
329 (mapcar (lambda (buffer)
330 (let ((name (buffer-name buffer)))
331 (if (with-current-buffer buffer
332 (eq major-mode 'shell-mode))
333 ;; Shell mode buffers.
334 (if (> (length name) 2)
340 (got (completing-read prompt
341 candidates ; COLLECTION
343 'confirm ; REQUIRE-MATCH
345 'multishell:buffer-name-history ; HIST
347 (if (not (string= got "")) (multishell:bracket-asterisks got) default)))
348 (defun multishell:derive-target-name-and-path (path-ish)
349 "Give tramp-style PATH-ISH, determine target name and default directory.
351 The name is the part of the string after the final '/' slash, if
352 any. Otherwise, it's either the host-name, domain-name, or local
353 host name. The path is everything besides the string following
356 Return them as a list (name dir), with dir nil if none given."
357 (let (name (path "") dir)
358 (cond ((string= path-ish "") (setq dir multishell:primary-name))
359 ((string-match "^\\*\\(/.*/\\)\\(.*\\)\\*" path-ish)
360 (setq path (match-string 1 path-ish))
362 (multishell:bracket-asterisks
363 (if (string= (match-string 2 path-ish) "")
364 (let ((v (tramp-dissect-file-name
366 (or (tramp-file-name-host v)
367 (tramp-file-name-domain v)
368 (tramp-file-name-localname v)
370 (match-string 2 path-ish)))))
371 (t (setq name (multishell:bracket-asterisks path-ish))))
374 (defun multishell:bracket-asterisks (name)
375 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
376 (if (not (string= (substring name 0 1) "*"))
377 (setq name (concat "*" name)))
378 (if (not (string= (substring name -1) "*"))
379 (setq name (concat name "*")))
381 (defun multishell:unbracket-asterisks (name)
382 "Return a copy of name, removing asterisks, if any, at beginning and end."
383 (if (string= (substring name 0 1) "*")
384 (setq name (substring name 1)))
385 (if (string= (substring name -1) "*")
386 (setq name (substring name 0 -1)))
388 (defun multishell:start-shell-in-buffer (buffer-name dir)
389 "Ensure a shell is started, using whatever name we're passed."
390 ;; We work around shell-mode's bracketing of the buffer name, and do
391 ;; some tramp-mode hygiene for remote connections.
393 (let* ((buffer buffer-name)
394 (prog (or explicit-shell-file-name
398 (name (file-name-nondirectory prog))
399 (startfile (concat "~/.emacs_" name))
400 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
401 (set-buffer buffer-name)
402 (when (and (file-remote-p default-directory)
403 (eq major-mode 'shell-mode)
404 (not (comint-check-proc (current-buffer))))
405 ;; We're returning to an already established but disconnected remote
407 (tramp-cleanup-connection
408 (tramp-dissect-file-name default-directory 'noexpand)
409 'keep-debug 'keep-password))
412 (setq buffer (set-buffer (apply 'make-comint
413 (multishell:unbracket-asterisks buffer-name)
415 (if (file-exists-p startfile)
419 (symbol-value xargs-name)
423 (provide 'multishell)
425 ;;; multishell.el ends here