]> code.delx.au - gnu-emacs-elpa/blob - multishell.el
e1fdbf8980dba9834bdc6c59d57e98796dc375bd
[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.5
7 ;; Created: 1999 -- first public availability
8 ;; Keywords: processes
9 ;; URL: https://github.com/kenmanheimer/EmacsUtils
10 ;;
11 ;;; Commentary:
12 ;;
13 ;; Easily use and navigate 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 ;; - Editible
37 ;; - New shell prompts for confirmation
38 ;; - Including path from history, if any
39 ;; - which offers opportunity to entry
40 ;; - ?completions list toggles between short and long?
41 ;; - "Toggle short/long listing by immediately repeating completion key"
42 ;; - History tracks buffer disposition
43 ;; - Deleting buffer removes history entry
44 ;; - Track buffer name change using buffer-list-update-hook
45 ;; - Option to track last directory - multishell-remember-last-dir
46 ;; - dig into tramp to find out where the actual remote+dir path is
47 ;; - Include note about tramp not tracking remote dir changes well
48 ;; - use `M-x shell-resync-dirs'; I bind to M-return
49 ;; * Note in multishell doc to activate (customize) savehist to preserve history
50
51 ;;; Code:
52
53 (require 'comint)
54 (require 'shell)
55
56 (defgroup multishell nil
57 "Allout extension that highlights outline structure graphically.
58
59 Customize `allout-widgets-auto-activation' to activate allout-widgets
60 with allout-mode."
61 :group 'shell)
62
63 (defcustom multishell-command-key "\M- "
64 "The key to use if `multishell-activate-command-key' is true.
65
66 You can instead manually bind `multishell-pop-to-shell` using emacs
67 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
68 :type 'key-sequence
69 :group 'multishell)
70
71 (defvar multishell--responsible-for-command-key nil
72 "Multishell internal.")
73 (defun multishell-activate-command-key-setter (symbol setting)
74 "Implement `multishell-activate-command-key' choice."
75 (set-default 'multishell-activate-command-key setting)
76 (when (or setting multishell--responsible-for-command-key)
77 (multishell-implement-command-key-choice (not setting))))
78 (defun multishell-implement-command-key-choice (&optional unbind)
79 "If settings dicate, implement binding of multishell command key.
80
81 If optional UNBIND is true, globally unbind the key.
82
83 * `multishell-activate-command-key' - Set this to get the binding or not.
84 * `multishell-command-key' - The key to use for the binding, if appropriate."
85 (cond (unbind
86 (when (and (boundp 'multishell-command-key) multishell-command-key)
87 (global-unset-key multishell-command-key)))
88 ((not (and (boundp 'multishell-activate-command-key)
89 (boundp 'multishell-command-key)))
90 nil)
91 ((and multishell-activate-command-key multishell-command-key)
92 (setq multishell--responsible-for-command-key t)
93 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
94
95 (defcustom multishell-activate-command-key nil
96 "Set this to impose the `multishell-command-key' binding.
97
98 You can instead manually bind `multishell-pop-to-shell` using emacs
99 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
100 :type 'boolean
101 :set 'multishell-activate-command-key-setter
102 :group 'multishell)
103
104 ;; Assert the customizations whenever the package is loaded:
105 (with-eval-after-load "multishell"
106 (multishell-implement-command-key-choice))
107
108 (defcustom multishell-pop-to-frame nil
109 "*If non-nil, jump to a frame already showing the shell, if another is.
110
111 Otherwise, disregard already-open windows on the shell if they're
112 in another frame, and open a new window on the shell in the
113 current frame.
114
115 \(Use `pop-up-windows' to change multishell other-buffer vs
116 current-buffer behavior.)"
117 :type 'boolean
118 :group 'multishell)
119
120 ;; (defcustom multishell-persist-shell-names nil
121 ;; "Remember shell name/path associations across sessions. Note well:
122 ;; This will activate minibuffer history persistence, in general, if it's not
123 ;; already active."
124 ;; :type 'boolean
125 ;; :set 'multishell-activate-persistence
126 ;; :group 'shell)
127
128 (defvar multishell-history nil
129 "Name/path entries, most recent first.")
130
131 (defvar multishell-primary-name "*shell*"
132 "Shell name to use for un-modified multishell-pop-to-shell buffer target.")
133
134 (defun multishell-register-name-to-path (name path)
135 "Add or replace entry associating NAME with PATH in `multishell-history'.
136
137 Return a list of the prior entry and current one, to indicate
138 disposition changes."
139 (let* ((entry (multishell-name-entry name))
140 (becomes (concat name path)))
141 ;; Promote to the front, tracking path changes in the process:
142 (setq multishell-history (delete entry multishell-history))
143 (if (string= path "")
144 (push entry multishell-history)
145 (push becomes multishell-history))))
146
147 (defun multishell-name-entry (name)
148 "Return `multishell-history' entry that starts with NAME, or nil if none."
149 (let ((match-expr (concat "^" name "\\\(/.*$\\\)?")))
150 (dolist (entry multishell-history)
151 (when (string-match match-expr entry)
152 (return entry)))))
153
154 (defun multishell-pop-to-shell (&optional arg)
155 "Easily navigate to and within multiple shell buffers, local and remote.
156
157 Use universal arguments to launch and choose between alternate
158 shell buffers and to select which is default. Append a path to
159 a new shell name to launch a shell in that directory, and use
160 Emacs tramp syntax to launch a remote shell.
161
162 Customize-group `multishell' to set up a key binding and tweak behaviors.
163
164 ==== Basic operation:
165
166 - If the current buffer is shell-mode (or shell-mode derived)
167 buffer then focus is moved to the process input point.
168
169 \(You can use a universal argument go to a different shell
170 buffer when already in a buffer that has a process - see
171 below.)
172
173 - If not in a shell buffer (or with universal argument), go to a
174 window that is already showing the (a) shell buffer, if any.
175
176 In this case, the cursor is left in its prior position in the
177 shell buffer. Repeating the command will then go to the
178 process input point, per the first item in this list.
179
180 We respect `pop-up-windows', so you can adjust it to set the
181 other-buffer/same-buffer behavior.
182
183 - Otherwise, start a new shell buffer, using the current
184 directory as the working directory.
185
186 If a buffer with the resulting name exists and its shell process
187 was disconnected or otherwise stopped, it's resumed.
188
189 ===== Universal arg to start and select between named shell buffers:
190
191 You can name alternate shell buffers to create or return to using
192 single or doubled universal arguments:
193
194 - With a single universal argument, prompt for the buffer name
195 to use (without the asterisks that shell mode will put around
196 the name), defaulting to 'shell'.
197
198 Completion is available.
199
200 This combination makes it easy to start and switch between
201 multiple shell buffers.
202
203 - A double universal argument will prompt for the name *and* set
204 the default to that name, so the target shell becomes the
205 primary.
206
207 ===== Select starting directory and remote host:
208
209 The shell buffer name you give to the prompt for a universal arg
210 can include an appended path. That will be used for the startup
211 directory. You can use tramp remote syntax to specify a remote
212 shell. If there is an element after a final '/', that's used for
213 the buffer name. Otherwise, the host, domain, or path is used.
214
215 For example:
216
217 * Use '/ssh:example.net:/' for a shell buffer on example.net named
218 \"example.net\".
219 * '\#ex/ssh:example.net|sudo:root@example.net:/' for a root shell on
220 example.net named \"#ex\".
221
222 You can change the startup path for a shell buffer by editing it
223 at the completion prompt. The new path will be preserved in
224 history but will not take effect for an already-running shell.
225
226 To remove a shell buffer's history entry, kill the buffer and
227 affirm removal of the entry when prompted.
228
229 ===== Activate savehist to persisting your shell buffer names and paths:
230
231 To have emacs maintain your history of shell buffer names and paths,
232 customize the savehist group to activate savehist."
233
234 (interactive "P")
235
236 (let* ((from-buffer (current-buffer))
237 (from-buffer-is-shell (derived-mode-p 'shell-mode))
238 (doublearg (equal arg '(16)))
239 (target-name-and-path
240 (multishell-derive-target-name-and-path
241 (if arg
242 (multishell-read-bare-shell-buffer-name
243 (format "Shell buffer name [%s]%s "
244 (substring-no-properties
245 multishell-primary-name
246 1 (- (length multishell-primary-name) 1))
247 (if doublearg " <==" ":"))
248 multishell-primary-name)
249 multishell-primary-name)))
250 (use-default-dir (cadr target-name-and-path))
251 (target-shell-buffer-name (car target-name-and-path))
252 (curr-buff-proc (get-buffer-process from-buffer))
253 (target-buffer (if from-buffer-is-shell
254 from-buffer
255 (get-buffer target-shell-buffer-name)))
256 inwin
257 already-there)
258
259 (when doublearg
260 (setq multishell-primary-name target-shell-buffer-name))
261
262 ;; Situate:
263
264 (cond
265
266 ((and (or curr-buff-proc from-buffer-is-shell)
267 (not arg)
268 (eq from-buffer target-buffer)
269 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
270 ;; In a shell buffer, but not named - stay in buffer, but go to end.
271 (setq already-there t))
272
273 ((string= (buffer-name) target-shell-buffer-name)
274 ;; Already in the specified shell buffer:
275 (setq already-there t))
276
277 ((or (not target-buffer)
278 (not (setq inwin
279 (multishell-get-visible-window-for-buffer target-buffer))))
280 ;; No preexisting shell buffer, or not in a visible window:
281 (pop-to-buffer target-shell-buffer-name pop-up-windows))
282
283 ;; Buffer exists and already has a window - jump to it:
284 (t (if (and multishell-pop-to-frame
285 inwin
286 (not (equal (window-frame (selected-window))
287 (window-frame inwin))))
288 (select-frame-set-input-focus (window-frame inwin)))
289 (if (not (string= (buffer-name (current-buffer))
290 target-shell-buffer-name))
291 (pop-to-buffer target-shell-buffer-name t))))
292
293 ;; We're in the buffer. Activate:
294
295 (cond ((not (comint-check-proc (current-buffer)))
296 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
297 use-default-dir))
298 (use-default-dir
299 (cd use-default-dir)))
300
301 ;; If the destination buffer has a stopped process, resume it:
302 (let ((process (get-buffer-process (current-buffer))))
303 (if (and process (equal 'stop (process-status process)))
304 (continue-process process)))
305 (multishell-register-name-to-path (multishell-unbracket-asterisks
306 target-shell-buffer-name)
307 use-default-dir)
308 (when (or already-there
309 (equal (current-buffer) from-buffer))
310 (goto-char (point-max))
311 (and (get-buffer-process from-buffer)
312 (goto-char (process-mark (get-buffer-process from-buffer)))))))
313
314 (defun multishell-kill-buffer-query-function ()
315 "Offer to remove multishell-history entry for buffer."
316 ;; Removal choice is crucial, so users can, eg, kill and a runaway shell
317 ;; and keep the history entry to easily restart it.
318 ;;
319 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
320 ;;
321 ;; 1. It enables the user to remove the history without killing the buffer,
322 ;; by cancelling the kill-buffer process after affirming history removal.
323 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
324 ;; I've failed to resolve that, and like the first reason well enough.
325
326 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
327 ;; activity. kill-buffer happens behind the scenes a whole lot.)
328 (condition-case anyerr
329 (let ((entry (and (derived-mode-p 'shell-mode)
330 (multishell-name-entry (multishell-unbracket-asterisks
331 (buffer-name))))))
332 (when (and entry
333 (y-or-n-p (format "Remove multishell history entry `%s'? "
334 entry)))
335 (setq multishell-history
336 (delete entry multishell-history))))
337 (error nil))
338 t)
339 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
340
341 (defun multishell-get-visible-window-for-buffer (buffer)
342 "Return visible window containing buffer."
343 (catch 'got-a-vis
344 (walk-windows
345 (function (lambda (win)
346 (if (and (eq (window-buffer win) buffer)
347 (equal (frame-parameter
348 (selected-frame) 'display)
349 (frame-parameter
350 (window-frame win) 'display)))
351 (throw 'got-a-vis win))))
352 nil 'visible)
353 nil))
354
355 (defun multishell-read-bare-shell-buffer-name (prompt default)
356 "PROMPT for shell buffer name, sans asterisks.
357
358 Return the supplied name bracketed with the asterisks, or specified DEFAULT
359 on empty input."
360 (let* ((candidates
361 (append
362 ;; Plain shell buffer names appended with names from name/path hist:
363 (remq nil
364 (mapcar (lambda (buffer)
365 (let* ((name (multishell-unbracket-asterisks
366 (buffer-name buffer))))
367 (and (with-current-buffer buffer
368 ;; Shell mode buffers.
369 (derived-mode-p 'shell-mode))
370 (not (multishell-name-entry name))
371 name)))
372 (buffer-list)))
373 multishell-history))
374 (got (completing-read prompt
375 ;; COLLECTION:
376 (reverse candidates)
377 ;; PREDICATE:
378 nil
379 ;; REQUIRE-MATCH:
380 'confirm
381 ;; INITIAL-INPUT
382 nil
383 ;; HIST:
384 'multishell-history)))
385 (if (not (string= got ""))
386 (multishell-bracket-asterisks got)
387 default)))
388
389 (defun multishell-derive-target-name-and-path (path-ish)
390 "Give tramp-style PATH-ISH, determine target name and default directory.
391
392 The name is the part of the string before the initial '/' slash,
393 if any. Otherwise, it's either the host-name, domain-name, final
394 directory name, or local host name. The path is everything
395 besides the string before the initial '/' slash.
396
397 Return them as a list (name dir), with dir nil if none given."
398 (let (name (path "") dir)
399 (cond ((string= path-ish "") (setq dir multishell-primary-name))
400 ((string-match "^\\*\\([^/]*\\)\\(/.*/\\)\\(.*\\)\\*" path-ish)
401 ;; We have a path, use it
402 (let ((overt-name (match-string 1 path-ish))
403 (overt-path (match-string 2 path-ish))
404 (trailing-name (match-string 3 path-ish)))
405 (if (string= overt-name "") (setq overt-name nil))
406 (if (string= overt-path "") (setq overt-path nil))
407 (if (string= trailing-name "") (setq trailing-name nil))
408 (setq path (concat overt-path trailing-name))
409 (setq name
410 (multishell-bracket-asterisks
411 (or overt-name
412 (if (file-remote-p path)
413 (let ((vec (tramp-dissect-file-name path)))
414 (or (tramp-file-name-host vec)
415 (tramp-file-name-domain vec)
416 (tramp-file-name-localname vec)
417 trailing-name
418 system-name))
419 (multishell-unbracket-asterisks
420 multishell-primary-name)))))))
421 (t (setq name (multishell-bracket-asterisks path-ish))))
422 (list name path)))
423
424 (defun multishell-bracket-asterisks (name)
425 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
426 (if (not (string= (substring name 0 1) "*"))
427 (setq name (concat "*" name)))
428 (if (not (string= (substring name -1) "*"))
429 (setq name (concat name "*")))
430 name)
431 (defun multishell-unbracket-asterisks (name)
432 "Return a copy of name, removing asterisks, if any, at beginning and end."
433 (if (string= (substring name 0 1) "*")
434 (setq name (substring name 1)))
435 (if (string= (substring name -1) "*")
436 (setq name (substring name 0 -1)))
437 name)
438
439 (defun multishell-start-shell-in-buffer (buffer-name path)
440 "Ensure a shell is started, with name NAME and PATH."
441 ;; We work around shell-mode's bracketing of the buffer name, and do
442 ;; some tramp-mode hygiene for remote connections.
443
444 (let* ((buffer buffer-name)
445 (prog (or explicit-shell-file-name
446 (getenv "ESHELL")
447 (getenv "SHELL")
448 "/bin/sh"))
449 (name (file-name-nondirectory prog))
450 (startfile (concat "~/.emacs_" name))
451 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
452 (set-buffer buffer-name)
453 (if (and path (not (string= path "")))
454 (setq default-directory path))
455 (when (and (file-remote-p default-directory)
456 (derived-mode-p 'shell-mode)
457 (not (comint-check-proc (current-buffer))))
458 ;; We're returning to an already established but disconnected remote
459 ;; shell, tidy it:
460 (tramp-cleanup-connection
461 (tramp-dissect-file-name default-directory 'noexpand)
462 'keep-debug 'keep-password))
463 ;; (cd default-directory) will reconnect a disconnected remote:
464 (cd default-directory)
465 (setq buffer (set-buffer (apply 'make-comint
466 (multishell-unbracket-asterisks buffer-name)
467 prog
468 (if (file-exists-p startfile)
469 startfile)
470 (if (and xargs-name
471 (boundp xargs-name))
472 (symbol-value xargs-name)
473 '("-i")))))
474 (shell-mode)))
475
476 (provide 'multishell)
477
478 ;;; multishell.el ends here