Sync to HEAD
[bpt/emacs.git] / lisp / shell.el
CommitLineData
1cd7adc6 1;;; shell.el --- specialized comint.el for running the shell
5109bfb0 2
fd1035aa 3;; Copyright (C) 1988, 93, 94, 95, 96, 1997, 2000 Free Software Foundation, Inc.
6d74b528 4
1cd7adc6 5;; Author: Olin Shivers <shivers@cs.cmu.edu>
5762abec 6;; Simon Marshall <simon@gnu.org>
f8604035 7;; Maintainer: FSF
d7b4d18f 8;; Keywords: processes
630cc463 9
5109bfb0 10;; This file is part of GNU Emacs.
c88ab9ce 11
5109bfb0
KH
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation; either version 2, or (at your option)
15;; any later version.
c88ab9ce 16
5109bfb0
KH
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
c88ab9ce 21
5109bfb0 22;; You should have received a copy of the GNU General Public License
b578f267
EN
23;; along with GNU Emacs; see the file COPYING. If not, write to the
24;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25;; Boston, MA 02111-1307, USA.
be9b65ac 26
630cc463
ER
27;;; Commentary:
28
b578f267
EN
29;; Please send me bug reports, bug fixes, and extensions, so that I can
30;; merge them into the master source.
31;; - Olin Shivers (shivers@cs.cmu.edu)
5762abec 32;; - Simon Marshall (simon@gnu.org)
be9b65ac 33
4696802b
JB
34;; This file defines a shell-in-a-buffer package (shell mode) built on
35;; top of comint mode. This is actually cmushell with things renamed
36;; to replace its counterpart in Emacs 18. cmushell is more
b578f267 37;; featureful, robust, and uniform than the Emacs 18 version.
be9b65ac 38
b578f267 39;; Since this mode is built on top of the general command-interpreter-in-
84728570 40;; a-buffer mode (comint mode), it shares a common base functionality,
b578f267
EN
41;; and a common set of bindings, with all modes derived from comint mode.
42;; This makes these modes easier to use.
be9b65ac 43
b578f267
EN
44;; For documentation on the functionality provided by comint mode, and
45;; the hooks available for customising it, see the file comint.el.
46;; For further information on shell mode, see the comments below.
be9b65ac 47
b578f267 48;; Needs fixin:
84728570 49;; When sending text from a source file to a subprocess, the process-mark can
b578f267
EN
50;; move off the window, so you can lose sight of the process interactions.
51;; Maybe I should ensure the process mark is in the window when I send
52;; text to the process? Switch selectable?
be9b65ac 53
a9ec2adb
JB
54;; YOUR .EMACS FILE
55;;=============================================================================
56;; Some suggestions for your .emacs file.
57;;
0b3c9cf1
SM
58;; ;; Define M-# to run some strange command:
59;; (eval-after-load "shell"
60;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
84728570 61
b578f267
EN
62;; Brief Command Documentation:
63;;============================================================================
64;; Comint Mode Commands: (common to shell and all comint-derived modes)
65;;
a9e73449
RS
66;; m-p comint-previous-input Cycle backwards in input history
67;; m-n comint-next-input Cycle forwards
b578f267
EN
68;; m-r comint-previous-matching-input Previous input matching a regexp
69;; m-s comint-next-matching-input Next input that matches
a9e73449 70;; m-c-l comint-show-output Show last batch of process output
b578f267 71;; return comint-send-input
a9e73449 72;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
b578f267 73;; c-c c-a comint-bol Beginning of line; skip prompt
a9e73449
RS
74;; c-c c-u comint-kill-input ^u
75;; c-c c-w backward-kill-word ^w
76;; c-c c-c comint-interrupt-subjob ^c
77;; c-c c-z comint-stop-subjob ^z
78;; c-c c-\ comint-quit-subjob ^\
79;; c-c c-o comint-kill-output Delete last batch of process output
80;; c-c c-r comint-show-output Show last batch of process output
94c34f7a 81;; c-c c-l comint-dynamic-list-input-ring List input history
b578f267 82;; send-invisible Read line w/o echo & send to proc
a9e73449 83;; comint-continue-subjob Useful if you accidentally suspend
b578f267
EN
84;; top-level job
85;; comint-mode-hook is the comint mode hook.
86
87;; Shell Mode Commands:
88;; shell Fires up the shell process
89;; tab comint-dynamic-complete Complete filename/command/history
90;; m-? comint-dynamic-list-filename-completions
91;; List completions in help buffer
92;; m-c-f shell-forward-command Forward a shell command
93;; m-c-b shell-backward-command Backward a shell command
a9e73449
RS
94;; dirs Resync the buffer's dir stack
95;; dirtrack-mode Turn dir tracking on/off
b578f267
EN
96;; comint-strip-ctrl-m Remove trailing ^Ms from output
97;;
98;; The shell mode hook is shell-mode-hook
99;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
100;; compatibility.
a9ec2adb 101
b578f267 102;; Read the rest of this file for more information.
84728570 103
630cc463
ER
104;;; Code:
105
106(require 'comint)
107
b578f267
EN
108;;; Customization and Buffer Variables
109
ed366e87
RS
110(defgroup shell nil
111 "Running shell from within Emacs buffers"
112 :group 'processes
113 :group 'unix)
114
115(defgroup shell-directories nil
116 "Directory support in shell mode"
117 :group 'shell)
118
119(defgroup shell-faces nil
120 "Faces in shell buffers"
121 :group 'shell)
122
c88ab9ce 123;;;###autoload
4dced927 124(defcustom shell-dumb-shell-regexp "cmd\\(proxy\\)?\\.exe"
f5058b96
EZ
125 "Regexp to match shells that don't save their command history, and
126don't handle the backslash as a quote character. For shells that
127match this regexp, Emacs will write out the command history when the
128shell finishes, and won't remove backslashes when it unquotes shell
129arguments."
4dced927
AI
130 :type 'regexp
131 :group 'shell)
132
fad22e2e 133(defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
a9ec2adb 134 "Regexp to match prompts in the inferior shell.
ac75ef20 135Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
84728570 136This variable is used to initialise `comint-prompt-regexp' in the
a9ec2adb
JB
137shell buffer.
138
28bc09d6
MB
139This variable is only used if the variable
140`comint-use-prompt-regexp-instead-of-fields' is non-nil.
141
ac75ef20 142The pattern should probably not match more than one line. If it does,
221ca406 143Shell mode may become confused trying to distinguish prompt from input
ac75ef20
JB
144on lines which don't start with a prompt.
145
fad22e2e
RS
146This is a fine thing to set in your `.emacs' file."
147 :type 'regexp
148 :group 'shell)
a9ec2adb 149
ed366e87 150(defcustom shell-completion-fignore nil
e11284d5
RS
151 "*List of suffixes to be disregarded during file/command completion.
152This variable is used to initialize `comint-completion-fignore' in the shell
153buffer. The default is nil, for compatibility with most shells.
154Some people like (\"~\" \"#\" \"%\").
155
ed366e87
RS
156This is a fine thing to set in your `.emacs' file."
157 :type '(repeat (string :tag "Suffix"))
158 :group 'shell)
e11284d5 159
56eb1060 160(defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
d76b71af 161 "List of characters to recognise as separate arguments.
56eb1060 162This variable is used to initialize `comint-delimiter-argument-list' in the
39d1a2ce
SM
163shell buffer. The value may depend on the operating system or shell.
164
165This is a fine thing to set in your `.emacs' file.")
166
76f63ea0 167(defvar shell-file-name-chars
c60ee5e7 168 (if (memq system-type '(ms-dos windows-nt cygwin))
4aed0379 169 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
6b61353c 170 "[]~/A-Za-z0-9+@:_.$#%,={}-")
76f63ea0
RS
171 "String of characters valid in a file name.
172This variable is used to initialize `comint-file-name-chars' in the
39d1a2ce 173shell buffer. The value may depend on the operating system or shell.
d76b71af
RS
174
175This is a fine thing to set in your `.emacs' file.")
176
7b4c6503 177(defvar shell-file-name-quote-list
39d1a2ce
SM
178 (if (memq system-type '(ms-dos windows-nt))
179 nil
6b61353c 180 (append shell-delimiter-argument-list '(?\ ?\* ?\! ?\" ?\' ?\` ?\# ?\\)))
7b4c6503
SM
181 "List of characters to quote when in a file name.
182This variable is used to initialize `comint-file-name-quote-list' in the
39d1a2ce 183shell buffer. The value may depend on the operating system or shell.
7b4c6503
SM
184
185This is a fine thing to set in your `.emacs' file.")
186
988a4d60
RS
187(defvar shell-dynamic-complete-functions
188 '(comint-replace-by-expanded-history
189 shell-dynamic-complete-environment-variable
190 shell-dynamic-complete-command
191 shell-replace-by-expanded-directory
192 comint-dynamic-complete-filename)
193 "List of functions called to perform completion.
194This variable is used to initialise `comint-dynamic-complete-functions' in the
195shell buffer.
196
197This is a fine thing to set in your `.emacs' file.")
198
ed366e87 199(defcustom shell-command-regexp "[^;&|\n]+"
a8e0effb 200 "*Regexp to match a single command within a pipeline.
ed366e87
RS
201This is used for directory tracking and does not do a perfect job."
202 :type 'regexp
203 :group 'shell)
d76b71af 204
6ed020c8
JB
205(defcustom shell-command-separator-regexp "[;&|\n \t]*"
206 "*Regexp to match a single command within a pipeline.
207This is used for directory tracking and does not do a perfect job."
208 :type 'regexp
209 :group 'shell)
210
ed366e87 211(defcustom shell-completion-execonly t
d76b71af 212 "*If non-nil, use executable files only for completion candidates.
5394cb44 213This mirrors the optional behavior of tcsh.
d76b71af 214
ed366e87
RS
215Detecting executability of files may slow command completion considerably."
216 :type 'boolean
217 :group 'shell)
d76b71af 218
ed366e87
RS
219(defcustom shell-popd-regexp "popd"
220 "*Regexp to match subshell commands equivalent to popd."
221 :type 'regexp
222 :group 'shell-directories)
be9b65ac 223
ed366e87
RS
224(defcustom shell-pushd-regexp "pushd"
225 "*Regexp to match subshell commands equivalent to pushd."
226 :type 'regexp
227 :group 'shell-directories)
be9b65ac 228
ed366e87 229(defcustom shell-pushd-tohome nil
d76b71af 230 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
ed366e87
RS
231This mirrors the optional behavior of tcsh."
232 :type 'boolean
233 :group 'shell-directories)
d76b71af 234
ed366e87 235(defcustom shell-pushd-dextract nil
d76b71af 236 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
ed366e87
RS
237This mirrors the optional behavior of tcsh."
238 :type 'boolean
239 :group 'shell-directories)
d76b71af 240
ed366e87 241(defcustom shell-pushd-dunique nil
d76b71af 242 "*If non-nil, make pushd only add unique directories to the stack.
ed366e87
RS
243This mirrors the optional behavior of tcsh."
244 :type 'boolean
245 :group 'shell-directories)
d76b71af 246
ed366e87
RS
247(defcustom shell-cd-regexp "cd"
248 "*Regexp to match subshell commands equivalent to cd."
249 :type 'regexp
250 :group 'shell-directories)
be9b65ac 251
ed366e87 252(defcustom shell-chdrive-regexp
84728570 253 (if (memq system-type '(ms-dos windows-nt))
32d01212
RS
254 ; NetWare allows the five chars between upper and lower alphabetics.
255 "[]a-zA-Z^_`\\[\\\\]:"
256 nil)
ed366e87 257 "*If non-nil, is regexp used to track drive changes."
233f3fb8
RS
258 :type '(choice regexp
259 (const nil))
ed366e87 260 :group 'shell-directories)
32d01212 261
8a6387ed
SM
262(defcustom shell-dirtrack-verbose t
263 "*If non-nil, show the directory stack following directory change.
264This is effective only if directory tracking is enabled."
265 :type 'boolean
266 :group 'shell-directories)
267
ed366e87
RS
268(defcustom explicit-shell-file-name nil
269 "*If non-nil, is file name to use for explicitly requested inferior shell."
270 :type '(choice (const :tag "None" nil) file)
271 :group 'shell)
be9b65ac 272
ed366e87 273(defcustom explicit-csh-args
be9b65ac
DL
274 (if (eq system-type 'hpux)
275 ;; -T persuades HP's csh not to think it is smarter
276 ;; than us about what terminal modes to use.
277 '("-i" "-T")
278 '("-i"))
279 "*Args passed to inferior shell by M-x shell, if the shell is csh.
ed366e87
RS
280Value is a list of strings, which may be nil."
281 :type '(repeat (string :tag "Argument"))
282 :group 'shell)
be9b65ac 283
6674676b 284(defcustom explicit-bash-args
969a0631
KS
285 ;; Tell bash not to use readline, except for bash 1.x which doesn't grook --noediting.
286 ;; Bash 1.x has -nolineediting, but process-send-eof cannot terminate bash if we use it.
287 (let* ((prog (or (and (boundp 'explicit-shell-file-name) explicit-shell-file-name)
288 (getenv "ESHELL") shell-file-name))
289 (name (file-name-nondirectory prog)))
290 (if (and (not purify-flag)
291 (equal name "bash")
292 (file-executable-p prog)
293 (string-match "bad option"
294 (shell-command-to-string (concat prog " --noediting"))))
295 '("-i")
296 '("--noediting" "-i")))
6674676b
AS
297 "*Args passed to inferior shell by M-x shell, if the shell is bash.
298Value is a list of strings, which may be nil."
299 :type '(repeat (string :tag "Argument"))
300 :group 'shell)
301
ed366e87 302(defcustom shell-input-autoexpand 'history
4f99443b
RS
303 "*If non-nil, expand input command history references on completion.
304This mirrors the optional behavior of tcsh (its autoexpand and histlit).
305
306If the value is `input', then the expansion is seen on input.
307If the value is `history', then the expansion is only when inserting
308into the buffer's input ring. See also `comint-magic-space' and
309`comint-dynamic-complete'.
310
311This variable supplies a default for `comint-input-autoexpand',
ed366e87 312for Shell mode only."
6f0984e5
AS
313 :type '(choice (const :tag "off" nil)
314 (const input)
315 (const history)
316 (const :tag "on" t))
362ae0b3 317 :group 'shell)
4f99443b 318
be9b65ac 319(defvar shell-dirstack nil
c88ab9ce
ER
320 "List of directories saved by pushd in this buffer's shell.
321Thus, this does not include the shell's current directory.")
be9b65ac 322
b493a9b2
RS
323(defvar shell-dirtrackp t
324 "Non-nil in a shell buffer means directory tracking is enabled.")
325
fa8f1b25
ER
326(defvar shell-last-dir nil
327 "Keep track of last directory for ksh `cd -' command.")
328
c63e83a4 329(defvar shell-dirstack-query nil
24fdffaa 330 "Command used by `shell-resync-dir' to query the shell.")
be9b65ac 331
9376442d 332(defvar shell-mode-map nil)
be9b65ac 333(cond ((not shell-mode-map)
1ed30e75 334 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
d76b71af
RS
335 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
336 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
8f36167a 337 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
d76b71af 338 (define-key shell-mode-map "\M-?"
988a4d60 339 'comint-dynamic-list-filename-completions)
1ed30e75 340 (define-key shell-mode-map [menu-bar completion]
f19be163 341 (cons "Complete"
cdf07453 342 (copy-keymap (lookup-key comint-mode-map [menu-bar completion]))))
5109bfb0
KH
343 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
344 [complete-env-variable] '("Complete Env. Variable Name" .
345 shell-dynamic-complete-environment-variable)
346 'complete-file)
347 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
348 [expand-directory] '("Expand Directory Reference" .
349 shell-replace-by-expanded-directory)
350 'complete-expand)))
be9b65ac 351
ed366e87
RS
352(defcustom shell-mode-hook '()
353 "*Hook for customising Shell mode."
354 :type 'hook
355 :group 'shell)
be9b65ac 356
5945a1f7 357(defvar shell-font-lock-keywords
cb6e07b1 358 '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
473fbd89
SM
359 ("^[^ \t\n]+:.*" . font-lock-string-face)
360 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
5945a1f7 361 "Additional expressions to highlight in Shell mode.")
84728570 362
be9b65ac 363;;; Basic Procedures
be9b65ac 364
e9904b59
RS
365(put 'shell-mode 'mode-class 'special)
366
9f299ecb 367(define-derived-mode shell-mode comint-mode "Shell"
be9b65ac 368 "Major mode for interacting with an inferior shell.
8079b590
SM
369\\[comint-send-input] after the end of the process' output sends the text from
370 the end of process to the end of the current line.
371\\[comint-send-input] before end of process output copies the current line minus the prompt to
372 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
e9933cb1 373\\[send-invisible] reads a line of text without echoing it, and sends it to
56783585
RS
374 the shell. This is useful for entering passwords. Or, add the function
375 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
be9b65ac 376
e9933cb1
SM
377If you want to make multiple shell buffers, rename the `*shell*' buffer
378using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
379
8079b590 380If you want to make shell buffers limited in length, add the function
4841acc4 381`comint-truncate-buffer' to `comint-output-filter-functions'.
8079b590 382
be9b65ac
DL
383If you accidentally suspend your process, use \\[comint-continue-subjob]
384to continue it.
385
e9933cb1
SM
386`cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
387keep this buffer's default directory the same as the shell's working directory.
0b3c9cf1
SM
388While directory tracking is enabled, the shell's working directory is displayed
389by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
84728570 390\\[dirs] queries the shell and resyncs Emacs' idea of what the current
be9b65ac 391 directory stack is.
2154db49 392\\[dirtrack-mode] turns directory tracking on and off.
be9b65ac
DL
393
394\\{shell-mode-map}
24fdffaa 395Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
988a4d60 396`shell-mode-hook' (in that order). Before each input, the hooks on
ba02c167
RS
397`comint-input-filter-functions' are run. After each shell output, the hooks
398on `comint-output-filter-functions' are run.
be9b65ac 399
84728570
SS
400Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
401and `shell-popd-regexp' are used to match their respective commands,
402while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
32d01212 403control the behavior of the relevant command.
d76b71af 404
e11284d5
RS
405Variables `comint-completion-autolist', `comint-completion-addsuffix',
406`comint-completion-recexact' and `comint-completion-fignore' control the
407behavior of file name, command name and variable name completion. Variable
408`shell-completion-execonly' controls the behavior of command name completion.
409Variable `shell-completion-fignore' is used to initialise the value of
410`comint-completion-fignore'.
d76b71af
RS
411
412Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
413the initialisation of the input ring history, and history expansion.
414
ba02c167 415Variables `comint-output-filter-functions', a hook, and
e11284d5 416`comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
988a4d60
RS
417control whether input and output cause the window to scroll to the end of the
418buffer."
d76b71af 419 (setq comint-prompt-regexp shell-prompt-pattern)
e11284d5 420 (setq comint-completion-fignore shell-completion-fignore)
d76b71af 421 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
76f63ea0 422 (setq comint-file-name-chars shell-file-name-chars)
7b4c6503 423 (setq comint-file-name-quote-list shell-file-name-quote-list)
8f36167a 424 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
d76b71af
RS
425 (make-local-variable 'paragraph-start)
426 (setq paragraph-start comint-prompt-regexp)
c156572f
SM
427 (make-local-variable 'font-lock-defaults)
428 (setq font-lock-defaults '(shell-font-lock-keywords t))
be9b65ac 429 (make-local-variable 'shell-dirstack)
a9ec2adb 430 (setq shell-dirstack nil)
fdcc1ef7 431 (make-local-variable 'shell-last-dir)
fa8f1b25 432 (setq shell-last-dir nil)
a9ec2adb
JB
433 (make-local-variable 'shell-dirtrackp)
434 (setq shell-dirtrackp t)
1458efa0 435 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
4f99443b 436 (setq comint-input-autoexpand shell-input-autoexpand)
5d9719e6
RS
437 ;; This is not really correct, since the shell buffer does not really
438 ;; edit this directory. But it is useful in the buffer list and menus.
439 (make-local-variable 'list-buffers-directory)
440 (setq list-buffers-directory (expand-file-name default-directory))
d76b71af 441 ;; shell-dependent assignments.
6ba0fd3e 442 (when (ring-empty-p comint-input-ring)
ee8107c0
RS
443 (let ((shell (file-name-nondirectory (car
444 (process-command (get-buffer-process (current-buffer)))))))
445 (setq comint-input-ring-file-name
446 (or (getenv "HISTFILE")
447 (cond ((string-equal shell "bash") "~/.bash_history")
448 ((string-equal shell "ksh") "~/.sh_history")
449 (t "~/.history"))))
450 (if (or (equal comint-input-ring-file-name "")
451 (equal (file-truename comint-input-ring-file-name)
452 (file-truename "/dev/null")))
453 (setq comint-input-ring-file-name nil))
454 ;; Arrange to write out the input ring on exit, if the shell doesn't
455 ;; do this itself.
456 (if (and comint-input-ring-file-name
457 (string-match shell-dumb-shell-regexp shell))
458 (set-process-sentinel (get-buffer-process (current-buffer))
459 #'shell-write-history-on-exit))
460 (setq shell-dirstack-query
461 (cond ((string-equal shell "sh") "pwd")
462 ((string-equal shell "ksh") "echo $PWD ~-")
3811bec8
LK
463 (t "dirs")))
464 ;; Bypass a bug in certain versions of bash.
465 (when (string-equal shell "bash")
466 (add-hook 'comint-output-filter-functions
467 'shell-filter-ctrl-a-ctrl-b nil t)))
ee8107c0 468 (comint-read-input-ring t)))
4dced927 469
3811bec8
LK
470(defun shell-filter-ctrl-a-ctrl-b (string)
471 "Remove `^A' and `^B' characters from comint output.
472
473Bash uses these characters as internal quoting characters in its
474prompt. Due to a bug in some bash versions (including 2.03,
4752.04, and 2.05b), they may erroneously show up when bash is
476started with the `--noediting' option and Select Graphic
477Rendition (SGR) control sequences (formerly known as ANSI escape
478sequences) are used to color the prompt.
479
480This function can be put on `comint-output-filter-functions'.
481The argument STRING is ignored."
482 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
483 (save-excursion
484 (goto-char (or comint-last-output-start (point-min)))
485 (while (re-search-forward "[\C-a\C-b]" pmark t)
486 (replace-match "")))))
487
4dced927
AI
488(defun shell-write-history-on-exit (process event)
489 "Called when the shell process is stopped.
490
491Writes the input history to a history file
84728570 492`comint-input-ring-file-name' using `comint-write-input-ring'
4dced927
AI
493and inserts a short message in the shell buffer.
494
495This function is a sentinel watching the shell interpreter process.
496Sentinels will always get the two parameters PROCESS and EVENT."
497 ;; Write history.
498 (comint-write-input-ring)
84728570
SS
499 (let ((buf (process-buffer process)))
500 (when (buffer-live-p buf)
501 (with-current-buffer buf
502 (insert (format "\nProcess %s %s\n" process event))))))
503
c88ab9ce 504;;;###autoload
fd1035aa
MB
505(defun shell (&optional buffer)
506 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
507Interactively, a prefix arg means to prompt for BUFFER.
508If BUFFER exists but shell process is not running, make new shell.
509If BUFFER exists and shell process is running, just switch to BUFFER.
24fdffaa 510Program used comes from variable `explicit-shell-file-name',
a9ec2adb
JB
511 or (if that is nil) from the ESHELL environment variable,
512 or else from SHELL if there is no ESHELL.
fbc270e7 513If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
a9ec2adb
JB
514 (Note that this may lose due to a timing error if the shell
515 discards input when it starts up.)
fbc270e7
RS
516The buffer is put in Shell mode, giving commands for sending input
517and controlling the subjobs of the shell. See `shell-mode'.
518See also the variable `shell-prompt-pattern'.
be9b65ac 519
ebe4d555
RS
520To specify a coding system for converting non-ASCII characters
521in the input and output to the shell, use \\[universal-coding-system-argument]
522before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
523in the shell buffer, after you start the shell.
524The default comes from `process-coding-system-alist' and
525`default-process-coding-system'.
526
a9ec2adb 527The shell file name (sans directories) is used to make a symbol name
62c9fad7 528such as `explicit-csh-args'. If that symbol is a variable,
be9b65ac
DL
529its value is used as a list of arguments when invoking the shell.
530Otherwise, one argument `-i' is passed to the shell.
531
532\(Type \\[describe-mode] in the shell buffer for a list of commands.)"
fd1035aa
MB
533 (interactive
534 (list
535 (and current-prefix-arg
6b61353c
KH
536 (read-buffer "Shell buffer: "
537 (generate-new-buffer-name "*shell*")))))
5a45735a
SM
538 (setq buffer (get-buffer-create (or buffer "*shell*")))
539 ;; Pop to buffer, so that the buffer's window will be correctly set
540 ;; when we call comint (so that comint sets the COLUMNS env var properly).
541 (pop-to-buffer buffer)
542 (unless (comint-check-proc buffer)
543 (let* ((prog (or explicit-shell-file-name
544 (getenv "ESHELL") shell-file-name))
545 (name (file-name-nondirectory prog))
546 (startfile (concat "~/.emacs_" name))
547 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
4df54202
RS
548 (if (not (file-exists-p startfile))
549 (setq startfile (concat "~/.emacs.d/.emacs_" name)))
5a45735a
SM
550 (apply 'make-comint-in-buffer "shell" buffer prog
551 (if (file-exists-p startfile) startfile)
552 (if (and xargs-name (boundp xargs-name))
553 (symbol-value xargs-name)
554 '("-i")))
555 (shell-mode)))
556 buffer)
519bfec4
RS
557
558;;; Don't do this when shell.el is loaded, only while dumping.
559;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
84728570 560
be9b65ac 561;;; Directory tracking
b578f267 562;;;
be9b65ac
DL
563;;; This code provides the shell mode input sentinel
564;;; SHELL-DIRECTORY-TRACKER
565;;; that tracks cd, pushd, and popd commands issued to the shell, and
566;;; changes the current directory of the shell buffer accordingly.
567;;;
568;;; This is basically a fragile hack, although it's more accurate than
b7fc702e 569;;; the version in Emacs 18's shell.el. It has the following failings:
be9b65ac 570;;; 1. It doesn't know about the cdpath shell variable.
d76b71af
RS
571;;; 2. It cannot infallibly deal with command sequences, though it does well
572;;; with these and with ignoring commands forked in another shell with ()s.
573;;; 3. More generally, any complex command is going to throw it. Otherwise,
574;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
575;;; that, there's no way to catch shell commands where cd's are buried
576;;; inside conditional expressions, aliases, and so forth.
be9b65ac
DL
577;;;
578;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
579;;; messes it up. You run other processes under the shell; these each have
580;;; separate working directories, and some have commands for manipulating
581;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
a9ec2adb 582;;; commands that do *not* affect the current w.d. at all, but look like they
be9b65ac
DL
583;;; do (e.g., the cd command in ftp). In shells that allow you job
584;;; control, you can switch between jobs, all having different w.d.'s. So
585;;; simply saying %3 can shift your w.d..
586;;;
587;;; The solution is to relax, not stress out about it, and settle for
588;;; a hack that works pretty well in typical circumstances. Remember
84728570 589;;; that a half-assed solution is more in keeping with the spirit of Unix,
be9b65ac
DL
590;;; anyway. Blech.
591;;;
592;;; One good hack not implemented here for users of programmable shells
593;;; is to program up the shell w.d. manipulation commands to output
594;;; a coded command sequence to the tty. Something like
595;;; ESC | <cwd> |
596;;; where <cwd> is the new current working directory. Then trash the
597;;; directory tracking machinery currently used in this package, and
598;;; replace it with a process filter that watches for and strips out
599;;; these messages.
600
be9b65ac
DL
601(defun shell-directory-tracker (str)
602 "Tracks cd, pushd and popd commands issued to the shell.
603This function is called on each input passed to the shell.
604It watches for cd, pushd and popd commands and sets the buffer's
605default directory to track these commands.
606
2154db49 607You may toggle this tracking on and off with M-x dirtrack-mode.
be9b65ac
DL
608If emacs gets confused, you can resync with the shell with M-x dirs.
609
32d01212 610See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
84728570 611and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
32d01212 612and `shell-pushd-dunique' control the behavior of the relevant command.
d76b71af 613
24fdffaa 614Environment variables are expanded, see function `substitute-in-file-name'."
d76b71af
RS
615 (if shell-dirtrackp
616 ;; We fail gracefully if we think the command will fail in the shell.
617 (condition-case chdir-failure
6ed020c8
JB
618 (let ((start (progn (string-match
619 (concat "^" shell-command-separator-regexp)
620 str) ; skip whitespace
d76b71af
RS
621 (match-end 0)))
622 end cmd arg1)
623 (while (string-match shell-command-regexp str start)
624 (setq end (match-end 0)
625 cmd (comint-arguments (substring str start end) 0 0)
626 arg1 (comint-arguments (substring str start end) 1 1))
5f49d5e8
KH
627 (if arg1
628 (setq arg1 (shell-unquote-argument arg1)))
54021695
KH
629 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
630 "\\)\\($\\|[ \t]\\)")
631 cmd)
32d01212 632 (shell-process-popd (comint-substitute-in-file-name arg1)))
54021695
KH
633 ((string-match (concat "\\`\\(" shell-pushd-regexp
634 "\\)\\($\\|[ \t]\\)")
635 cmd)
32d01212 636 (shell-process-pushd (comint-substitute-in-file-name arg1)))
54021695
KH
637 ((string-match (concat "\\`\\(" shell-cd-regexp
638 "\\)\\($\\|[ \t]\\)")
639 cmd)
32d01212
RS
640 (shell-process-cd (comint-substitute-in-file-name arg1)))
641 ((and shell-chdrive-regexp
642 (string-match (concat "\\`\\(" shell-chdrive-regexp
643 "\\)\\($\\|[ \t]\\)")
644 cmd))
645 (shell-process-cd (comint-substitute-in-file-name cmd))))
6ed020c8
JB
646 (setq start (progn (string-match shell-command-separator-regexp
647 str end)
648 ;; skip again
d76b71af 649 (match-end 0)))))
ba02c167 650 (error "Couldn't cd"))))
d76b71af 651
5f49d5e8
KH
652(defun shell-unquote-argument (string)
653 "Remove all kinds of shell quoting from STRING."
654 (save-match-data
f5058b96
EZ
655 (let ((idx 0) next inside
656 (quote-chars
657 (if (string-match shell-dumb-shell-regexp
658 (file-name-nondirectory
659 (car (process-command (get-buffer-process (current-buffer))))))
660 "['`\"]"
661 "[\\'`\"]")))
5f49d5e8 662 (while (and (< idx (length string))
f5058b96 663 (setq next (string-match quote-chars string next)))
5f49d5e8
KH
664 (cond ((= (aref string next) ?\\)
665 (setq string (replace-match "" nil nil string))
666 (setq next (1+ next)))
667 ((and inside (= (aref string next) inside))
668 (setq string (replace-match "" nil nil string))
669 (setq inside nil))
670 (inside
671 (setq next (1+ next)))
672 (t
673 (setq inside (aref string next))
674 (setq string (replace-match "" nil nil string)))))
675 string)))
676
be9b65ac
DL
677;;; popd [+n]
678(defun shell-process-popd (arg)
d76b71af
RS
679 (let ((num (or (shell-extract-num arg) 0)))
680 (cond ((and num (= num 0) shell-dirstack)
0b3c9cf1 681 (shell-cd (car shell-dirstack))
d76b71af
RS
682 (setq shell-dirstack (cdr shell-dirstack))
683 (shell-dirstack-message))
684 ((and num (> num 0) (<= num (length shell-dirstack)))
685 (let* ((ds (cons nil shell-dirstack))
686 (cell (nthcdr (1- num) ds)))
687 (rplacd cell (cdr (cdr cell)))
688 (setq shell-dirstack (cdr ds))
689 (shell-dirstack-message)))
690 (t
ba02c167 691 (error "Couldn't popd")))))
be9b65ac 692
3db9a4eb 693;; Return DIR prefixed with comint-file-name-prefix as appropriate.
4a02b552
RS
694(defun shell-prefixed-directory-name (dir)
695 (if (= (length comint-file-name-prefix) 0)
696 dir
697 (if (file-name-absolute-p dir)
698 ;; The name is absolute, so prepend the prefix.
699 (concat comint-file-name-prefix dir)
0b3c9cf1 700 ;; For relative name we assume default-directory already has the prefix.
4a02b552 701 (expand-file-name dir))))
3db9a4eb 702
be9b65ac
DL
703;;; cd [dir]
704(defun shell-process-cd (arg)
3db9a4eb
RM
705 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
706 "~"))
d76b71af 707 ((string-equal "-" arg) shell-last-dir)
3db9a4eb 708 (t (shell-prefixed-directory-name arg)))))
d76b71af 709 (setq shell-last-dir default-directory)
0b3c9cf1 710 (shell-cd new-dir)
d76b71af 711 (shell-dirstack-message)))
be9b65ac
DL
712
713;;; pushd [+n | dir]
714(defun shell-process-pushd (arg)
d76b71af
RS
715 (let ((num (shell-extract-num arg)))
716 (cond ((zerop (length arg))
717 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
718 (cond (shell-pushd-tohome
3db9a4eb 719 (shell-process-pushd (concat comint-file-name-prefix "~")))
d76b71af
RS
720 (shell-dirstack
721 (let ((old default-directory))
0b3c9cf1 722 (shell-cd (car shell-dirstack))
221ca406 723 (setq shell-dirstack (cons old (cdr shell-dirstack)))
d76b71af
RS
724 (shell-dirstack-message)))
725 (t
726 (message "Directory stack empty."))))
727 ((numberp num)
728 ;; pushd +n
729 (cond ((> num (length shell-dirstack))
730 (message "Directory stack not that deep."))
731 ((= num 0)
1cd7adc6 732 (error (message "Couldn't cd")))
d76b71af
RS
733 (shell-pushd-dextract
734 (let ((dir (nth (1- num) shell-dirstack)))
735 (shell-process-popd arg)
736 (shell-process-pushd default-directory)
0b3c9cf1 737 (shell-cd dir)
d76b71af
RS
738 (shell-dirstack-message)))
739 (t
740 (let* ((ds (cons default-directory shell-dirstack))
741 (dslen (length ds))
742 (front (nthcdr num ds))
743 (back (reverse (nthcdr (- dslen num) (reverse ds))))
744 (new-ds (append front back)))
0b3c9cf1 745 (shell-cd (car new-ds))
d76b71af
RS
746 (setq shell-dirstack (cdr new-ds))
747 (shell-dirstack-message)))))
748 (t
749 ;; pushd <dir>
750 (let ((old-wd default-directory))
0b3c9cf1 751 (shell-cd (shell-prefixed-directory-name arg))
d76b71af
RS
752 (if (or (null shell-pushd-dunique)
753 (not (member old-wd shell-dirstack)))
754 (setq shell-dirstack (cons old-wd shell-dirstack)))
755 (shell-dirstack-message))))))
be9b65ac
DL
756
757;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
758(defun shell-extract-num (str)
759 (and (string-match "^\\+[1-9][0-9]*$" str)
760 (string-to-int str)))
761
762
2154db49 763(defun shell-dirtrack-mode ()
be9b65ac
DL
764 "Turn directory tracking on and off in a shell buffer."
765 (interactive)
0b3c9cf1
SM
766 (if (setq shell-dirtrackp (not shell-dirtrackp))
767 (setq list-buffers-directory default-directory)
768 (setq list-buffers-directory nil))
d76b71af 769 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
be9b65ac
DL
770
771;;; For your typing convenience:
2154db49
KH
772(defalias 'shell-dirtrack-toggle 'shell-dirtrack-mode)
773(defalias 'dirtrack-toggle 'shell-dirtrack-mode)
774(defalias 'dirtrack-mode 'shell-dirtrack-mode)
be9b65ac 775
0b3c9cf1
SM
776(defun shell-cd (dir)
777 "Do normal `cd' to DIR, and set `list-buffers-directory'."
b7e97ed5
SM
778 (if shell-dirtrackp
779 (setq list-buffers-directory (file-name-as-directory
780 (expand-file-name dir))))
0b3c9cf1 781 (cd dir))
be9b65ac
DL
782
783(defun shell-resync-dirs ()
784 "Resync the buffer's idea of the current directory stack.
84728570 785This command queries the shell with the command bound to
24fdffaa 786`shell-dirstack-query' (default \"dirs\"), reads the next
be9b65ac
DL
787line output and parses it to form the new directory stack.
788DON'T issue this command unless the buffer is at a shell prompt.
789Also, note that if some other subprocess decides to do output
790immediately after the query, its output will be taken as the
791new directory stack -- you lose. If this happens, just do the
792command again."
793 (interactive)
794 (let* ((proc (get-buffer-process (current-buffer)))
795 (pmark (process-mark proc)))
796 (goto-char pmark)
797 (insert shell-dirstack-query) (insert "\n")
798 (sit-for 0) ; force redisplay
84728570 799 (comint-send-string proc shell-dirstack-query)
be9b65ac
DL
800 (comint-send-string proc "\n")
801 (set-marker pmark (point))
802 (let ((pt (point))) ; wait for 1 line
803 ;; This extra newline prevents the user's pending input from spoofing us.
804 (insert "\n") (backward-char 1)
87a1fe1d
JB
805 (while (not (looking-at
806 (concat "\\(" ; skip literal echo in case of stty echo
807 (regexp-quote shell-dirstack-query)
808 "\n\\)?" ; skip if present
809 "\\(" ".+\n" "\\)")) ) ; what to actually look for
be9b65ac
DL
810 (accept-process-output proc)
811 (goto-char pt)))
812 (goto-char pmark) (delete-char 1) ; remove the extra newline
813 ;; That's the dirlist. grab it & parse it.
87a1fe1d 814 (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
be9b65ac
DL
815 (dl-len (length dl))
816 (ds '()) ; new dir stack
817 (i 0))
818 (while (< i dl-len)
819 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
820 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
3db9a4eb
RM
821 (setq ds (cons (concat comint-file-name-prefix
822 (substring dl (match-beginning 1)
823 (match-end 1)))
be9b65ac
DL
824 ds))
825 (setq i (match-end 0)))
3db9a4eb 826 (let ((ds (nreverse ds)))
be9b65ac 827 (condition-case nil
0b3c9cf1 828 (progn (shell-cd (car ds))
221ca406
SM
829 (setq shell-dirstack (cdr ds)
830 shell-last-dir (car shell-dirstack))
be9b65ac 831 (shell-dirstack-message))
1cd7adc6 832 (error (message "Couldn't cd")))))))
be9b65ac
DL
833
834;;; For your typing convenience:
31e1d920 835(defalias 'dirs 'shell-resync-dirs)
be9b65ac
DL
836
837
838;;; Show the current dirstack on the message line.
839;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
840;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
841;;; All the commands that mung the buffer's dirstack finish by calling
842;;; this guy.
843(defun shell-dirstack-message ()
8a6387ed
SM
844 (when shell-dirtrack-verbose
845 (let* ((msg "")
846 (ds (cons default-directory shell-dirstack))
847 (home (expand-file-name (concat comint-file-name-prefix "~/")))
848 (homelen (length home)))
849 (while ds
850 (let ((dir (car ds)))
851 (and (>= (length dir) homelen)
852 (string= home (substring dir 0 homelen))
853 (setq dir (concat "~/" (substring dir homelen))))
854 ;; Strip off comint-file-name-prefix if present.
855 (and comint-file-name-prefix
856 (>= (length dir) (length comint-file-name-prefix))
857 (string= comint-file-name-prefix
858 (substring dir 0 (length comint-file-name-prefix)))
859 (setq dir (substring dir (length comint-file-name-prefix)))
860 (setcar ds dir))
861 (setq msg (concat msg (directory-file-name dir) " "))
862 (setq ds (cdr ds))))
863 (message "%s" msg))))
84728570 864
c64d8c55
RS
865;; This was mostly copied from shell-resync-dirs.
866(defun shell-snarf-envar (var)
867 "Return as a string the shell's value of environment variable VAR."
868 (let* ((cmd (format "printenv '%s'\n" var))
869 (proc (get-buffer-process (current-buffer)))
870 (pmark (process-mark proc)))
871 (goto-char pmark)
872 (insert cmd)
873 (sit-for 0) ; force redisplay
874 (comint-send-string proc cmd)
875 (set-marker pmark (point))
876 (let ((pt (point))) ; wait for 1 line
877 ;; This extra newline prevents the user's pending input from spoofing us.
878 (insert "\n") (backward-char 1)
879 (while (not (looking-at ".+\n"))
880 (accept-process-output proc)
881 (goto-char pt)))
882 (goto-char pmark) (delete-char 1) ; remove the extra newline
883 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
884
885(defun shell-copy-environment-variable (variable)
886 "Copy the environment variable VARIABLE from the subshell to Emacs.
887This command reads the value of the specified environment variable
888in the shell, and sets the same environment variable in Emacs
a9e73449 889\(what `getenv' in Emacs would return) to that value.
c64d8c55
RS
890That value will affect any new subprocesses that you subsequently start
891from Emacs."
892 (interactive (list (read-envvar-name "\
893Copy Shell environment variable to Emacs: ")))
894 (setenv variable (shell-snarf-envar variable)))
84728570 895
d76b71af
RS
896(defun shell-forward-command (&optional arg)
897 "Move forward across ARG shell command(s). Does not cross lines.
898See `shell-command-regexp'."
899 (interactive "p")
900 (let ((limit (save-excursion (end-of-line nil) (point))))
19134c18 901 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
d76b71af 902 limit 'move arg)
b0f86743 903 (skip-syntax-backward " "))))
d76b71af
RS
904
905
906(defun shell-backward-command (&optional arg)
907 "Move backward across ARG shell command(s). Does not cross lines.
908See `shell-command-regexp'."
909 (interactive "p")
910 (let ((limit (save-excursion (comint-bol nil) (point))))
28bc09d6
MB
911 (when (> limit (point))
912 (setq limit (line-beginning-position)))
b0f86743 913 (skip-syntax-backward " " limit)
d76b71af 914 (if (re-search-backward
19134c18 915 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
d76b71af 916 (progn (goto-char (match-beginning 1))
b0f86743 917 (skip-chars-forward ";&|")))))
d76b71af 918
d76b71af
RS
919(defun shell-dynamic-complete-command ()
920 "Dynamically complete the command at point.
921This function is similar to `comint-dynamic-complete-filename', except that it
922searches `exec-path' (minus the trailing emacs library path) for completion
923candidates. Note that this may not be the same as the shell's idea of the
924path.
925
926Completion is dependent on the value of `shell-completion-execonly', plus
988a4d60
RS
927those that effect file completion. See `shell-dynamic-complete-as-command'.
928
929Returns t if successful."
d76b71af 930 (interactive)
988a4d60
RS
931 (let ((filename (comint-match-partial-filename)))
932 (if (and filename
933 (save-match-data (not (string-match "[~/]" filename)))
934 (eq (match-beginning 0)
935 (save-excursion (shell-backward-command 1) (point))))
936 (prog2 (message "Completing command name...")
937 (shell-dynamic-complete-as-command)))))
938
939
940(defun shell-dynamic-complete-as-command ()
941 "Dynamically complete at point as a command.
942See `shell-dynamic-complete-filename'. Returns t if successful."
56783585 943 (let* ((filename (or (comint-match-partial-filename) ""))
6b61353c
KH
944 (filenondir (file-name-nondirectory filename))
945 (path-dirs (cdr (reverse exec-path)))
d76b71af
RS
946 (cwd (file-name-as-directory (expand-file-name default-directory)))
947 (ignored-extensions
a867a90a
RS
948 (and comint-completion-fignore
949 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
950 comint-completion-fignore "\\|")))
6b61353c
KH
951 (dir "") (comps-in-dir ())
952 (file "") (abs-file-name "") (completions ()))
953 ;; Go thru each dir in the search path, finding completions.
954 (while path-dirs
955 (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
956 comps-in-dir (and (file-accessible-directory-p dir)
957 (file-name-all-completions filenondir dir)))
d76b71af 958 ;; Go thru each completion found, to see whether it should be used.
6b61353c
KH
959 (while comps-in-dir
960 (setq file (car comps-in-dir)
961 abs-file-name (concat dir file))
d76b71af 962 (if (and (not (member file completions))
7b2db0a0
KH
963 (not (and ignored-extensions
964 (string-match ignored-extensions file)))
6b61353c
KH
965 (or (string-equal dir cwd)
966 (not (file-directory-p abs-file-name)))
d76b71af 967 (or (null shell-completion-execonly)
6b61353c 968 (file-executable-p abs-file-name)))
d76b71af 969 (setq completions (cons file completions)))
6b61353c
KH
970 (setq comps-in-dir (cdr comps-in-dir)))
971 (setq path-dirs (cdr path-dirs)))
d76b71af 972 ;; OK, we've got a list of completions.
56783585 973 (let ((success (let ((comint-completion-addsuffix nil))
6b61353c 974 (comint-dynamic-simple-complete filenondir completions))))
56783585
RS
975 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
976 (not (file-directory-p (comint-match-partial-filename))))
977 (insert " "))
978 success)))
988a4d60
RS
979
980
981(defun shell-match-partial-variable ()
da6a48c9 982 "Return the shell variable at point, or nil if none is found."
988a4d60
RS
983 (save-excursion
984 (let ((limit (point)))
985 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
986 (or (looking-at "\\$") (forward-char 1)))
987 ;; Anchor the search forwards.
988 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
989 nil
990 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
991 (buffer-substring (match-beginning 0) (match-end 0))))))
a9ec2adb 992
988a4d60
RS
993
994(defun shell-dynamic-complete-environment-variable ()
995 "Dynamically complete the environment variable at point.
996Completes if after a variable, i.e., if it starts with a \"$\".
997See `shell-dynamic-complete-as-environment-variable'.
998
999This function is similar to `comint-dynamic-complete-filename', except that it
1000searches `process-environment' for completion candidates. Note that this may
1001not be the same as the interpreter's idea of variable names. The main problem
1002with this type of completion is that `process-environment' is the environment
1003which Emacs started with. Emacs does not track changes to the environment made
1004by the interpreter. Perhaps it would be more accurate if this function was
1005called `shell-dynamic-complete-process-environment-variable'.
1006
1007Returns non-nil if successful."
1008 (interactive)
1009 (let ((variable (shell-match-partial-variable)))
1010 (if (and variable (string-match "^\\$" variable))
1011 (prog2 (message "Completing variable name...")
1012 (shell-dynamic-complete-as-environment-variable)))))
1013
1014
1015(defun shell-dynamic-complete-as-environment-variable ()
1016 "Dynamically complete at point as an environment variable.
1017Used by `shell-dynamic-complete-environment-variable'.
1018Uses `comint-dynamic-simple-complete'."
1019 (let* ((var (or (shell-match-partial-variable) ""))
1020 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
1021 (variables (mapcar (function (lambda (x)
1022 (substring x 0 (string-match "=" x))))
1023 process-environment))
1024 (addsuffix comint-completion-addsuffix)
1025 (comint-completion-addsuffix nil)
1026 (success (comint-dynamic-simple-complete variable variables)))
1027 (if (memq success '(sole shortest))
1028 (let* ((var (shell-match-partial-variable))
1029 (variable (substring var (string-match "[^$({]" var)))
1030 (protection (cond ((string-match "{" var) "}")
1031 ((string-match "(" var) ")")
1032 (t "")))
1033 (suffix (cond ((null addsuffix) "")
1034 ((file-directory-p
1035 (comint-directory (getenv variable))) "/")
1036 (t " "))))
1037 (insert protection suffix)))
1038 success))
1039
1040
1041(defun shell-replace-by-expanded-directory ()
1042 "Expand directory stack reference before point.
1043Directory stack references are of the form \"=digit\" or \"=-\".
1044See `default-directory' and `shell-dirstack'.
1045
1046Returns t if successful."
1047 (interactive)
1048 (if (comint-match-partial-filename)
1049 (save-excursion
988a4d60
RS
1050 (goto-char (match-beginning 0))
1051 (let ((stack (cons default-directory shell-dirstack))
1052 (index (cond ((looking-at "=-/?")
1053 (length shell-dirstack))
1b93984e 1054 ((looking-at "=\\([0-9]+\\)/?")
988a4d60
RS
1055 (string-to-number
1056 (buffer-substring
1057 (match-beginning 1) (match-end 1)))))))
1058 (cond ((null index)
1059 nil)
1060 ((>= index (length stack))
1cd7adc6 1061 (error "Directory stack not that deep"))
988a4d60
RS
1062 (t
1063 (replace-match (file-name-as-directory (nth index stack)) t t)
1064 (message "Directory item: %d" index)
1065 t))))))
84728570 1066
c88ab9ce
ER
1067(provide 'shell)
1068
6b61353c 1069;;; arch-tag: bcb5f12a-c1f4-4aea-a809-2504bd5bd797
c88ab9ce 1070;;; shell.el ends here