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