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' -
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 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 ;; * Append 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 multishell-pop-to-shell docstring for details.
31 ;; 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
35 ;; * Preserveable (savehist) history that associates names with paths
36 ;; - Using an association list between names and paths
37 ;; - Searched for search backwards/forwards on isearch-like M-r/M-s bindings
38 ;; - *Not* searched for regular completion
40 ;; - New shell prompts for confirmation
41 ;; - Including path from history, if any
42 ;; - which offers opportunity to edit association
43 ;; - New association overrides previous
44 ;; - History tracks buffer disposition
45 ;; - Track buffer name change using buffer-list-update-hook
46 ;; - Deleting buffer removes history entry!
47 ;; - Option to track last directory - multishell-remember-last-dir
48 ;; - Include note about tramp not tracking remote dirs well
49 ;; - use `M-x shell-resync-dirs'; I bind to M-return
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
60 (defgroup multishell nil
61 "Allout extension that highlights outline structure graphically.
63 Customize `allout-widgets-auto-activation' to activate allout-widgets
67 (defcustom multishell-command-key "\M- "
68 "The key to use if `multishell-activate-command-key' is true.
70 You can instead manually bind `multishell-pop-to-shell` using emacs
71 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
75 (defvar multishell--responsible-for-command-key nil
76 "Multishell internal.")
77 (defun multishell-activate-command-key-setter (symbol setting)
78 "Implement `multishell-activate-command-key' choice."
79 (set-default 'multishell-activate-command-key setting)
80 (when (or setting multishell--responsible-for-command-key)
81 (multishell-implement-command-key-choice (not setting))))
82 (defun multishell-implement-command-key-choice (&optional unbind)
83 "If settings dicate, implement binding of multishell command key.
85 If optional UNBIND is true, globally unbind the key.
87 * `multishell-activate-command-key' - Set this to get the binding or not.
88 * `multishell-command-key' - The key to use for the binding, if appropriate."
90 (when (and (boundp 'multishell-command-key) multishell-command-key)
91 (global-unset-key multishell-command-key)))
92 ((not (and (boundp 'multishell-activate-command-key)
93 (boundp 'multishell-command-key)))
95 ((and multishell-activate-command-key multishell-command-key)
96 (setq multishell--responsible-for-command-key t)
97 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
99 (defcustom multishell-activate-command-key nil
100 "Set this to impose the `multishell-command-key' binding.
102 You can instead manually bind `multishell-pop-to-shell` using emacs
103 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
105 :set 'multishell-activate-command-key-setter
108 ;; Assert the customizations whenever the package is loaded:
109 (with-eval-after-load "multishell"
110 (multishell-implement-command-key-choice))
112 (defcustom multishell-pop-to-frame nil
113 "*If non-nil, jump to a frame already showing the shell, if another is.
115 Otherwise, disregard already-open windows on the shell if they're
116 in another frame, and open a new window on the shell in the
119 \(Use `pop-up-windows' to change multishell other-buffer vs
120 current-buffer behavior.)"
124 ;; (defcustom multishell-persist-shell-names nil
125 ;; "Remember shell name/path associations across sessions. Note well:
126 ;; This will activate minibuffer history persistence, in general, if it's not
131 (defvar multishell-name-path-assoc nil
132 "Assoc list from name to path")
134 (defvar multishell-primary-name "*shell*"
135 "Shell name to use for un-modified multishell-pop-to-shell buffer target.")
136 (defvar multishell-buffer-name-history nil
137 "Distinct multishell-pop-to-shell completion history container.")
138 (defvar multishell-buffer-name-path-history nil
139 "Another multishell-pop-to-shell completion history container,
142 (defun multishell-pop-to-shell (&optional arg)
143 "Easily navigate to and within multiple shell buffers, local and remote.
145 Use universal arguments to launch and choose between alternate
146 shell buffers and to select which is default. Append a path to
147 a new shell name to launch a shell in that directory, and use
148 Emacs tramp syntax to launch a remote shell.
150 Customize-group `multishell' to set up a key binding and tweak behaviors.
152 ==== Basic operation:
154 - If the current buffer is shell-mode (or shell-mode derived)
155 buffer then focus is moved to the process input point.
157 \(You can use a universal argument go to a different shell
158 buffer when already in a buffer that has a process - see
161 - If not in a shell buffer (or with universal argument), go to a
162 window that is already showing the (a) shell buffer, if any.
164 In this case, the cursor is left in its prior position in the
165 shell buffer. Repeating the command will then go to the
166 process input point, per the first item in this list.
168 We respect `pop-up-windows', so you can adjust it to set the
169 other-buffer/same-buffer behavior.
171 - Otherwise, start a new shell buffer, using the current
172 directory as the working directory.
174 If a buffer with the resulting name exists and its shell process
175 was disconnected or otherwise stopped, it's resumed.
177 ===== Universal arg to start and select between named shell buffers:
179 You can name alternate shell buffers to create or return to using
180 single or doubled universal arguments:
182 - With a single universal argument, prompt for the buffer name
183 to use (without the asterisks that shell mode will put around
184 the name), defaulting to 'shell'.
186 Completion is available.
188 This combination makes it easy to start and switch between
189 multiple shell buffers.
191 - A double universal argument will prompt for the name *and* set
192 the default to that name, so the target shell becomes the
195 ===== Select starting directory and remote host:
197 The shell buffer name you give to the prompt for a universal arg
198 can include an appended path. That will be used for the startup
199 directory. You can use tramp remote syntax to specify a remote
200 shell. If there is an element after a final '/', that's used for
201 the buffer name. Otherwise, the host, domain, or path is used.
205 * Use '/ssh:example.net:/' for a shell buffer on example.net named
207 * '\#ex/ssh:example.net|sudo:root@example.net:/' for a root shell on
208 example.net named \"#ex\"."
210 ;; I'm leaving the following out of the docstring for now because just
211 ;; saving the buffer names, and not the paths, yields sometimes unwanted
214 ;; ===== Persisting your alternate shell buffer names and paths:
216 ;; You can use emacs builtin SaveHist to preserve your alternate
217 ;; shell buffer names and paths across emacs sessions. To do so,
218 ;; customize the `savehist' group, and:
220 ;; 1. Add `multishell-pop-to-shell-buffer-name-history' to Savehist Additional
222 ;; 2. Activate Savehist Mode, if not already activated.
227 (let* ((from-buffer (current-buffer))
228 (from-buffer-is-shell (derived-mode-p 'shell-mode))
229 (doublearg (equal arg '(16)))
230 (target-name-and-path
231 (multishell-derive-target-name-and-path
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)))
241 (use-default-dir (cadr target-name-and-path))
242 (target-shell-buffer-name (car target-name-and-path))
243 (curr-buff-proc (get-buffer-process from-buffer))
244 (target-buffer (if from-buffer-is-shell
246 (get-buffer target-shell-buffer-name)))
251 (setq multishell-primary-name target-shell-buffer-name))
257 ((and (or curr-buff-proc from-buffer-is-shell)
259 (eq from-buffer target-buffer)
260 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
261 ;; In a shell buffer, but not named - stay in buffer, but go to end.
262 (setq already-there t))
264 ((string= (buffer-name) target-shell-buffer-name)
265 ;; Already in the specified shell buffer:
266 (setq already-there t))
268 ((or (not target-buffer)
270 (multishell-get-visible-window-for-buffer target-buffer))))
271 ;; No preexisting shell buffer, or not in a visible window:
272 (pop-to-buffer target-shell-buffer-name pop-up-windows))
274 ;; Buffer exists and already has a window - jump to it:
275 (t (if (and multishell-pop-to-frame
277 (not (equal (window-frame (selected-window))
278 (window-frame inwin))))
279 (select-frame-set-input-focus (window-frame inwin)))
280 (if (not (string= (buffer-name (current-buffer))
281 target-shell-buffer-name))
282 (pop-to-buffer target-shell-buffer-name t))))
284 ;; We're in the buffer. Activate:
286 (cond ((not (comint-check-proc (current-buffer)))
287 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
290 (cd use-default-dir)))
292 ;; If the destination buffer has a stopped process, resume it:
293 (let ((process (get-buffer-process (current-buffer))))
294 (if (and process (equal 'stop (process-status process)))
295 (continue-process process)))
296 (when (or already-there
297 (equal (current-buffer) from-buffer))
298 (goto-char (point-max))
299 (and (get-buffer-process from-buffer)
300 (goto-char (process-mark (get-buffer-process from-buffer)))))))
302 (defun multishell-get-visible-window-for-buffer (buffer)
303 "Return visible window containing buffer."
306 (function (lambda (win)
307 (if (and (eq (window-buffer win) buffer)
308 (equal (frame-parameter
309 (selected-frame) 'display)
311 (window-frame win) 'display)))
312 (throw 'got-a-vis win))))
316 (defun multishell-read-bare-shell-buffer-name (prompt default)
317 "PROMPT for shell buffer name, sans asterisks.
319 Return the supplied name bracketed with the asterisks, or specified DEFAULT
321 (let* ((candidates (append
323 (mapcar (lambda (buffer)
324 (let ((name (buffer-name buffer)))
325 (if (with-current-buffer buffer
326 (derived-mode-p 'shell-mode))
327 ;; Shell mode buffers.
328 (if (> (length name) 2)
334 (got (completing-read prompt
335 candidates ; COLLECTION
337 'confirm ; REQUIRE-MATCH
339 'multishell-buffer-name-history ; HIST
341 (if (not (string= got "")) (multishell-bracket-asterisks got) default)))
342 (defun multishell-derive-target-name-and-path (path-ish)
343 "Give tramp-style PATH-ISH, determine target name and default directory.
345 The name is the part of the string before the initial '/' slash,
346 if any. Otherwise, it's either the host-name, domain-name, final
347 directory name, or local host name. The path is everything
348 besides the string before the initial '/' slash.
350 Return them as a list (name dir), with dir nil if none given."
351 (let (name (path "") dir)
352 (cond ((string= path-ish "") (setq dir multishell-primary-name))
353 ((string-match "^\\*\\([^/]*\\)\\(/.*/\\)\\(.*\\)\\*" path-ish)
354 ;; We have a path, use it
355 (let ((overt-name (match-string 1 path-ish))
356 (overt-path (match-string 2 path-ish))
357 (trailing-name (match-string 3 path-ish)))
358 (if (string= overt-name "") (setq overt-name nil))
359 (if (string= overt-path "") (setq overt-path nil))
360 (if (string= trailing-name "") (setq trailing-name nil))
361 (setq path (concat overt-path trailing-name))
363 (multishell-bracket-asterisks
365 (if (file-remote-p path)
366 (let ((vec (tramp-dissect-file-name path)))
367 (or (tramp-file-name-host vec)
368 (tramp-file-name-domain vec)
369 (tramp-file-name-localname vec)
372 (multishell-unbracket-asterisks
373 multishell-primary-name)))))))
374 (t (setq name (multishell-bracket-asterisks path-ish))))
377 (defun multishell-bracket-asterisks (name)
378 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
379 (if (not (string= (substring name 0 1) "*"))
380 (setq name (concat "*" name)))
381 (if (not (string= (substring name -1) "*"))
382 (setq name (concat name "*")))
384 (defun multishell-unbracket-asterisks (name)
385 "Return a copy of name, removing asterisks, if any, at beginning and end."
386 (if (string= (substring name 0 1) "*")
387 (setq name (substring name 1)))
388 (if (string= (substring name -1) "*")
389 (setq name (substring name 0 -1)))
392 (defun multishell-start-shell-in-buffer (buffer-name path)
393 "Ensure a shell is started, with name NAME and PATH."
394 ;; We work around shell-mode's bracketing of the buffer name, and do
395 ;; some tramp-mode hygiene for remote connections.
397 (let* ((buffer buffer-name)
398 (prog (or explicit-shell-file-name
402 (name (file-name-nondirectory prog))
403 (startfile (concat "~/.emacs_" name))
404 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
405 (set-buffer buffer-name)
406 (if (and path (not (string= path "")))
407 (setq default-directory path))
408 (when (and (file-remote-p default-directory)
409 (derived-mode-p 'shell-mode)
410 (not (comint-check-proc (current-buffer))))
411 ;; We're returning to an already established but disconnected remote
413 (tramp-cleanup-connection
414 (tramp-dissect-file-name default-directory 'noexpand)
415 'keep-debug 'keep-password))
416 ;; (cd default-directory) will reconnect a disconnected remote:
417 (cd default-directory)
418 (setq buffer (set-buffer (apply 'make-comint
419 (multishell-unbracket-asterisks buffer-name)
421 (if (file-exists-p startfile)
425 (symbol-value xargs-name)
429 (provide 'multishell)
431 ;;; multishell.el ends here