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