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 dot manheimer at gmail...>
7 ;; Maintainer: Ken Manheimer <ken dot manheimer at gmail...>
8 ;; Created: 1999 -- first public availability
10 ;; URL: https://github.com/kenmanheimer/EmacsUtils
14 ;; Easily use and manage multiple shell buffers, including remote shells.
15 ;; Fundamentally, multishell is the function `multishell:pop-to-shell - like
16 ;; pop-to-buffer - plus a keybinding. Together, they enable you to:
18 ;; * Get to the input point from wherever you are in a shell buffer,
19 ;; * ... or to a shell buffer if you're not currently in one.
20 ;; * Use universal arguments to launch and choose among alternate shell buffers,
21 ;; * ... and select which is default.
22 ;; * Prepend a path to a new shell name to launch a shell in that directory,
23 ;; * ... and use a path with Emacs tramp syntax to launch a remote shell.
25 ;; Customize-group `multishell` to select and activate a keybinding and set
28 ;; See the pop-to-shell docstring for details.
32 ;; 2016-01-02 Ken Manheimer - initial release
36 ;; * Fix operation given local path without specified name
37 ;; * Preserveable (savehist) history that associates names with paths
38 ;; - Using an association list between names and paths
39 ;; - Searched for search backwards/forwards on isearch-like M-r/M-s bindings
40 ;; - *Not* searched for regular completion
42 ;; - During confirmation for new buffers - to use historical one
43 ;; - Or with minibuffer setup created key binding (isearch-like) M-e
44 ;; - M-e in empty initial provides completion on historicals
45 ;; - User can edit the entire path, changing the association
46 ;; - New association overrides previous
47 ;; - Deleting path removes association and history entry
48 ;; - Tracks buffer name changes
49 ;; - Using buffer-list-update-hook
50 ;; * Customize activation of savehist
51 ;; - Customize entry has warning about activating savehist
52 ;; - Adds the name/path association list to savehist-additional-variables
53 ;; - Activates savehist, if inactive
57 (defvar non-interactive-process-buffers '("*compilation*" "*grep*"))
62 (defgroup multishell nil
63 "Allout extension that highlights outline structure graphically.
65 Customize `allout-widgets-auto-activation' to activate allout-widgets
69 (defcustom multishell:non-interactive-process-buffers
70 '("*compilation*" "*grep*")
71 "Names of buffers that have processes but are not for interaction.
72 Add names of buffers that you don't want pop-to-shell to stick around in."
73 :type '(repeat string)
75 (defcustom multishell:command-key "\M- "
76 "The key to use if `multishell:activate-command-key' is true.
78 You can instead bind `pop-to-shell` to your preferred key using emacs
79 lisp, eg: (global-set-key \"\\M- \" 'pop-to-shell)."
83 (defvar multishell:responsible-for-command-key nil
84 "Multishell internal.")
85 (defun multishell:activate-command-key-setter (symbol setting)
86 "Implement `multishell:activate-command-key' choice."
87 (set-default 'multishell:activate-command-key setting)
88 (when (or setting multishell:responsible-for-command-key)
89 (multishell:implement-command-key-choice (not setting))))
90 (defun multishell:implement-command-key-choice (&optional unbind)
91 "If settings dicate, implement binding of multishell command key.
93 If optional UNBIND is true, globally unbind the key.
95 * `multishell:activate-command-key' - Set this to get the binding or not.
96 * `multishell:command-key' - The key to use for the binding, if appropriate."
98 (when (and (boundp 'multishell:command-key) multishell:command-key)
99 (global-unset-key multishell:command-key)))
100 ((not (and (boundp 'multishell:activate-command-key)
101 (boundp 'multishell:command-key)))
103 ((and multishell:activate-command-key multishell:command-key)
104 (setq multishell:responsible-for-command-key t)
105 (global-set-key multishell:command-key 'pop-to-shell))))
107 (defcustom multishell:activate-command-key nil
108 "Set this to impose the `multishell:command-key' binding.
110 You can instead bind `pop-to-shell` to your preferred key using emacs
111 lisp, eg: (global-set-key \"\\M- \" 'pop-to-shell)."
113 :set 'multishell:activate-command-key-setter
116 ;; Assert the customizations whenever the package is loaded:
117 (with-eval-after-load "multishell"
118 (multishell:implement-command-key-choice))
120 (defcustom multishell:pop-to-frame nil
121 "*If non-nil, jump to a frame already showing the shell, if another is.
123 Otherwise, open a new window in the current frame.
125 \(Adjust `pop-up-windows' to change other-buffer vs current-buffer behavior.)"
129 ;; (defcustom multishell:persist-shell-names nil
130 ;; "Remember shell name/path associations across sessions. Note well:
131 ;; This will activate minibuffer history persistence, in general, if it's not
136 (defvar multishell:name-path-assoc nil
137 "Assoc list from name to path")
139 (defvar multishell:primary-name "*shell*"
140 "Shell name to use for un-modified pop-to-shell buffer target.")
141 (defvar multishell:buffer-name-history nil
142 "Distinct pop-to-shell completion history container.")
144 (defun pop-to-shell (&optional arg)
145 "Easily navigate to and within multiple shell buffers, local and remote.
147 Use universal arguments to launch and choose between alternate
148 shell buffers and to select which is default. Prepend a path to
149 a new shell name to launch a shell in that directory, and use
150 Emacs tramp syntax to launch a remote shell.
152 Customize-group `multishell' to set up a key binding and tweak behaviors.
154 ==== Basic operation:
156 - If the current buffer is associated with a subprocess (that is
157 not among those named on `non-interactive-process-buffers'),
158 then focus is moved to the process input point.
160 \(You can use a universal argument go to a different shell
161 buffer when already in a buffer that has a process - see
164 - If not in a shell buffer (or with universal argument), go to a
165 window that is already showing the (a) shell buffer, if any.
167 In this case, the cursor is left in its prior position in the
168 shell buffer. Repeating the command will then go to the
169 process input point, per the first item in this list.
171 We respect `pop-up-windows', so you can adjust it to set the
172 other-buffer/same-buffer behavior.
174 - Otherwise, start a new shell buffer, using the current
175 directory as the working directory.
177 If a buffer with the resulting name exists and its shell process
178 was disconnected or otherwise stopped, it's resumed.
180 ===== Universal arg to start and select between named shell buffers:
182 You can name alternate shell buffers to create or return to using
183 single or doubled universal arguments:
185 - With a single universal argument, prompt for the buffer name
186 to use (without the asterisks that shell mode will put around
187 the name), defaulting to 'shell'.
189 Completion is available.
191 This combination makes it easy to start and switch between
192 multiple shell buffers.
194 - A double universal argument will prompt for the name *and* set
195 the default to that name, so the target shell becomes the
198 ===== Select starting directory and remote host:
200 The shell buffer name you give to the prompt for a universal arg
201 can include a preceding path. That will be used for the startup
202 directory. You can use tramp remote syntax to specify a remote
203 shell. If there is an element after a final '/', that's used for
204 the buffer name. Otherwise, the host, domain, or path is used.
208 * Use '/ssh:example.net:/' for a shell buffer on example.net named
210 * '/ssh:example.net|sudo:root@example.net:/\#ex' for a root shell on
211 example.net named \"#ex\"."
213 ;; I'm leaving the following out of the docstring for now because just
214 ;; saving the buffer names, and not the paths, yields sometimes unwanted
217 ;; ===== Persisting your alternate shell buffer names and paths:
219 ;; You can use emacs builtin SaveHist to preserve your alternate
220 ;; shell buffer names and paths across emacs sessions. To do so,
221 ;; customize the `savehist' group, and:
223 ;; 1. Add `multishell:pop-to-shell-buffer-name-history' to Savehist Additional
225 ;; 2. Activate Savehist Mode, if not already activated.
230 (let* ((from-buffer (current-buffer))
231 (from-buffer-is-shell (eq major-mode 'shell-mode))
232 (doublearg (equal arg '(16)))
234 (multishell:read-bare-shell-buffer-name
235 (format "Shell buffer name [%s]%s "
236 (substring-no-properties
237 multishell:primary-name
238 1 (- (length multishell:primary-name) 1))
239 (if doublearg " <==" ":"))
240 multishell:primary-name)
241 multishell:primary-name))
243 (target-shell-buffer-name
244 ;; Derive target name, and default-dir if any, from temp.
245 (cond ((string= temp "") multishell:primary-name)
246 ((string-match "^\\*\\(/.*/\\)\\(.*\\)\\*" temp)
247 (setq use-default-dir (match-string 1 temp))
248 (multishell:bracket-asterisks
249 (if (string= (match-string 2 temp) "")
250 (let ((v (tramp-dissect-file-name
252 (or (tramp-file-name-host v)
253 (tramp-file-name-domain v)
254 (tramp-file-name-localname v)
256 (match-string 2 temp))))
257 (t (multishell:bracket-asterisks temp))))
258 (curr-buff-proc (get-buffer-process from-buffer))
259 (target-buffer (if (and (or curr-buff-proc from-buffer-is-shell)
260 (not (member (buffer-name from-buffer)
261 non-interactive-process-buffers)))
263 (get-buffer target-shell-buffer-name)))
268 (setq multishell:primary-name target-shell-buffer-name))
274 ((and (or curr-buff-proc from-buffer-is-shell)
276 (eq from-buffer target-buffer)
277 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
278 ;; In a shell buffer, but not named - stay in buffer, but go to end.
279 (setq already-there t))
281 ((string= (buffer-name) target-shell-buffer-name)
282 ;; Already in the specified shell buffer:
283 (setq already-there t))
285 ((or (not target-buffer)
287 (multishell:get-visible-window-for-buffer target-buffer))))
288 ;; No preexisting shell buffer, or not in a visible window:
289 (pop-to-buffer target-shell-buffer-name pop-up-windows))
291 ;; Buffer exists and already has a window - jump to it:
292 (t (if (and multishell:pop-to-frame
294 (not (equal (window-frame (selected-window))
295 (window-frame inwin))))
296 (select-frame-set-input-focus (window-frame inwin)))
297 (if (not (string= (buffer-name (current-buffer))
298 target-shell-buffer-name))
299 (pop-to-buffer target-shell-buffer-name t))))
301 ;; We're in the buffer.
303 ;; If we have a use-default-dir, impose it:
304 (when use-default-dir
305 (cd use-default-dir))
309 (if (not (comint-check-proc (current-buffer)))
310 (multishell:start-shell-in-buffer (buffer-name (current-buffer))))
312 ;; If the destination buffer has a stopped process, resume it:
313 (let ((process (get-buffer-process (current-buffer))))
314 (if (and process (equal 'stop (process-status process)))
315 (continue-process process)))
316 (when (or already-there
317 (equal (current-buffer) from-buffer))
318 (goto-char (point-max))
319 (and (get-buffer-process from-buffer)
320 (goto-char (process-mark (get-buffer-process from-buffer)))))))
322 (defun multishell:get-visible-window-for-buffer (buffer)
323 "Return visible window containing buffer."
326 (function (lambda (win)
327 (if (and (eq (window-buffer win) buffer)
328 (equal (frame-parameter
329 (selected-frame) 'display)
331 (window-frame win) 'display)))
332 (throw 'got-a-vis win))))
336 (defun multishell:read-bare-shell-buffer-name (prompt default)
337 "PROMPT for shell buffer name, sans asterisks.
339 Return the supplied name bracketed with the asterisks, or specified DEFAULT
341 (let* ((candidates (append
343 (mapcar (lambda (buffer)
344 (let ((name (buffer-name buffer)))
345 (if (with-current-buffer buffer
346 (eq major-mode 'shell-mode))
347 ;; Shell mode buffers.
348 (if (> (length name) 2)
354 (got (completing-read prompt
355 candidates ; COLLECTION
357 'confirm ; REQUIRE-MATCH
359 'multishell:buffer-name-history ; HIST
361 (if (not (string= got "")) (multishell:bracket-asterisks got) default)))
363 (defun multishell:bracket-asterisks (name)
364 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
365 (if (not (string= (substring name 0 1) "*"))
366 (setq name (concat "*" name)))
367 (if (not (string= (substring name -1) "*"))
368 (setq name (concat name "*")))
370 (defun multishell:unbracket-asterisks (name)
371 "Return a copy of name, removing asterisks, if any, at beginning and end."
372 (if (string= (substring name 0 1) "*")
373 (setq name (substring name 1)))
374 (if (string= (substring name -1) "*")
375 (setq name (substring name 0 -1)))
377 (defun multishell:start-shell-in-buffer (buffer-name)
378 "Ensure a shell is started, using whatever name we're passed."
379 ;; We work around shell-mode's bracketing of the buffer name, and do
380 ;; some tramp-mode hygiene for remote connections.
385 (let* ((buffer buffer-name)
386 (prog (or explicit-shell-file-name
390 (name (file-name-nondirectory prog))
391 (startfile (concat "~/.emacs_" name))
392 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
393 (set-buffer buffer-name)
394 (when (and (file-remote-p default-directory)
395 (eq major-mode 'shell-mode)
396 (not (comint-check-proc (current-buffer))))
397 ;; We're returning to an already established but disconnected remote
399 (tramp-cleanup-connection
400 (tramp-dissect-file-name default-directory 'noexpand)
401 'keep-debug 'keep-password))
402 (setq buffer (set-buffer (apply 'make-comint
403 (multishell:unbracket-asterisks buffer-name)
405 (if (file-exists-p startfile)
409 (symbol-value xargs-name)
413 (provide 'multishell)
415 ;;; multishell.el ends here