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