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.")
143 (defvar multishell:buffer-name-path-history nil
144 "Another pop-to-shell completion history container, including paths.")
146 (defun pop-to-shell (&optional arg)
147 "Easily navigate to and within multiple shell buffers, local and remote.
149 Use universal arguments to launch and choose between alternate
150 shell buffers and to select which is default. Prepend a path to
151 a new shell name to launch a shell in that directory, and use
152 Emacs tramp syntax to launch a remote shell.
154 Customize-group `multishell' to set up a key binding and tweak behaviors.
156 ==== Basic operation:
158 - If the current buffer is associated with a subprocess (that is
159 not among those named on `non-interactive-process-buffers'),
160 then focus is moved to the process input point.
162 \(You can use a universal argument go to a different shell
163 buffer when already in a buffer that has a process - see
166 - If not in a shell buffer (or with universal argument), go to a
167 window that is already showing the (a) shell buffer, if any.
169 In this case, the cursor is left in its prior position in the
170 shell buffer. Repeating the command will then go to the
171 process input point, per the first item in this list.
173 We respect `pop-up-windows', so you can adjust it to set the
174 other-buffer/same-buffer behavior.
176 - Otherwise, start a new shell buffer, using the current
177 directory as the working directory.
179 If a buffer with the resulting name exists and its shell process
180 was disconnected or otherwise stopped, it's resumed.
182 ===== Universal arg to start and select between named shell buffers:
184 You can name alternate shell buffers to create or return to using
185 single or doubled universal arguments:
187 - With a single universal argument, prompt for the buffer name
188 to use (without the asterisks that shell mode will put around
189 the name), defaulting to 'shell'.
191 Completion is available.
193 This combination makes it easy to start and switch between
194 multiple shell buffers.
196 - A double universal argument will prompt for the name *and* set
197 the default to that name, so the target shell becomes the
200 ===== Select starting directory and remote host:
202 The shell buffer name you give to the prompt for a universal arg
203 can include a preceding path. That will be used for the startup
204 directory. You can use tramp remote syntax to specify a remote
205 shell. If there is an element after a final '/', that's used for
206 the buffer name. Otherwise, the host, domain, or path is used.
210 * Use '/ssh:example.net:/' for a shell buffer on example.net named
212 * '/ssh:example.net|sudo:root@example.net:/\#ex' for a root shell on
213 example.net named \"#ex\"."
215 ;; I'm leaving the following out of the docstring for now because just
216 ;; saving the buffer names, and not the paths, yields sometimes unwanted
219 ;; ===== Persisting your alternate shell buffer names and paths:
221 ;; You can use emacs builtin SaveHist to preserve your alternate
222 ;; shell buffer names and paths across emacs sessions. To do so,
223 ;; customize the `savehist' group, and:
225 ;; 1. Add `multishell:pop-to-shell-buffer-name-history' to Savehist Additional
227 ;; 2. Activate Savehist Mode, if not already activated.
232 (let* ((from-buffer (current-buffer))
233 (from-buffer-is-shell (eq major-mode 'shell-mode))
234 (doublearg (equal arg '(16)))
235 (target-name-and-path
236 (multishell:derive-target-name-and-path
238 (multishell:read-bare-shell-buffer-name
239 (format "Shell buffer name [%s]%s "
240 (substring-no-properties
241 multishell:primary-name
242 1 (- (length multishell:primary-name) 1))
243 (if doublearg " <==" ":"))
244 multishell:primary-name)
245 multishell:primary-name)))
246 (use-default-dir (cadr target-name-and-path))
247 (target-shell-buffer-name (car target-name-and-path))
248 (curr-buff-proc (get-buffer-process from-buffer))
249 (target-buffer (if (and (or curr-buff-proc from-buffer-is-shell)
250 (not (member (buffer-name from-buffer)
251 non-interactive-process-buffers)))
253 (get-buffer target-shell-buffer-name)))
258 (setq multishell:primary-name target-shell-buffer-name))
264 ((and (or curr-buff-proc from-buffer-is-shell)
266 (eq from-buffer target-buffer)
267 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
268 ;; In a shell buffer, but not named - stay in buffer, but go to end.
269 (setq already-there t))
271 ((string= (buffer-name) target-shell-buffer-name)
272 ;; Already in the specified shell buffer:
273 (setq already-there t))
275 ((or (not target-buffer)
277 (multishell:get-visible-window-for-buffer target-buffer))))
278 ;; No preexisting shell buffer, or not in a visible window:
279 (pop-to-buffer target-shell-buffer-name pop-up-windows))
281 ;; Buffer exists and already has a window - jump to it:
282 (t (if (and multishell:pop-to-frame
284 (not (equal (window-frame (selected-window))
285 (window-frame inwin))))
286 (select-frame-set-input-focus (window-frame inwin)))
287 (if (not (string= (buffer-name (current-buffer))
288 target-shell-buffer-name))
289 (pop-to-buffer target-shell-buffer-name t))))
291 ;; We're in the buffer.
294 (when (not (comint-check-proc (current-buffer)))
295 (multishell:start-shell-in-buffer (buffer-name (current-buffer))))
296 ;; If we have a use-default-dir, impose it:
297 (when use-default-dir
298 (cd use-default-dir))
300 ;; If the destination buffer has a stopped process, resume it:
301 (let ((process (get-buffer-process (current-buffer))))
302 (if (and process (equal 'stop (process-status process)))
303 (continue-process process)))
304 (when (or already-there
305 (equal (current-buffer) from-buffer))
306 (goto-char (point-max))
307 (and (get-buffer-process from-buffer)
308 (goto-char (process-mark (get-buffer-process from-buffer)))))))
310 (defun multishell:get-visible-window-for-buffer (buffer)
311 "Return visible window containing buffer."
314 (function (lambda (win)
315 (if (and (eq (window-buffer win) buffer)
316 (equal (frame-parameter
317 (selected-frame) 'display)
319 (window-frame win) 'display)))
320 (throw 'got-a-vis win))))
324 (defun multishell:read-bare-shell-buffer-name (prompt default)
325 "PROMPT for shell buffer name, sans asterisks.
327 Return the supplied name bracketed with the asterisks, or specified DEFAULT
329 (let* ((candidates (append
331 (mapcar (lambda (buffer)
332 (let ((name (buffer-name buffer)))
333 (if (with-current-buffer buffer
334 (eq major-mode 'shell-mode))
335 ;; Shell mode buffers.
336 (if (> (length name) 2)
342 (got (completing-read prompt
343 candidates ; COLLECTION
345 'confirm ; REQUIRE-MATCH
347 'multishell:buffer-name-history ; HIST
349 (if (not (string= got "")) (multishell:bracket-asterisks got) default)))
350 (defun multishell:derive-target-name-and-path (path-ish)
351 "Give tramp-style PATH-ISH, determine target name and default directory.
353 The name is the part of the string after the final '/' slash, if
354 any. Otherwise, it's either the host-name, domain-name, or local
355 host name. The path is everything besides the string following
358 Return them as a list (name dir), with dir nil if none given."
359 (let (name (path "") dir)
360 (cond ((string= path-ish "") (setq dir multishell:primary-name))
361 ((string-match "^\\*\\(/.*/\\)\\(.*\\)\\*" path-ish)
362 (setq path (match-string 1 path-ish))
364 (multishell:bracket-asterisks
365 (if (string= (match-string 2 path-ish) "")
366 (let ((v (tramp-dissect-file-name
368 (or (tramp-file-name-host v)
369 (tramp-file-name-domain v)
370 (tramp-file-name-localname v)
372 (match-string 2 path-ish)))))
373 (t (setq name (multishell:bracket-asterisks path-ish))))
376 (defun multishell:bracket-asterisks (name)
377 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
378 (if (not (string= (substring name 0 1) "*"))
379 (setq name (concat "*" name)))
380 (if (not (string= (substring name -1) "*"))
381 (setq name (concat name "*")))
383 (defun multishell:unbracket-asterisks (name)
384 "Return a copy of name, removing asterisks, if any, at beginning and end."
385 (if (string= (substring name 0 1) "*")
386 (setq name (substring name 1)))
387 (if (string= (substring name -1) "*")
388 (setq name (substring name 0 -1)))
390 (defun multishell:start-shell-in-buffer (buffer-name)
391 "Ensure a shell is started, using whatever name we're passed."
392 ;; We work around shell-mode's bracketing of the buffer name, and do
393 ;; some tramp-mode hygiene for remote connections.
395 (let* ((buffer buffer-name)
396 (prog (or explicit-shell-file-name
400 (name (file-name-nondirectory prog))
401 (startfile (concat "~/.emacs_" name))
402 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
403 (set-buffer buffer-name)
404 (when (and (file-remote-p default-directory)
405 (eq major-mode 'shell-mode)
406 (not (comint-check-proc (current-buffer))))
407 ;; We're returning to an already established but disconnected remote
409 (tramp-cleanup-connection
410 (tramp-dissect-file-name default-directory 'noexpand)
411 '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