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