; doc/emacs/misc.texi (Network Security): Fix typo.
[emacs.git] / lisp / shell.el
blob91c65ed171e8a294a714282ed3b92b845dffd79e
1 ;;; shell.el --- specialized comint.el for running the shell -*- lexical-binding: t -*-
3 ;; Copyright (C) 1988, 1993-1997, 2000-2018 Free Software Foundation,
4 ;; Inc.
6 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
7 ;; Simon Marshall <simon@gnu.org>
8 ;; Maintainer: 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 <https://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 ;; c-c c-f shell-forward-command Forward a shell command
87 ;; c-c 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 ;; Unused.
115 ;;; (defgroup shell-faces nil
116 ;;; "Faces in shell buffers."
117 ;;; :group 'shell)
119 ;;;###autoload
120 (defcustom shell-dumb-shell-regexp (purecopy "cmd\\(proxy\\)?\\.exe")
121 "Regexp to match shells that don't save their command history, and
122 don't handle the backslash as a quote character. For shells that
123 match this regexp, Emacs will write out the command history when the
124 shell finishes, and won't remove backslashes when it unquotes shell
125 arguments."
126 :type 'regexp
127 :group 'shell)
129 (defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
130 "Regexp to match prompts in the inferior shell.
131 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
132 This variable is used to initialize `comint-prompt-regexp' in the
133 shell buffer.
135 If `comint-use-prompt-regexp' is nil, then this variable is only used
136 to determine paragraph boundaries. See Info node `Shell Prompts' for
137 how Shell mode treats paragraphs.
139 The pattern should probably not match more than one line. If it does,
140 Shell mode may become confused trying to distinguish prompt from input
141 on lines which don't start with a prompt."
142 :type 'regexp
143 :group 'shell)
145 (defcustom shell-completion-fignore nil
146 "List of suffixes to be disregarded during file/command completion.
147 This variable is used to initialize `comint-completion-fignore' in the shell
148 buffer. The default is nil, for compatibility with most shells.
149 Some people like (\"~\" \"#\" \"%\")."
150 :type '(repeat (string :tag "Suffix"))
151 :group 'shell)
153 (defcustom shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
154 "List of characters to recognize as separate arguments.
155 This variable is used to initialize `comint-delimiter-argument-list' in the
156 shell buffer. The value may depend on the operating system or shell."
157 :type '(choice (const nil)
158 (repeat :tag "List of characters" character))
159 :group 'shell)
161 (defcustom shell-file-name-chars
162 (if (memq system-type '(ms-dos windows-nt cygwin))
163 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
164 "[]~/A-Za-z0-9+@:_.$#%,={}-")
165 "String of characters valid in a file name.
166 This variable is used to initialize `comint-file-name-chars' in the
167 shell buffer. The value may depend on the operating system or shell."
168 :type 'string
169 :group 'shell)
171 (defcustom shell-file-name-quote-list
172 (if (memq system-type '(ms-dos windows-nt))
174 (append shell-delimiter-argument-list '(?\s ?$ ?\* ?\! ?\" ?\' ?\` ?\# ?\\)))
175 "List of characters to quote when in a file name.
176 This variable is used to initialize `comint-file-name-quote-list' in the
177 shell buffer. The value may depend on the operating system or shell."
178 :type '(repeat character)
179 :group 'shell)
181 (defcustom shell-dynamic-complete-functions
182 '(comint-c-a-p-replace-by-expanded-history
183 shell-environment-variable-completion
184 shell-command-completion
185 shell-c-a-p-replace-by-expanded-directory
186 pcomplete-completions-at-point
187 shell-filename-completion
188 comint-filename-completion)
189 "List of functions called to perform completion.
190 This variable is used to initialize `comint-dynamic-complete-functions' in the
191 shell buffer."
192 :type '(repeat function)
193 :group 'shell)
195 (defcustom shell-command-regexp "[^;&|\n]+"
196 "Regexp to match a single command within a pipeline.
197 This is used for directory tracking and does not do a perfect job."
198 :type 'regexp
199 :group 'shell)
201 (defcustom shell-command-separator-regexp "[;&|\n \t]*"
202 "Regexp to match a single command within a pipeline.
203 This is used for directory tracking and does not do a perfect job."
204 :type 'regexp
205 :group 'shell)
207 (defcustom shell-completion-execonly t
208 "If non-nil, use executable files only for completion candidates.
209 This mirrors the optional behavior of tcsh.
211 Detecting executability of files may slow command completion considerably."
212 :type 'boolean
213 :group 'shell)
215 (defcustom shell-popd-regexp "popd"
216 "Regexp to match subshell commands equivalent to popd."
217 :type 'regexp
218 :group 'shell-directories)
220 (defcustom shell-pushd-regexp "pushd"
221 "Regexp to match subshell commands equivalent to pushd."
222 :type 'regexp
223 :group 'shell-directories)
225 (defcustom shell-pushd-tohome nil
226 "If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
227 This mirrors the optional behavior of tcsh."
228 :type 'boolean
229 :group 'shell-directories)
231 (defcustom shell-pushd-dextract nil
232 "If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
233 This mirrors the optional behavior of tcsh."
234 :type 'boolean
235 :group 'shell-directories)
237 (defcustom shell-pushd-dunique nil
238 "If non-nil, make pushd only add unique directories to the stack.
239 This mirrors the optional behavior of tcsh."
240 :type 'boolean
241 :group 'shell-directories)
243 (defcustom shell-cd-regexp "cd"
244 "Regexp to match subshell commands equivalent to cd."
245 :type 'regexp
246 :group 'shell-directories)
248 (defcustom shell-chdrive-regexp
249 (if (memq system-type '(ms-dos windows-nt))
250 ; NetWare allows the five chars between upper and lower alphabetics.
251 "[]a-zA-Z^_`\\[\\\\]:"
252 nil)
253 "If non-nil, is regexp used to track drive changes."
254 :type '(choice regexp
255 (const nil))
256 :group 'shell-directories)
258 (defcustom shell-dirtrack-verbose t
259 "If non-nil, show the directory stack following directory change.
260 This is effective only if directory tracking is enabled.
261 The `dirtrack' package provides an alternative implementation of this feature -
262 see the function `dirtrack-mode'."
263 :type 'boolean
264 :group 'shell-directories)
266 (defcustom explicit-shell-file-name nil
267 "If non-nil, is file name to use for explicitly requested inferior shell.
268 When nil, such interactive shell sessions fallback to using either
269 the shell specified in $ESHELL or in `shell-file-name'."
270 :type '(choice (const :tag "None" nil) file)
271 :group 'shell)
273 ;; Note: There are no explicit references to the variable `explicit-csh-args'.
274 ;; It is used implicitly by M-x shell when the shell is `csh'.
275 (defcustom explicit-csh-args
276 (if (eq system-type 'hpux)
277 ;; -T persuades HP's csh not to think it is smarter
278 ;; than us about what terminal modes to use.
279 '("-i" "-T")
280 '("-i"))
281 "Args passed to inferior shell by \\[shell], if the shell is csh.
282 Value is a list of strings, which may be nil."
283 :type '(repeat (string :tag "Argument"))
284 :group 'shell)
286 ;; Note: There are no explicit references to the variable `explicit-bash-args'.
287 ;; It is used implicitly by M-x shell when the interactive shell is `bash'.
288 (defcustom explicit-bash-args
289 ;; Tell bash not to use readline. It's safe to assume --noediting now,
290 ;; as it was introduced in 1996 in Bash version 2.
291 '("--noediting" "-i")
292 "Args passed to inferior shell by \\[shell], if the shell is bash.
293 Value is a list of strings, which may be nil."
294 :type '(repeat (string :tag "Argument"))
295 :group 'shell)
297 (defcustom shell-input-autoexpand 'history
298 "If non-nil, expand input command history references on completion.
299 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
301 If the value is `input', then the expansion is seen on input.
302 If the value is `history', then the expansion is only when inserting
303 into the buffer's input ring. See also `comint-magic-space' and
304 `comint-dynamic-complete-functions'.
306 This variable supplies a default for `comint-input-autoexpand',
307 for Shell mode only."
308 :type '(choice (const :tag "off" nil)
309 (const input)
310 (const history)
311 (const :tag "on" t))
312 :group 'shell)
314 (defvar shell-dirstack nil
315 "List of directories saved by pushd in this buffer's shell.
316 Thus, this does not include the shell's current directory.")
318 (defvaralias 'shell-dirtrack-mode 'shell-dirtrackp)
320 (defvar shell-dirtrackp t
321 "Non-nil in a shell buffer means directory tracking is enabled.")
323 (defvar shell-last-dir nil
324 "Keep track of last directory for ksh `cd -' command.")
326 (defvar shell-dirstack-query nil
327 "Command used by `shell-resync-dirs' to query the shell.")
329 (defvar shell-mode-map
330 (let ((map (nconc (make-sparse-keymap) comint-mode-map)))
331 (define-key map "\C-c\C-f" 'shell-forward-command)
332 (define-key map "\C-c\C-b" 'shell-backward-command)
333 (define-key map "\t" 'completion-at-point)
334 (define-key map (kbd "M-RET") 'shell-resync-dirs)
335 (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
336 (define-key map [menu-bar completion]
337 (cons "Complete"
338 (copy-keymap (lookup-key comint-mode-map [menu-bar completion]))))
339 (define-key-after (lookup-key map [menu-bar completion])
340 [complete-env-variable] '("Complete Env. Variable Name" .
341 shell-dynamic-complete-environment-variable)
342 'complete-file)
343 (define-key-after (lookup-key map [menu-bar completion])
344 [expand-directory] '("Expand Directory Reference" .
345 shell-replace-by-expanded-directory)
346 'complete-expand)
347 map))
349 (defcustom shell-mode-hook '()
350 "Hook for customizing Shell mode."
351 :type 'hook
352 :group 'shell)
354 (defvar shell-font-lock-keywords
355 '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
356 ("^[^ \t\n]+:.*" . font-lock-string-face)
357 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
358 "Additional expressions to highlight in Shell mode.")
360 ;;; Basic Procedures
362 (defun shell--unquote&requote-argument (qstr &optional upos)
363 (unless upos (setq upos 0))
364 (let* ((qpos 0)
365 (dquotes nil)
366 (ustrs '())
367 (re (concat
368 "[\"']"
369 "\\|\\$\\(?:\\([[:alpha:]][[:alnum:]]*\\)"
370 "\\|{\\(?1:[^{}]+\\)}\\)"
371 (when (memq system-type '(ms-dos windows-nt))
372 "\\|%\\(?1:[^\\\\/]*\\)%")
373 (when comint-file-name-quote-list
374 "\\|\\\\\\(.\\)")))
375 (qupos nil)
376 (push (lambda (str end)
377 (push str ustrs)
378 (setq upos (- upos (length str)))
379 (unless (or qupos (> upos 0))
380 (setq qupos (if (< end 0) (- end) (+ upos end))))))
381 match)
382 (while (setq match (string-match re qstr qpos))
383 (funcall push (substring qstr qpos match) match)
384 (cond
385 ((match-beginning 2) (funcall push (match-string 2 qstr) (match-end 0)))
386 ((match-beginning 1) (funcall push (getenv (match-string 1 qstr))
387 (- (match-end 0))))
388 ((eq (aref qstr match) ?\") (setq dquotes (not dquotes)))
389 ((eq (aref qstr match) ?\')
390 (cond
391 ;; Treat single quote as text if inside double quotes.
392 (dquotes (funcall push "'" (match-end 0)))
393 ((< (1+ match) (length qstr))
394 (let ((end (string-match "'" qstr (1+ match))))
395 (unless end
396 (setq end (length qstr))
397 (set-match-data (list match (length qstr))))
398 (funcall push (substring qstr (1+ match) end) end)))
399 ;; Ignore if at the end of string.
400 (t nil)))
401 (t (error "Unexpected case in shell--unquote&requote-argument!")))
402 (setq qpos (match-end 0)))
403 (funcall push (substring qstr qpos) (length qstr))
404 (list (mapconcat #'identity (nreverse ustrs) "")
405 qupos #'comint-quote-filename)))
407 (defun shell--unquote-argument (str)
408 (car (shell--unquote&requote-argument str)))
409 (defun shell--requote-argument (upos qstr)
410 ;; See `completion-table-with-quoting'.
411 (let ((res (shell--unquote&requote-argument qstr upos)))
412 (cons (nth 1 res) (nth 2 res))))
414 (defun shell--parse-pcomplete-arguments ()
415 "Parse whitespace separated arguments in the current region."
416 ;; FIXME: share code with shell--unquote&requote-argument.
417 (let ((begin (save-excursion (shell-backward-command 1) (point)))
418 (end (point))
419 begins args)
420 (save-excursion
421 (goto-char begin)
422 (while (< (point) end)
423 (skip-chars-forward " \t\n")
424 (push (point) begins)
425 (let ((arg ()))
426 (while (looking-at
427 (eval-when-compile
428 (concat
429 "\\(?:[^\s\t\n\\\"']+"
430 "\\|'\\([^']*\\)'?"
431 "\\|\"\\(\\(?:[^\"\\]\\|\\\\.\\)*\\)\"?"
432 "\\|\\\\\\(\\(?:.\\|\n\\)?\\)\\)")))
433 (goto-char (match-end 0))
434 (cond
435 ((match-beginning 3) ;Backslash escape.
436 (push (cond
437 ((null comint-file-name-quote-list)
438 (goto-char (match-beginning 3)) "\\")
439 ((= (match-beginning 3) (match-end 3)) "\\")
440 (t (match-string 3)))
441 arg))
442 ((match-beginning 2) ;Double quote.
443 (push (if (null comint-file-name-quote-list) (match-string 2)
444 (replace-regexp-in-string
445 "\\\\\\(.\\)" "\\1" (match-string 2)))
446 arg))
447 ((match-beginning 1) ;Single quote.
448 (push (match-string 1) arg))
449 (t (push (match-string 0) arg))))
450 (push (mapconcat #'identity (nreverse arg) "") args)))
451 (cons (nreverse args) (nreverse begins)))))
453 (defun shell-command-completion-function ()
454 "Completion function for shell command names.
455 This is the value of `pcomplete-command-completion-function' for
456 Shell buffers. It implements `shell-completion-execonly' for
457 `pcomplete' completion."
458 (pcomplete-here (pcomplete-entries nil
459 (if shell-completion-execonly
460 'file-executable-p))))
462 (defun shell-completion-vars ()
463 "Setup completion vars for `shell-mode' and `read-shell-command'."
464 (set (make-local-variable 'comint-completion-fignore)
465 shell-completion-fignore)
466 (set (make-local-variable 'comint-delimiter-argument-list)
467 shell-delimiter-argument-list)
468 (set (make-local-variable 'comint-file-name-chars) shell-file-name-chars)
469 (set (make-local-variable 'comint-file-name-quote-list)
470 shell-file-name-quote-list)
471 (set (make-local-variable 'comint-file-name-prefix)
472 (file-remote-p default-directory))
473 (set (make-local-variable 'comint-dynamic-complete-functions)
474 shell-dynamic-complete-functions)
475 (setq-local comint-unquote-function #'shell--unquote-argument)
476 (setq-local comint-requote-function #'shell--requote-argument)
477 (set (make-local-variable 'pcomplete-parse-arguments-function)
478 #'shell--parse-pcomplete-arguments)
479 (set (make-local-variable 'pcomplete-termination-string)
480 (cond ((not comint-completion-addsuffix) "")
481 ((stringp comint-completion-addsuffix)
482 comint-completion-addsuffix)
483 ((not (consp comint-completion-addsuffix)) " ")
484 (t (cdr comint-completion-addsuffix))))
485 (set (make-local-variable 'pcomplete-command-completion-function)
486 #'shell-command-completion-function)
487 ;; Don't use pcomplete's defaulting mechanism, rely on
488 ;; shell-dynamic-complete-functions instead.
489 (set (make-local-variable 'pcomplete-default-completion-function) #'ignore)
490 (setq comint-input-autoexpand shell-input-autoexpand)
491 ;; Not needed in shell-mode because it's inherited from comint-mode, but
492 ;; placed here for read-shell-command.
493 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t))
495 (put 'shell-mode 'mode-class 'special)
497 (define-derived-mode shell-mode comint-mode "Shell"
498 "Major mode for interacting with an inferior shell.\\<shell-mode-map>
499 \\[comint-send-input] after the end of the process' output sends the text from
500 the end of process to the end of the current line.
501 \\[comint-send-input] before end of process output copies the current line minus the prompt to
502 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
503 \\[send-invisible] reads a line of text without echoing it, and sends it to
504 the shell. This is useful for entering passwords. Or, add the function
505 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
507 If you want to make multiple shell buffers, rename the `*shell*' buffer
508 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
510 If you want to make shell buffers limited in length, add the function
511 `comint-truncate-buffer' to `comint-output-filter-functions'.
513 If you accidentally suspend your process, use \\[comint-continue-subjob]
514 to continue it.
516 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
517 keep this buffer's default directory the same as the shell's working directory.
518 While directory tracking is enabled, the shell's working directory is displayed
519 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
520 \\[dirs] queries the shell and resyncs Emacs's idea of what the current
521 directory stack is.
522 \\[shell-dirtrack-mode] turns directory tracking on and off.
523 \(The `dirtrack' package provides an alternative implementation of this
524 feature - see the function `dirtrack-mode'.)
526 \\{shell-mode-map}
527 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
528 `shell-mode-hook' (in that order). Before each input, the hooks on
529 `comint-input-filter-functions' are run. After each shell output, the hooks
530 on `comint-output-filter-functions' are run.
532 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
533 and `shell-popd-regexp' are used to match their respective commands,
534 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
535 control the behavior of the relevant command.
537 Variables `comint-completion-autolist', `comint-completion-addsuffix',
538 `comint-completion-recexact' and `comint-completion-fignore' control the
539 behavior of file name, command name and variable name completion. Variable
540 `shell-completion-execonly' controls the behavior of command name completion.
541 Variable `shell-completion-fignore' is used to initialize the value of
542 `comint-completion-fignore'.
544 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
545 the initialization of the input ring history, and history expansion.
547 Variables `comint-output-filter-functions', a hook, and
548 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
549 control whether input and output cause the window to scroll to the end of the
550 buffer."
551 (setq comint-prompt-regexp shell-prompt-pattern)
552 (shell-completion-vars)
553 (setq-local paragraph-separate "\\'")
554 (setq-local paragraph-start comint-prompt-regexp)
555 (setq-local font-lock-defaults '(shell-font-lock-keywords t))
556 (setq-local shell-dirstack nil)
557 (setq-local shell-last-dir nil)
558 ;; People expect Shell mode to keep the last line of output at
559 ;; window bottom.
560 (setq-local scroll-conservatively 101)
561 (shell-dirtrack-mode 1)
563 ;; By default, ansi-color applies faces using overlays. This is
564 ;; very inefficient in Shell buffers (e.g. Bug#10835). We use a
565 ;; custom `ansi-color-apply-face-function' to convert color escape
566 ;; sequences into `font-lock-face' properties.
567 (setq-local ansi-color-apply-face-function #'shell-apply-ansi-color)
568 (shell-reapply-ansi-color)
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 (if (get-buffer-process (current-buffer))
576 (file-name-nondirectory
577 (car (process-command (get-buffer-process (current-buffer)))))
578 ""))
579 (hsize (getenv "HISTSIZE")))
580 (and (stringp hsize)
581 (integerp (setq hsize (string-to-number hsize)))
582 (> hsize 0)
583 (set (make-local-variable 'comint-input-ring-size) hsize))
584 (setq comint-input-ring-file-name
585 (or (getenv "HISTFILE")
586 (cond ((string-equal shell "bash") "~/.bash_history")
587 ((string-equal shell "ksh") "~/.sh_history")
588 (t "~/.history"))))
589 (if (or (equal comint-input-ring-file-name "")
590 (equal (file-truename comint-input-ring-file-name)
591 (file-truename "/dev/null")))
592 (setq comint-input-ring-file-name nil))
593 ;; Arrange to write out the input ring on exit, if the shell doesn't
594 ;; do this itself.
595 (if (and comint-input-ring-file-name
596 (string-match shell-dumb-shell-regexp shell))
597 (set-process-sentinel (get-buffer-process (current-buffer))
598 #'shell-write-history-on-exit))
599 (setq shell-dirstack-query
600 (cond ((string-equal shell "sh") "pwd")
601 ((string-equal shell "ksh") "echo $PWD ~-")
602 ;; Bypass any aliases. TODO all shells could use this.
603 ((string-equal shell "bash") "command dirs")
604 ((string-equal shell "zsh") "dirs -l")
605 (t "dirs")))
606 ;; Bypass a bug in certain versions of bash.
607 (when (string-equal shell "bash")
608 (add-hook 'comint-preoutput-filter-functions
609 'shell-filter-ctrl-a-ctrl-b nil t)))
610 (comint-read-input-ring t)))
612 (defun shell-apply-ansi-color (beg end face)
613 "Apply FACE as the ansi-color face for the text between BEG and END."
614 (when face
615 (put-text-property beg end 'ansi-color-face face)
616 (put-text-property beg end 'font-lock-face face)))
618 (defun shell-reapply-ansi-color ()
619 "Reapply ansi-color faces to the existing contents of the buffer."
620 (save-restriction
621 (widen)
622 (let* ((pos (point-min))
623 (end (or (next-single-property-change pos 'ansi-color-face)
624 (point-max)))
625 face)
626 (while end
627 (if (setq face (get-text-property pos 'ansi-color-face))
628 (put-text-property pos (or end (point-max))
629 'font-lock-face face))
630 (setq pos end
631 end (next-single-property-change pos 'ansi-color-face))))))
633 (defun shell-filter-ctrl-a-ctrl-b (string)
634 "Remove `^A' and `^B' characters from comint output.
636 Bash uses these characters as internal quoting characters in its
637 prompt. Due to a bug in some bash versions (including 2.03,
638 2.04, and 2.05b), they may erroneously show up when bash is
639 started with the `--noediting' option and Select Graphic
640 Rendition (SGR) control sequences (formerly known as ANSI escape
641 sequences) are used to color the prompt.
643 This function can be put on `comint-preoutput-filter-functions'."
644 (if (string-match "[\C-a\C-b]" string)
645 (replace-regexp-in-string "[\C-a\C-b]" "" string t t)
646 string))
648 (defun shell-write-history-on-exit (process event)
649 "Called when the shell process is stopped.
651 Writes the input history to a history file
652 `comint-input-ring-file-name' using `comint-write-input-ring'
653 and inserts a short message in the shell buffer.
655 This function is a sentinel watching the shell interpreter process.
656 Sentinels will always get the two parameters PROCESS and EVENT."
657 ;; Write history.
658 (comint-write-input-ring)
659 (let ((buf (process-buffer process)))
660 (when (buffer-live-p buf)
661 (with-current-buffer buf
662 (insert (format "\nProcess %s %s\n" process event))))))
664 ;;;###autoload
665 (defun shell (&optional buffer)
666 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
667 Interactively, a prefix arg means to prompt for BUFFER.
668 If `default-directory' is a remote file name, it is also prompted
669 to change if called with a prefix arg.
671 If BUFFER exists but shell process is not running, make new shell.
672 If BUFFER exists and shell process is running, just switch to BUFFER.
673 Program used comes from variable `explicit-shell-file-name',
674 or (if that is nil) from the ESHELL environment variable,
675 or (if that is nil) from `shell-file-name'.
676 If a file `~/.emacs_SHELLNAME' exists, or `~/.emacs.d/init_SHELLNAME.sh',
677 it is given as initial input (but this may be lost, due to a timing
678 error, if the shell discards input when it starts up).
679 The buffer is put in Shell mode, giving commands for sending input
680 and controlling the subjobs of the shell. See `shell-mode'.
681 See also the variable `shell-prompt-pattern'.
683 To specify a coding system for converting non-ASCII characters
684 in the input and output to the shell, use \\[universal-coding-system-argument]
685 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
686 in the shell buffer, after you start the shell.
687 The default comes from `process-coding-system-alist' and
688 `default-process-coding-system'.
690 The shell file name (sans directories) is used to make a symbol name
691 such as `explicit-csh-args'. If that symbol is a variable,
692 its value is used as a list of arguments when invoking the shell.
693 Otherwise, one argument `-i' is passed to the shell.
695 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
696 (interactive
697 (list
698 (and current-prefix-arg
699 (prog1
700 (read-buffer "Shell buffer: "
701 ;; If the current buffer is an inactive
702 ;; shell buffer, use it as the default.
703 (if (and (eq major-mode 'shell-mode)
704 (null (get-buffer-process (current-buffer))))
705 (buffer-name)
706 (generate-new-buffer-name "*shell*")))
707 (if (file-remote-p default-directory)
708 ;; It must be possible to declare a local default-directory.
709 ;; FIXME: This can't be right: it changes the default-directory
710 ;; of the current-buffer rather than of the *shell* buffer.
711 (setq default-directory
712 (expand-file-name
713 (read-directory-name
714 "Default directory: " default-directory default-directory
715 t nil))))))))
716 (setq buffer (if (or buffer (not (derived-mode-p 'shell-mode))
717 (comint-check-proc (current-buffer)))
718 (get-buffer-create (or buffer "*shell*"))
719 ;; If the current buffer is a dead shell buffer, use it.
720 (current-buffer)))
722 (with-current-buffer buffer
723 (when (file-remote-p default-directory)
724 ;; Apply connection-local variables.
725 (hack-connection-local-variables-apply
726 `(:application tramp
727 :protocol ,(file-remote-p default-directory 'method)
728 :user ,(file-remote-p default-directory 'user)
729 :machine ,(file-remote-p default-directory 'host)))
731 ;; On remote hosts, the local `shell-file-name' might be useless.
732 (if (and (called-interactively-p 'any)
733 (null explicit-shell-file-name)
734 (null (getenv "ESHELL")))
735 (set (make-local-variable 'explicit-shell-file-name)
736 (file-local-name
737 (expand-file-name
738 (read-file-name
739 "Remote shell path: " default-directory shell-file-name
740 t shell-file-name)))))))
742 ;; The buffer's window must be correctly set when we call comint
743 ;; (so that comint sets the COLUMNS env var properly).
744 (pop-to-buffer buffer)
745 ;; Rain or shine, BUFFER must be current by now.
746 (unless (comint-check-proc buffer)
747 (let* ((prog (or explicit-shell-file-name
748 (getenv "ESHELL") shell-file-name))
749 (name (file-name-nondirectory prog))
750 (startfile (concat "~/.emacs_" name))
751 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
752 (unless (file-exists-p startfile)
753 (setq startfile (concat user-emacs-directory "init_" name ".sh")))
754 (apply 'make-comint-in-buffer "shell" buffer prog
755 (if (file-exists-p startfile) startfile)
756 (if (and xargs-name (boundp xargs-name))
757 (symbol-value xargs-name)
758 '("-i")))
759 (shell-mode)))
760 buffer)
762 ;;; Directory tracking
764 ;; This code provides the shell mode input sentinel
765 ;; SHELL-DIRECTORY-TRACKER
766 ;; that tracks cd, pushd, and popd commands issued to the shell, and
767 ;; changes the current directory of the shell buffer accordingly.
769 ;; This is basically a fragile hack, although it's more accurate than
770 ;; the version in Emacs 18's shell.el. It has the following failings:
771 ;; 1. It doesn't know about the cdpath shell variable.
772 ;; 2. It cannot infallibly deal with command sequences, though it does well
773 ;; with these and with ignoring commands forked in another shell with ()s.
774 ;; 3. More generally, any complex command is going to throw it. Otherwise,
775 ;; you'd have to build an entire shell interpreter in Emacs Lisp. Failing
776 ;; that, there's no way to catch shell commands where cd's are buried
777 ;; inside conditional expressions, aliases, and so forth.
779 ;; The whole approach is a crock. Shell aliases mess it up. File sourcing
780 ;; messes it up. You run other processes under the shell; these each have
781 ;; separate working directories, and some have commands for manipulating
782 ;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
783 ;; commands that do *not* affect the current w.d. at all, but look like they
784 ;; do (e.g., the cd command in ftp). In shells that allow you job
785 ;; control, you can switch between jobs, all having different w.d.'s. So
786 ;; simply saying %3 can shift your w.d..
788 ;; The solution is to relax, not stress out about it, and settle for
789 ;; a hack that works pretty well in typical circumstances. Remember
790 ;; that a half-assed solution is more in keeping with the spirit of Unix,
791 ;; anyway. Blech.
793 ;; One good hack not implemented here for users of programmable shells
794 ;; is to program up the shell w.d. manipulation commands to output
795 ;; a coded command sequence to the tty. Something like
796 ;; ESC | <cwd> |
797 ;; where <cwd> is the new current working directory. Then trash the
798 ;; directory tracking machinery currently used in this package, and
799 ;; replace it with a process filter that watches for and strips out
800 ;; these messages.
802 (defun shell-directory-tracker (str)
803 "Tracks cd, pushd and popd commands issued to the shell.
804 This function is called on each input passed to the shell.
805 It watches for cd, pushd and popd commands and sets the buffer's
806 default directory to track these commands.
808 You may toggle this tracking on and off with \\[shell-dirtrack-mode].
809 If Emacs gets confused, you can resync with the shell with \\[dirs].
810 \(The `dirtrack' package provides an alternative implementation of this
811 feature - see the function `dirtrack-mode'.)
813 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
814 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
815 and `shell-pushd-dunique' control the behavior of the relevant command.
817 Environment variables are expanded, see function `substitute-in-file-name'."
818 (if shell-dirtrackp
819 ;; We fail gracefully if we think the command will fail in the shell.
820 ;;; (with-demoted-errors "Directory tracker failure: %s"
821 ;; This fails so often that it seems better to just ignore errors (?).
822 ;; Eg even: foo=/tmp; cd $foo is beyond us (bug#17159).
823 (ignore-errors
824 (let ((start (progn (string-match
825 (concat "^" shell-command-separator-regexp)
826 str) ; skip whitespace
827 (match-end 0)))
828 (case-fold-search)
829 end cmd arg1)
830 (while (string-match shell-command-regexp str start)
831 (setq end (match-end 0)
832 cmd (comint-arguments (substring str start end) 0 0)
833 arg1 (comint-arguments (substring str start end) 1 1))
834 (if arg1
835 (setq arg1 (shell-unquote-argument arg1)))
836 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
837 "\\)\\($\\|[ \t]\\)")
838 cmd)
839 (shell-process-popd (comint-substitute-in-file-name arg1)))
840 ((string-match (concat "\\`\\(" shell-pushd-regexp
841 "\\)\\($\\|[ \t]\\)")
842 cmd)
843 (shell-process-pushd (comint-substitute-in-file-name arg1)))
844 ((string-match (concat "\\`\\(" shell-cd-regexp
845 "\\)\\($\\|[ \t]\\)")
846 cmd)
847 (shell-process-cd (comint-substitute-in-file-name arg1)))
848 ((and shell-chdrive-regexp
849 (string-match (concat "\\`\\(" shell-chdrive-regexp
850 "\\)\\($\\|[ \t]\\)")
851 cmd))
852 (shell-process-cd (comint-substitute-in-file-name cmd))))
853 (setq start (progn (string-match shell-command-separator-regexp
854 str end)
855 ;; skip again
856 (match-end 0))))))))
858 (defun shell-unquote-argument (string)
859 "Remove all kinds of shell quoting from STRING."
860 (save-match-data
861 (let ((idx 0) next inside
862 (quote-chars
863 (if (string-match shell-dumb-shell-regexp
864 (file-name-nondirectory
865 (car (process-command (get-buffer-process (current-buffer))))))
866 "['`\"]"
867 "[\\'`\"]")))
868 (while (and (< idx (length string))
869 (setq next (string-match quote-chars string next)))
870 (cond ((= (aref string next) ?\\)
871 (setq string (replace-match "" nil nil string))
872 (setq next (1+ next)))
873 ((and inside (= (aref string next) inside))
874 (setq string (replace-match "" nil nil string))
875 (setq inside nil))
876 (inside
877 (setq next (1+ next)))
879 (setq inside (aref string next))
880 (setq string (replace-match "" nil nil string)))))
881 string)))
883 ;; popd [+n]
884 (defun shell-process-popd (arg)
885 (let ((num (or (shell-extract-num arg) 0)))
886 (cond ((and num (= num 0) shell-dirstack)
887 (shell-cd (shell-prefixed-directory-name (car shell-dirstack)))
888 (setq shell-dirstack (cdr shell-dirstack))
889 (shell-dirstack-message))
890 ((and num (> num 0) (<= num (length shell-dirstack)))
891 (let* ((ds (cons nil shell-dirstack))
892 (cell (nthcdr (1- num) ds)))
893 (rplacd cell (cdr (cdr cell)))
894 (setq shell-dirstack (cdr ds))
895 (shell-dirstack-message)))
897 (error "Couldn't popd")))))
899 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
900 (defun shell-prefixed-directory-name (dir)
901 (if (= (length comint-file-name-prefix) 0)
903 (if (file-name-absolute-p dir)
904 ;; The name is absolute, so prepend the prefix.
905 (concat comint-file-name-prefix dir)
906 ;; For relative name we assume default-directory already has the prefix.
907 (expand-file-name dir))))
909 ;; cd [dir]
910 (defun shell-process-cd (arg)
911 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
912 "~"))
913 ((string-equal "-" arg) shell-last-dir)
914 (t (shell-prefixed-directory-name arg)))))
915 (setq shell-last-dir default-directory)
916 (shell-cd new-dir)
917 (shell-dirstack-message)))
919 ;; pushd [+n | dir]
920 (defun shell-process-pushd (arg)
921 (let ((num (shell-extract-num arg)))
922 (cond ((zerop (length arg))
923 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
924 (cond (shell-pushd-tohome
925 (shell-process-pushd (concat comint-file-name-prefix "~")))
926 (shell-dirstack
927 (let ((old default-directory))
928 (shell-cd (car shell-dirstack))
929 (setq shell-dirstack (cons old (cdr shell-dirstack)))
930 (shell-dirstack-message)))
932 (message "Directory stack empty."))))
933 ((numberp num)
934 ;; pushd +n
935 (cond ((> num (length shell-dirstack))
936 (message "Directory stack not that deep."))
937 ((= num 0)
938 (error "Couldn't cd"))
939 (shell-pushd-dextract
940 (let ((dir (nth (1- num) shell-dirstack)))
941 (shell-process-popd arg)
942 (shell-process-pushd default-directory)
943 (shell-cd dir)
944 (shell-dirstack-message)))
946 (let* ((ds (cons default-directory shell-dirstack))
947 (dslen (length ds))
948 (front (nthcdr num ds))
949 (back (reverse (nthcdr (- dslen num) (reverse ds))))
950 (new-ds (append front back)))
951 (shell-cd (car new-ds))
952 (setq shell-dirstack (cdr new-ds))
953 (shell-dirstack-message)))))
955 ;; pushd <dir>
956 (let ((old-wd default-directory))
957 (shell-cd (shell-prefixed-directory-name arg))
958 (if (or (null shell-pushd-dunique)
959 (not (member old-wd shell-dirstack)))
960 (setq shell-dirstack (cons old-wd shell-dirstack)))
961 (shell-dirstack-message))))))
963 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
964 (defun shell-extract-num (str)
965 (and (string-match "^\\+[1-9][0-9]*$" str)
966 (string-to-number str)))
968 (define-minor-mode shell-dirtrack-mode
969 "Toggle directory tracking in this shell buffer (Shell Dirtrack mode).
970 With a prefix argument ARG, enable Shell Dirtrack mode if ARG is
971 positive, and disable it otherwise. If called from Lisp, enable
972 the mode if ARG is omitted or nil.
974 The `dirtrack' package provides an alternative implementation of
975 this feature; see the function `dirtrack-mode'."
976 nil nil nil
977 (setq list-buffers-directory (if shell-dirtrack-mode default-directory))
978 (if shell-dirtrack-mode
979 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
980 (remove-hook 'comint-input-filter-functions 'shell-directory-tracker t)))
982 (define-obsolete-function-alias 'shell-dirtrack-toggle 'shell-dirtrack-mode
983 "23.1")
985 (defun shell-cd (dir)
986 "Do normal `cd' to DIR, and set `list-buffers-directory'."
987 (cd dir)
988 (if shell-dirtrackp
989 (setq list-buffers-directory default-directory)))
991 (defun shell-resync-dirs ()
992 "Resync the buffer's idea of the current directory stack.
993 This command queries the shell with the command bound to
994 `shell-dirstack-query' (default \"dirs\"), reads the next
995 line output and parses it to form the new directory stack.
996 DON'T issue this command unless the buffer is at a shell prompt.
997 Also, note that if some other subprocess decides to do output
998 immediately after the query, its output will be taken as the
999 new directory stack -- you lose. If this happens, just do the
1000 command again."
1001 (interactive)
1002 (let* ((proc (get-buffer-process (current-buffer)))
1003 (pmark (process-mark proc))
1004 (started-at-pmark (= (point) (marker-position pmark))))
1005 (save-excursion
1006 (goto-char pmark)
1007 ;; If the process echoes commands, don't insert a fake command in
1008 ;; the buffer or it will appear twice.
1009 (unless comint-process-echoes
1010 (insert shell-dirstack-query) (insert "\n"))
1011 (sit-for 0) ; force redisplay
1012 (comint-send-string proc shell-dirstack-query)
1013 (comint-send-string proc "\n")
1014 (set-marker pmark (point))
1015 (let ((pt (point))
1016 (regexp
1017 (concat
1018 (if comint-process-echoes
1019 ;; Skip command echo if the process echoes
1020 (concat "\\(" (regexp-quote shell-dirstack-query) "\n\\)")
1021 "\\(\\)")
1022 "\\(.+\n\\)")))
1023 ;; This extra newline prevents the user's pending input from spoofing us.
1024 (insert "\n") (backward-char 1)
1025 ;; Wait for one line.
1026 (while (not (looking-at regexp))
1027 (accept-process-output proc)
1028 (goto-char pt)))
1029 (goto-char pmark) (delete-char 1) ; remove the extra newline
1030 ;; That's the dirlist. grab it & parse it.
1031 (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
1032 (dl-len (length dl))
1033 (ds '()) ; new dir stack
1034 (i 0))
1035 (while (< i dl-len)
1036 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
1037 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
1038 (setq ds (cons (concat comint-file-name-prefix
1039 (substring dl (match-beginning 1)
1040 (match-end 1)))
1041 ds))
1042 (setq i (match-end 0)))
1043 (let ((ds (nreverse ds)))
1044 (with-demoted-errors "Couldn't cd: %s"
1045 (shell-cd (car ds))
1046 (setq shell-dirstack (cdr ds)
1047 shell-last-dir (car shell-dirstack))
1048 (shell-dirstack-message)))))
1049 (if started-at-pmark (goto-char (marker-position pmark)))))
1051 ;; For your typing convenience:
1052 (defalias 'dirs 'shell-resync-dirs)
1055 ;; Show the current dirstack on the message line.
1056 ;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
1057 ;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
1058 ;; All the commands that mung the buffer's dirstack finish by calling
1059 ;; this guy.
1060 (defun shell-dirstack-message ()
1061 (when shell-dirtrack-verbose
1062 (let* ((msg "")
1063 (ds (cons default-directory shell-dirstack))
1064 (home (expand-file-name (concat comint-file-name-prefix "~/")))
1065 (homelen (length home)))
1066 (while ds
1067 (let ((dir (car ds)))
1068 (and (>= (length dir) homelen)
1069 (string= home (substring dir 0 homelen))
1070 (setq dir (concat "~/" (substring dir homelen))))
1071 ;; Strip off comint-file-name-prefix if present.
1072 (and comint-file-name-prefix
1073 (>= (length dir) (length comint-file-name-prefix))
1074 (string= comint-file-name-prefix
1075 (substring dir 0 (length comint-file-name-prefix)))
1076 (setq dir (substring dir (length comint-file-name-prefix)))
1077 (setcar ds dir))
1078 (setq msg (concat msg (directory-file-name dir) " "))
1079 (setq ds (cdr ds))))
1080 (message "%s" msg))))
1082 ;; This was mostly copied from shell-resync-dirs.
1083 (defun shell-snarf-envar (var)
1084 "Return as a string the shell's value of environment variable VAR."
1085 (let* ((cmd (format "printenv '%s'\n" var))
1086 (proc (get-buffer-process (current-buffer)))
1087 (pmark (process-mark proc)))
1088 (goto-char pmark)
1089 (insert cmd)
1090 (sit-for 0) ; force redisplay
1091 (comint-send-string proc cmd)
1092 (set-marker pmark (point))
1093 (let ((pt (point))) ; wait for 1 line
1094 ;; This extra newline prevents the user's pending input from spoofing us.
1095 (insert "\n") (backward-char 1)
1096 (while (not (looking-at ".+\n"))
1097 (accept-process-output proc)
1098 (goto-char pt)))
1099 (goto-char pmark) (delete-char 1) ; remove the extra newline
1100 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
1102 (defun shell-copy-environment-variable (variable)
1103 "Copy the environment variable VARIABLE from the subshell to Emacs.
1104 This command reads the value of the specified environment variable
1105 in the shell, and sets the same environment variable in Emacs
1106 \(what `getenv' in Emacs would return) to that value.
1107 That value will affect any new subprocesses that you subsequently start
1108 from Emacs."
1109 (interactive (list (read-envvar-name "\
1110 Copy Shell environment variable to Emacs: ")))
1111 (setenv variable (shell-snarf-envar variable)))
1113 (defun shell-forward-command (&optional arg)
1114 "Move forward across ARG shell command(s). Does not cross lines.
1115 See `shell-command-regexp'."
1116 (interactive "p")
1117 (let ((limit (line-end-position))
1118 (pt (point)))
1119 (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
1120 limit 'move arg)
1121 (and (/= pt (point))
1122 (skip-syntax-backward " " pt))))
1125 (defun shell-backward-command (&optional arg)
1126 "Move backward across ARG shell command(s). Does not cross lines.
1127 See `shell-command-regexp'."
1128 (interactive "p")
1129 (let ((limit (save-excursion (comint-bol nil) (point))))
1130 (when (> limit (point))
1131 (setq limit (line-beginning-position)))
1132 (skip-syntax-backward " " limit)
1133 (let ((pt (point)))
1134 (if (re-search-backward
1135 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
1136 (progn (goto-char (match-beginning 1))
1137 (skip-chars-forward ";&|")))
1138 (and (/= pt (point))
1139 (skip-syntax-forward " " pt)))))
1141 (defun shell-dynamic-complete-command ()
1142 "Dynamically complete the command at point.
1143 This function is similar to `comint-dynamic-complete-filename', except that it
1144 searches `exec-path' (minus trailing `exec-directory') for completion
1145 candidates. Note that this may not be the same as the shell's idea of the
1146 path.
1148 Completion is dependent on the value of `shell-completion-execonly',
1149 `shell-completion-fignore', plus those that affect file completion. See Info
1150 node `Shell Options'.
1152 Returns t if successful."
1153 (interactive)
1154 (let ((data (shell-command-completion)))
1155 (if data
1156 (prog2 (unless (window-minibuffer-p)
1157 (message "Completing command name..."))
1158 (apply #'completion-in-region data)))))
1160 (defun shell-command-completion ()
1161 "Return the completion data for the command at point, if any."
1162 (let ((filename (comint-match-partial-filename)))
1163 (if (and filename
1164 (save-match-data (not (string-match "[~/]" filename)))
1165 (eq (match-beginning 0)
1166 (save-excursion (shell-backward-command 1) (point))))
1167 (shell--command-completion-data))))
1169 (defun shell--command-completion-data ()
1170 "Return the completion data for the command at point."
1171 (let* ((filename (or (comint-match-partial-filename) ""))
1172 (start (if (zerop (length filename)) (point) (match-beginning 0)))
1173 (end (if (zerop (length filename)) (point) (match-end 0)))
1174 (filenondir (file-name-nondirectory filename))
1175 (path-dirs
1176 ;; Ignore `exec-directory', the last entry in `exec-path'.
1177 (append (cdr (reverse (exec-path)))
1178 (if (and (memq system-type '(windows-nt ms-dos))
1179 (not (file-remote-p default-directory)))
1180 '("."))))
1181 (cwd (file-name-as-directory (expand-file-name default-directory)))
1182 (ignored-extensions
1183 (and comint-completion-fignore
1184 (mapconcat (function (lambda (x) (concat (regexp-quote x) "\\'")))
1185 comint-completion-fignore "\\|")))
1186 (dir "") (comps-in-dir ())
1187 (file "") (abs-file-name "") (completions ()))
1188 ;; Go thru each dir in the search path, finding completions.
1189 (while path-dirs
1190 (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
1191 comps-in-dir (and (file-accessible-directory-p dir)
1192 (file-name-all-completions filenondir dir)))
1193 ;; Go thru each completion found, to see whether it should be used.
1194 (while comps-in-dir
1195 (setq file (car comps-in-dir)
1196 abs-file-name (concat dir file))
1197 (if (and (not (member file completions))
1198 (not (and ignored-extensions
1199 (string-match ignored-extensions file)))
1200 (or (string-equal dir cwd)
1201 (not (file-directory-p abs-file-name)))
1202 (or (null shell-completion-execonly)
1203 (file-executable-p abs-file-name)))
1204 (setq completions (cons file completions)))
1205 (setq comps-in-dir (cdr comps-in-dir)))
1206 (setq path-dirs (cdr path-dirs)))
1207 ;; OK, we've got a list of completions.
1208 (list
1209 start end
1210 (lambda (string pred action)
1211 (if (string-match "/" string)
1212 (completion-file-name-table string pred action)
1213 (complete-with-action action completions string pred)))
1214 :exit-function
1215 (lambda (_string finished)
1216 (when (memq finished '(sole finished))
1217 (if (looking-at " ")
1218 (goto-char (match-end 0))
1219 (insert " ")))))))
1221 ;; (defun shell-dynamic-complete-as-command ()
1222 ;; "Dynamically complete at point as a command.
1223 ;; See `shell-dynamic-complete-filename'. Returns t if successful."
1224 ;; (apply #'completion-in-region shell--command-completion-data))
1226 (defun shell-dynamic-complete-filename ()
1227 "Dynamically complete the filename at point.
1228 This completes only if point is at a suitable position for a
1229 filename argument."
1230 (interactive)
1231 (let ((data (shell-filename-completion)))
1232 (if data (apply #'completion-in-region data))))
1234 (defun shell-filename-completion ()
1235 "Return the completion data for file name at point, if any."
1236 (let ((opoint (point))
1237 (beg (comint-line-beginning-position)))
1238 (when (save-excursion
1239 (goto-char (if (re-search-backward "[;|&]" beg t)
1240 (match-end 0)
1241 beg))
1242 (re-search-forward "[^ \t][ \t]" opoint t))
1243 (comint-filename-completion))))
1245 (defun shell-match-partial-variable ()
1246 "Return the shell variable at point, or nil if none is found."
1247 (save-excursion
1248 (if (re-search-backward "[^A-Za-z0-9_{(]" nil 'move)
1249 (or (looking-at "\\$") (forward-char 1)))
1250 (if (or (eolp) (looking-at "[^A-Za-z0-9_{($]"))
1252 (looking-at "\\$?[{(]?[A-Za-z0-9_]*[})]?")
1253 (buffer-substring (match-beginning 0) (match-end 0)))))
1255 (defun shell-dynamic-complete-environment-variable ()
1256 "Dynamically complete the environment variable at point.
1257 Completes if after a variable, i.e., if it starts with a \"$\".
1259 This function is similar to `comint-dynamic-complete-filename', except that it
1260 searches `process-environment' for completion candidates. Note that this may
1261 not be the same as the interpreter's idea of variable names. The main problem
1262 with this type of completion is that `process-environment' is the environment
1263 which Emacs started with. Emacs does not track changes to the environment made
1264 by the interpreter. Perhaps it would be more accurate if this function was
1265 called `shell-dynamic-complete-process-environment-variable'.
1267 Returns non-nil if successful."
1268 (interactive)
1269 (let ((data (shell-environment-variable-completion)))
1270 (if data
1271 (prog2 (unless (window-minibuffer-p)
1272 (message "Completing variable name..."))
1273 (apply #'completion-in-region data)))))
1276 (defun shell-environment-variable-completion ()
1277 "Completion data for an environment variable at point, if any."
1278 (let* ((var (shell-match-partial-variable))
1279 (end (match-end 0)))
1280 (when (and (not (zerop (length var))) (eq (aref var 0) ?$))
1281 (let* ((start
1282 (save-excursion
1283 (goto-char (match-beginning 0))
1284 (looking-at "\\$?[({]*")
1285 (match-end 0)))
1286 (variables (mapcar (lambda (x)
1287 (substring x 0 (string-match "=" x)))
1288 process-environment))
1289 (suffix (pcase (char-before start) (?\{ "}") (?\( ")") (_ ""))))
1290 (list start end variables
1291 :exit-function
1292 (lambda (s finished)
1293 (when (memq finished '(sole finished))
1294 (let ((suf (concat suffix
1295 (if (file-directory-p
1296 (comint-directory (getenv s)))
1297 "/"))))
1298 (if (looking-at (regexp-quote suf))
1299 (goto-char (match-end 0))
1300 (insert suf))))))))))
1303 (defun shell-c-a-p-replace-by-expanded-directory ()
1304 "Expand directory stack reference before point.
1305 For use on `completion-at-point-functions'."
1306 (when (comint-match-partial-filename)
1307 (save-excursion
1308 (goto-char (match-beginning 0))
1309 (let ((stack (cons default-directory shell-dirstack))
1310 (index (cond ((looking-at "=-/?")
1311 (length shell-dirstack))
1312 ((looking-at "=\\([0-9]+\\)/?")
1313 (string-to-number
1314 (buffer-substring
1315 (match-beginning 1) (match-end 1)))))))
1316 (when index
1317 (let ((start (match-beginning 0))
1318 (end (match-end 0))
1319 (replacement (file-name-as-directory (nth index stack))))
1320 (lambda ()
1321 (cond
1322 ((>= index (length stack))
1323 (error "Directory stack not that deep"))
1325 (save-excursion
1326 (goto-char start)
1327 (insert replacement)
1328 (delete-char (- end start)))
1329 (message "Directory item: %d" index)
1330 t)))))))))
1332 (defun shell-replace-by-expanded-directory ()
1333 "Expand directory stack reference before point.
1334 Directory stack references are of the form \"=digit\" or \"=-\".
1335 See `default-directory' and `shell-dirstack'.
1337 Returns t if successful."
1338 (interactive)
1339 (let ((f (shell-c-a-p-replace-by-expanded-directory)))
1340 (if f (funcall f))))
1342 (provide 'shell)
1344 ;;; shell.el ends here