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