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