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 ;; * 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.")
143 (defun pop-to-shell (&optional arg)
144 "Easily navigate to and within multiple shell buffers, local and remote.
146 Use universal arguments to launch and choose between alternate
147 shell buffers and to select which is default. Prepend a path to
148 a new shell name to launch a shell in that directory, and use
149 Emacs tramp syntax to launch a remote shell.
151 Customize-group `multishell' to set up a key binding and tweak behaviors.
153 ==== Basic operation:
155 - If the current buffer is associated with a subprocess (that is
156 not among those named on `non-interactive-process-buffers'),
157 then focus is moved to the process input point.
159 \(You can use a universal argument go to a different shell
160 buffer when already in a buffer that has a process - see
163 - If not in a shell buffer (or with universal argument), go to a
164 window that is already showing the (a) shell buffer, if any.
166 In this case, the cursor is left in its prior position in the
167 shell buffer. Repeating the command will then go to the
168 process input point, per the first item in this list.
170 We respect `pop-up-windows', so you can adjust it to set the
171 other-buffer/same-buffer behavior.
173 - Otherwise, start a new shell buffer, using the current
174 directory as the working directory.
176 If a buffer with the resulting name exists and its shell process
177 was disconnected or otherwise stopped, it's resumed.
179 ===== Universal arg to start and select between named shell buffers:
181 You can name alternate shell buffers to create or return to using
182 single or doubled universal arguments:
184 - With a single universal argument, prompt for the buffer name
185 to use (without the asterisks that shell mode will put around
186 the name), defaulting to 'shell'.
188 Completion is available.
190 This combination makes it easy to start and switch between
191 multiple shell buffers.
193 - A double universal argument will prompt for the name *and* set
194 the default to that name, so the target shell becomes the
197 ===== Select starting directory and remote host:
199 The shell buffer name you give to the prompt for a universal arg
200 can include a preceding path. That will be used for the startup
201 directory. You can use tramp remote syntax to specify a remote
202 shell. If there is an element after a final '/', that's used for
203 the buffer name. Otherwise, the host, domain, or path is used.
207 * Use '/ssh:example.net:/' for a shell buffer on example.net named
209 * '/ssh:example.net|sudo:root@example.net:/\#ex' for a root shell on
210 example.net named \"#ex\"."
212 ;; I'm leaving the following out of the docstring for now because just
213 ;; saving the buffer names, and not the paths, yields sometimes unwanted
216 ;; ===== Persisting your alternate shell buffer names and paths:
218 ;; You can use emacs builtin SaveHist to preserve your alternate
219 ;; shell buffer names and paths across emacs sessions. To do so,
220 ;; customize the `savehist' group, and:
222 ;; 1. Add `multishell:pop-to-shell-buffer-name-history' to Savehist Additional
224 ;; 2. Activate Savehist Mode, if not already activated.
229 (let* ((from-buffer (current-buffer))
230 (from-buffer-is-shell (eq major-mode 'shell-mode))
231 (doublearg (equal arg '(16)))
233 (multishell:read-bare-shell-buffer-name
234 (format "Shell buffer name [%s]%s "
235 (substring-no-properties
236 multishell:primary-name
237 1 (- (length multishell:primary-name) 1))
238 (if doublearg " <==" ":"))
239 multishell:primary-name)
240 multishell:primary-name))
242 (target-shell-buffer-name
243 ;; Derive target name, and default-dir if any, from temp.
244 (cond ((string= temp "") multishell:primary-name)
245 ((string-match "^\\*\\(/.*/\\)\\(.*\\)\\*" temp)
246 (setq use-default-dir (match-string 1 temp))
247 (multishell:bracket-asterisks
248 (if (string= (match-string 2 temp) "")
249 (let ((v (tramp-dissect-file-name
251 (or (tramp-file-name-host v)
252 (tramp-file-name-domain v)
253 (tramp-file-name-localname v)
255 (match-string 2 temp))))
256 (t (multishell:bracket-asterisks temp))))
257 (curr-buff-proc (get-buffer-process from-buffer))
258 (target-buffer (if (and (or curr-buff-proc from-buffer-is-shell)
259 (not (member (buffer-name from-buffer)
260 non-interactive-process-buffers)))
262 (get-buffer target-shell-buffer-name)))
267 (setq multishell:primary-name target-shell-buffer-name))
273 ((and (or curr-buff-proc from-buffer-is-shell)
275 (eq from-buffer target-buffer)
276 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
277 ;; In a shell buffer, but not named - stay in buffer, but go to end.
278 (setq already-there t))
280 ((string= (buffer-name) target-shell-buffer-name)
281 ;; Already in the specified shell buffer:
282 (setq already-there t))
284 ((or (not target-buffer)
286 (multishell:get-visible-window-for-buffer target-buffer))))
287 ;; No preexisting shell buffer, or not in a visible window:
288 (pop-to-buffer target-shell-buffer-name pop-up-windows))
290 ;; Buffer exists and already has a window - jump to it:
291 (t (if (and multishell:pop-to-frame
293 (not (equal (window-frame (selected-window))
294 (window-frame inwin))))
295 (select-frame-set-input-focus (window-frame inwin)))
296 (if (not (string= (buffer-name (current-buffer))
297 target-shell-buffer-name))
298 (pop-to-buffer target-shell-buffer-name t))))
300 ;; We're in the buffer.
302 ;; If we have a use-default-dir, impose it:
303 (when use-default-dir
304 (cd use-default-dir))
308 (if (not (comint-check-proc (current-buffer)))
309 (multishell:start-shell-in-buffer (buffer-name (current-buffer))))
311 ;; If the destination buffer has a stopped process, resume it:
312 (let ((process (get-buffer-process (current-buffer))))
313 (if (and process (equal 'stop (process-status process)))
314 (continue-process process)))
315 (when (or already-there
316 (equal (current-buffer) from-buffer))
317 (goto-char (point-max))
318 (and (get-buffer-process from-buffer)
319 (goto-char (process-mark (get-buffer-process from-buffer)))))))
321 (defun multishell:get-visible-window-for-buffer (buffer)
322 "Return visible window containing buffer."
325 (function (lambda (win)
326 (if (and (eq (window-buffer win) buffer)
327 (equal (frame-parameter
328 (selected-frame) 'display)
330 (window-frame win) 'display)))
331 (throw 'got-a-vis win))))
335 (defun multishell:read-bare-shell-buffer-name (prompt default)
336 "PROMPT for shell buffer name, sans asterisks.
338 Return the supplied name bracketed with the asterisks, or specified DEFAULT
340 (let* ((candidates (append
342 (mapcar (lambda (buffer)
343 (let ((name (buffer-name buffer)))
344 (if (with-current-buffer buffer
345 (eq major-mode 'shell-mode))
346 ;; Shell mode buffers.
347 (if (> (length name) 2)
353 (got (completing-read prompt
354 candidates ; COLLECTION
356 'confirm ; REQUIRE-MATCH
358 'multishell:buffer-name-history ; HIST
360 (if (not (string= got "")) (multishell:bracket-asterisks got) default)))
362 (defun multishell:bracket-asterisks (name)
363 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
364 (if (not (string= (substring name 0 1) "*"))
365 (setq name (concat "*" name)))
366 (if (not (string= (substring name -1) "*"))
367 (setq name (concat name "*")))
369 (defun multishell:unbracket-asterisks (name)
370 "Return a copy of name, removing asterisks, if any, at beginning and end."
371 (if (string= (substring name 0 1) "*")
372 (setq name (substring name 1)))
373 (if (string= (substring name -1) "*")
374 (setq name (substring name 0 -1)))
376 (defun multishell:start-shell-in-buffer (buffer-name)
377 "Ensure a shell is started, using whatever name we're passed."
378 ;; We work around shell-mode's bracketing of the buffer name, and do
379 ;; some tramp-mode hygiene for remote connections.
384 (let* ((buffer buffer-name)
385 (prog (or explicit-shell-file-name
389 (name (file-name-nondirectory prog))
390 (startfile (concat "~/.emacs_" name))
391 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
392 (set-buffer buffer-name)
393 (when (and (file-remote-p default-directory)
394 (eq major-mode 'shell-mode)
395 (not (comint-check-proc (current-buffer))))
396 ;; We're returning to an already established but disconnected remote
398 (tramp-cleanup-connection
399 (tramp-dissect-file-name default-directory 'noexpand)
400 'keep-debug 'keep-password))
401 (setq buffer (set-buffer (apply 'make-comint
402 (multishell:unbracket-asterisks buffer-name)
404 (if (file-exists-p startfile)
408 (symbol-value xargs-name)
412 (provide 'multishell)
414 ;;; multishell.el ends here