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