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