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