]> code.delx.au - gnu-emacs-elpa/blob - multishell.el
b3f55ad62e74e0a0fa8c0e9cf028010dc1b17244
[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/EmacsMultishell
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 one of your shell buffers 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 ;; For example:
25 ;;
26 ;; * `/ssh:example.net:/` for a shell buffer in / on
27 ;; example.net; the buffer will be named "*example.net*".
28 ;;
29 ;; * `#ex/ssh:example.net|sudo:root@example.net:/etc` for a root shell
30 ;; starting in /etc on example.net named "*#ex*".
31 ;;
32 ;; (NOTE that there is a frequent problem with specifying a remote homedir
33 ;; using tramp syntax, eg `/ssh:example.net:` or `/ssh:example.net:~`. That
34 ;; sometimes fails on an obscure bug - particularly for remote+sudo with
35 ;; homedir syntax. Until fixed, you may need to start remote+sudo shells with
36 ;; an explicit path, then cd ~. With `multishell`s dir-tracking persistent
37 ;; history, you'll be able to use completion to start that shell in the right
38 ;; place, in your subsequent sessions.)
39 ;;
40 ;; See the `multishell-pop-to-shell` docstring for details.
41 ;;
42 ;; Customize-group `multishell' to select and activate a keybinding and set
43 ;; various behaviors. Customize-group `savehist' to preserve buffer
44 ;; names/paths across emacs sessions.
45 ;;
46 ;; See the `multishell-pop-to-shell' docstring for details.
47 ;;
48 ;;; Change Log:
49 ;;
50 ;; * 2016-01-16 1.0.5 Ken Manheimer:
51 ;; - History now includes paths, when designated
52 ;; - Actively track current directory in history entries that have a path.
53 ;; Custom control: multishell-history-entry-tracks-current-directory
54 ;; - Offer to remove shell's history entry when buffer is killed
55 ;; (For now, the only UI way to remove history entries.)
56 ;; - Fix - prevent duplicate entries for same name but different paths
57 ;; - Fix - recognize and respect tramp path syntax to start in home dir
58 ;; - But tramp bug, remote+sudo hops to a home dir can fail, get wedged.
59 ;; - Simplify history var name, migrate existing history if any from old name
60 ;; * 2016-01-04 Ken Manheimer - Released to ELPA
61 ;; * 2016-01-02 Ken Manheimer - working on this in public, but not yet released.
62 ;;
63 ;;; TODO:
64 ;;
65 ;; * Isolate tramp sporadic failure to connect to remote+sudo+homedir syntax
66 ;; (eg, /ssh:xyz.com|sudo:root@xyz.com: or /ssh:xyz.com|sudo:root@xyz.com:~)
67 ;; * Find suitable, internally consistent ways to sort tidy completions, eg:
68 ;; - first list completions for active shells, then present but inactive,
69 ;; then historical
70 ;; - some way for user to toggle between presenting just buffer names vs
71 ;; full buffer/path
72 ;; - without cutting user off from easy editing of path
73 ;; * Find proper method for setting field boundary at beginning of tramp path
74 ;; in the minibuffer, in order to see whether the field boundary magically
75 ;; enables tramp completion of the path.
76 ;; * Assess whether option to delete history entry on kill-buffer is
77 ;; sufficient.
78
79 ;;; Code:
80
81 (require 'comint)
82 (require 'shell)
83
84 (defgroup multishell nil
85 "Allout extension that highlights outline structure graphically.
86
87 Customize `allout-widgets-auto-activation' to activate allout-widgets
88 with allout-mode."
89 :group 'shell)
90
91 (defcustom multishell-command-key "\M- "
92 "The key to use if `multishell-activate-command-key' is true.
93
94 You can instead manually bind `multishell-pop-to-shell` using emacs
95 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
96 :type 'key-sequence
97 :group 'multishell)
98
99 (defvar multishell--responsible-for-command-key nil
100 "Coordination for multishell key assignment.")
101 (defun multishell-activate-command-key-setter (symbol setting)
102 "Implement `multishell-activate-command-key' choice."
103 (set-default 'multishell-activate-command-key setting)
104 (when (or setting multishell--responsible-for-command-key)
105 (multishell-implement-command-key-choice (not setting))))
106 (defun multishell-implement-command-key-choice (&optional unbind)
107 "If settings dicate, implement binding of multishell command key.
108
109 If optional UNBIND is true, globally unbind the key.
110
111 * `multishell-activate-command-key' - Set this to get the binding or not.
112 * `multishell-command-key' - The key to use for the binding, if appropriate."
113 (cond (unbind
114 (when (and (boundp 'multishell-command-key) multishell-command-key)
115 (global-unset-key multishell-command-key)))
116 ((not (and (boundp 'multishell-activate-command-key)
117 (boundp 'multishell-command-key)))
118 nil)
119 ((and multishell-activate-command-key multishell-command-key)
120 (setq multishell--responsible-for-command-key t)
121 (global-set-key multishell-command-key 'multishell-pop-to-shell))))
122
123 (defcustom multishell-activate-command-key nil
124 "Set this to impose the `multishell-command-key' binding.
125
126 You can instead manually bind `multishell-pop-to-shell` using emacs
127 lisp, eg: (global-set-key \"\\M- \" 'multishell-pop-to-shell)."
128 :type 'boolean
129 :set 'multishell-activate-command-key-setter
130 :group 'multishell)
131
132 ;; Assert the customizations whenever the package is loaded:
133 (with-eval-after-load "multishell"
134 (multishell-implement-command-key-choice))
135
136 (defcustom multishell-pop-to-frame nil
137 "*If non-nil, jump to a frame already showing the shell, if another is.
138
139 Otherwise, disregard already-open windows on the shell if they're
140 in another frame, and open a new window on the shell in the
141 current frame.
142
143 \(Use `pop-up-windows' to change multishell other-buffer vs
144 current-buffer behavior.)"
145 :type 'boolean
146 :group 'multishell)
147
148 (defcustom multishell-history-entry-tracks-current-directory t
149 "Modify shell buffer's multishell entry to track the current directory.
150
151 When set, the path part of the name/path entry for each shell
152 will track the current directory of the shell with emacs. If
153 `savehist' is active, the directory tracking will extend across
154 emacs sessions."
155 :type 'boolean
156 :group 'multishell)
157
158 (defvar multishell-history nil
159 "Name/path entries, most recent first.")
160 (when (and (not multishell-history)
161 (boundp 'multishell-buffer-name-history)
162 multishell-buffer-name-history)
163 ;; Migrate few users who had old var to new.
164 (setq multishell-history multishell-buffer-name-history)
165 )
166
167 (defvar multishell-primary-name "*shell*"
168 "Shell name to use for un-modified multishell-pop-to-shell buffer target.")
169
170 ;; There is usually only one entry per name, but disruptions happen.
171 (defun multishell-register-name-to-path (name path)
172 "Add or replace entry associating NAME with PATH in `multishell-history'.
173
174 Promote to added/changed entry to the front of the list."
175 ;; Add or promote to the front, tracking path changes in the process.
176 (let* ((entries (multishell-history-entries name))
177 (becomes (concat name path)))
178 (dolist (entry entries)
179 (setq multishell-history (delete entry multishell-history)))
180 (setq multishell-history (push becomes multishell-history))))
181
182 (defun multishell-history-entries (name)
183 "Return `multishell-history' entry that starts with NAME, or nil if none."
184 (let ((match-expr (concat "^" name "\\\(/.*$\\\)?"))
185 got)
186 (dolist (entry multishell-history)
187 (when (and (string-match match-expr entry)
188 (not (member entry got)))
189 (setq got (cons entry got))))
190 got))
191
192 (defun multishell-pop-to-shell (&optional arg)
193 "Easily navigate to and within multiple shell buffers, local and remote.
194
195 Use universal arguments to launch and choose between alternate
196 shell buffers and to select which is default. Append a path to
197 a new shell name to launch a shell in that directory, and use
198 Emacs tramp syntax to launch a remote shell.
199
200 Customize-group `multishell' to set up a key binding and tweak behaviors.
201
202 ==== Basic operation:
203
204 - If the current buffer is shell-mode (or shell-mode derived)
205 buffer then focus is moved to the process input point.
206
207 \(You can use a universal argument go to a different shell
208 buffer when already in a buffer that has a process - see
209 below.)
210
211 - If not in a shell buffer (or with universal argument), go to a
212 window that is already showing the (a) shell buffer, if any.
213
214 In this case, the cursor is left in its prior position in the
215 shell buffer. Repeating the command will then go to the
216 process input point, per the first item in this list.
217
218 We respect `pop-up-windows', so you can adjust it to set the
219 other-buffer/same-buffer behavior.
220
221 - Otherwise, start a new shell buffer, using the current
222 directory as the working directory.
223
224 If a buffer with the resulting name exists and its shell process
225 was disconnected or otherwise stopped, it's resumed.
226
227 ===== Universal arg to start and select between named shell buffers:
228
229 You can name alternate shell buffers to create or return to using
230 single or doubled universal arguments:
231
232 - With a single universal argument, prompt for the buffer name
233 to use (without the asterisks that shell mode will put around
234 the name), defaulting to 'shell'.
235
236 Completion is available.
237
238 This combination makes it easy to start and switch between
239 multiple shell buffers.
240
241 - A double universal argument will prompt for the name *and* set
242 the default to that name, so the target shell becomes the
243 primary.
244
245 ===== Select starting directory and remote host:
246
247 The shell buffer name you give to the prompt for a universal arg
248 can include an appended path. That will be used for the startup
249 directory. You can use tramp remote syntax to specify a remote
250 shell. If there is an element after a final '/', that's used for
251 the buffer name. Otherwise, the host, domain, or path is used.
252
253 For example:
254
255 * Use '/ssh:example.net:/home/myaccount' for a shell buffer in
256 /home/myaccount on example.net; the buffer will be named
257 \"*example.net*\".
258 * '\#ex/ssh:example.net|sudo:root@example.net:/etc' for a root
259 shell in /etc on example.net named \"*#ex*\".
260
261 \(NOTE that there is a problem with specifying a remote homedir using
262 tramp syntax, eg '/ssh:example.net:'. That sometimes fails on an obscure
263 bug - particularly for remote+sudo with homedir syntax. Until fixed, you
264 may need to start remote+sudo shells with an explicit path, then cd ~.)
265
266 You can change the startup path for a shell buffer by editing it
267 at the completion prompt. The new path will be preserved in
268 history but will not take effect for an already-running shell.
269
270 To remove a shell buffer's history entry, kill the buffer and
271 affirm removal of the entry when prompted.
272
273 ===== Activate savehist to persisting your shell buffer names and paths:
274
275 To have emacs maintain your history of shell buffer names and paths,
276 customize the savehist group to activate savehist."
277
278 (interactive "P")
279
280 (let* ((from-buffer (current-buffer))
281 (from-buffer-is-shell (derived-mode-p 'shell-mode))
282 (doublearg (equal arg '(16)))
283 (target-name-and-path
284 (multishell-derive-target-name-and-path
285 (if arg
286 (multishell-read-bare-shell-buffer-name
287 (format "Shell buffer name [%s]%s "
288 (substring-no-properties
289 multishell-primary-name
290 1 (- (length multishell-primary-name) 1))
291 (if doublearg " <==" ":"))
292 multishell-primary-name)
293 multishell-primary-name)))
294 (use-default-dir (cadr target-name-and-path))
295 (target-shell-buffer-name (car target-name-and-path))
296 (curr-buff-proc (get-buffer-process from-buffer))
297 (target-buffer (if from-buffer-is-shell
298 from-buffer
299 (let ((got (get-buffer target-shell-buffer-name)))
300 (if (buffer-live-p got)
301 got
302 (kill-buffer got)
303 (get-buffer target-shell-buffer-name)))))
304 inwin
305 already-there)
306
307 (when doublearg
308 (setq multishell-primary-name target-shell-buffer-name))
309
310 ;; Situate:
311
312 (cond
313
314 ((and (or curr-buff-proc from-buffer-is-shell)
315 (not arg)
316 (eq from-buffer target-buffer)
317 (not (eq target-shell-buffer-name (buffer-name from-buffer))))
318 ;; In a shell buffer, but not named - stay in buffer, but go to end.
319 (setq already-there t))
320
321 ((string= (buffer-name) target-shell-buffer-name)
322 ;; Already in the specified shell buffer:
323 (setq already-there t))
324
325 ((or (not target-buffer)
326 (not (setq inwin
327 (multishell-get-visible-window-for-buffer target-buffer))))
328 ;; No preexisting shell buffer, or not in a visible window:
329 (pop-to-buffer target-shell-buffer-name pop-up-windows))
330
331 ;; Buffer exists and already has a window - jump to it:
332 (t (if (and multishell-pop-to-frame
333 inwin
334 (not (equal (window-frame (selected-window))
335 (window-frame inwin))))
336 (select-frame-set-input-focus (window-frame inwin)))
337 (if (not (string= (buffer-name (current-buffer))
338 target-shell-buffer-name))
339 (pop-to-buffer target-shell-buffer-name t))))
340
341 ;; We're in the buffer. Activate:
342
343 (if (not (comint-check-proc (current-buffer)))
344 (multishell-start-shell-in-buffer (buffer-name (current-buffer))
345 use-default-dir))
346
347 ;; If the destination buffer has a stopped process, resume it:
348 (let ((process (get-buffer-process (current-buffer))))
349 (if (and process (equal 'stop (process-status process)))
350 (continue-process process)))
351 (multishell-register-name-to-path (multishell-unbracket-asterisks
352 target-shell-buffer-name)
353 use-default-dir)
354 (when (or already-there
355 (equal (current-buffer) from-buffer))
356 (goto-char (point-max))
357 (and (get-buffer-process from-buffer)
358 (goto-char (process-mark (get-buffer-process from-buffer)))))))
359
360 (defun multishell-kill-buffer-query-function ()
361 "Offer to remove multishell-history entry for buffer."
362 ;; Removal choice is crucial, so users can, eg, kill and a runaway shell
363 ;; and keep the history entry to easily restart it.
364 ;;
365 ;; We use kill-buffer-query-functions instead of kill-buffer-hook because:
366 ;;
367 ;; 1. It enables the user to remove the history without killing the buffer,
368 ;; by cancelling the kill-buffer process after affirming history removal.
369 ;; 2. kill-buffer-hooks often fails to run when killing shell buffers!
370 ;; I've failed to resolve that, and like the first reason well enough.
371
372 ;; (Use condition-case to avoid inadvertant disruption of kill-buffer
373 ;; activity. kill-buffer happens behind the scenes a whole lot.)
374 (condition-case anyerr
375 (let ((entries (and (derived-mode-p 'shell-mode)
376 (multishell-history-entries
377 (multishell-unbracket-asterisks (buffer-name))))))
378 (dolist (entry entries)
379 (when (and entry
380 (y-or-n-p (format "Remove multishell history entry `%s'? "
381 entry)))
382 (setq multishell-history
383 (delete entry multishell-history)))))
384 (error nil))
385 t)
386 (add-hook 'kill-buffer-query-functions 'multishell-kill-buffer-query-function)
387
388 (defun multishell-get-visible-window-for-buffer (buffer)
389 "Return visible window containing buffer."
390 (catch 'got-a-vis
391 (walk-windows
392 (function (lambda (win)
393 (if (and (eq (window-buffer win) buffer)
394 (equal (frame-parameter
395 (selected-frame) 'display)
396 (frame-parameter
397 (window-frame win) 'display)))
398 (throw 'got-a-vis win))))
399 nil 'visible)
400 nil))
401
402 (defun multishell-read-bare-shell-buffer-name (prompt default)
403 "PROMPT for shell buffer name, sans asterisks.
404
405 Return the supplied name bracketed with the asterisks, or specified DEFAULT
406 on empty input."
407 (let* ((candidates
408 (append
409 ;; Plain shell buffer names appended with names from name/path hist:
410 (remq nil
411 (mapcar (lambda (buffer)
412 (let* ((name (multishell-unbracket-asterisks
413 (buffer-name buffer))))
414 (and (buffer-live-p buffer)
415 (with-current-buffer buffer
416 ;; Shell mode buffers.
417 (derived-mode-p 'shell-mode))
418 (not (multishell-history-entries name))
419 name)))
420 (buffer-list)))
421 multishell-history))
422 (got (completing-read prompt
423 ;; COLLECTION:
424 (reverse candidates)
425 ;; PREDICATE:
426 nil
427 ;; REQUIRE-MATCH:
428 'confirm
429 ;; INITIAL-INPUT
430 nil
431 ;; HIST:
432 'multishell-history)))
433 (if (not (string= got ""))
434 (multishell-bracket-asterisks got)
435 default)))
436
437 (defun multishell-derive-target-name-and-path (path-ish)
438 "Give tramp-style PATH-ISH, determine target name and default directory.
439
440 The name is the part of the string before the initial '/' slash,
441 if any. Otherwise, it's either the host-name, domain-name, final
442 directory name, or local host name. The path is everything
443 besides the string before the initial '/' slash.
444
445 Return them as a list (name dir), with dir nil if none given."
446 (let (name (path "") dir)
447 (cond ((string= path-ish "") (setq dir multishell-primary-name))
448 ((string-match "^\\*\\([^/]*\\)\\(/.*\\)\\*" path-ish)
449 ;; We have a path, use it
450 (let ((overt-name (match-string 1 path-ish)))
451 (setq path (match-string 2 path-ish))
452 (if (string= overt-name "") (setq overt-name nil))
453 (if (string= path "") (setq path nil))
454 (setq name
455 (multishell-bracket-asterisks
456 (or overt-name
457 (if (file-remote-p path)
458 (let ((vec (tramp-dissect-file-name path)))
459 (or (tramp-file-name-host vec)
460 (tramp-file-name-domain vec)
461 (tramp-file-name-localname vec)
462 system-name))
463 (multishell-unbracket-asterisks
464 multishell-primary-name)))))))
465 (t (setq name (multishell-bracket-asterisks path-ish))))
466 (list name path)))
467
468 (defun multishell-bracket-asterisks (name)
469 "Return a copy of name, ensuring it has an asterisk at the beginning and end."
470 (if (not (string= (substring name 0 1) "*"))
471 (setq name (concat "*" name)))
472 (if (not (string= (substring name -1) "*"))
473 (setq name (concat name "*")))
474 name)
475 (defun multishell-unbracket-asterisks (name)
476 "Return a copy of name, removing asterisks, if any, at beginning and end."
477 (if (string= (substring name 0 1) "*")
478 (setq name (substring name 1)))
479 (if (string= (substring name -1) "*")
480 (setq name (substring name 0 -1)))
481 name)
482
483 (defun multishell-start-shell-in-buffer (buffer-name path)
484 "Ensure a shell is started, with name NAME and PATH."
485 ;; We work around shell-mode's bracketing of the buffer name, and do
486 ;; some tramp-mode hygiene for remote connections.
487
488 (let* ((buffer buffer-name)
489 (prog (or explicit-shell-file-name
490 (getenv "ESHELL")
491 (getenv "SHELL")
492 "/bin/sh"))
493 (name (file-name-nondirectory prog))
494 (startfile (concat "~/.emacs_" name))
495 (xargs-name (intern-soft (concat "explicit-" name "-args")))
496 is-remote)
497 (set-buffer buffer-name)
498 (if (and path (not (string= path "")))
499 (setq default-directory path))
500 (setq is-remote (file-remote-p default-directory))
501 (when (and is-remote
502 (derived-mode-p 'shell-mode)
503 (not (comint-check-proc (current-buffer))))
504 ;; We're returning to an already established but disconnected remote
505 ;; shell, tidy it:
506 (tramp-cleanup-connection
507 (tramp-dissect-file-name default-directory 'noexpand)
508 'keep-debug 'keep-password))
509 ;; (cd default-directory) will connect if remote:
510 (when is-remote
511 (message "Connecting to %s" default-directory))
512 (condition-case err
513 (cd default-directory)
514 (error
515 ;; Aargh. Need to isolate this tramp bug.
516 (when (and (stringp (cadr err))
517 (string-equal (cadr err)
518 "Selecting deleted buffer"))
519 (signal (car err)
520 (list
521 (format "Tramp shell can fail on homedir paths, %s (\"%s\")"
522 "please try with an explicit path"
523 (cadr err)))))))
524 (setq buffer (set-buffer (apply 'make-comint
525 (multishell-unbracket-asterisks buffer-name)
526 prog
527 (if (file-exists-p startfile)
528 startfile)
529 (if (and xargs-name
530 (boundp xargs-name))
531 (symbol-value xargs-name)
532 '("-i")))))
533 (shell-mode)))
534
535 (defun multishell-track-dirchange (name newpath)
536 "Change multishell history entry to track current directory."
537 (let* ((entries (multishell-history-entries name)))
538 (dolist (entry entries)
539 (let* ((name-path (multishell-split-entry-name-and-tramp entry))
540 (name (car name-path))
541 (path (cadr name-path)))
542 (when path
543 (let* ((is-remote (file-remote-p path))
544 (vec (and is-remote (tramp-dissect-file-name path nil)))
545 (localname (if is-remote
546 (tramp-file-name-localname vec)
547 path))
548 (newlocalname
549 (replace-regexp-in-string (if (string= localname "")
550 "$"
551 (regexp-quote localname))
552 ;; REP
553 newpath
554 ;; STRING
555 localname
556 ;; FIXEDCASE
557 t
558 ;; LITERAL
559 t
560 ))
561 (newpath (if is-remote
562 (tramp-make-tramp-file-name (aref vec 0)
563 (aref vec 1)
564 (aref vec 2)
565 newlocalname
566 (aref vec 4))
567 newlocalname))
568 (newentry (concat name newpath))
569 (membership (member entry multishell-history)))
570 (when membership
571 (setcar membership newentry))))))))
572 (defvar multishell-was-default-directory ()
573 "Provide for tracking directory changes.")
574 (make-variable-buffer-local 'multishell-was-default-directory)
575 (defun multishell-post-command-business ()
576 "Do multishell bookkeeping."
577 ;; Update multishell-history with dir changes.
578 (condition-case err
579 (when (and multishell-history-entry-tracks-current-directory
580 (derived-mode-p 'shell-mode))
581 (let ((curdir (if (file-remote-p default-directory)
582 (tramp-file-name-localname
583 (tramp-dissect-file-name default-directory))
584 default-directory)))
585 (when (and multishell-was-default-directory
586 (not (string= curdir multishell-was-default-directory)))
587 (multishell-track-dirchange (multishell-unbracket-asterisks
588 (buffer-name))
589 curdir))
590 (setq multishell-was-default-directory curdir)))
591 ;; To avoid disruption as a pervasive hook function, swallow all errors:
592 (error nil)))
593 (add-hook 'post-command-hook 'multishell-post-command-business)
594
595 (defun multishell-split-entry-name-and-tramp (entry)
596 "Given multishell name/path ENTRY, return the separated name and path pair.
597
598 Returns nil for empty parts, rather than the empty string."
599 (string-match "^\\([^/]*\\)\\(/?.*\\)?" entry)
600 (let ((name (match-string 1 entry))
601 (path (match-string 2 entry)))
602 (and (string= name "") (setq name nil))
603 (and (string= path "") (setq path nil))
604 (list name path)))
605
606 (provide 'multishell)
607
608 ;;; multishell.el ends here