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