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