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