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