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