(shell-match-partial-variable): Doc fix.
[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
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 343 (setq shell-dirstack-query
221ca406
SM
344 (cond ((string-equal shell "sh") "pwd")
345 ((string-equal shell "ksh") "echo $PWD ~-")
346 (t "dirs"))))
d76b71af 347 (run-hooks 'shell-mode-hook)
4f99443b 348 (comint-read-input-ring t))
be9b65ac 349\f
c88ab9ce 350;;;###autoload
be9b65ac
DL
351(defun shell ()
352 "Run an inferior shell, with I/O through buffer *shell*.
353If buffer exists but shell process is not running, make new shell.
d76b71af 354If buffer exists and shell process is running, just switch to buffer `*shell*'.
24fdffaa 355Program used comes from variable `explicit-shell-file-name',
a9ec2adb
JB
356 or (if that is nil) from the ESHELL environment variable,
357 or else from SHELL if there is no ESHELL.
fbc270e7 358If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
a9ec2adb
JB
359 (Note that this may lose due to a timing error if the shell
360 discards input when it starts up.)
fbc270e7
RS
361The buffer is put in Shell mode, giving commands for sending input
362and controlling the subjobs of the shell. See `shell-mode'.
363See also the variable `shell-prompt-pattern'.
be9b65ac 364
a9ec2adb 365The shell file name (sans directories) is used to make a symbol name
62c9fad7 366such as `explicit-csh-args'. If that symbol is a variable,
be9b65ac
DL
367its value is used as a list of arguments when invoking the shell.
368Otherwise, one argument `-i' is passed to the shell.
369
370\(Type \\[describe-mode] in the shell buffer for a list of commands.)"
371 (interactive)
d76b71af
RS
372 (if (not (comint-check-proc "*shell*"))
373 (let* ((prog (or explicit-shell-file-name
374 (getenv "ESHELL")
375 (getenv "SHELL")
376 "/bin/sh"))
377 (name (file-name-nondirectory prog))
378 (startfile (concat "~/.emacs_" name))
519bfec4
RS
379 (xargs-name (intern-soft (concat "explicit-" name "-args")))
380 shell-buffer)
381 (save-excursion
382 (set-buffer (apply 'make-comint "shell" prog
383 (if (file-exists-p startfile) startfile)
384 (if (and xargs-name (boundp xargs-name))
385 (symbol-value xargs-name)
386 '("-i"))))
387 (setq shell-buffer (current-buffer))
388 (shell-mode))
389 (pop-to-buffer shell-buffer))
390 (pop-to-buffer "*shell*")))
391
392;;; Don't do this when shell.el is loaded, only while dumping.
393;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
be9b65ac
DL
394\f
395;;; Directory tracking
b578f267 396;;;
be9b65ac
DL
397;;; This code provides the shell mode input sentinel
398;;; SHELL-DIRECTORY-TRACKER
399;;; that tracks cd, pushd, and popd commands issued to the shell, and
400;;; changes the current directory of the shell buffer accordingly.
401;;;
402;;; This is basically a fragile hack, although it's more accurate than
b7fc702e 403;;; the version in Emacs 18's shell.el. It has the following failings:
be9b65ac 404;;; 1. It doesn't know about the cdpath shell variable.
d76b71af
RS
405;;; 2. It cannot infallibly deal with command sequences, though it does well
406;;; with these and with ignoring commands forked in another shell with ()s.
407;;; 3. More generally, any complex command is going to throw it. Otherwise,
408;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
409;;; that, there's no way to catch shell commands where cd's are buried
410;;; inside conditional expressions, aliases, and so forth.
be9b65ac
DL
411;;;
412;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
413;;; messes it up. You run other processes under the shell; these each have
414;;; separate working directories, and some have commands for manipulating
415;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
a9ec2adb 416;;; commands that do *not* affect the current w.d. at all, but look like they
be9b65ac
DL
417;;; do (e.g., the cd command in ftp). In shells that allow you job
418;;; control, you can switch between jobs, all having different w.d.'s. So
419;;; simply saying %3 can shift your w.d..
420;;;
421;;; The solution is to relax, not stress out about it, and settle for
422;;; a hack that works pretty well in typical circumstances. Remember
423;;; that a half-assed solution is more in keeping with the spirit of Unix,
424;;; anyway. Blech.
425;;;
426;;; One good hack not implemented here for users of programmable shells
427;;; is to program up the shell w.d. manipulation commands to output
428;;; a coded command sequence to the tty. Something like
429;;; ESC | <cwd> |
430;;; where <cwd> is the new current working directory. Then trash the
431;;; directory tracking machinery currently used in this package, and
432;;; replace it with a process filter that watches for and strips out
433;;; these messages.
434
be9b65ac
DL
435(defun shell-directory-tracker (str)
436 "Tracks cd, pushd and popd commands issued to the shell.
437This function is called on each input passed to the shell.
438It watches for cd, pushd and popd commands and sets the buffer's
439default directory to track these commands.
440
441You may toggle this tracking on and off with M-x dirtrack-toggle.
442If emacs gets confused, you can resync with the shell with M-x dirs.
443
d76b71af
RS
444See variables `shell-cd-regexp', `shell-pushd-regexp', and `shell-popd-regexp',
445while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
5394cb44 446control the behavior of the relevant command.
d76b71af 447
24fdffaa 448Environment variables are expanded, see function `substitute-in-file-name'."
d76b71af
RS
449 (if shell-dirtrackp
450 ;; We fail gracefully if we think the command will fail in the shell.
451 (condition-case chdir-failure
54021695 452 (let ((start (progn (string-match "^[; \t]*" str) ; skip whitespace
d76b71af
RS
453 (match-end 0)))
454 end cmd arg1)
455 (while (string-match shell-command-regexp str start)
456 (setq end (match-end 0)
457 cmd (comint-arguments (substring str start end) 0 0)
458 arg1 (comint-arguments (substring str start end) 1 1))
54021695
KH
459 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
460 "\\)\\($\\|[ \t]\\)")
461 cmd)
d76b71af 462 (shell-process-popd (substitute-in-file-name arg1)))
54021695
KH
463 ((string-match (concat "\\`\\(" shell-pushd-regexp
464 "\\)\\($\\|[ \t]\\)")
465 cmd)
d76b71af 466 (shell-process-pushd (substitute-in-file-name arg1)))
54021695
KH
467 ((string-match (concat "\\`\\(" shell-cd-regexp
468 "\\)\\($\\|[ \t]\\)")
469 cmd)
d76b71af 470 (shell-process-cd (substitute-in-file-name arg1))))
54021695 471 (setq start (progn (string-match "[; \t]*" str end) ; skip again
d76b71af 472 (match-end 0)))))
ba02c167 473 (error "Couldn't cd"))))
d76b71af 474
be9b65ac
DL
475;;; popd [+n]
476(defun shell-process-popd (arg)
d76b71af
RS
477 (let ((num (or (shell-extract-num arg) 0)))
478 (cond ((and num (= num 0) shell-dirstack)
0b3c9cf1 479 (shell-cd (car shell-dirstack))
d76b71af
RS
480 (setq shell-dirstack (cdr shell-dirstack))
481 (shell-dirstack-message))
482 ((and num (> num 0) (<= num (length shell-dirstack)))
483 (let* ((ds (cons nil shell-dirstack))
484 (cell (nthcdr (1- num) ds)))
485 (rplacd cell (cdr (cdr cell)))
486 (setq shell-dirstack (cdr ds))
487 (shell-dirstack-message)))
488 (t
ba02c167 489 (error "Couldn't popd")))))
be9b65ac 490
3db9a4eb 491;; Return DIR prefixed with comint-file-name-prefix as appropriate.
4a02b552
RS
492(defun shell-prefixed-directory-name (dir)
493 (if (= (length comint-file-name-prefix) 0)
494 dir
495 (if (file-name-absolute-p dir)
496 ;; The name is absolute, so prepend the prefix.
497 (concat comint-file-name-prefix dir)
0b3c9cf1 498 ;; For relative name we assume default-directory already has the prefix.
4a02b552 499 (expand-file-name dir))))
3db9a4eb 500
be9b65ac
DL
501;;; cd [dir]
502(defun shell-process-cd (arg)
3db9a4eb
RM
503 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
504 "~"))
d76b71af 505 ((string-equal "-" arg) shell-last-dir)
3db9a4eb 506 (t (shell-prefixed-directory-name arg)))))
d76b71af 507 (setq shell-last-dir default-directory)
0b3c9cf1 508 (shell-cd new-dir)
d76b71af 509 (shell-dirstack-message)))
be9b65ac
DL
510
511;;; pushd [+n | dir]
512(defun shell-process-pushd (arg)
d76b71af
RS
513 (let ((num (shell-extract-num arg)))
514 (cond ((zerop (length arg))
515 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
516 (cond (shell-pushd-tohome
3db9a4eb 517 (shell-process-pushd (concat comint-file-name-prefix "~")))
d76b71af
RS
518 (shell-dirstack
519 (let ((old default-directory))
0b3c9cf1 520 (shell-cd (car shell-dirstack))
221ca406 521 (setq shell-dirstack (cons old (cdr shell-dirstack)))
d76b71af
RS
522 (shell-dirstack-message)))
523 (t
524 (message "Directory stack empty."))))
525 ((numberp num)
526 ;; pushd +n
527 (cond ((> num (length shell-dirstack))
528 (message "Directory stack not that deep."))
529 ((= num 0)
530 (error (message "Couldn't cd.")))
531 (shell-pushd-dextract
532 (let ((dir (nth (1- num) shell-dirstack)))
533 (shell-process-popd arg)
534 (shell-process-pushd default-directory)
0b3c9cf1 535 (shell-cd dir)
d76b71af
RS
536 (shell-dirstack-message)))
537 (t
538 (let* ((ds (cons default-directory shell-dirstack))
539 (dslen (length ds))
540 (front (nthcdr num ds))
541 (back (reverse (nthcdr (- dslen num) (reverse ds))))
542 (new-ds (append front back)))
0b3c9cf1 543 (shell-cd (car new-ds))
d76b71af
RS
544 (setq shell-dirstack (cdr new-ds))
545 (shell-dirstack-message)))))
546 (t
547 ;; pushd <dir>
548 (let ((old-wd default-directory))
0b3c9cf1 549 (shell-cd (shell-prefixed-directory-name arg))
d76b71af
RS
550 (if (or (null shell-pushd-dunique)
551 (not (member old-wd shell-dirstack)))
552 (setq shell-dirstack (cons old-wd shell-dirstack)))
553 (shell-dirstack-message))))))
be9b65ac
DL
554
555;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
556(defun shell-extract-num (str)
557 (and (string-match "^\\+[1-9][0-9]*$" str)
558 (string-to-int str)))
559
560
561(defun shell-dirtrack-toggle ()
562 "Turn directory tracking on and off in a shell buffer."
563 (interactive)
0b3c9cf1
SM
564 (if (setq shell-dirtrackp (not shell-dirtrackp))
565 (setq list-buffers-directory default-directory)
566 (setq list-buffers-directory nil))
d76b71af 567 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
be9b65ac
DL
568
569;;; For your typing convenience:
31e1d920 570(defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
be9b65ac 571
0b3c9cf1
SM
572(defun shell-cd (dir)
573 "Do normal `cd' to DIR, and set `list-buffers-directory'."
b7e97ed5
SM
574 (if shell-dirtrackp
575 (setq list-buffers-directory (file-name-as-directory
576 (expand-file-name dir))))
0b3c9cf1 577 (cd dir))
be9b65ac
DL
578
579(defun shell-resync-dirs ()
580 "Resync the buffer's idea of the current directory stack.
581This command queries the shell with the command bound to
24fdffaa 582`shell-dirstack-query' (default \"dirs\"), reads the next
be9b65ac
DL
583line output and parses it to form the new directory stack.
584DON'T issue this command unless the buffer is at a shell prompt.
585Also, note that if some other subprocess decides to do output
586immediately after the query, its output will be taken as the
587new directory stack -- you lose. If this happens, just do the
588command again."
589 (interactive)
590 (let* ((proc (get-buffer-process (current-buffer)))
591 (pmark (process-mark proc)))
592 (goto-char pmark)
593 (insert shell-dirstack-query) (insert "\n")
594 (sit-for 0) ; force redisplay
595 (comint-send-string proc shell-dirstack-query)
596 (comint-send-string proc "\n")
597 (set-marker pmark (point))
598 (let ((pt (point))) ; wait for 1 line
599 ;; This extra newline prevents the user's pending input from spoofing us.
600 (insert "\n") (backward-char 1)
601 (while (not (looking-at ".+\n"))
602 (accept-process-output proc)
603 (goto-char pt)))
604 (goto-char pmark) (delete-char 1) ; remove the extra newline
605 ;; That's the dirlist. grab it & parse it.
d76b71af 606 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
be9b65ac
DL
607 (dl-len (length dl))
608 (ds '()) ; new dir stack
609 (i 0))
610 (while (< i dl-len)
611 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
612 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
3db9a4eb
RM
613 (setq ds (cons (concat comint-file-name-prefix
614 (substring dl (match-beginning 1)
615 (match-end 1)))
be9b65ac
DL
616 ds))
617 (setq i (match-end 0)))
3db9a4eb 618 (let ((ds (nreverse ds)))
be9b65ac 619 (condition-case nil
0b3c9cf1 620 (progn (shell-cd (car ds))
221ca406
SM
621 (setq shell-dirstack (cdr ds)
622 shell-last-dir (car shell-dirstack))
be9b65ac
DL
623 (shell-dirstack-message))
624 (error (message "Couldn't cd.")))))))
625
626;;; For your typing convenience:
31e1d920 627(defalias 'dirs 'shell-resync-dirs)
be9b65ac
DL
628
629
630;;; Show the current dirstack on the message line.
631;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
632;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
633;;; All the commands that mung the buffer's dirstack finish by calling
634;;; this guy.
635(defun shell-dirstack-message ()
94f9dcbe
RM
636 (let* ((msg "")
637 (ds (cons default-directory shell-dirstack))
d76b71af 638 (home (expand-file-name (concat comint-file-name-prefix "~/")))
94f9dcbe 639 (homelen (length home)))
be9b65ac
DL
640 (while ds
641 (let ((dir (car ds)))
94f9dcbe
RM
642 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
643 (setq dir (concat "~/" (substring dir homelen))))
d76b71af
RS
644 ;; Strip off comint-file-name-prefix if present.
645 (and comint-file-name-prefix
646 (>= (length dir) (length comint-file-name-prefix))
647 (string= comint-file-name-prefix
648 (substring dir 0 (length comint-file-name-prefix)))
649 (setq dir (substring dir (length comint-file-name-prefix)))
94f9dcbe 650 (setcar ds dir))
d76b71af 651 (setq msg (concat msg (directory-file-name dir) " "))
be9b65ac 652 (setq ds (cdr ds))))
6048fac7 653 (message "%s" msg)))
a9ec2adb 654\f
d76b71af
RS
655(defun shell-forward-command (&optional arg)
656 "Move forward across ARG shell command(s). Does not cross lines.
657See `shell-command-regexp'."
658 (interactive "p")
659 (let ((limit (save-excursion (end-of-line nil) (point))))
19134c18 660 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
d76b71af 661 limit 'move arg)
b0f86743 662 (skip-syntax-backward " "))))
d76b71af
RS
663
664
665(defun shell-backward-command (&optional arg)
666 "Move backward across ARG shell command(s). Does not cross lines.
667See `shell-command-regexp'."
668 (interactive "p")
669 (let ((limit (save-excursion (comint-bol nil) (point))))
b0f86743
RS
670 (if (> limit (point))
671 (save-excursion (beginning-of-line) (setq limit (point))))
672 (skip-syntax-backward " " limit)
d76b71af 673 (if (re-search-backward
19134c18 674 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
d76b71af 675 (progn (goto-char (match-beginning 1))
b0f86743 676 (skip-chars-forward ";&|")))))
d76b71af
RS
677
678
d76b71af
RS
679(defun shell-dynamic-complete-command ()
680 "Dynamically complete the command at point.
681This function is similar to `comint-dynamic-complete-filename', except that it
682searches `exec-path' (minus the trailing emacs library path) for completion
683candidates. Note that this may not be the same as the shell's idea of the
684path.
685
686Completion is dependent on the value of `shell-completion-execonly', plus
988a4d60
RS
687those that effect file completion. See `shell-dynamic-complete-as-command'.
688
689Returns t if successful."
d76b71af 690 (interactive)
988a4d60
RS
691 (let ((filename (comint-match-partial-filename)))
692 (if (and filename
693 (save-match-data (not (string-match "[~/]" filename)))
694 (eq (match-beginning 0)
695 (save-excursion (shell-backward-command 1) (point))))
696 (prog2 (message "Completing command name...")
697 (shell-dynamic-complete-as-command)))))
698
699
700(defun shell-dynamic-complete-as-command ()
701 "Dynamically complete at point as a command.
702See `shell-dynamic-complete-filename'. Returns t if successful."
56783585 703 (let* ((filename (or (comint-match-partial-filename) ""))
d76b71af
RS
704 (pathnondir (file-name-nondirectory filename))
705 (paths (cdr (reverse exec-path)))
706 (cwd (file-name-as-directory (expand-file-name default-directory)))
707 (ignored-extensions
a867a90a
RS
708 (and comint-completion-fignore
709 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
710 comint-completion-fignore "\\|")))
d76b71af
RS
711 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
712 ;; Go thru each path in the search path, finding completions.
713 (while paths
714 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
715 comps-in-path (and (file-accessible-directory-p path)
716 (file-name-all-completions pathnondir path)))
717 ;; Go thru each completion found, to see whether it should be used.
718 (while comps-in-path
719 (setq file (car comps-in-path)
720 filepath (concat path file))
721 (if (and (not (member file completions))
7b2db0a0
KH
722 (not (and ignored-extensions
723 (string-match ignored-extensions file)))
d76b71af
RS
724 (or (string-equal path cwd)
725 (not (file-directory-p filepath)))
726 (or (null shell-completion-execonly)
727 (file-executable-p filepath)))
728 (setq completions (cons file completions)))
729 (setq comps-in-path (cdr comps-in-path)))
730 (setq paths (cdr paths)))
731 ;; OK, we've got a list of completions.
56783585
RS
732 (let ((success (let ((comint-completion-addsuffix nil))
733 (comint-dynamic-simple-complete pathnondir completions))))
734 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
735 (not (file-directory-p (comint-match-partial-filename))))
736 (insert " "))
737 success)))
988a4d60
RS
738
739
740(defun shell-match-partial-variable ()
da6a48c9 741 "Return the shell variable at point, or nil if none is found."
988a4d60
RS
742 (save-excursion
743 (let ((limit (point)))
744 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
745 (or (looking-at "\\$") (forward-char 1)))
746 ;; Anchor the search forwards.
747 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
748 nil
749 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
750 (buffer-substring (match-beginning 0) (match-end 0))))))
a9ec2adb 751
988a4d60
RS
752
753(defun shell-dynamic-complete-environment-variable ()
754 "Dynamically complete the environment variable at point.
755Completes if after a variable, i.e., if it starts with a \"$\".
756See `shell-dynamic-complete-as-environment-variable'.
757
758This function is similar to `comint-dynamic-complete-filename', except that it
759searches `process-environment' for completion candidates. Note that this may
760not be the same as the interpreter's idea of variable names. The main problem
761with this type of completion is that `process-environment' is the environment
762which Emacs started with. Emacs does not track changes to the environment made
763by the interpreter. Perhaps it would be more accurate if this function was
764called `shell-dynamic-complete-process-environment-variable'.
765
766Returns non-nil if successful."
767 (interactive)
768 (let ((variable (shell-match-partial-variable)))
769 (if (and variable (string-match "^\\$" variable))
770 (prog2 (message "Completing variable name...")
771 (shell-dynamic-complete-as-environment-variable)))))
772
773
774(defun shell-dynamic-complete-as-environment-variable ()
775 "Dynamically complete at point as an environment variable.
776Used by `shell-dynamic-complete-environment-variable'.
777Uses `comint-dynamic-simple-complete'."
778 (let* ((var (or (shell-match-partial-variable) ""))
779 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
780 (variables (mapcar (function (lambda (x)
781 (substring x 0 (string-match "=" x))))
782 process-environment))
783 (addsuffix comint-completion-addsuffix)
784 (comint-completion-addsuffix nil)
785 (success (comint-dynamic-simple-complete variable variables)))
786 (if (memq success '(sole shortest))
787 (let* ((var (shell-match-partial-variable))
788 (variable (substring var (string-match "[^$({]" var)))
789 (protection (cond ((string-match "{" var) "}")
790 ((string-match "(" var) ")")
791 (t "")))
792 (suffix (cond ((null addsuffix) "")
793 ((file-directory-p
794 (comint-directory (getenv variable))) "/")
795 (t " "))))
796 (insert protection suffix)))
797 success))
798
799
800(defun shell-replace-by-expanded-directory ()
801 "Expand directory stack reference before point.
802Directory stack references are of the form \"=digit\" or \"=-\".
803See `default-directory' and `shell-dirstack'.
804
805Returns t if successful."
806 (interactive)
807 (if (comint-match-partial-filename)
808 (save-excursion
988a4d60
RS
809 (goto-char (match-beginning 0))
810 (let ((stack (cons default-directory shell-dirstack))
811 (index (cond ((looking-at "=-/?")
812 (length shell-dirstack))
813 ((looking-at "=\\([0-9]+\\)")
814 (string-to-number
815 (buffer-substring
816 (match-beginning 1) (match-end 1)))))))
817 (cond ((null index)
818 nil)
819 ((>= index (length stack))
820 (error "Directory stack not that deep."))
821 (t
822 (replace-match (file-name-as-directory (nth index stack)) t t)
823 (message "Directory item: %d" index)
824 t))))))
825\f
c88ab9ce
ER
826(provide 'shell)
827
828;;; shell.el ends here