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