]> code.delx.au - gnu-emacs/blob - lisp/shell.el
Initial revision
[gnu-emacs] / lisp / shell.el
1 ;;; shell.el --- specialized comint.el for running the shell.
2 ;;; Copyright (C) 1988, 1993, 1994 Free Software Foundation, Inc.
3
4 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
5 ;; Maintainer: Simon Marshall <s.marshall@dcs.hull.ac.uk>
6 ;; Keywords: processes
7
8 ;;; This file is part of GNU Emacs.
9
10 ;;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;;; it under the terms of the GNU General Public License as published by
12 ;;; the Free Software Foundation; either version 2, or (at your option)
13 ;;; any later version.
14
15 ;;; GNU Emacs is distributed in the hope that it will be useful,
16 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;;; GNU General Public License for more details.
19
20 ;;; You should have received a copy of the GNU General Public License
21 ;;; along with GNU Emacs; see the file COPYING. If not, write to
22 ;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 ;;; Commentary:
25
26 ;;; Please send me bug reports, bug fixes, and extensions, so that I can
27 ;;; merge them into the master source.
28 ;;; - Olin Shivers (shivers@cs.cmu.edu)
29 ;;; - Simon Marshall (s.marshall@dcs.hull.ac.uk)
30
31 ;;; This file defines a a shell-in-a-buffer package (shell mode) built
32 ;;; on top of comint mode. This is actually cmushell with things
33 ;;; renamed to replace its counterpart in Emacs 18. cmushell is more
34 ;;; featureful, robust, and uniform than the Emacs 18 version.
35
36 ;;; Since this mode is built on top of the general command-interpreter-in-
37 ;;; a-buffer mode (comint mode), it shares a common base functionality,
38 ;;; and a common set of bindings, with all modes derived from comint mode.
39 ;;; This makes these modes easier to use.
40
41 ;;; For documentation on the functionality provided by comint mode, and
42 ;;; the hooks available for customising it, see the file comint.el.
43 ;;; For further information on shell mode, see the comments below.
44
45 ;;; Needs fixin:
46 ;;; When sending text from a source file to a subprocess, the process-mark can
47 ;;; move off the window, so you can lose sight of the process interactions.
48 ;;; Maybe I should ensure the process mark is in the window when I send
49 ;;; text to the process? Switch selectable?
50
51 ;; YOUR .EMACS FILE
52 ;;=============================================================================
53 ;; Some suggestions for your .emacs file.
54 ;;
55 ;; ;; Define C-c t to run my favorite command in shell mode:
56 ;; (setq shell-mode-hook
57 ;; '((lambda ()
58 ;; (define-key shell-mode-map "\C-ct" 'favorite-cmd))))
59
60 \f
61 ;;; Brief Command Documentation:
62 ;;;============================================================================
63 ;;; Comint Mode Commands: (common to shell and all comint-derived modes)
64 ;;;
65 ;;; m-p comint-previous-input Cycle backwards in input history
66 ;;; m-n comint-next-input Cycle forwards
67 ;;; m-r comint-previous-matching-input Previous input matching a regexp
68 ;;; m-R comint-previous-matching-input-from-input -"- matching input
69 ;;; m-s comint-next-matching-input Next input that matches
70 ;;; m-S comint-next-matching-input-from-input -"- matching input
71 ;;; m-c-l comint-show-output Show last batch of process output
72 ;;; return comint-send-input
73 ;;; c-a comint-bol Beginning of line; skip prompt
74 ;;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
75 ;;; c-c c-u comint-kill-input ^u
76 ;;; c-c c-w backward-kill-word ^w
77 ;;; c-c c-c comint-interrupt-subjob ^c
78 ;;; c-c c-z comint-stop-subjob ^z
79 ;;; c-c c-\ comint-quit-subjob ^\
80 ;;; c-c c-o comint-kill-output Delete last batch of process output
81 ;;; c-c c-r comint-show-output Show last batch of process output
82 ;;; c-c c-h comint-dynamic-list-input-ring List input history
83 ;;; send-invisible Read line w/o echo & send to proc
84 ;;; comint-continue-subjob Useful if you accidentally suspend
85 ;;; top-level job
86 ;;; comint-mode-hook is the comint mode hook.
87
88 ;;; Shell Mode Commands:
89 ;;; shell Fires up the shell process
90 ;;; tab comint-dynamic-complete Complete filename/command/history
91 ;;; m-? comint-dynamic-list-filename-completions List completions in help buffer
92 ;;; m-c-f shell-forward-command Forward a shell command
93 ;;; m-c-b shell-backward-command Backward a shell command
94 ;;; dirs Resync the buffer's dir stack
95 ;;; dirtrack-toggle Turn dir tracking on/off
96 ;;; shell-strip-ctrl-m Remove trailing ^Ms from output
97 ;;;
98 ;;; The shell mode hook is shell-mode-hook
99 ;;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
100 ;;; compatibility.
101
102 ;;; Read the rest of this file for more information.
103 \f
104 ;;; SHELL.EL COMPATIBILITY
105 ;;; Notes from when this was called cmushell, and was not the standard emacs
106 ;;; shell package.
107 ;;;============================================================================
108 ;;; In brief: this package should have no trouble coexisting with shell.el.
109 ;;;
110 ;;; Most customising variables -- e.g., explicit-shell-file-name -- are the
111 ;;; same, so the users shouldn't have much trouble. Hooks have different
112 ;;; names, however, so you can customise shell mode differently from cmushell
113 ;;; mode. You basically just have to remember to type M-x cmushell instead of
114 ;;; M-x shell.
115 ;;;
116 ;;; It would be nice if this file was completely plug-compatible with the old
117 ;;; shell package -- if you could just name this file shell.el, and have it
118 ;;; transparently replace the old one. But you can't. Several other packages
119 ;;; (tex-mode, background, dbx, gdb, kermit, monkey, prolog, telnet) are also
120 ;;; clients of shell mode. These packages assume detailed knowledge of shell
121 ;;; mode internals in ways that are incompatible with cmushell mode (mostly
122 ;;; because of cmushell mode's greater functionality). So, unless we are
123 ;;; willing to port all of these packages, we can't have this file be a
124 ;;; complete replacement for shell.el -- that is, we can't name this file
125 ;;; shell.el, and its main entry point (shell), because dbx.el will break
126 ;;; when it loads it in and tries to use it.
127 ;;;
128 ;;; There are two ways to fix this. One: rewrite these other modes to use the
129 ;;; new package. This is a win, but can't be assumed. The other, backwards
130 ;;; compatible route, is to make this package non-conflict with shell.el, so
131 ;;; both files can be loaded in at the same time. And *that* is why some
132 ;;; functions and variables have different names: (cmushell),
133 ;;; cmushell-mode-map, that sort of thing. All the names have been carefully
134 ;;; chosen so that shell.el and cmushell.el won't tromp on each other.
135 \f
136 ;;; Customization and Buffer Variables
137 ;;; ===========================================================================
138 ;;;
139
140 ;;; Code:
141
142 (require 'comint)
143
144 ;;;###autoload
145 (defvar shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
146 "Regexp to match prompts in the inferior shell.
147 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
148 This variable is used to initialise `comint-prompt-regexp' in the
149 shell buffer.
150
151 The pattern should probably not match more than one line. If it does,
152 shell-mode may become confused trying to distinguish prompt from input
153 on lines which don't start with a prompt.
154
155 This is a fine thing to set in your `.emacs' file.")
156
157 (defvar shell-completion-fignore nil
158 "*List of suffixes to be disregarded during file/command completion.
159 This variable is used to initialize `comint-completion-fignore' in the shell
160 buffer. The default is nil, for compatibility with most shells.
161 Some people like (\"~\" \"#\" \"%\").
162
163 This is a fine thing to set in your `.emacs' file.")
164
165 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
166 "List of characters to recognise as separate arguments.
167 This variable is used to initialize `comint-delimiter-argument-list' in the
168 shell buffer. The default is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
169
170 This is a fine thing to set in your `.emacs' file.")
171
172 (defvar shell-dynamic-complete-functions
173 '(comint-replace-by-expanded-history
174 shell-dynamic-complete-environment-variable
175 shell-dynamic-complete-command
176 shell-replace-by-expanded-directory
177 comint-dynamic-complete-filename)
178 "List of functions called to perform completion.
179 This variable is used to initialise `comint-dynamic-complete-functions' in the
180 shell buffer.
181
182 This is a fine thing to set in your `.emacs' file.")
183
184 (defvar shell-command-regexp "\\((.*)\\|[^;&|]\\)+"
185 "*Regexp to match shell commands.
186 Elements of pipes are considered as separate commands, forks and redirections
187 as part of one command.")
188
189 (defvar shell-completion-execonly t
190 "*If non-nil, use executable files only for completion candidates.
191 This mirrors the optional behavior of tcsh.
192
193 Detecting executability of files may slow command completion considerably.")
194
195 (defvar shell-popd-regexp "popd"
196 "*Regexp to match subshell commands equivalent to popd.")
197
198 (defvar shell-pushd-regexp "pushd"
199 "*Regexp to match subshell commands equivalent to pushd.")
200
201 (defvar shell-pushd-tohome nil
202 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
203 This mirrors the optional behavior of tcsh.")
204
205 (defvar shell-pushd-dextract nil
206 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
207 This mirrors the optional behavior of tcsh.")
208
209 (defvar shell-pushd-dunique nil
210 "*If non-nil, make pushd only add unique directories to the stack.
211 This mirrors the optional behavior of tcsh.")
212
213 (defvar shell-cd-regexp "cd"
214 "*Regexp to match subshell commands equivalent to cd.")
215
216 (defvar explicit-shell-file-name nil
217 "*If non-nil, is file name to use for explicitly requested inferior shell.")
218
219 (defvar explicit-csh-args
220 (if (eq system-type 'hpux)
221 ;; -T persuades HP's csh not to think it is smarter
222 ;; than us about what terminal modes to use.
223 '("-i" "-T")
224 '("-i"))
225 "*Args passed to inferior shell by M-x shell, if the shell is csh.
226 Value is a list of strings, which may be nil.")
227
228 (defvar shell-input-autoexpand 'history
229 "*If non-nil, expand input command history references on completion.
230 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
231
232 If the value is `input', then the expansion is seen on input.
233 If the value is `history', then the expansion is only when inserting
234 into the buffer's input ring. See also `comint-magic-space' and
235 `comint-dynamic-complete'.
236
237 This variable supplies a default for `comint-input-autoexpand',
238 for Shell mode only.")
239
240 (defvar shell-dirstack nil
241 "List of directories saved by pushd in this buffer's shell.
242 Thus, this does not include the shell's current directory.")
243
244 (defvar shell-dirtrackp t
245 "Non-nil in a shell buffer means directory tracking is enabled.")
246
247 (defvar shell-last-dir nil
248 "Keep track of last directory for ksh `cd -' command.")
249
250 (defvar shell-dirstack-query "dirs"
251 "Command used by `shell-resync-dir' to query the shell.")
252
253 (defvar shell-mode-map nil)
254 (cond ((not shell-mode-map)
255 (setq shell-mode-map (copy-keymap comint-mode-map))
256 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
257 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
258 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
259 (define-key shell-mode-map "\M-?"
260 'comint-dynamic-list-filename-completions)
261 ;; Undefine the general completion first.
262 (define-key shell-mode-map [menu-bar completion complete] nil)
263 (define-key shell-mode-map [menu-bar completion expand-directory]
264 '("Expand Directory Reference" . shell-replace-by-expanded-directory))
265 (define-key shell-mode-map [menu-bar completion complete-env-variable]
266 '("Complete Env. Variable Name" .
267 shell-dynamic-complete-environment-variable))
268 (define-key shell-mode-map [menu-bar completion complete-command]
269 '("Complete Command Name" . shell-dynamic-complete-command))
270 ;; Redefine (requires a new key) so that it is at the top.
271 (define-key shell-mode-map [menu-bar completion complete-shell]
272 '("Complete Before Point" . comint-dynamic-complete))
273 ))
274
275 (defvar shell-mode-hook '()
276 "*Hook for customising Shell mode.")
277
278 \f
279 ;;; Basic Procedures
280 ;;; ===========================================================================
281 ;;;
282
283 (defun shell-mode ()
284 "Major mode for interacting with an inferior shell.
285 Return after the end of the process' output sends the text from the
286 end of process to the end of the current line.
287 Return before end of process output copies the current line (except
288 for the prompt) to the end of the buffer and sends it.
289 M-x send-invisible reads a line of text without echoing it, and sends it to
290 the shell. This is useful for entering passwords. Or, add the function
291 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
292
293 If you accidentally suspend your process, use \\[comint-continue-subjob]
294 to continue it.
295
296 cd, pushd and popd commands given to the shell are watched by Emacs to keep
297 this buffer's default directory the same as the shell's working directory.
298 M-x dirs queries the shell and resyncs Emacs' idea of what the current
299 directory stack is.
300 M-x dirtrack-toggle turns directory tracking on and off.
301
302 \\{shell-mode-map}
303 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
304 `shell-mode-hook' (in that order). Before each input, the hooks on
305 `comint-input-filter-functions' are run. After each shell output, the hooks
306 on `comint-output-filter-functions' are run.
307
308 Variables `shell-cd-regexp', `shell-pushd-regexp' and `shell-popd-regexp'
309 are used to match their respective commands, while `shell-pushd-tohome',
310 `shell-pushd-dextract' and `shell-pushd-dunique' control the behavior of the
311 relevant command.
312
313 Variables `comint-completion-autolist', `comint-completion-addsuffix',
314 `comint-completion-recexact' and `comint-completion-fignore' control the
315 behavior of file name, command name and variable name completion. Variable
316 `shell-completion-execonly' controls the behavior of command name completion.
317 Variable `shell-completion-fignore' is used to initialise the value of
318 `comint-completion-fignore'.
319
320 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
321 the initialisation of the input ring history, and history expansion.
322
323 Variables `comint-output-filter-functions', a hook, and
324 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
325 control whether input and output cause the window to scroll to the end of the
326 buffer."
327 (interactive)
328 (comint-mode)
329 (setq major-mode 'shell-mode)
330 (setq mode-name "Shell")
331 (use-local-map shell-mode-map)
332 (setq comint-prompt-regexp shell-prompt-pattern)
333 (setq comint-completion-fignore shell-completion-fignore)
334 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
335 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
336 (make-local-variable 'paragraph-start)
337 (setq paragraph-start comint-prompt-regexp)
338 (make-local-variable 'shell-dirstack)
339 (setq shell-dirstack nil)
340 (setq shell-last-dir nil)
341 (make-local-variable 'shell-dirtrackp)
342 (setq shell-dirtrackp t)
343 (add-hook 'comint-input-filter-functions 'shell-directory-tracker)
344 (setq comint-input-autoexpand shell-input-autoexpand)
345 ;; shell-dependent assignments.
346 (let ((shell (car (process-command (get-buffer-process (current-buffer))))))
347 (setq comint-input-ring-file-name
348 (or (getenv "HISTFILE")
349 (cond ((string-match "csh$" shell) "~/.history")
350 ((string-match "bash$" shell) "~/.bash_history")
351 ((string-match "ksh$" shell) "~/.sh_history")
352 (t "~/.history")))))
353 (run-hooks 'shell-mode-hook)
354 (comint-read-input-ring t))
355 \f
356 ;;;###autoload
357 (defun shell ()
358 "Run an inferior shell, with I/O through buffer *shell*.
359 If buffer exists but shell process is not running, make new shell.
360 If buffer exists and shell process is running, just switch to buffer `*shell*'.
361 Program used comes from variable `explicit-shell-file-name',
362 or (if that is nil) from the ESHELL environment variable,
363 or else from SHELL if there is no ESHELL.
364 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
365 (Note that this may lose due to a timing error if the shell
366 discards input when it starts up.)
367 The buffer is put in Shell mode, giving commands for sending input
368 and controlling the subjobs of the shell. See `shell-mode'.
369 See also the variable `shell-prompt-pattern'.
370
371 The shell file name (sans directories) is used to make a symbol name
372 such as `explicit-csh-args'. If that symbol is a variable,
373 its value is used as a list of arguments when invoking the shell.
374 Otherwise, one argument `-i' is passed to the shell.
375
376 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
377 (interactive)
378 (if (not (comint-check-proc "*shell*"))
379 (let* ((prog (or explicit-shell-file-name
380 (getenv "ESHELL")
381 (getenv "SHELL")
382 "/bin/sh"))
383 (name (file-name-nondirectory prog))
384 (startfile (concat "~/.emacs_" name))
385 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
386 (set-buffer (apply 'make-comint "shell" prog
387 (if (file-exists-p startfile) startfile)
388 (if (and xargs-name (boundp xargs-name))
389 (symbol-value xargs-name)
390 '("-i"))))
391 (shell-mode)))
392 (switch-to-buffer "*shell*"))
393 \f
394 ;;; Directory tracking
395 ;;; ===========================================================================
396 ;;; This code provides the shell mode input sentinel
397 ;;; SHELL-DIRECTORY-TRACKER
398 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
399 ;;; changes the current directory of the shell buffer accordingly.
400 ;;;
401 ;;; This is basically a fragile hack, although it's more accurate than
402 ;;; the version in Emacs 18's shell.el. It has the following failings:
403 ;;; 1. It doesn't know about the cdpath shell variable.
404 ;;; 2. It cannot infallibly deal with command sequences, though it does well
405 ;;; with these and with ignoring commands forked in another shell with ()s.
406 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
407 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
408 ;;; that, there's no way to catch shell commands where cd's are buried
409 ;;; inside conditional expressions, aliases, and so forth.
410 ;;;
411 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
412 ;;; messes it up. You run other processes under the shell; these each have
413 ;;; separate working directories, and some have commands for manipulating
414 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
415 ;;; commands that do *not* affect the current w.d. at all, but look like they
416 ;;; do (e.g., the cd command in ftp). In shells that allow you job
417 ;;; control, you can switch between jobs, all having different w.d.'s. So
418 ;;; simply saying %3 can shift your w.d..
419 ;;;
420 ;;; The solution is to relax, not stress out about it, and settle for
421 ;;; a hack that works pretty well in typical circumstances. Remember
422 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
423 ;;; anyway. Blech.
424 ;;;
425 ;;; One good hack not implemented here for users of programmable shells
426 ;;; is to program up the shell w.d. manipulation commands to output
427 ;;; a coded command sequence to the tty. Something like
428 ;;; ESC | <cwd> |
429 ;;; where <cwd> is the new current working directory. Then trash the
430 ;;; directory tracking machinery currently used in this package, and
431 ;;; replace it with a process filter that watches for and strips out
432 ;;; these messages.
433
434 (defun shell-directory-tracker (str)
435 "Tracks cd, pushd and popd commands issued to the shell.
436 This function is called on each input passed to the shell.
437 It watches for cd, pushd and popd commands and sets the buffer's
438 default directory to track these commands.
439
440 You may toggle this tracking on and off with M-x dirtrack-toggle.
441 If emacs gets confused, you can resync with the shell with M-x dirs.
442
443 See variables `shell-cd-regexp', `shell-pushd-regexp', and `shell-popd-regexp',
444 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
445 control the behavior of the relevant command.
446
447 Environment variables are expanded, see function `substitute-in-file-name'."
448 (if shell-dirtrackp
449 ;; We fail gracefully if we think the command will fail in the shell.
450 (condition-case chdir-failure
451 (let ((start (progn (string-match "^[;\\s ]*" str) ; skip whitespace
452 (match-end 0)))
453 end cmd arg1)
454 (while (string-match shell-command-regexp str start)
455 (setq end (match-end 0)
456 cmd (comint-arguments (substring str start end) 0 0)
457 arg1 (comint-arguments (substring str start end) 1 1))
458 (cond ((eq (string-match shell-popd-regexp cmd) 0)
459 (shell-process-popd (substitute-in-file-name arg1)))
460 ((eq (string-match shell-pushd-regexp cmd) 0)
461 (shell-process-pushd (substitute-in-file-name arg1)))
462 ((eq (string-match shell-cd-regexp cmd) 0)
463 (shell-process-cd (substitute-in-file-name arg1))))
464 (setq start (progn (string-match "[;\\s ]*" str end) ; skip again
465 (match-end 0)))))
466 (error "Couldn't cd"))))
467
468 ;;; popd [+n]
469 (defun shell-process-popd (arg)
470 (let ((num (or (shell-extract-num arg) 0)))
471 (cond ((and num (= num 0) shell-dirstack)
472 (cd (car shell-dirstack))
473 (setq shell-dirstack (cdr shell-dirstack))
474 (shell-dirstack-message))
475 ((and num (> num 0) (<= num (length shell-dirstack)))
476 (let* ((ds (cons nil shell-dirstack))
477 (cell (nthcdr (1- num) ds)))
478 (rplacd cell (cdr (cdr cell)))
479 (setq shell-dirstack (cdr ds))
480 (shell-dirstack-message)))
481 (t
482 (error "Couldn't popd")))))
483
484 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
485 (defsubst shell-prefixed-directory-name (dir)
486 (if (file-name-absolute-p dir)
487 ;; The name is absolute, so prepend the prefix.
488 (concat comint-file-name-prefix dir)
489 ;; For a relative name we assume default-directory already has the prefix.
490 (expand-file-name dir)))
491
492 ;;; cd [dir]
493 (defun shell-process-cd (arg)
494 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
495 "~"))
496 ((string-equal "-" arg) shell-last-dir)
497 (t (shell-prefixed-directory-name arg)))))
498 (setq shell-last-dir default-directory)
499 (cd new-dir)
500 (shell-dirstack-message)))
501
502 ;;; pushd [+n | dir]
503 (defun shell-process-pushd (arg)
504 (let ((num (shell-extract-num arg)))
505 (cond ((zerop (length arg))
506 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
507 (cond (shell-pushd-tohome
508 (shell-process-pushd (concat comint-file-name-prefix "~")))
509 (shell-dirstack
510 (let ((old default-directory))
511 (cd (car shell-dirstack))
512 (setq shell-dirstack
513 (cons old (cdr shell-dirstack)))
514 (shell-dirstack-message)))
515 (t
516 (message "Directory stack empty."))))
517 ((numberp num)
518 ;; pushd +n
519 (cond ((> num (length shell-dirstack))
520 (message "Directory stack not that deep."))
521 ((= num 0)
522 (error (message "Couldn't cd.")))
523 (shell-pushd-dextract
524 (let ((dir (nth (1- num) shell-dirstack)))
525 (shell-process-popd arg)
526 (shell-process-pushd default-directory)
527 (cd dir)
528 (shell-dirstack-message)))
529 (t
530 (let* ((ds (cons default-directory shell-dirstack))
531 (dslen (length ds))
532 (front (nthcdr num ds))
533 (back (reverse (nthcdr (- dslen num) (reverse ds))))
534 (new-ds (append front back)))
535 (cd (car new-ds))
536 (setq shell-dirstack (cdr new-ds))
537 (shell-dirstack-message)))))
538 (t
539 ;; pushd <dir>
540 (let ((old-wd default-directory))
541 (cd (shell-prefixed-directory-name arg))
542 (if (or (null shell-pushd-dunique)
543 (not (member old-wd shell-dirstack)))
544 (setq shell-dirstack (cons old-wd shell-dirstack)))
545 (shell-dirstack-message))))))
546
547 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
548 (defun shell-extract-num (str)
549 (and (string-match "^\\+[1-9][0-9]*$" str)
550 (string-to-int str)))
551
552
553 (defun shell-dirtrack-toggle ()
554 "Turn directory tracking on and off in a shell buffer."
555 (interactive)
556 (setq shell-dirtrackp (not shell-dirtrackp))
557 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
558
559 ;;; For your typing convenience:
560 (defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
561
562
563 (defun shell-resync-dirs ()
564 "Resync the buffer's idea of the current directory stack.
565 This command queries the shell with the command bound to
566 `shell-dirstack-query' (default \"dirs\"), reads the next
567 line output and parses it to form the new directory stack.
568 DON'T issue this command unless the buffer is at a shell prompt.
569 Also, note that if some other subprocess decides to do output
570 immediately after the query, its output will be taken as the
571 new directory stack -- you lose. If this happens, just do the
572 command again."
573 (interactive)
574 (let* ((proc (get-buffer-process (current-buffer)))
575 (pmark (process-mark proc)))
576 (goto-char pmark)
577 (insert shell-dirstack-query) (insert "\n")
578 (sit-for 0) ; force redisplay
579 (comint-send-string proc shell-dirstack-query)
580 (comint-send-string proc "\n")
581 (set-marker pmark (point))
582 (let ((pt (point))) ; wait for 1 line
583 ;; This extra newline prevents the user's pending input from spoofing us.
584 (insert "\n") (backward-char 1)
585 (while (not (looking-at ".+\n"))
586 (accept-process-output proc)
587 (goto-char pt)))
588 (goto-char pmark) (delete-char 1) ; remove the extra newline
589 ;; That's the dirlist. grab it & parse it.
590 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
591 (dl-len (length dl))
592 (ds '()) ; new dir stack
593 (i 0))
594 (while (< i dl-len)
595 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
596 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
597 (setq ds (cons (concat comint-file-name-prefix
598 (substring dl (match-beginning 1)
599 (match-end 1)))
600 ds))
601 (setq i (match-end 0)))
602 (let ((ds (nreverse ds)))
603 (condition-case nil
604 (progn (cd (car ds))
605 (setq shell-dirstack (cdr ds))
606 (shell-dirstack-message))
607 (error (message "Couldn't cd.")))))))
608
609 ;;; For your typing convenience:
610 (defalias 'dirs 'shell-resync-dirs)
611
612
613 ;;; Show the current dirstack on the message line.
614 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
615 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
616 ;;; All the commands that mung the buffer's dirstack finish by calling
617 ;;; this guy.
618 (defun shell-dirstack-message ()
619 (let* ((msg "")
620 (ds (cons default-directory shell-dirstack))
621 (home (expand-file-name (concat comint-file-name-prefix "~/")))
622 (homelen (length home)))
623 (while ds
624 (let ((dir (car ds)))
625 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
626 (setq dir (concat "~/" (substring dir homelen))))
627 ;; Strip off comint-file-name-prefix if present.
628 (and comint-file-name-prefix
629 (>= (length dir) (length comint-file-name-prefix))
630 (string= comint-file-name-prefix
631 (substring dir 0 (length comint-file-name-prefix)))
632 (setq dir (substring dir (length comint-file-name-prefix)))
633 (setcar ds dir))
634 (setq msg (concat msg (directory-file-name dir) " "))
635 (setq ds (cdr ds))))
636 (message msg)))
637 \f
638 (defun shell-forward-command (&optional arg)
639 "Move forward across ARG shell command(s). Does not cross lines.
640 See `shell-command-regexp'."
641 (interactive "p")
642 (let ((limit (save-excursion (end-of-line nil) (point))))
643 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\\s ]*\\)+")
644 limit 'move arg)
645 (skip-syntax-backward " "))))
646
647
648 (defun shell-backward-command (&optional arg)
649 "Move backward across ARG shell command(s). Does not cross lines.
650 See `shell-command-regexp'."
651 (interactive "p")
652 (let ((limit (save-excursion (comint-bol nil) (point))))
653 (if (> limit (point))
654 (save-excursion (beginning-of-line) (setq limit (point))))
655 (skip-syntax-backward " " limit)
656 (if (re-search-backward
657 (format "[;&|]+[\\s ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
658 (progn (goto-char (match-beginning 1))
659 (skip-chars-forward ";&|")))))
660
661
662 (defun shell-dynamic-complete-command ()
663 "Dynamically complete the command at point.
664 This function is similar to `comint-dynamic-complete-filename', except that it
665 searches `exec-path' (minus the trailing emacs library path) for completion
666 candidates. Note that this may not be the same as the shell's idea of the
667 path.
668
669 Completion is dependent on the value of `shell-completion-execonly', plus
670 those that effect file completion. See `shell-dynamic-complete-as-command'.
671
672 Returns t if successful."
673 (interactive)
674 (let ((filename (comint-match-partial-filename)))
675 (if (and filename
676 (save-match-data (not (string-match "[~/]" filename)))
677 (eq (match-beginning 0)
678 (save-excursion (shell-backward-command 1) (point))))
679 (prog2 (message "Completing command name...")
680 (shell-dynamic-complete-as-command)))))
681
682
683 (defun shell-dynamic-complete-as-command ()
684 "Dynamically complete at point as a command.
685 See `shell-dynamic-complete-filename'. Returns t if successful."
686 (let* ((filename (or (comint-match-partial-filename) ""))
687 (pathnondir (file-name-nondirectory filename))
688 (paths (cdr (reverse exec-path)))
689 (cwd (file-name-as-directory (expand-file-name default-directory)))
690 (ignored-extensions
691 (and comint-completion-fignore
692 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
693 comint-completion-fignore "\\|")))
694 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
695 ;; Go thru each path in the search path, finding completions.
696 (while paths
697 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
698 comps-in-path (and (file-accessible-directory-p path)
699 (file-name-all-completions pathnondir path)))
700 ;; Go thru each completion found, to see whether it should be used.
701 (while comps-in-path
702 (setq file (car comps-in-path)
703 filepath (concat path file))
704 (if (and (not (member file completions))
705 (not (string-match ignored-extensions file))
706 (or (string-equal path cwd)
707 (not (file-directory-p filepath)))
708 (or (null shell-completion-execonly)
709 (file-executable-p filepath)))
710 (setq completions (cons file completions)))
711 (setq comps-in-path (cdr comps-in-path)))
712 (setq paths (cdr paths)))
713 ;; OK, we've got a list of completions.
714 (let ((success (let ((comint-completion-addsuffix nil))
715 (comint-dynamic-simple-complete pathnondir completions))))
716 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
717 (not (file-directory-p (comint-match-partial-filename))))
718 (insert " "))
719 success)))
720
721
722 (defun shell-match-partial-variable ()
723 "Return the variable at point, or nil if non is found."
724 (save-excursion
725 (let ((limit (point)))
726 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
727 (or (looking-at "\\$") (forward-char 1)))
728 ;; Anchor the search forwards.
729 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
730 nil
731 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
732 (buffer-substring (match-beginning 0) (match-end 0))))))
733
734
735 (defun shell-dynamic-complete-environment-variable ()
736 "Dynamically complete the environment variable at point.
737 Completes if after a variable, i.e., if it starts with a \"$\".
738 See `shell-dynamic-complete-as-environment-variable'.
739
740 This function is similar to `comint-dynamic-complete-filename', except that it
741 searches `process-environment' for completion candidates. Note that this may
742 not be the same as the interpreter's idea of variable names. The main problem
743 with this type of completion is that `process-environment' is the environment
744 which Emacs started with. Emacs does not track changes to the environment made
745 by the interpreter. Perhaps it would be more accurate if this function was
746 called `shell-dynamic-complete-process-environment-variable'.
747
748 Returns non-nil if successful."
749 (interactive)
750 (let ((variable (shell-match-partial-variable)))
751 (if (and variable (string-match "^\\$" variable))
752 (prog2 (message "Completing variable name...")
753 (shell-dynamic-complete-as-environment-variable)))))
754
755
756 (defun shell-dynamic-complete-as-environment-variable ()
757 "Dynamically complete at point as an environment variable.
758 Used by `shell-dynamic-complete-environment-variable'.
759 Uses `comint-dynamic-simple-complete'."
760 (let* ((var (or (shell-match-partial-variable) ""))
761 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
762 (variables (mapcar (function (lambda (x)
763 (substring x 0 (string-match "=" x))))
764 process-environment))
765 (addsuffix comint-completion-addsuffix)
766 (comint-completion-addsuffix nil)
767 (success (comint-dynamic-simple-complete variable variables)))
768 (if (memq success '(sole shortest))
769 (let* ((var (shell-match-partial-variable))
770 (variable (substring var (string-match "[^$({]" var)))
771 (protection (cond ((string-match "{" var) "}")
772 ((string-match "(" var) ")")
773 (t "")))
774 (suffix (cond ((null addsuffix) "")
775 ((file-directory-p
776 (comint-directory (getenv variable))) "/")
777 (t " "))))
778 (insert protection suffix)))
779 success))
780
781
782 (defun shell-replace-by-expanded-directory ()
783 "Expand directory stack reference before point.
784 Directory stack references are of the form \"=digit\" or \"=-\".
785 See `default-directory' and `shell-dirstack'.
786
787 Returns t if successful."
788 (interactive)
789 (if (comint-match-partial-filename)
790 (save-excursion
791 (message "Expanding directory references...")
792 (goto-char (match-beginning 0))
793 (let ((stack (cons default-directory shell-dirstack))
794 (index (cond ((looking-at "=-/?")
795 (length shell-dirstack))
796 ((looking-at "=\\([0-9]+\\)")
797 (string-to-number
798 (buffer-substring
799 (match-beginning 1) (match-end 1)))))))
800 (cond ((null index)
801 nil)
802 ((>= index (length stack))
803 (error "Directory stack not that deep."))
804 (t
805 (replace-match (file-name-as-directory (nth index stack)) t t)
806 (message "Directory item: %d" index)
807 t))))))
808 \f
809 (defun shell-strip-ctrl-m (&optional string)
810 "Strip trailing `^M' characters from the current output group.
811
812 This function could be in the list `comint-output-filter-functions' or bound to
813 a key."
814 (interactive)
815 (let ((pmark (process-mark (get-buffer-process (current-buffer))))
816 (ctrl-m (concat (char-to-string 13) "$")))
817 (save-excursion
818 (goto-char
819 (if (interactive-p) comint-last-input-end comint-last-output-start))
820 (while (re-search-forward ctrl-m pmark t)
821 (replace-match "" t t)))))
822 \f
823 (provide 'shell)
824
825 ;;; shell.el ends here