(gnus-group-set-mode-line): Allow user defined specs in the group
[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
54021695 453 (let ((start (progn (string-match "^[; \t]*" str) ; skip whitespace
d76b71af
RS
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))
54021695
KH
460 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
461 "\\)\\($\\|[ \t]\\)")
462 cmd)
d76b71af 463 (shell-process-popd (substitute-in-file-name arg1)))
54021695
KH
464 ((string-match (concat "\\`\\(" shell-pushd-regexp
465 "\\)\\($\\|[ \t]\\)")
466 cmd)
d76b71af 467 (shell-process-pushd (substitute-in-file-name arg1)))
54021695
KH
468 ((string-match (concat "\\`\\(" shell-cd-regexp
469 "\\)\\($\\|[ \t]\\)")
470 cmd)
d76b71af 471 (shell-process-cd (substitute-in-file-name arg1))))
54021695 472 (setq start (progn (string-match "[; \t]*" str end) ; skip again
d76b71af 473 (match-end 0)))))
ba02c167 474 (error "Couldn't cd"))))
d76b71af 475
be9b65ac
DL
476;;; popd [+n]
477(defun shell-process-popd (arg)
d76b71af
RS
478 (let ((num (or (shell-extract-num arg) 0)))
479 (cond ((and num (= num 0) shell-dirstack)
0b3c9cf1 480 (shell-cd (car shell-dirstack))
d76b71af
RS
481 (setq shell-dirstack (cdr shell-dirstack))
482 (shell-dirstack-message))
483 ((and num (> num 0) (<= num (length shell-dirstack)))
484 (let* ((ds (cons nil shell-dirstack))
485 (cell (nthcdr (1- num) ds)))
486 (rplacd cell (cdr (cdr cell)))
487 (setq shell-dirstack (cdr ds))
488 (shell-dirstack-message)))
489 (t
ba02c167 490 (error "Couldn't popd")))))
be9b65ac 491
3db9a4eb 492;; Return DIR prefixed with comint-file-name-prefix as appropriate.
4a02b552
RS
493(defun shell-prefixed-directory-name (dir)
494 (if (= (length comint-file-name-prefix) 0)
495 dir
496 (if (file-name-absolute-p dir)
497 ;; The name is absolute, so prepend the prefix.
498 (concat comint-file-name-prefix dir)
0b3c9cf1 499 ;; For relative name we assume default-directory already has the prefix.
4a02b552 500 (expand-file-name dir))))
3db9a4eb 501
be9b65ac
DL
502;;; cd [dir]
503(defun shell-process-cd (arg)
3db9a4eb
RM
504 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
505 "~"))
d76b71af 506 ((string-equal "-" arg) shell-last-dir)
3db9a4eb 507 (t (shell-prefixed-directory-name arg)))))
d76b71af 508 (setq shell-last-dir default-directory)
0b3c9cf1 509 (shell-cd new-dir)
d76b71af 510 (shell-dirstack-message)))
be9b65ac
DL
511
512;;; pushd [+n | dir]
513(defun shell-process-pushd (arg)
d76b71af
RS
514 (let ((num (shell-extract-num arg)))
515 (cond ((zerop (length arg))
516 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
517 (cond (shell-pushd-tohome
3db9a4eb 518 (shell-process-pushd (concat comint-file-name-prefix "~")))
d76b71af
RS
519 (shell-dirstack
520 (let ((old default-directory))
0b3c9cf1 521 (shell-cd (car shell-dirstack))
d76b71af
RS
522 (setq shell-dirstack
523 (cons old (cdr shell-dirstack)))
524 (shell-dirstack-message)))
525 (t
526 (message "Directory stack empty."))))
527 ((numberp num)
528 ;; pushd +n
529 (cond ((> num (length shell-dirstack))
530 (message "Directory stack not that deep."))
531 ((= num 0)
532 (error (message "Couldn't cd.")))
533 (shell-pushd-dextract
534 (let ((dir (nth (1- num) shell-dirstack)))
535 (shell-process-popd arg)
536 (shell-process-pushd default-directory)
0b3c9cf1 537 (shell-cd dir)
d76b71af
RS
538 (shell-dirstack-message)))
539 (t
540 (let* ((ds (cons default-directory shell-dirstack))
541 (dslen (length ds))
542 (front (nthcdr num ds))
543 (back (reverse (nthcdr (- dslen num) (reverse ds))))
544 (new-ds (append front back)))
0b3c9cf1 545 (shell-cd (car new-ds))
d76b71af
RS
546 (setq shell-dirstack (cdr new-ds))
547 (shell-dirstack-message)))))
548 (t
549 ;; pushd <dir>
550 (let ((old-wd default-directory))
0b3c9cf1 551 (shell-cd (shell-prefixed-directory-name arg))
d76b71af
RS
552 (if (or (null shell-pushd-dunique)
553 (not (member old-wd shell-dirstack)))
554 (setq shell-dirstack (cons old-wd shell-dirstack)))
555 (shell-dirstack-message))))))
be9b65ac
DL
556
557;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
558(defun shell-extract-num (str)
559 (and (string-match "^\\+[1-9][0-9]*$" str)
560 (string-to-int str)))
561
562
563(defun shell-dirtrack-toggle ()
564 "Turn directory tracking on and off in a shell buffer."
565 (interactive)
0b3c9cf1
SM
566 (if (setq shell-dirtrackp (not shell-dirtrackp))
567 (setq list-buffers-directory default-directory)
568 (setq list-buffers-directory nil))
d76b71af 569 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
be9b65ac
DL
570
571;;; For your typing convenience:
31e1d920 572(defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
be9b65ac 573
0b3c9cf1
SM
574(defun shell-cd (dir)
575 "Do normal `cd' to DIR, and set `list-buffers-directory'."
b7e97ed5
SM
576 (if shell-dirtrackp
577 (setq list-buffers-directory (file-name-as-directory
578 (expand-file-name dir))))
0b3c9cf1 579 (cd dir))
be9b65ac
DL
580
581(defun shell-resync-dirs ()
582 "Resync the buffer's idea of the current directory stack.
583This command queries the shell with the command bound to
24fdffaa 584`shell-dirstack-query' (default \"dirs\"), reads the next
be9b65ac
DL
585line output and parses it to form the new directory stack.
586DON'T issue this command unless the buffer is at a shell prompt.
587Also, note that if some other subprocess decides to do output
588immediately after the query, its output will be taken as the
589new directory stack -- you lose. If this happens, just do the
590command again."
591 (interactive)
592 (let* ((proc (get-buffer-process (current-buffer)))
593 (pmark (process-mark proc)))
594 (goto-char pmark)
595 (insert shell-dirstack-query) (insert "\n")
596 (sit-for 0) ; force redisplay
597 (comint-send-string proc shell-dirstack-query)
598 (comint-send-string proc "\n")
599 (set-marker pmark (point))
600 (let ((pt (point))) ; wait for 1 line
601 ;; This extra newline prevents the user's pending input from spoofing us.
602 (insert "\n") (backward-char 1)
603 (while (not (looking-at ".+\n"))
604 (accept-process-output proc)
605 (goto-char pt)))
606 (goto-char pmark) (delete-char 1) ; remove the extra newline
607 ;; That's the dirlist. grab it & parse it.
d76b71af 608 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
be9b65ac
DL
609 (dl-len (length dl))
610 (ds '()) ; new dir stack
611 (i 0))
612 (while (< i dl-len)
613 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
614 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
3db9a4eb
RM
615 (setq ds (cons (concat comint-file-name-prefix
616 (substring dl (match-beginning 1)
617 (match-end 1)))
be9b65ac
DL
618 ds))
619 (setq i (match-end 0)))
3db9a4eb 620 (let ((ds (nreverse ds)))
be9b65ac 621 (condition-case nil
0b3c9cf1 622 (progn (shell-cd (car ds))
be9b65ac
DL
623 (setq shell-dirstack (cdr ds))
624 (shell-dirstack-message))
625 (error (message "Couldn't cd.")))))))
626
627;;; For your typing convenience:
31e1d920 628(defalias 'dirs 'shell-resync-dirs)
be9b65ac
DL
629
630
631;;; Show the current dirstack on the message line.
632;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
633;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
634;;; All the commands that mung the buffer's dirstack finish by calling
635;;; this guy.
636(defun shell-dirstack-message ()
94f9dcbe
RM
637 (let* ((msg "")
638 (ds (cons default-directory shell-dirstack))
d76b71af 639 (home (expand-file-name (concat comint-file-name-prefix "~/")))
94f9dcbe 640 (homelen (length home)))
be9b65ac
DL
641 (while ds
642 (let ((dir (car ds)))
94f9dcbe
RM
643 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
644 (setq dir (concat "~/" (substring dir homelen))))
d76b71af
RS
645 ;; Strip off comint-file-name-prefix if present.
646 (and comint-file-name-prefix
647 (>= (length dir) (length comint-file-name-prefix))
648 (string= comint-file-name-prefix
649 (substring dir 0 (length comint-file-name-prefix)))
650 (setq dir (substring dir (length comint-file-name-prefix)))
94f9dcbe 651 (setcar ds dir))
d76b71af 652 (setq msg (concat msg (directory-file-name dir) " "))
be9b65ac
DL
653 (setq ds (cdr ds))))
654 (message msg)))
a9ec2adb 655\f
d76b71af
RS
656(defun shell-forward-command (&optional arg)
657 "Move forward across ARG shell command(s). Does not cross lines.
658See `shell-command-regexp'."
659 (interactive "p")
660 (let ((limit (save-excursion (end-of-line nil) (point))))
19134c18 661 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
d76b71af 662 limit 'move arg)
b0f86743 663 (skip-syntax-backward " "))))
d76b71af
RS
664
665
666(defun shell-backward-command (&optional arg)
667 "Move backward across ARG shell command(s). Does not cross lines.
668See `shell-command-regexp'."
669 (interactive "p")
670 (let ((limit (save-excursion (comint-bol nil) (point))))
b0f86743
RS
671 (if (> limit (point))
672 (save-excursion (beginning-of-line) (setq limit (point))))
673 (skip-syntax-backward " " limit)
d76b71af 674 (if (re-search-backward
19134c18 675 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
d76b71af 676 (progn (goto-char (match-beginning 1))
b0f86743 677 (skip-chars-forward ";&|")))))
d76b71af
RS
678
679
d76b71af
RS
680(defun shell-dynamic-complete-command ()
681 "Dynamically complete the command at point.
682This function is similar to `comint-dynamic-complete-filename', except that it
683searches `exec-path' (minus the trailing emacs library path) for completion
684candidates. Note that this may not be the same as the shell's idea of the
685path.
686
687Completion is dependent on the value of `shell-completion-execonly', plus
988a4d60
RS
688those that effect file completion. See `shell-dynamic-complete-as-command'.
689
690Returns t if successful."
d76b71af 691 (interactive)
988a4d60
RS
692 (let ((filename (comint-match-partial-filename)))
693 (if (and filename
694 (save-match-data (not (string-match "[~/]" filename)))
695 (eq (match-beginning 0)
696 (save-excursion (shell-backward-command 1) (point))))
697 (prog2 (message "Completing command name...")
698 (shell-dynamic-complete-as-command)))))
699
700
701(defun shell-dynamic-complete-as-command ()
702 "Dynamically complete at point as a command.
703See `shell-dynamic-complete-filename'. Returns t if successful."
56783585 704 (let* ((filename (or (comint-match-partial-filename) ""))
d76b71af
RS
705 (pathnondir (file-name-nondirectory filename))
706 (paths (cdr (reverse exec-path)))
707 (cwd (file-name-as-directory (expand-file-name default-directory)))
708 (ignored-extensions
a867a90a
RS
709 (and comint-completion-fignore
710 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
711 comint-completion-fignore "\\|")))
d76b71af
RS
712 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
713 ;; Go thru each path in the search path, finding completions.
714 (while paths
715 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
716 comps-in-path (and (file-accessible-directory-p path)
717 (file-name-all-completions pathnondir path)))
718 ;; Go thru each completion found, to see whether it should be used.
719 (while comps-in-path
720 (setq file (car comps-in-path)
721 filepath (concat path file))
722 (if (and (not (member file completions))
7b2db0a0
KH
723 (not (and ignored-extensions
724 (string-match ignored-extensions file)))
d76b71af
RS
725 (or (string-equal path cwd)
726 (not (file-directory-p filepath)))
727 (or (null shell-completion-execonly)
728 (file-executable-p filepath)))
729 (setq completions (cons file completions)))
730 (setq comps-in-path (cdr comps-in-path)))
731 (setq paths (cdr paths)))
732 ;; OK, we've got a list of completions.
56783585
RS
733 (let ((success (let ((comint-completion-addsuffix nil))
734 (comint-dynamic-simple-complete pathnondir completions))))
735 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
736 (not (file-directory-p (comint-match-partial-filename))))
737 (insert " "))
738 success)))
988a4d60
RS
739
740
741(defun shell-match-partial-variable ()
742 "Return the variable at point, or nil if non is found."
743 (save-excursion
744 (let ((limit (point)))
745 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
746 (or (looking-at "\\$") (forward-char 1)))
747 ;; Anchor the search forwards.
748 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
749 nil
750 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
751 (buffer-substring (match-beginning 0) (match-end 0))))))
a9ec2adb 752
988a4d60
RS
753
754(defun shell-dynamic-complete-environment-variable ()
755 "Dynamically complete the environment variable at point.
756Completes if after a variable, i.e., if it starts with a \"$\".
757See `shell-dynamic-complete-as-environment-variable'.
758
759This function is similar to `comint-dynamic-complete-filename', except that it
760searches `process-environment' for completion candidates. Note that this may
761not be the same as the interpreter's idea of variable names. The main problem
762with this type of completion is that `process-environment' is the environment
763which Emacs started with. Emacs does not track changes to the environment made
764by the interpreter. Perhaps it would be more accurate if this function was
765called `shell-dynamic-complete-process-environment-variable'.
766
767Returns non-nil if successful."
768 (interactive)
769 (let ((variable (shell-match-partial-variable)))
770 (if (and variable (string-match "^\\$" variable))
771 (prog2 (message "Completing variable name...")
772 (shell-dynamic-complete-as-environment-variable)))))
773
774
775(defun shell-dynamic-complete-as-environment-variable ()
776 "Dynamically complete at point as an environment variable.
777Used by `shell-dynamic-complete-environment-variable'.
778Uses `comint-dynamic-simple-complete'."
779 (let* ((var (or (shell-match-partial-variable) ""))
780 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
781 (variables (mapcar (function (lambda (x)
782 (substring x 0 (string-match "=" x))))
783 process-environment))
784 (addsuffix comint-completion-addsuffix)
785 (comint-completion-addsuffix nil)
786 (success (comint-dynamic-simple-complete variable variables)))
787 (if (memq success '(sole shortest))
788 (let* ((var (shell-match-partial-variable))
789 (variable (substring var (string-match "[^$({]" var)))
790 (protection (cond ((string-match "{" var) "}")
791 ((string-match "(" var) ")")
792 (t "")))
793 (suffix (cond ((null addsuffix) "")
794 ((file-directory-p
795 (comint-directory (getenv variable))) "/")
796 (t " "))))
797 (insert protection suffix)))
798 success))
799
800
801(defun shell-replace-by-expanded-directory ()
802 "Expand directory stack reference before point.
803Directory stack references are of the form \"=digit\" or \"=-\".
804See `default-directory' and `shell-dirstack'.
805
806Returns t if successful."
807 (interactive)
808 (if (comint-match-partial-filename)
809 (save-excursion
988a4d60
RS
810 (goto-char (match-beginning 0))
811 (let ((stack (cons default-directory shell-dirstack))
812 (index (cond ((looking-at "=-/?")
813 (length shell-dirstack))
814 ((looking-at "=\\([0-9]+\\)")
815 (string-to-number
816 (buffer-substring
817 (match-beginning 1) (match-end 1)))))))
818 (cond ((null index)
819 nil)
820 ((>= index (length stack))
821 (error "Directory stack not that deep."))
822 (t
823 (replace-match (file-name-as-directory (nth index stack)) t t)
824 (message "Directory item: %d" index)
825 t))))))
826\f
c88ab9ce
ER
827(provide 'shell)
828
829;;; shell.el ends here