Merge from origin/emacs-24
[emacs.git] / lisp / shell.el
blob480d04a03ebeaac30c545fa54199223f3b3090db
1 ;;; shell.el --- specialized comint.el for running the shell -*- lexical-binding: t -*-
3 ;; Copyright (C) 1988, 1993-1997, 2000-2014 Free Software Foundation, Inc.
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
6 ;; Simon Marshall <simon@gnu.org>
7 ;; Maintainer: 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 customizing 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 init 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 initialized to shell-prompt-pattern, for backwards
93 ;; compatibility.
95 ;; Read the rest of this file for more information.
97 ;;; Code:
99 (require 'comint)
100 (require 'pcomplete)
102 ;;; Customization and Buffer Variables
104 (defgroup shell nil
105 "Running shell from within Emacs buffers."
106 :group 'processes
107 :group 'unix)
109 (defgroup shell-directories nil
110 "Directory support in shell mode."
111 :group 'shell)
113 ;; Unused.
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 ;; Tell bash not to use readline. It's safe to assume --noediting now,
287 ;; as it was introduced in 1996 in Bash version 2.
288 '("--noediting" "-i")
289 "Args passed to inferior shell by \\[shell], if the shell is bash.
290 Value is a list of strings, which may be nil."
291 :type '(repeat (string :tag "Argument"))
292 :group 'shell)
294 (defcustom shell-input-autoexpand 'history
295 "If non-nil, expand input command history references on completion.
296 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
298 If the value is `input', then the expansion is seen on input.
299 If the value is `history', then the expansion is only when inserting
300 into the buffer's input ring. See also `comint-magic-space' and
301 `comint-dynamic-complete-functions'.
303 This variable supplies a default for `comint-input-autoexpand',
304 for Shell mode only."
305 :type '(choice (const :tag "off" nil)
306 (const input)
307 (const history)
308 (const :tag "on" t))
309 :group 'shell)
311 (defcustom shell-display-buffer-actions display-buffer-base-action
312 "The `display-buffer' actions for the `*shell*' buffer."
313 :type display-buffer--action-custom-type
314 :risky t
315 :version "25.1"
316 :group 'shell)
318 (defvar shell-dirstack nil
319 "List of directories saved by pushd in this buffer's shell.
320 Thus, this does not include the shell's current directory.")
322 (defvar shell-dirtrackp t
323 "Non-nil in a shell buffer means directory tracking is enabled.")
325 (defvar shell-last-dir nil
326 "Keep track of last directory for ksh `cd -' command.")
328 (defvar shell-dirstack-query nil
329 "Command used by `shell-resync-dirs' to query the shell.")
331 (defvar shell-mode-map
332 (let ((map (nconc (make-sparse-keymap) comint-mode-map)))
333 (define-key map "\C-c\C-f" 'shell-forward-command)
334 (define-key map "\C-c\C-b" 'shell-backward-command)
335 (define-key map "\t" 'completion-at-point)
336 (define-key map (kbd "M-RET") 'shell-resync-dirs)
337 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
338 (define-key map [menu-bar completion]
339 (cons "Complete"
340 (copy-keymap (lookup-key comint-mode-map [menu-bar completion]))))
341 (define-key-after (lookup-key map [menu-bar completion])
342 [complete-env-variable] '("Complete Env. Variable Name" .
343 shell-dynamic-complete-environment-variable)
344 'complete-file)
345 (define-key-after (lookup-key map [menu-bar completion])
346 [expand-directory] '("Expand Directory Reference" .
347 shell-replace-by-expanded-directory)
348 'complete-expand)
349 map))
351 (defcustom shell-mode-hook '()
352 "Hook for customizing Shell mode."
353 :type 'hook
354 :group 'shell)
356 (defvar shell-font-lock-keywords
357 '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
358 ("^[^ \t\n]+:.*" . font-lock-string-face)
359 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
360 "Additional expressions to highlight in Shell mode.")
362 ;;; Basic Procedures
364 (defun shell--unquote&requote-argument (qstr &optional upos)
365 (unless upos (setq upos 0))
366 (let* ((qpos 0)
367 (dquotes nil)
368 (ustrs '())
369 (re (concat
370 "[\"']"
371 "\\|\\$\\(?:\\([[:alpha:]][[:alnum:]]*\\)"
372 "\\|{\\(?1:[^{}]+\\)}\\)"
373 (when (memq system-type '(ms-dos windows-nt))
374 "\\|%\\(?1:[^\\\\/]*\\)%")
375 (when comint-file-name-quote-list
376 "\\|\\\\\\(.\\)")))
377 (qupos nil)
378 (push (lambda (str end)
379 (push str ustrs)
380 (setq upos (- upos (length str)))
381 (unless (or qupos (> upos 0))
382 (setq qupos (if (< end 0) (- end) (+ upos end))))))
383 match)
384 (while (setq match (string-match re qstr qpos))
385 (funcall push (substring qstr qpos match) match)
386 (cond
387 ((match-beginning 2) (funcall push (match-string 2 qstr) (match-end 0)))
388 ((match-beginning 1) (funcall push (getenv (match-string 1 qstr))
389 (- (match-end 0))))
390 ((eq (aref qstr match) ?\") (setq dquotes (not dquotes)))
391 ((eq (aref qstr match) ?\')
392 (cond
393 (dquotes (funcall push "'" (match-end 0)))
394 ((< match (1+ (length qstr)))
395 (let ((end (string-match "'" qstr (1+ match))))
396 (funcall push (substring qstr (1+ match) end)
397 (or end (length qstr)))))
398 (t nil)))
399 (t (error "Unexpected case in shell--unquote&requote-argument!")))
400 (setq qpos (match-end 0)))
401 (funcall push (substring qstr qpos) (length qstr))
402 (list (mapconcat #'identity (nreverse ustrs) "")
403 qupos #'comint-quote-filename)))
405 (defun shell--unquote-argument (str)
406 (car (shell--unquote&requote-argument str)))
407 (defun shell--requote-argument (upos qstr)
408 ;; See `completion-table-with-quoting'.
409 (let ((res (shell--unquote&requote-argument qstr upos)))
410 (cons (nth 1 res) (nth 2 res))))
412 (defun shell--parse-pcomplete-arguments ()
413 "Parse whitespace separated arguments in the current region."
414 ;; FIXME: share code with shell--unquote&requote-argument.
415 (let ((begin (save-excursion (shell-backward-command 1) (point)))
416 (end (point))
417 begins args)
418 (save-excursion
419 (goto-char begin)
420 (while (< (point) end)
421 (skip-chars-forward " \t\n")
422 (push (point) begins)
423 (let ((arg ()))
424 (while (looking-at
425 (eval-when-compile
426 (concat
427 "\\(?:[^\s\t\n\\\"']+"
428 "\\|'\\([^']*\\)'?"
429 "\\|\"\\(\\(?:[^\"\\]\\|\\\\.\\)*\\)\"?"
430 "\\|\\\\\\(\\(?:.\\|\n\\)?\\)\\)")))
431 (goto-char (match-end 0))
432 (cond
433 ((match-beginning 3) ;Backslash escape.
434 (push (cond
435 ((null comint-file-name-quote-list)
436 (goto-char (match-beginning 3)) "\\")
437 ((= (match-beginning 3) (match-end 3)) "\\")
438 (t (match-string 3)))
439 arg))
440 ((match-beginning 2) ;Double quote.
441 (push (if (null comint-file-name-quote-list) (match-string 2)
442 (replace-regexp-in-string
443 "\\\\\\(.\\)" "\\1" (match-string 2)))
444 arg))
445 ((match-beginning 1) ;Single quote.
446 (push (match-string 1) arg))
447 (t (push (match-string 0) arg))))
448 (push (mapconcat #'identity (nreverse arg) "") args)))
449 (cons (nreverse args) (nreverse begins)))))
451 (defun shell-command-completion-function ()
452 "Completion function for shell command names.
453 This is the value of `pcomplete-command-completion-function' for
454 Shell buffers. It implements `shell-completion-execonly' for
455 `pcomplete' completion."
456 (pcomplete-here (pcomplete-entries nil
457 (if shell-completion-execonly
458 'file-executable-p))))
460 (defun shell-completion-vars ()
461 "Setup completion vars for `shell-mode' and `read-shell-command'."
462 (set (make-local-variable 'comint-completion-fignore)
463 shell-completion-fignore)
464 (set (make-local-variable 'comint-delimiter-argument-list)
465 shell-delimiter-argument-list)
466 (set (make-local-variable 'comint-file-name-chars) shell-file-name-chars)
467 (set (make-local-variable 'comint-file-name-quote-list)
468 shell-file-name-quote-list)
469 (set (make-local-variable 'comint-dynamic-complete-functions)
470 shell-dynamic-complete-functions)
471 (setq-local comint-unquote-function #'shell--unquote-argument)
472 (setq-local comint-requote-function #'shell--requote-argument)
473 (set (make-local-variable 'pcomplete-parse-arguments-function)
474 #'shell--parse-pcomplete-arguments)
475 (set (make-local-variable 'pcomplete-termination-string)
476 (cond ((not comint-completion-addsuffix) "")
477 ((stringp comint-completion-addsuffix)
478 comint-completion-addsuffix)
479 ((not (consp comint-completion-addsuffix)) " ")
480 (t (cdr comint-completion-addsuffix))))
481 (set (make-local-variable 'pcomplete-command-completion-function)
482 #'shell-command-completion-function)
483 ;; Don't use pcomplete's defaulting mechanism, rely on
484 ;; shell-dynamic-complete-functions instead.
485 (set (make-local-variable 'pcomplete-default-completion-function) #'ignore)
486 (setq comint-input-autoexpand shell-input-autoexpand)
487 ;; Not needed in shell-mode because it's inherited from comint-mode, but
488 ;; placed here for read-shell-command.
489 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t))
491 (put 'shell-mode 'mode-class 'special)
493 (define-derived-mode shell-mode comint-mode "Shell"
494 "Major mode for interacting with an inferior shell.\\<shell-mode-map>
495 \\[comint-send-input] after the end of the process' output sends the text from
496 the end of process to the end of the current line.
497 \\[comint-send-input] before end of process output copies the current line minus the prompt to
498 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
499 \\[send-invisible] reads a line of text without echoing it, and sends it to
500 the shell. This is useful for entering passwords. Or, add the function
501 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
503 If you want to make multiple shell buffers, rename the `*shell*' buffer
504 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
506 If you want to make shell buffers limited in length, add the function
507 `comint-truncate-buffer' to `comint-output-filter-functions'.
509 If you accidentally suspend your process, use \\[comint-continue-subjob]
510 to continue it.
512 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
513 keep this buffer's default directory the same as the shell's working directory.
514 While directory tracking is enabled, the shell's working directory is displayed
515 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
516 \\[dirs] queries the shell and resyncs Emacs's idea of what the current
517 directory stack is.
518 \\[shell-dirtrack-mode] turns directory tracking on and off.
519 \(The `dirtrack' package provides an alternative implementation of this
520 feature - see the function `dirtrack-mode'.)
522 \\{shell-mode-map}
523 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
524 `shell-mode-hook' (in that order). Before each input, the hooks on
525 `comint-input-filter-functions' are run. After each shell output, the hooks
526 on `comint-output-filter-functions' are run.
528 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
529 and `shell-popd-regexp' are used to match their respective commands,
530 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
531 control the behavior of the relevant command.
533 Variables `comint-completion-autolist', `comint-completion-addsuffix',
534 `comint-completion-recexact' and `comint-completion-fignore' control the
535 behavior of file name, command name and variable name completion. Variable
536 `shell-completion-execonly' controls the behavior of command name completion.
537 Variable `shell-completion-fignore' is used to initialize the value of
538 `comint-completion-fignore'.
540 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
541 the initialization of the input ring history, and history expansion.
543 Variables `comint-output-filter-functions', a hook, and
544 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
545 control whether input and output cause the window to scroll to the end of the
546 buffer."
547 (setq comint-prompt-regexp shell-prompt-pattern)
548 (shell-completion-vars)
549 (set (make-local-variable 'paragraph-separate) "\\'")
550 (set (make-local-variable 'paragraph-start) comint-prompt-regexp)
551 (set (make-local-variable 'font-lock-defaults) '(shell-font-lock-keywords t))
552 (set (make-local-variable 'shell-dirstack) nil)
553 (set (make-local-variable 'shell-last-dir) nil)
554 (shell-dirtrack-mode 1)
556 ;; By default, ansi-color applies faces using overlays. This is
557 ;; very inefficient in Shell buffers (e.g. Bug#10835). We use a
558 ;; custom `ansi-color-apply-face-function' to convert color escape
559 ;; sequences into `font-lock-face' properties.
560 (setq-local ansi-color-apply-face-function #'shell-apply-ansi-color)
561 (shell-reapply-ansi-color)
563 ;; This is not really correct, since the shell buffer does not really
564 ;; edit this directory. But it is useful in the buffer list and menus.
565 (setq list-buffers-directory (expand-file-name default-directory))
566 ;; shell-dependent assignments.
567 (when (ring-empty-p comint-input-ring)
568 (let ((shell (file-name-nondirectory (car
569 (process-command (get-buffer-process (current-buffer))))))
570 (hsize (getenv "HISTSIZE")))
571 (and (stringp hsize)
572 (integerp (setq hsize (string-to-number hsize)))
573 (> hsize 0)
574 (set (make-local-variable 'comint-input-ring-size) hsize))
575 (setq comint-input-ring-file-name
576 (or (getenv "HISTFILE")
577 (cond ((string-equal shell "bash") "~/.bash_history")
578 ((string-equal shell "ksh") "~/.sh_history")
579 (t "~/.history"))))
580 (if (or (equal comint-input-ring-file-name "")
581 (equal (file-truename comint-input-ring-file-name)
582 (file-truename "/dev/null")))
583 (setq comint-input-ring-file-name nil))
584 ;; Arrange to write out the input ring on exit, if the shell doesn't
585 ;; do this itself.
586 (if (and comint-input-ring-file-name
587 (string-match shell-dumb-shell-regexp shell))
588 (set-process-sentinel (get-buffer-process (current-buffer))
589 #'shell-write-history-on-exit))
590 (setq shell-dirstack-query
591 (cond ((string-equal shell "sh") "pwd")
592 ((string-equal shell "ksh") "echo $PWD ~-")
593 ;; Bypass any aliases. TODO all shells could use this.
594 ((string-equal shell "bash") "command dirs")
595 (t "dirs")))
596 ;; Bypass a bug in certain versions of bash.
597 (when (string-equal shell "bash")
598 (add-hook 'comint-preoutput-filter-functions
599 'shell-filter-ctrl-a-ctrl-b nil t)))
600 (comint-read-input-ring t)))
602 (defun shell-apply-ansi-color (beg end face)
603 "Apply FACE as the ansi-color face for the text between BEG and END."
604 (when face
605 (put-text-property beg end 'ansi-color-face face)
606 (put-text-property beg end 'font-lock-face face)))
608 (defun shell-reapply-ansi-color ()
609 "Reapply ansi-color faces to the existing contents of the buffer."
610 (save-restriction
611 (widen)
612 (let* ((pos (point-min))
613 (end (or (next-single-property-change pos 'ansi-color-face)
614 (point-max)))
615 face)
616 (while end
617 (if (setq face (get-text-property pos 'ansi-color-face))
618 (put-text-property pos (or end (point-max))
619 'font-lock-face face))
620 (setq pos end
621 end (next-single-property-change pos 'ansi-color-face))))))
623 (defun shell-filter-ctrl-a-ctrl-b (string)
624 "Remove `^A' and `^B' characters from comint output.
626 Bash uses these characters as internal quoting characters in its
627 prompt. Due to a bug in some bash versions (including 2.03,
628 2.04, and 2.05b), they may erroneously show up when bash is
629 started with the `--noediting' option and Select Graphic
630 Rendition (SGR) control sequences (formerly known as ANSI escape
631 sequences) are used to color the prompt.
633 This function can be put on `comint-preoutput-filter-functions'."
634 (if (string-match "[\C-a\C-b]" string)
635 (replace-regexp-in-string "[\C-a\C-b]" "" string t t)
636 string))
638 (defun shell-write-history-on-exit (process event)
639 "Called when the shell process is stopped.
641 Writes the input history to a history file
642 `comint-input-ring-file-name' using `comint-write-input-ring'
643 and inserts a short message in the shell buffer.
645 This function is a sentinel watching the shell interpreter process.
646 Sentinels will always get the two parameters PROCESS and EVENT."
647 ;; Write history.
648 (comint-write-input-ring)
649 (let ((buf (process-buffer process)))
650 (when (buffer-live-p buf)
651 (with-current-buffer buf
652 (insert (format "\nProcess %s %s\n" process event))))))
654 ;;;###autoload
655 (defun shell (&optional buffer)
656 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
657 Interactively, a prefix arg means to prompt for BUFFER.
658 If `default-directory' is a remote file name, it is also prompted
659 to change if called with a prefix arg.
661 If BUFFER exists but shell process is not running, make new shell.
662 If BUFFER exists and shell process is running, just switch to BUFFER.
663 Program used comes from variable `explicit-shell-file-name',
664 or (if that is nil) from the ESHELL environment variable,
665 or (if that is nil) from `shell-file-name'.
666 If a file `~/.emacs_SHELLNAME' exists, or `~/.emacs.d/init_SHELLNAME.sh',
667 it is given as initial input (but this may be lost, due to a timing
668 error, if the shell discards input when it starts up).
669 The buffer is put in Shell mode, giving commands for sending input
670 and controlling the subjobs of the shell. See `shell-mode'.
671 See also the variable `shell-prompt-pattern'.
673 To specify a coding system for converting non-ASCII characters
674 in the input and output to the shell, use \\[universal-coding-system-argument]
675 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
676 in the shell buffer, after you start the shell.
677 The default comes from `process-coding-system-alist' and
678 `default-process-coding-system'.
680 The shell file name (sans directories) is used to make a symbol name
681 such as `explicit-csh-args'. If that symbol is a variable,
682 its value is used as a list of arguments when invoking the shell.
683 Otherwise, one argument `-i' is passed to the shell.
685 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
686 (interactive
687 (list
688 (and current-prefix-arg
689 (prog1
690 (read-buffer "Shell buffer: "
691 ;; If the current buffer is an inactive
692 ;; shell buffer, use it as the default.
693 (if (and (eq major-mode 'shell-mode)
694 (null (get-buffer-process (current-buffer))))
695 (buffer-name)
696 (generate-new-buffer-name "*shell*")))
697 (if (file-remote-p default-directory)
698 ;; It must be possible to declare a local default-directory.
699 ;; FIXME: This can't be right: it changes the default-directory
700 ;; of the current-buffer rather than of the *shell* buffer.
701 (setq default-directory
702 (expand-file-name
703 (read-directory-name
704 "Default directory: " default-directory default-directory
705 t nil))))))))
706 (setq buffer (if (or buffer (not (derived-mode-p 'shell-mode))
707 (comint-check-proc (current-buffer)))
708 (get-buffer-create (or buffer "*shell*"))
709 ;; If the current buffer is a dead shell buffer, use it.
710 (current-buffer)))
712 ;; On remote hosts, the local `shell-file-name' might be useless.
713 (if (and (called-interactively-p 'any)
714 (file-remote-p default-directory)
715 (null explicit-shell-file-name)
716 (null (getenv "ESHELL")))
717 (with-current-buffer buffer
718 (set (make-local-variable 'explicit-shell-file-name)
719 (file-remote-p
720 (expand-file-name
721 (read-file-name
722 "Remote shell path: " default-directory shell-file-name
723 t shell-file-name))
724 'localname))))
726 ;; The buffer's window must be correctly set when we call comint (so
727 ;; that comint sets the COLUMNS env var properly).
728 (pop-to-buffer buffer shell-display-buffer-actions)
729 (unless (comint-check-proc buffer)
730 (let* ((prog (or explicit-shell-file-name
731 (getenv "ESHELL") shell-file-name))
732 (name (file-name-nondirectory prog))
733 (startfile (concat "~/.emacs_" name))
734 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
735 (unless (file-exists-p startfile)
736 (setq startfile (concat user-emacs-directory "init_" name ".sh")))
737 (apply 'make-comint-in-buffer "shell" buffer prog
738 (if (file-exists-p startfile) startfile)
739 (if (and xargs-name (boundp xargs-name))
740 (symbol-value xargs-name)
741 '("-i")))
742 (shell-mode)))
743 buffer)
745 ;;; Directory tracking
747 ;; This code provides the shell mode input sentinel
748 ;; SHELL-DIRECTORY-TRACKER
749 ;; that tracks cd, pushd, and popd commands issued to the shell, and
750 ;; changes the current directory of the shell buffer accordingly.
752 ;; This is basically a fragile hack, although it's more accurate than
753 ;; the version in Emacs 18's shell.el. It has the following failings:
754 ;; 1. It doesn't know about the cdpath shell variable.
755 ;; 2. It cannot infallibly deal with command sequences, though it does well
756 ;; with these and with ignoring commands forked in another shell with ()s.
757 ;; 3. More generally, any complex command is going to throw it. Otherwise,
758 ;; you'd have to build an entire shell interpreter in Emacs Lisp. Failing
759 ;; that, there's no way to catch shell commands where cd's are buried
760 ;; inside conditional expressions, aliases, and so forth.
762 ;; The whole approach is a crock. Shell aliases mess it up. File sourcing
763 ;; messes it up. You run other processes under the shell; these each have
764 ;; separate working directories, and some have commands for manipulating
765 ;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
766 ;; commands that do *not* affect the current w.d. at all, but look like they
767 ;; do (e.g., the cd command in ftp). In shells that allow you job
768 ;; control, you can switch between jobs, all having different w.d.'s. So
769 ;; simply saying %3 can shift your w.d..
771 ;; The solution is to relax, not stress out about it, and settle for
772 ;; a hack that works pretty well in typical circumstances. Remember
773 ;; that a half-assed solution is more in keeping with the spirit of Unix,
774 ;; anyway. Blech.
776 ;; One good hack not implemented here for users of programmable shells
777 ;; is to program up the shell w.d. manipulation commands to output
778 ;; a coded command sequence to the tty. Something like
779 ;; ESC | <cwd> |
780 ;; where <cwd> is the new current working directory. Then trash the
781 ;; directory tracking machinery currently used in this package, and
782 ;; replace it with a process filter that watches for and strips out
783 ;; these messages.
785 (defun shell-directory-tracker (str)
786 "Tracks cd, pushd and popd commands issued to the shell.
787 This function is called on each input passed to the shell.
788 It watches for cd, pushd and popd commands and sets the buffer's
789 default directory to track these commands.
791 You may toggle this tracking on and off with \\[shell-dirtrack-mode].
792 If Emacs gets confused, you can resync with the shell with \\[dirs].
793 \(The `dirtrack' package provides an alternative implementation of this
794 feature - see the function `dirtrack-mode'.)
796 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
797 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
798 and `shell-pushd-dunique' control the behavior of the relevant command.
800 Environment variables are expanded, see function `substitute-in-file-name'."
801 (if shell-dirtrackp
802 ;; We fail gracefully if we think the command will fail in the shell.
803 ;;; (with-demoted-errors "Directory tracker failure: %s"
804 ;; This fails so often that it seems better to just ignore errors (?).
805 ;; Eg even: foo=/tmp; cd $foo is beyond us (bug#17159).
806 (ignore-errors
807 (let ((start (progn (string-match
808 (concat "^" shell-command-separator-regexp)
809 str) ; skip whitespace
810 (match-end 0)))
811 (case-fold-search)
812 end cmd arg1)
813 (while (string-match shell-command-regexp str start)
814 (setq end (match-end 0)
815 cmd (comint-arguments (substring str start end) 0 0)
816 arg1 (comint-arguments (substring str start end) 1 1))
817 (if arg1
818 (setq arg1 (shell-unquote-argument arg1)))
819 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
820 "\\)\\($\\|[ \t]\\)")
821 cmd)
822 (shell-process-popd (comint-substitute-in-file-name arg1)))
823 ((string-match (concat "\\`\\(" shell-pushd-regexp
824 "\\)\\($\\|[ \t]\\)")
825 cmd)
826 (shell-process-pushd (comint-substitute-in-file-name arg1)))
827 ((string-match (concat "\\`\\(" shell-cd-regexp
828 "\\)\\($\\|[ \t]\\)")
829 cmd)
830 (shell-process-cd (comint-substitute-in-file-name arg1)))
831 ((and shell-chdrive-regexp
832 (string-match (concat "\\`\\(" shell-chdrive-regexp
833 "\\)\\($\\|[ \t]\\)")
834 cmd))
835 (shell-process-cd (comint-substitute-in-file-name cmd))))
836 (setq start (progn (string-match shell-command-separator-regexp
837 str end)
838 ;; skip again
839 (match-end 0))))))))
841 (defun shell-unquote-argument (string)
842 "Remove all kinds of shell quoting from STRING."
843 (save-match-data
844 (let ((idx 0) next inside
845 (quote-chars
846 (if (string-match shell-dumb-shell-regexp
847 (file-name-nondirectory
848 (car (process-command (get-buffer-process (current-buffer))))))
849 "['`\"]"
850 "[\\'`\"]")))
851 (while (and (< idx (length string))
852 (setq next (string-match quote-chars string next)))
853 (cond ((= (aref string next) ?\\)
854 (setq string (replace-match "" nil nil string))
855 (setq next (1+ next)))
856 ((and inside (= (aref string next) inside))
857 (setq string (replace-match "" nil nil string))
858 (setq inside nil))
859 (inside
860 (setq next (1+ next)))
862 (setq inside (aref string next))
863 (setq string (replace-match "" nil nil string)))))
864 string)))
866 ;; popd [+n]
867 (defun shell-process-popd (arg)
868 (let ((num (or (shell-extract-num arg) 0)))
869 (cond ((and num (= num 0) shell-dirstack)
870 (shell-cd (shell-prefixed-directory-name (car shell-dirstack)))
871 (setq shell-dirstack (cdr shell-dirstack))
872 (shell-dirstack-message))
873 ((and num (> num 0) (<= num (length shell-dirstack)))
874 (let* ((ds (cons nil shell-dirstack))
875 (cell (nthcdr (1- num) ds)))
876 (rplacd cell (cdr (cdr cell)))
877 (setq shell-dirstack (cdr ds))
878 (shell-dirstack-message)))
880 (error "Couldn't popd")))))
882 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
883 (defun shell-prefixed-directory-name (dir)
884 (if (= (length comint-file-name-prefix) 0)
886 (if (file-name-absolute-p dir)
887 ;; The name is absolute, so prepend the prefix.
888 (concat comint-file-name-prefix dir)
889 ;; For relative name we assume default-directory already has the prefix.
890 (expand-file-name dir))))
892 ;; cd [dir]
893 (defun shell-process-cd (arg)
894 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
895 "~"))
896 ((string-equal "-" arg) shell-last-dir)
897 (t (shell-prefixed-directory-name arg)))))
898 (setq shell-last-dir default-directory)
899 (shell-cd new-dir)
900 (shell-dirstack-message)))
902 ;; pushd [+n | dir]
903 (defun shell-process-pushd (arg)
904 (let ((num (shell-extract-num arg)))
905 (cond ((zerop (length arg))
906 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
907 (cond (shell-pushd-tohome
908 (shell-process-pushd (concat comint-file-name-prefix "~")))
909 (shell-dirstack
910 (let ((old default-directory))
911 (shell-cd (car shell-dirstack))
912 (setq shell-dirstack (cons old (cdr shell-dirstack)))
913 (shell-dirstack-message)))
915 (message "Directory stack empty."))))
916 ((numberp num)
917 ;; pushd +n
918 (cond ((> num (length shell-dirstack))
919 (message "Directory stack not that deep."))
920 ((= num 0)
921 (error "Couldn't cd"))
922 (shell-pushd-dextract
923 (let ((dir (nth (1- num) shell-dirstack)))
924 (shell-process-popd arg)
925 (shell-process-pushd default-directory)
926 (shell-cd dir)
927 (shell-dirstack-message)))
929 (let* ((ds (cons default-directory shell-dirstack))
930 (dslen (length ds))
931 (front (nthcdr num ds))
932 (back (reverse (nthcdr (- dslen num) (reverse ds))))
933 (new-ds (append front back)))
934 (shell-cd (car new-ds))
935 (setq shell-dirstack (cdr new-ds))
936 (shell-dirstack-message)))))
938 ;; pushd <dir>
939 (let ((old-wd default-directory))
940 (shell-cd (shell-prefixed-directory-name arg))
941 (if (or (null shell-pushd-dunique)
942 (not (member old-wd shell-dirstack)))
943 (setq shell-dirstack (cons old-wd shell-dirstack)))
944 (shell-dirstack-message))))))
946 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
947 (defun shell-extract-num (str)
948 (and (string-match "^\\+[1-9][0-9]*$" str)
949 (string-to-number str)))
951 (defvaralias 'shell-dirtrack-mode 'shell-dirtrackp)
952 (define-minor-mode shell-dirtrack-mode
953 "Toggle directory tracking in this shell buffer (Shell Dirtrack mode).
954 With a prefix argument ARG, enable Shell Dirtrack mode if ARG is
955 positive, and disable it otherwise. If called from Lisp, enable
956 the mode if ARG is omitted or nil.
958 The `dirtrack' package provides an alternative implementation of
959 this feature; see the function `dirtrack-mode'."
960 nil nil nil
961 (setq list-buffers-directory (if shell-dirtrack-mode default-directory))
962 (if shell-dirtrack-mode
963 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
964 (remove-hook 'comint-input-filter-functions 'shell-directory-tracker t)))
966 (define-obsolete-function-alias 'shell-dirtrack-toggle 'shell-dirtrack-mode
967 "23.1")
969 (defun shell-cd (dir)
970 "Do normal `cd' to DIR, and set `list-buffers-directory'."
971 (cd dir)
972 (if shell-dirtrackp
973 (setq list-buffers-directory default-directory)))
975 (defun shell-resync-dirs ()
976 "Resync the buffer's idea of the current directory stack.
977 This command queries the shell with the command bound to
978 `shell-dirstack-query' (default \"dirs\"), reads the next
979 line output and parses it to form the new directory stack.
980 DON'T issue this command unless the buffer is at a shell prompt.
981 Also, note that if some other subprocess decides to do output
982 immediately after the query, its output will be taken as the
983 new directory stack -- you lose. If this happens, just do the
984 command again."
985 (interactive)
986 (let* ((proc (get-buffer-process (current-buffer)))
987 (pmark (process-mark proc))
988 (started-at-pmark (= (point) (marker-position pmark))))
989 (save-excursion
990 (goto-char pmark)
991 ;; If the process echoes commands, don't insert a fake command in
992 ;; the buffer or it will appear twice.
993 (unless comint-process-echoes
994 (insert shell-dirstack-query) (insert "\n"))
995 (sit-for 0) ; force redisplay
996 (comint-send-string proc shell-dirstack-query)
997 (comint-send-string proc "\n")
998 (set-marker pmark (point))
999 (let ((pt (point))
1000 (regexp
1001 (concat
1002 (if comint-process-echoes
1003 ;; Skip command echo if the process echoes
1004 (concat "\\(" (regexp-quote shell-dirstack-query) "\n\\)")
1005 "\\(\\)")
1006 "\\(.+\n\\)")))
1007 ;; This extra newline prevents the user's pending input from spoofing us.
1008 (insert "\n") (backward-char 1)
1009 ;; Wait for one line.
1010 (while (not (looking-at regexp))
1011 (accept-process-output proc)
1012 (goto-char pt)))
1013 (goto-char pmark) (delete-char 1) ; remove the extra newline
1014 ;; That's the dirlist. grab it & parse it.
1015 (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
1016 (dl-len (length dl))
1017 (ds '()) ; new dir stack
1018 (i 0))
1019 (while (< i dl-len)
1020 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
1021 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
1022 (setq ds (cons (concat comint-file-name-prefix
1023 (substring dl (match-beginning 1)
1024 (match-end 1)))
1025 ds))
1026 (setq i (match-end 0)))
1027 (let ((ds (nreverse ds)))
1028 (with-demoted-errors "Couldn't cd: %s"
1029 (shell-cd (car ds))
1030 (setq shell-dirstack (cdr ds)
1031 shell-last-dir (car shell-dirstack))
1032 (shell-dirstack-message)))))
1033 (if started-at-pmark (goto-char (marker-position pmark)))))
1035 ;; For your typing convenience:
1036 (defalias 'dirs 'shell-resync-dirs)
1039 ;; Show the current dirstack on the message line.
1040 ;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
1041 ;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
1042 ;; All the commands that mung the buffer's dirstack finish by calling
1043 ;; this guy.
1044 (defun shell-dirstack-message ()
1045 (when shell-dirtrack-verbose
1046 (let* ((msg "")
1047 (ds (cons default-directory shell-dirstack))
1048 (home (expand-file-name (concat comint-file-name-prefix "~/")))
1049 (homelen (length home)))
1050 (while ds
1051 (let ((dir (car ds)))
1052 (and (>= (length dir) homelen)
1053 (string= home (substring dir 0 homelen))
1054 (setq dir (concat "~/" (substring dir homelen))))
1055 ;; Strip off comint-file-name-prefix if present.
1056 (and comint-file-name-prefix
1057 (>= (length dir) (length comint-file-name-prefix))
1058 (string= comint-file-name-prefix
1059 (substring dir 0 (length comint-file-name-prefix)))
1060 (setq dir (substring dir (length comint-file-name-prefix)))
1061 (setcar ds dir))
1062 (setq msg (concat msg (directory-file-name dir) " "))
1063 (setq ds (cdr ds))))
1064 (message "%s" msg))))
1066 ;; This was mostly copied from shell-resync-dirs.
1067 (defun shell-snarf-envar (var)
1068 "Return as a string the shell's value of environment variable VAR."
1069 (let* ((cmd (format "printenv '%s'\n" var))
1070 (proc (get-buffer-process (current-buffer)))
1071 (pmark (process-mark proc)))
1072 (goto-char pmark)
1073 (insert cmd)
1074 (sit-for 0) ; force redisplay
1075 (comint-send-string proc cmd)
1076 (set-marker pmark (point))
1077 (let ((pt (point))) ; wait for 1 line
1078 ;; This extra newline prevents the user's pending input from spoofing us.
1079 (insert "\n") (backward-char 1)
1080 (while (not (looking-at ".+\n"))
1081 (accept-process-output proc)
1082 (goto-char pt)))
1083 (goto-char pmark) (delete-char 1) ; remove the extra newline
1084 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
1086 (defun shell-copy-environment-variable (variable)
1087 "Copy the environment variable VARIABLE from the subshell to Emacs.
1088 This command reads the value of the specified environment variable
1089 in the shell, and sets the same environment variable in Emacs
1090 \(what `getenv' in Emacs would return) to that value.
1091 That value will affect any new subprocesses that you subsequently start
1092 from Emacs."
1093 (interactive (list (read-envvar-name "\
1094 Copy Shell environment variable to Emacs: ")))
1095 (setenv variable (shell-snarf-envar variable)))
1097 (defun shell-forward-command (&optional arg)
1098 "Move forward across ARG shell command(s). Does not cross lines.
1099 See `shell-command-regexp'."
1100 (interactive "p")
1101 (let ((limit (line-end-position)))
1102 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
1103 limit 'move arg)
1104 (skip-syntax-backward " "))))
1107 (defun shell-backward-command (&optional arg)
1108 "Move backward across ARG shell command(s). Does not cross lines.
1109 See `shell-command-regexp'."
1110 (interactive "p")
1111 (let ((limit (save-excursion (comint-bol nil) (point))))
1112 (when (> limit (point))
1113 (setq limit (line-beginning-position)))
1114 (skip-syntax-backward " " limit)
1115 (if (re-search-backward
1116 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
1117 (progn (goto-char (match-beginning 1))
1118 (skip-chars-forward ";&|")))))
1120 (defun shell-dynamic-complete-command ()
1121 "Dynamically complete the command at point.
1122 This function is similar to `comint-dynamic-complete-filename', except that it
1123 searches `exec-path' (minus trailing `exec-directory') for completion
1124 candidates. Note that this may not be the same as the shell's idea of the
1125 path.
1127 Completion is dependent on the value of `shell-completion-execonly',
1128 `shell-completion-fignore', plus those that affect file completion. See Info
1129 node `Shell Options'.
1131 Returns t if successful."
1132 (interactive)
1133 (let ((data (shell-command-completion)))
1134 (if data
1135 (prog2 (unless (window-minibuffer-p)
1136 (message "Completing command name..."))
1137 (apply #'completion-in-region data)))))
1139 (defun shell-command-completion ()
1140 "Return the completion data for the command at point, if any."
1141 (let ((filename (comint-match-partial-filename)))
1142 (if (and filename
1143 (save-match-data (not (string-match "[~/]" filename)))
1144 (eq (match-beginning 0)
1145 (save-excursion (shell-backward-command 1) (point))))
1146 (shell--command-completion-data))))
1148 (defun shell--command-completion-data ()
1149 "Return the completion data for the command at point."
1150 (let* ((filename (or (comint-match-partial-filename) ""))
1151 (start (if (zerop (length filename)) (point) (match-beginning 0)))
1152 (end (if (zerop (length filename)) (point) (match-end 0)))
1153 (filenondir (file-name-nondirectory filename))
1154 ; why cdr? see `shell-dynamic-complete-command'
1155 (path-dirs (append (cdr (reverse exec-path))
1156 (if (memq system-type '(windows-nt ms-dos)) '("."))))
1157 (cwd (file-name-as-directory (expand-file-name default-directory)))
1158 (ignored-extensions
1159 (and comint-completion-fignore
1160 (mapconcat (function (lambda (x) (concat (regexp-quote x) "\\'")))
1161 comint-completion-fignore "\\|")))
1162 (dir "") (comps-in-dir ())
1163 (file "") (abs-file-name "") (completions ()))
1164 ;; Go thru each dir in the search path, finding completions.
1165 (while path-dirs
1166 (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
1167 comps-in-dir (and (file-accessible-directory-p dir)
1168 (file-name-all-completions filenondir dir)))
1169 ;; Go thru each completion found, to see whether it should be used.
1170 (while comps-in-dir
1171 (setq file (car comps-in-dir)
1172 abs-file-name (concat dir file))
1173 (if (and (not (member file completions))
1174 (not (and ignored-extensions
1175 (string-match ignored-extensions file)))
1176 (or (string-equal dir cwd)
1177 (not (file-directory-p abs-file-name)))
1178 (or (null shell-completion-execonly)
1179 (file-executable-p abs-file-name)))
1180 (setq completions (cons file completions)))
1181 (setq comps-in-dir (cdr comps-in-dir)))
1182 (setq path-dirs (cdr path-dirs)))
1183 ;; OK, we've got a list of completions.
1184 (list
1185 start end
1186 (lambda (string pred action)
1187 (if (string-match "/" string)
1188 (completion-file-name-table string pred action)
1189 (complete-with-action action completions string pred)))
1190 :exit-function
1191 (lambda (_string finished)
1192 (when (memq finished '(sole finished))
1193 (if (looking-at " ")
1194 (goto-char (match-end 0))
1195 (insert " ")))))))
1197 ;; (defun shell-dynamic-complete-as-command ()
1198 ;; "Dynamically complete at point as a command.
1199 ;; See `shell-dynamic-complete-filename'. Returns t if successful."
1200 ;; (apply #'completion-in-region shell--command-completion-data))
1202 (defun shell-dynamic-complete-filename ()
1203 "Dynamically complete the filename at point.
1204 This completes only if point is at a suitable position for a
1205 filename argument."
1206 (interactive)
1207 (let ((data (shell-filename-completion)))
1208 (if data (apply #'completion-in-region data))))
1210 (defun shell-filename-completion ()
1211 "Return the completion data for file name at point, if any."
1212 (let ((opoint (point))
1213 (beg (comint-line-beginning-position)))
1214 (when (save-excursion
1215 (goto-char (if (re-search-backward "[;|&]" beg t)
1216 (match-end 0)
1217 beg))
1218 (re-search-forward "[^ \t][ \t]" opoint t))
1219 (comint-filename-completion))))
1221 (defun shell-match-partial-variable ()
1222 "Return the shell variable at point, or nil if none is found."
1223 (save-excursion
1224 (if (re-search-backward "[^A-Za-z0-9_{(]" nil 'move)
1225 (or (looking-at "\\$") (forward-char 1)))
1226 (if (or (eolp) (looking-at "[^A-Za-z0-9_{($]"))
1228 (looking-at "\\$?[{(]?[A-Za-z0-9_]*[})]?")
1229 (buffer-substring (match-beginning 0) (match-end 0)))))
1231 (defun shell-dynamic-complete-environment-variable ()
1232 "Dynamically complete the environment variable at point.
1233 Completes if after a variable, i.e., if it starts with a \"$\".
1235 This function is similar to `comint-dynamic-complete-filename', except that it
1236 searches `process-environment' for completion candidates. Note that this may
1237 not be the same as the interpreter's idea of variable names. The main problem
1238 with this type of completion is that `process-environment' is the environment
1239 which Emacs started with. Emacs does not track changes to the environment made
1240 by the interpreter. Perhaps it would be more accurate if this function was
1241 called `shell-dynamic-complete-process-environment-variable'.
1243 Returns non-nil if successful."
1244 (interactive)
1245 (let ((data (shell-environment-variable-completion)))
1246 (if data
1247 (prog2 (unless (window-minibuffer-p)
1248 (message "Completing variable name..."))
1249 (apply #'completion-in-region data)))))
1252 (defun shell-environment-variable-completion ()
1253 "Completion data for an environment variable at point, if any."
1254 (let* ((var (shell-match-partial-variable))
1255 (end (match-end 0)))
1256 (when (and (not (zerop (length var))) (eq (aref var 0) ?$))
1257 (let* ((start
1258 (save-excursion
1259 (goto-char (match-beginning 0))
1260 (looking-at "\\$?[({]*")
1261 (match-end 0)))
1262 (variables (mapcar (lambda (x)
1263 (substring x 0 (string-match "=" x)))
1264 process-environment))
1265 (suffix (pcase (char-before start) (?\{ "}") (?\( ")") (_ ""))))
1266 (list start end variables
1267 :exit-function
1268 (lambda (s finished)
1269 (when (memq finished '(sole finished))
1270 (let ((suf (concat suffix
1271 (if (file-directory-p
1272 (comint-directory (getenv s)))
1273 "/"))))
1274 (if (looking-at (regexp-quote suf))
1275 (goto-char (match-end 0))
1276 (insert suf))))))))))
1279 (defun shell-c-a-p-replace-by-expanded-directory ()
1280 "Expand directory stack reference before point.
1281 For use on `completion-at-point-functions'."
1282 (when (comint-match-partial-filename)
1283 (save-excursion
1284 (goto-char (match-beginning 0))
1285 (let ((stack (cons default-directory shell-dirstack))
1286 (index (cond ((looking-at "=-/?")
1287 (length shell-dirstack))
1288 ((looking-at "=\\([0-9]+\\)/?")
1289 (string-to-number
1290 (buffer-substring
1291 (match-beginning 1) (match-end 1)))))))
1292 (when index
1293 (let ((start (match-beginning 0))
1294 (end (match-end 0))
1295 (replacement (file-name-as-directory (nth index stack))))
1296 (lambda ()
1297 (cond
1298 ((>= index (length stack))
1299 (error "Directory stack not that deep"))
1301 (save-excursion
1302 (goto-char start)
1303 (insert replacement)
1304 (delete-char (- end start)))
1305 (message "Directory item: %d" index)
1306 t)))))))))
1308 (defun shell-replace-by-expanded-directory ()
1309 "Expand directory stack reference before point.
1310 Directory stack references are of the form \"=digit\" or \"=-\".
1311 See `default-directory' and `shell-dirstack'.
1313 Returns t if successful."
1314 (interactive)
1315 (let ((f (shell-c-a-p-replace-by-expanded-directory)))
1316 (if f (funcall f))))
1318 (provide 'shell)
1320 ;;; shell.el ends here