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