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