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