(normal-top-level, command-line-1):
[bpt/emacs.git] / lisp / shell.el
CommitLineData
5336e829 1;;; shell.el --- specialized comint.el for running the shell.
5109bfb0 2
0b3c9cf1 3;; Copyright (C) 1988, 1993, 1994, 1995 Free Software Foundation, Inc.
6d74b528 4
630cc463 5;; Author: Olin Shivers <shivers@cs.cmu.edu>
e9933cb1 6;; Maintainer: Simon Marshall <simon@gnu.ai.mit.edu>
d7b4d18f 7;; Keywords: processes
630cc463 8
5109bfb0 9;; This file is part of GNU Emacs.
c88ab9ce 10
5109bfb0
KH
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.
c88ab9ce 15
5109bfb0
KH
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.
c88ab9ce 20
5109bfb0
KH
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.
be9b65ac 24
630cc463
ER
25;;; Commentary:
26
a9ec2adb
JB
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)
e9933cb1 30;;; - Simon Marshall (simon@gnu.ai.mit.edu)
be9b65ac 31
a9ec2adb 32;;; This file defines a a shell-in-a-buffer package (shell mode) built
c88ab9ce
ER
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.
be9b65ac
DL
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.
a9ec2adb 40;;; This makes these modes easier to use.
be9b65ac
DL
41
42;;; For documentation on the functionality provided by comint mode, and
43;;; the hooks available for customising it, see the file comint.el.
a9ec2adb 44;;; For further information on shell mode, see the comments below.
be9b65ac
DL
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
a9ec2adb
JB
52;; YOUR .EMACS FILE
53;;=============================================================================
54;; Some suggestions for your .emacs file.
55;;
0b3c9cf1
SM
56;; ;; Define M-# to run some strange command:
57;; (eval-after-load "shell"
58;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
a9ec2adb
JB
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
d76b71af 66;;; m-r comint-previous-matching-input Previous input matching a regexp
d76b71af 67;;; m-s comint-next-matching-input Next input that matches
f5a131d8 68;;; m-c-l comint-show-output Show last batch of process output
a9ec2adb 69;;; return comint-send-input
a9ec2adb 70;;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
8137dca9 71;;; c-c c-a comint-bol Beginning of line; skip prompt
a9ec2adb
JB
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
d76b71af 79;;; c-c c-h comint-dynamic-list-input-ring List input history
a9ec2adb
JB
80;;; send-invisible Read line w/o echo & send to proc
81;;; comint-continue-subjob Useful if you accidentally suspend
d76b71af 82;;; top-level job
a9ec2adb
JB
83;;; comint-mode-hook is the comint mode hook.
84
85;;; Shell Mode Commands:
7b4c6503
SM
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
a9ec2adb
JB
95;;;
96;;; The shell mode hook is shell-mode-hook
a9ec2adb
JB
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
8f95f0ce 102;;; Customization and Buffer Variables
a9ec2adb
JB
103;;; ===========================================================================
104;;;
105
630cc463
ER
106;;; Code:
107
108(require 'comint)
109
c88ab9ce 110;;;###autoload
ac75ef20 111(defvar shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
a9ec2adb 112 "Regexp to match prompts in the inferior shell.
ac75ef20 113Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
24fdffaa 114This variable is used to initialise `comint-prompt-regexp' in the
a9ec2adb
JB
115shell buffer.
116
ac75ef20
JB
117The pattern should probably not match more than one line. If it does,
118shell-mode may become confused trying to distinguish prompt from input
119on lines which don't start with a prompt.
120
24fdffaa 121This is a fine thing to set in your `.emacs' file.")
a9ec2adb 122
e11284d5
RS
123(defvar shell-completion-fignore nil
124 "*List of suffixes to be disregarded during file/command completion.
125This variable is used to initialize `comint-completion-fignore' in the shell
126buffer. The default is nil, for compatibility with most shells.
127Some people like (\"~\" \"#\" \"%\").
128
129This is a fine thing to set in your `.emacs' file.")
130
56eb1060 131(defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
d76b71af 132 "List of characters to recognise as separate arguments.
56eb1060
RS
133This variable is used to initialize `comint-delimiter-argument-list' in the
134shell buffer. The default is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
d76b71af
RS
135
136This is a fine thing to set in your `.emacs' file.")
137
7b4c6503
SM
138(defvar shell-file-name-quote-list
139 (append shell-delimiter-argument-list '(?\ ?\* ?\! ?\" ?\' ?\`))
140 "List of characters to quote when in a file name.
141This variable is used to initialize `comint-file-name-quote-list' in the
142shell buffer. The default is (?\ ?\* ?\! ?\" ?\' ?\`) plus characters
143in `shell-delimiter-argument-list'.
144
145This is a fine thing to set in your `.emacs' file.")
146
988a4d60
RS
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.
154This variable is used to initialise `comint-dynamic-complete-functions' in the
155shell buffer.
156
157This is a fine thing to set in your `.emacs' file.")
158
a8e0effb
RS
159(defvar shell-command-regexp "[^;&|\n]+"
160 "*Regexp to match a single command within a pipeline.
161This is used for directory tracking and does not do a perfect job.")
d76b71af
RS
162
163(defvar shell-completion-execonly t
164 "*If non-nil, use executable files only for completion candidates.
5394cb44 165This mirrors the optional behavior of tcsh.
d76b71af
RS
166
167Detecting executability of files may slow command completion considerably.")
168
be9b65ac
DL
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
d76b71af
RS
175(defvar shell-pushd-tohome nil
176 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
5394cb44 177This mirrors the optional behavior of tcsh.")
d76b71af
RS
178
179(defvar shell-pushd-dextract nil
180 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
5394cb44 181This mirrors the optional behavior of tcsh.")
d76b71af
RS
182
183(defvar shell-pushd-dunique nil
184 "*If non-nil, make pushd only add unique directories to the stack.
5394cb44 185This mirrors the optional behavior of tcsh.")
d76b71af 186
be9b65ac
DL
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.
200Value is a list of strings, which may be nil.")
201
4f99443b
RS
202(defvar shell-input-autoexpand 'history
203 "*If non-nil, expand input command history references on completion.
204This mirrors the optional behavior of tcsh (its autoexpand and histlit).
205
206If the value is `input', then the expansion is seen on input.
207If the value is `history', then the expansion is only when inserting
208into the buffer's input ring. See also `comint-magic-space' and
209`comint-dynamic-complete'.
210
211This variable supplies a default for `comint-input-autoexpand',
212for Shell mode only.")
213
be9b65ac 214(defvar shell-dirstack nil
c88ab9ce
ER
215 "List of directories saved by pushd in this buffer's shell.
216Thus, this does not include the shell's current directory.")
be9b65ac 217
b493a9b2
RS
218(defvar shell-dirtrackp t
219 "Non-nil in a shell buffer means directory tracking is enabled.")
220
fa8f1b25
ER
221(defvar shell-last-dir nil
222 "Keep track of last directory for ksh `cd -' command.")
223
c63e83a4 224(defvar shell-dirstack-query nil
24fdffaa 225 "Command used by `shell-resync-dir' to query the shell.")
be9b65ac 226
9376442d 227(defvar shell-mode-map nil)
be9b65ac 228(cond ((not shell-mode-map)
1ed30e75 229 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
d76b71af
RS
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)
be9b65ac 232 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
d76b71af 233 (define-key shell-mode-map "\M-?"
988a4d60 234 'comint-dynamic-list-filename-completions)
1ed30e75
RS
235 (define-key shell-mode-map [menu-bar completion]
236 (copy-keymap (lookup-key comint-mode-map [menu-bar completion])))
5109bfb0
KH
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)))
be9b65ac
DL
245
246(defvar shell-mode-hook '()
24fdffaa 247 "*Hook for customising Shell mode.")
be9b65ac 248
5945a1f7
RS
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)
86a21134 252 '("^[^ \t\n]+:.*" . font-lock-string-face)
5945a1f7
RS
253 '("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
254 "Additional expressions to highlight in Shell mode.")
be9b65ac
DL
255\f
256;;; Basic Procedures
257;;; ===========================================================================
258;;;
259
260(defun shell-mode ()
261 "Major mode for interacting with an inferior shell.
8079b590
SM
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).
e9933cb1 266\\[send-invisible] reads a line of text without echoing it, and sends it to
56783585
RS
267 the shell. This is useful for entering passwords. Or, add the function
268 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
be9b65ac 269
e9933cb1
SM
270If you want to make multiple shell buffers, rename the `*shell*' buffer
271using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
272
8079b590 273If you want to make shell buffers limited in length, add the function
4841acc4 274`comint-truncate-buffer' to `comint-output-filter-functions'.
8079b590 275
be9b65ac
DL
276If you accidentally suspend your process, use \\[comint-continue-subjob]
277to continue it.
278
e9933cb1
SM
279`cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
280keep this buffer's default directory the same as the shell's working directory.
0b3c9cf1
SM
281While directory tracking is enabled, the shell's working directory is displayed
282by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
e9933cb1 283\\[dirs] queries the shell and resyncs Emacs' idea of what the current
be9b65ac 284 directory stack is.
e9933cb1 285\\[dirtrack-toggle] turns directory tracking on and off.
be9b65ac
DL
286
287\\{shell-mode-map}
24fdffaa 288Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
988a4d60 289`shell-mode-hook' (in that order). Before each input, the hooks on
ba02c167
RS
290`comint-input-filter-functions' are run. After each shell output, the hooks
291on `comint-output-filter-functions' are run.
be9b65ac 292
24fdffaa 293Variables `shell-cd-regexp', `shell-pushd-regexp' and `shell-popd-regexp'
d76b71af 294are used to match their respective commands, while `shell-pushd-tohome',
5394cb44 295`shell-pushd-dextract' and `shell-pushd-dunique' control the behavior of the
d76b71af
RS
296relevant command.
297
e11284d5
RS
298Variables `comint-completion-autolist', `comint-completion-addsuffix',
299`comint-completion-recexact' and `comint-completion-fignore' control the
300behavior of file name, command name and variable name completion. Variable
301`shell-completion-execonly' controls the behavior of command name completion.
302Variable `shell-completion-fignore' is used to initialise the value of
303`comint-completion-fignore'.
d76b71af
RS
304
305Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
306the initialisation of the input ring history, and history expansion.
307
ba02c167 308Variables `comint-output-filter-functions', a hook, and
e11284d5 309`comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
988a4d60
RS
310control whether input and output cause the window to scroll to the end of the
311buffer."
be9b65ac
DL
312 (interactive)
313 (comint-mode)
a9ec2adb 314 (setq major-mode 'shell-mode)
bd5201e3 315 (setq mode-name "Shell")
be9b65ac 316 (use-local-map shell-mode-map)
d76b71af 317 (setq comint-prompt-regexp shell-prompt-pattern)
e11284d5 318 (setq comint-completion-fignore shell-completion-fignore)
d76b71af 319 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
7b4c6503 320 (setq comint-file-name-quote-list shell-file-name-quote-list)
988a4d60 321 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
d76b71af
RS
322 (make-local-variable 'paragraph-start)
323 (setq paragraph-start comint-prompt-regexp)
c156572f
SM
324 (make-local-variable 'font-lock-defaults)
325 (setq font-lock-defaults '(shell-font-lock-keywords t))
be9b65ac 326 (make-local-variable 'shell-dirstack)
a9ec2adb 327 (setq shell-dirstack nil)
fa8f1b25 328 (setq shell-last-dir nil)
a9ec2adb
JB
329 (make-local-variable 'shell-dirtrackp)
330 (setq shell-dirtrackp t)
1458efa0 331 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
4f99443b 332 (setq comint-input-autoexpand shell-input-autoexpand)
0b3c9cf1
SM
333 (make-local-variable 'list-buffers-directory)
334 (setq list-buffers-directory (expand-file-name default-directory))
d76b71af 335 ;; shell-dependent assignments.
c63e83a4
RS
336 (let ((shell (file-name-nondirectory (car
337 (process-command (get-buffer-process (current-buffer)))))))
d76b71af
RS
338 (setq comint-input-ring-file-name
339 (or (getenv "HISTFILE")
c63e83a4
RS
340 (cond ((string-equal shell "bash") "~/.bash_history")
341 ((string-equal shell "ksh") "~/.sh_history")
342 (t "~/.history"))))
525c5be7
SM
343 (if (or (equal comint-input-ring-file-name "")
344 (equal (file-truename comint-input-ring-file-name) "/dev/null"))
3c24374d 345 (setq comint-input-ring-file-name nil))
c63e83a4
RS
346 (setq shell-dirstack-query
347 (if (string-match "^k?sh$" shell) "pwd" "dirs")))
d76b71af 348 (run-hooks 'shell-mode-hook)
4f99443b 349 (comint-read-input-ring t))
be9b65ac 350\f
c88ab9ce 351;;;###autoload
be9b65ac
DL
352(defun shell ()
353 "Run an inferior shell, with I/O through buffer *shell*.
354If buffer exists but shell process is not running, make new shell.
d76b71af 355If buffer exists and shell process is running, just switch to buffer `*shell*'.
24fdffaa 356Program used comes from variable `explicit-shell-file-name',
a9ec2adb
JB
357 or (if that is nil) from the ESHELL environment variable,
358 or else from SHELL if there is no ESHELL.
fbc270e7 359If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
a9ec2adb
JB
360 (Note that this may lose due to a timing error if the shell
361 discards input when it starts up.)
fbc270e7
RS
362The buffer is put in Shell mode, giving commands for sending input
363and controlling the subjobs of the shell. See `shell-mode'.
364See also the variable `shell-prompt-pattern'.
be9b65ac 365
a9ec2adb 366The shell file name (sans directories) is used to make a symbol name
62c9fad7 367such as `explicit-csh-args'. If that symbol is a variable,
be9b65ac
DL
368its value is used as a list of arguments when invoking the shell.
369Otherwise, one argument `-i' is passed to the shell.
370
371\(Type \\[describe-mode] in the shell buffer for a list of commands.)"
372 (interactive)
d76b71af
RS
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))
519bfec4
RS
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*")
be9b65ac
DL
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
b7fc702e 404;;; the version in Emacs 18's shell.el. It has the following failings:
be9b65ac 405;;; 1. It doesn't know about the cdpath shell variable.
d76b71af
RS
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.
be9b65ac
DL
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
a9ec2adb 417;;; commands that do *not* affect the current w.d. at all, but look like they
be9b65ac
DL
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
be9b65ac
DL
436(defun shell-directory-tracker (str)
437 "Tracks cd, pushd and popd commands issued to the shell.
438This function is called on each input passed to the shell.
439It watches for cd, pushd and popd commands and sets the buffer's
440default directory to track these commands.
441
442You may toggle this tracking on and off with M-x dirtrack-toggle.
443If emacs gets confused, you can resync with the shell with M-x dirs.
444
d76b71af
RS
445See variables `shell-cd-regexp', `shell-pushd-regexp', and `shell-popd-regexp',
446while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
5394cb44 447control the behavior of the relevant command.
d76b71af 448
24fdffaa 449Environment variables are expanded, see function `substitute-in-file-name'."
d76b71af
RS
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 "^[;\\s ]*" 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 ((eq (string-match shell-popd-regexp cmd) 0)
461 (shell-process-popd (substitute-in-file-name arg1)))
462 ((eq (string-match shell-pushd-regexp cmd) 0)
463 (shell-process-pushd (substitute-in-file-name arg1)))
464 ((eq (string-match shell-cd-regexp cmd) 0)
465 (shell-process-cd (substitute-in-file-name arg1))))
466 (setq start (progn (string-match "[;\\s ]*" str end) ; skip again
467 (match-end 0)))))
ba02c167 468 (error "Couldn't cd"))))
d76b71af 469
be9b65ac
DL
470;;; popd [+n]
471(defun shell-process-popd (arg)
d76b71af
RS
472 (let ((num (or (shell-extract-num arg) 0)))
473 (cond ((and num (= num 0) shell-dirstack)
0b3c9cf1 474 (shell-cd (car shell-dirstack))
d76b71af
RS
475 (setq shell-dirstack (cdr shell-dirstack))
476 (shell-dirstack-message))
477 ((and num (> num 0) (<= num (length shell-dirstack)))
478 (let* ((ds (cons nil shell-dirstack))
479 (cell (nthcdr (1- num) ds)))
480 (rplacd cell (cdr (cdr cell)))
481 (setq shell-dirstack (cdr ds))
482 (shell-dirstack-message)))
483 (t
ba02c167 484 (error "Couldn't popd")))))
be9b65ac 485
3db9a4eb 486;; Return DIR prefixed with comint-file-name-prefix as appropriate.
4a02b552
RS
487(defun shell-prefixed-directory-name (dir)
488 (if (= (length comint-file-name-prefix) 0)
489 dir
490 (if (file-name-absolute-p dir)
491 ;; The name is absolute, so prepend the prefix.
492 (concat comint-file-name-prefix dir)
0b3c9cf1 493 ;; For relative name we assume default-directory already has the prefix.
4a02b552 494 (expand-file-name dir))))
3db9a4eb 495
be9b65ac
DL
496;;; cd [dir]
497(defun shell-process-cd (arg)
3db9a4eb
RM
498 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
499 "~"))
d76b71af 500 ((string-equal "-" arg) shell-last-dir)
3db9a4eb 501 (t (shell-prefixed-directory-name arg)))))
d76b71af 502 (setq shell-last-dir default-directory)
0b3c9cf1 503 (shell-cd new-dir)
d76b71af 504 (shell-dirstack-message)))
be9b65ac
DL
505
506;;; pushd [+n | dir]
507(defun shell-process-pushd (arg)
d76b71af
RS
508 (let ((num (shell-extract-num arg)))
509 (cond ((zerop (length arg))
510 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
511 (cond (shell-pushd-tohome
3db9a4eb 512 (shell-process-pushd (concat comint-file-name-prefix "~")))
d76b71af
RS
513 (shell-dirstack
514 (let ((old default-directory))
0b3c9cf1 515 (shell-cd (car shell-dirstack))
d76b71af
RS
516 (setq shell-dirstack
517 (cons old (cdr shell-dirstack)))
518 (shell-dirstack-message)))
519 (t
520 (message "Directory stack empty."))))
521 ((numberp num)
522 ;; pushd +n
523 (cond ((> num (length shell-dirstack))
524 (message "Directory stack not that deep."))
525 ((= num 0)
526 (error (message "Couldn't cd.")))
527 (shell-pushd-dextract
528 (let ((dir (nth (1- num) shell-dirstack)))
529 (shell-process-popd arg)
530 (shell-process-pushd default-directory)
0b3c9cf1 531 (shell-cd dir)
d76b71af
RS
532 (shell-dirstack-message)))
533 (t
534 (let* ((ds (cons default-directory shell-dirstack))
535 (dslen (length ds))
536 (front (nthcdr num ds))
537 (back (reverse (nthcdr (- dslen num) (reverse ds))))
538 (new-ds (append front back)))
0b3c9cf1 539 (shell-cd (car new-ds))
d76b71af
RS
540 (setq shell-dirstack (cdr new-ds))
541 (shell-dirstack-message)))))
542 (t
543 ;; pushd <dir>
544 (let ((old-wd default-directory))
0b3c9cf1 545 (shell-cd (shell-prefixed-directory-name arg))
d76b71af
RS
546 (if (or (null shell-pushd-dunique)
547 (not (member old-wd shell-dirstack)))
548 (setq shell-dirstack (cons old-wd shell-dirstack)))
549 (shell-dirstack-message))))))
be9b65ac
DL
550
551;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
552(defun shell-extract-num (str)
553 (and (string-match "^\\+[1-9][0-9]*$" str)
554 (string-to-int str)))
555
556
557(defun shell-dirtrack-toggle ()
558 "Turn directory tracking on and off in a shell buffer."
559 (interactive)
0b3c9cf1
SM
560 (if (setq shell-dirtrackp (not shell-dirtrackp))
561 (setq list-buffers-directory default-directory)
562 (setq list-buffers-directory nil))
d76b71af 563 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
be9b65ac
DL
564
565;;; For your typing convenience:
31e1d920 566(defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
be9b65ac 567
0b3c9cf1
SM
568(defun shell-cd (dir)
569 "Do normal `cd' to DIR, and set `list-buffers-directory'."
b7e97ed5
SM
570 (if shell-dirtrackp
571 (setq list-buffers-directory (file-name-as-directory
572 (expand-file-name dir))))
0b3c9cf1 573 (cd dir))
be9b65ac
DL
574
575(defun shell-resync-dirs ()
576 "Resync the buffer's idea of the current directory stack.
577This command queries the shell with the command bound to
24fdffaa 578`shell-dirstack-query' (default \"dirs\"), reads the next
be9b65ac
DL
579line output and parses it to form the new directory stack.
580DON'T issue this command unless the buffer is at a shell prompt.
581Also, note that if some other subprocess decides to do output
582immediately after the query, its output will be taken as the
583new directory stack -- you lose. If this happens, just do the
584command again."
585 (interactive)
586 (let* ((proc (get-buffer-process (current-buffer)))
587 (pmark (process-mark proc)))
588 (goto-char pmark)
589 (insert shell-dirstack-query) (insert "\n")
590 (sit-for 0) ; force redisplay
591 (comint-send-string proc shell-dirstack-query)
592 (comint-send-string proc "\n")
593 (set-marker pmark (point))
594 (let ((pt (point))) ; wait for 1 line
595 ;; This extra newline prevents the user's pending input from spoofing us.
596 (insert "\n") (backward-char 1)
597 (while (not (looking-at ".+\n"))
598 (accept-process-output proc)
599 (goto-char pt)))
600 (goto-char pmark) (delete-char 1) ; remove the extra newline
601 ;; That's the dirlist. grab it & parse it.
d76b71af 602 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
be9b65ac
DL
603 (dl-len (length dl))
604 (ds '()) ; new dir stack
605 (i 0))
606 (while (< i dl-len)
607 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
608 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
3db9a4eb
RM
609 (setq ds (cons (concat comint-file-name-prefix
610 (substring dl (match-beginning 1)
611 (match-end 1)))
be9b65ac
DL
612 ds))
613 (setq i (match-end 0)))
3db9a4eb 614 (let ((ds (nreverse ds)))
be9b65ac 615 (condition-case nil
0b3c9cf1 616 (progn (shell-cd (car ds))
be9b65ac
DL
617 (setq shell-dirstack (cdr ds))
618 (shell-dirstack-message))
619 (error (message "Couldn't cd.")))))))
620
621;;; For your typing convenience:
31e1d920 622(defalias 'dirs 'shell-resync-dirs)
be9b65ac
DL
623
624
625;;; Show the current dirstack on the message line.
626;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
627;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
628;;; All the commands that mung the buffer's dirstack finish by calling
629;;; this guy.
630(defun shell-dirstack-message ()
94f9dcbe
RM
631 (let* ((msg "")
632 (ds (cons default-directory shell-dirstack))
d76b71af 633 (home (expand-file-name (concat comint-file-name-prefix "~/")))
94f9dcbe 634 (homelen (length home)))
be9b65ac
DL
635 (while ds
636 (let ((dir (car ds)))
94f9dcbe
RM
637 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
638 (setq dir (concat "~/" (substring dir homelen))))
d76b71af
RS
639 ;; Strip off comint-file-name-prefix if present.
640 (and comint-file-name-prefix
641 (>= (length dir) (length comint-file-name-prefix))
642 (string= comint-file-name-prefix
643 (substring dir 0 (length comint-file-name-prefix)))
644 (setq dir (substring dir (length comint-file-name-prefix)))
94f9dcbe 645 (setcar ds dir))
d76b71af 646 (setq msg (concat msg (directory-file-name dir) " "))
be9b65ac
DL
647 (setq ds (cdr ds))))
648 (message msg)))
a9ec2adb 649\f
d76b71af
RS
650(defun shell-forward-command (&optional arg)
651 "Move forward across ARG shell command(s). Does not cross lines.
652See `shell-command-regexp'."
653 (interactive "p")
654 (let ((limit (save-excursion (end-of-line nil) (point))))
19134c18 655 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
d76b71af 656 limit 'move arg)
b0f86743 657 (skip-syntax-backward " "))))
d76b71af
RS
658
659
660(defun shell-backward-command (&optional arg)
661 "Move backward across ARG shell command(s). Does not cross lines.
662See `shell-command-regexp'."
663 (interactive "p")
664 (let ((limit (save-excursion (comint-bol nil) (point))))
b0f86743
RS
665 (if (> limit (point))
666 (save-excursion (beginning-of-line) (setq limit (point))))
667 (skip-syntax-backward " " limit)
d76b71af 668 (if (re-search-backward
19134c18 669 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
d76b71af 670 (progn (goto-char (match-beginning 1))
b0f86743 671 (skip-chars-forward ";&|")))))
d76b71af
RS
672
673
d76b71af
RS
674(defun shell-dynamic-complete-command ()
675 "Dynamically complete the command at point.
676This function is similar to `comint-dynamic-complete-filename', except that it
677searches `exec-path' (minus the trailing emacs library path) for completion
678candidates. Note that this may not be the same as the shell's idea of the
679path.
680
681Completion is dependent on the value of `shell-completion-execonly', plus
988a4d60
RS
682those that effect file completion. See `shell-dynamic-complete-as-command'.
683
684Returns t if successful."
d76b71af 685 (interactive)
988a4d60
RS
686 (let ((filename (comint-match-partial-filename)))
687 (if (and filename
688 (save-match-data (not (string-match "[~/]" filename)))
689 (eq (match-beginning 0)
690 (save-excursion (shell-backward-command 1) (point))))
691 (prog2 (message "Completing command name...")
692 (shell-dynamic-complete-as-command)))))
693
694
695(defun shell-dynamic-complete-as-command ()
696 "Dynamically complete at point as a command.
697See `shell-dynamic-complete-filename'. Returns t if successful."
56783585 698 (let* ((filename (or (comint-match-partial-filename) ""))
d76b71af
RS
699 (pathnondir (file-name-nondirectory filename))
700 (paths (cdr (reverse exec-path)))
701 (cwd (file-name-as-directory (expand-file-name default-directory)))
702 (ignored-extensions
a867a90a
RS
703 (and comint-completion-fignore
704 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
705 comint-completion-fignore "\\|")))
d76b71af
RS
706 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
707 ;; Go thru each path in the search path, finding completions.
708 (while paths
709 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
710 comps-in-path (and (file-accessible-directory-p path)
711 (file-name-all-completions pathnondir path)))
712 ;; Go thru each completion found, to see whether it should be used.
713 (while comps-in-path
714 (setq file (car comps-in-path)
715 filepath (concat path file))
716 (if (and (not (member file completions))
7b2db0a0
KH
717 (not (and ignored-extensions
718 (string-match ignored-extensions file)))
d76b71af
RS
719 (or (string-equal path cwd)
720 (not (file-directory-p filepath)))
721 (or (null shell-completion-execonly)
722 (file-executable-p filepath)))
723 (setq completions (cons file completions)))
724 (setq comps-in-path (cdr comps-in-path)))
725 (setq paths (cdr paths)))
726 ;; OK, we've got a list of completions.
56783585
RS
727 (let ((success (let ((comint-completion-addsuffix nil))
728 (comint-dynamic-simple-complete pathnondir completions))))
729 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
730 (not (file-directory-p (comint-match-partial-filename))))
731 (insert " "))
732 success)))
988a4d60
RS
733
734
735(defun shell-match-partial-variable ()
736 "Return the variable at point, or nil if non is found."
737 (save-excursion
738 (let ((limit (point)))
739 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
740 (or (looking-at "\\$") (forward-char 1)))
741 ;; Anchor the search forwards.
742 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
743 nil
744 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
745 (buffer-substring (match-beginning 0) (match-end 0))))))
a9ec2adb 746
988a4d60
RS
747
748(defun shell-dynamic-complete-environment-variable ()
749 "Dynamically complete the environment variable at point.
750Completes if after a variable, i.e., if it starts with a \"$\".
751See `shell-dynamic-complete-as-environment-variable'.
752
753This function is similar to `comint-dynamic-complete-filename', except that it
754searches `process-environment' for completion candidates. Note that this may
755not be the same as the interpreter's idea of variable names. The main problem
756with this type of completion is that `process-environment' is the environment
757which Emacs started with. Emacs does not track changes to the environment made
758by the interpreter. Perhaps it would be more accurate if this function was
759called `shell-dynamic-complete-process-environment-variable'.
760
761Returns non-nil if successful."
762 (interactive)
763 (let ((variable (shell-match-partial-variable)))
764 (if (and variable (string-match "^\\$" variable))
765 (prog2 (message "Completing variable name...")
766 (shell-dynamic-complete-as-environment-variable)))))
767
768
769(defun shell-dynamic-complete-as-environment-variable ()
770 "Dynamically complete at point as an environment variable.
771Used by `shell-dynamic-complete-environment-variable'.
772Uses `comint-dynamic-simple-complete'."
773 (let* ((var (or (shell-match-partial-variable) ""))
774 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
775 (variables (mapcar (function (lambda (x)
776 (substring x 0 (string-match "=" x))))
777 process-environment))
778 (addsuffix comint-completion-addsuffix)
779 (comint-completion-addsuffix nil)
780 (success (comint-dynamic-simple-complete variable variables)))
781 (if (memq success '(sole shortest))
782 (let* ((var (shell-match-partial-variable))
783 (variable (substring var (string-match "[^$({]" var)))
784 (protection (cond ((string-match "{" var) "}")
785 ((string-match "(" var) ")")
786 (t "")))
787 (suffix (cond ((null addsuffix) "")
788 ((file-directory-p
789 (comint-directory (getenv variable))) "/")
790 (t " "))))
791 (insert protection suffix)))
792 success))
793
794
795(defun shell-replace-by-expanded-directory ()
796 "Expand directory stack reference before point.
797Directory stack references are of the form \"=digit\" or \"=-\".
798See `default-directory' and `shell-dirstack'.
799
800Returns t if successful."
801 (interactive)
802 (if (comint-match-partial-filename)
803 (save-excursion
988a4d60
RS
804 (goto-char (match-beginning 0))
805 (let ((stack (cons default-directory shell-dirstack))
806 (index (cond ((looking-at "=-/?")
807 (length shell-dirstack))
808 ((looking-at "=\\([0-9]+\\)")
809 (string-to-number
810 (buffer-substring
811 (match-beginning 1) (match-end 1)))))))
812 (cond ((null index)
813 nil)
814 ((>= index (length stack))
815 (error "Directory stack not that deep."))
816 (t
817 (replace-match (file-name-as-directory (nth index stack)) t t)
818 (message "Directory item: %d" index)
819 t))))))
820\f
c88ab9ce
ER
821(provide 'shell)
822
823;;; shell.el ends here