]> code.delx.au - gnu-emacs-elpa/blob - multishell.el
d4470b72f38e3dcbab8dd8281a3b3ef9603412ca
[gnu-emacs-elpa] / multishell.el
1 ;;; multishell.el --- manage interaction with multiple local and remote shells
2
3 ;; Copyright (C) 1999-2016 Free Software Foundation, Inc. and Ken Manheimer
4
5 ;; Author: Ken Manheimer <ken.manheimer@gmail.com>
6 ;; Version: 1.0.4
7 ;; Created: 1999 -- first public availability
8 ;; Keywords: processes
9 ;; URL: https://github.com/kenmanheimer/EmacsUtils
10 ;;
11 ;;; Commentary:
12 ;;
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:
16 ;;
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.
23 ;;
24 ;; Customize-group `multishell` to select and activate a keybinding and set
25 ;; various behaviors.
26 ;;
27 ;; See the multishell-pop-to-shell docstring for details.
28 ;;
29 ;;; Change Log:
30 ;;
31 ;; 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
32 ;;
33 ;;; TODO:
34 ;;
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
39 ;; - Editible
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
54
55 ;;; Code:
56
57 (require 'comint)
58 (require 'shell)
59
60 (defgroup multishell nil
61 "Allout extension that highlights outline structure graphically.
62
63 Customize `allout-widgets-auto-activation' to activate allout-widgets
64 with allout-mode."
65 :group 'shell)
66
67 (defcustom multishell-command-key "\M- "
68 "The key to use if `multishell-activate-command-key' is true.
69
70 You can instead manually bind `multishell-pop-to-shell` using emacs
71 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
72 :type 'key-sequence
73 :group 'multishell)
74
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.
84
85 If optional UNBIND is true, globally unbind the key.
86
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."
89 (cond (unbind
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)))
94 nil)
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))))
98
99 (defcustom multishell-activate-command-key nil
100 "Set this to impose the `multishell-command-key' binding.
101
102 You can instead manually bind `multishell-pop-to-shell` using emacs
103 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
104 :type 'boolean
105 :set 'multishell-activate-command-key-setter
106 :group 'multishell)
107
108 ;; Assert the customizations whenever the package is loaded:
109 (with-eval-after-load "multishell"
110 (multishell-implement-command-key-choice))
111
112 (defcustom multishell-pop-to-frame nil
113 "*If non-nil, jump to a frame already showing the shell, if another is.
114
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
117 current frame.
118
119 \(Use `pop-up-windows' to change multishell other-buffer vs
120 current-buffer behavior.)"
121 :type 'boolean
122 :group 'multishell)
123
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
127 ;; already active."
128 ;; :type 'boolean
129 ;; :group 'shell)
130
131 (defvar multishell-name-path-assoc nil
132 "Assoc list from name to path")
133
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,
140 including paths.")
141
142 (defun multishell-pop-to-shell (&optional arg)
143 "Easily navigate to and within multiple shell buffers, local and remote.
144
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.
149
150 Customize-group `multishell' to set up a key binding and tweak behaviors.
151
152 ==== Basic operation:
153
154 - If the current buffer is shell-mode (or shell-mode derived)
155 buffer then focus is moved to the process input point.
156
157 \(You can use a universal argument go to a different shell
158 buffer when already in a buffer that has a process - see
159 below.)
160
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.
163
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.
167
168 We respect `pop-up-windows', so you can adjust it to set the
169 other-buffer/same-buffer behavior.
170
171 - Otherwise, start a new shell buffer, using the current
172 directory as the working directory.
173
174 If a buffer with the resulting name exists and its shell process
175 was disconnected or otherwise stopped, it's resumed.
176
177 ===== Universal arg to start and select between named shell buffers:
178
179 You can name alternate shell buffers to create or return to using
180 single or doubled universal arguments:
181
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'.
185
186 Completion is available.
187
188 This combination makes it easy to start and switch between
189 multiple shell buffers.
190
191 - A double universal argument will prompt for the name *and* set
192 the default to that name, so the target shell becomes the
193 primary.
194
195 ===== Select starting directory and remote host:
196
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.
202
203 For example:
204
205 * Use '/ssh:example.net:/' for a shell buffer on example.net named
206 \"example.net\".
207 * '\#ex/ssh:example.net|sudo:root@example.net:/' for a root shell on
208 example.net named \"#ex\"."
209
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
212 ;; behavior.
213
214 ;; ===== Persisting your alternate shell buffer names and paths:
215
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:
219
220 ;; 1. Add `multishell-pop-to-shell-buffer-name-history' to Savehist Additional
221 ;; Variables.
222 ;; 2. Activate Savehist Mode, if not already activated.
223 ;; 3. Save.
224
225 (interactive "P")
226
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
232 (if arg
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
245 from-buffer
246 (get-buffer target-shell-buffer-name)))
247 inwin
248 already-there)
249
250 (when doublearg
251 (setq multishell-primary-name target-shell-buffer-name))
252
253 ;; Situate:
254
255 (cond
256
257 ((and (or curr-buff-proc from-buffer-is-shell)
258 (not arg)
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))
263
264 ((string= (buffer-name) target-shell-buffer-name)
265 ;; Already in the specified shell buffer:
266 (setq already-there t))
267
268 ((or (not target-buffer)
269 (not (setq inwin
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))
273
274 ;; Buffer exists and already has a window - jump to it:
275 (t (if (and multishell-pop-to-frame
276 inwin
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))))
283
284 ;; We're in the buffer. Activate:
285
286 (cond ((not (comint-check-proc (current-buffer)))
287 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
288 use-default-dir))
289 (use-default-dir
290 (cd use-default-dir)))
291
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)))))))
301
302 (defun multishell-get-visible-window-for-buffer (buffer)
303 "Return visible window containing buffer."
304 (catch 'got-a-vis
305 (walk-windows
306 (function (lambda (win)
307 (if (and (eq (window-buffer win) buffer)
308 (equal (frame-parameter
309 (selected-frame) 'display)
310 (frame-parameter
311 (window-frame win) 'display)))
312 (throw 'got-a-vis win))))
313 nil 'visible)
314 nil))
315
316 (defun multishell-read-bare-shell-buffer-name (prompt default)
317 "PROMPT for shell buffer name, sans asterisks.
318
319 Return the supplied name bracketed with the asterisks, or specified DEFAULT
320 on empty input."
321 (let* ((candidates (append
322 (remq nil
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)
329 ;; Strip asterisks.
330 (substring name 1
331 (1- (length name)))
332 name))))
333 (buffer-list)))))
334 (got (completing-read prompt
335 candidates ; COLLECTION
336 nil ; PREDICATE
337 'confirm ; REQUIRE-MATCH
338 nil ; INITIAL-INPUT
339 'multishell-buffer-name-history ; HIST
340 )))
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.
344
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.
349
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))
362 (setq name
363 (multishell-bracket-asterisks
364 (or overt-name
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)
370 trailing-name
371 system-name))
372 (multishell-unbracket-asterisks
373 multishell-primary-name)))))))
374 (t (setq name (multishell-bracket-asterisks path-ish))))
375 (list name path)))
376
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 "*")))
383 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)))
390 name)
391
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.
396
397 (let* ((buffer buffer-name)
398 (prog (or explicit-shell-file-name
399 (getenv "ESHELL")
400 (getenv "SHELL")
401 "/bin/sh"))
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
412 ;; shell, tidy it:
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)
420 prog
421 (if (file-exists-p startfile)
422 startfile)
423 (if (and xargs-name
424 (boundp xargs-name))
425 (symbol-value xargs-name)
426 '("-i")))))
427 (shell-mode)))
428
429 (provide 'multishell)
430
431 ;;; multishell.el ends here