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