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