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