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