* lisp/progmodes/sh-script.el (sh-syntax-propertize-function): Fix last
[emacs.git] / lisp / shell.el
blob1784188f6adb19c03bdc2f96e6c7f35d9c72eb83
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 (if (null pcomplete-arg-quote-list) (match-string 2)
404 (replace-regexp-in-string
405 "\\\\\\(.\\)" "\\1" (match-string 2)))
406 arg))
407 ((match-beginning 1) ;Single quote.
408 (push (match-string 1) arg))
409 (t (push (match-string 0) arg))))
410 (push (mapconcat #'identity (nreverse arg) "") args)))
411 (cons (nreverse args) (nreverse begins)))))
413 (defun shell-command-completion-function ()
414 "Completion function for shell command names.
415 This is the value of `pcomplete-command-completion-function' for
416 Shell buffers. It implements `shell-completion-execonly' for
417 `pcomplete' completion."
418 (pcomplete-here (pcomplete-entries nil
419 (if shell-completion-execonly
420 'file-executable-p))))
422 (defun shell-completion-vars ()
423 "Setup completion vars for `shell-mode' and `read-shell-command'."
424 (set (make-local-variable 'comint-completion-fignore)
425 shell-completion-fignore)
426 (set (make-local-variable 'comint-delimiter-argument-list)
427 shell-delimiter-argument-list)
428 (set (make-local-variable 'comint-file-name-chars) shell-file-name-chars)
429 (set (make-local-variable 'comint-file-name-quote-list)
430 shell-file-name-quote-list)
431 (set (make-local-variable 'comint-dynamic-complete-functions)
432 shell-dynamic-complete-functions)
433 (set (make-local-variable 'pcomplete-parse-arguments-function)
434 #'shell-parse-pcomplete-arguments)
435 (set (make-local-variable 'pcomplete-arg-quote-list)
436 comint-file-name-quote-list)
437 (set (make-local-variable 'pcomplete-termination-string)
438 (cond ((not comint-completion-addsuffix) "")
439 ((stringp comint-completion-addsuffix)
440 comint-completion-addsuffix)
441 ((not (consp comint-completion-addsuffix)) " ")
442 (t (cdr comint-completion-addsuffix))))
443 (set (make-local-variable 'pcomplete-command-completion-function)
444 #'shell-command-completion-function)
445 ;; Don't use pcomplete's defaulting mechanism, rely on
446 ;; shell-dynamic-complete-functions instead.
447 (set (make-local-variable 'pcomplete-default-completion-function) #'ignore)
448 (setq comint-input-autoexpand shell-input-autoexpand)
449 ;; Not needed in shell-mode because it's inherited from comint-mode, but
450 ;; placed here for read-shell-command.
451 (add-hook 'completion-at-point-functions 'comint-completion-at-point nil t))
453 (put 'shell-mode 'mode-class 'special)
455 (define-derived-mode shell-mode comint-mode "Shell"
456 "Major mode for interacting with an inferior shell.\\<shell-mode-map>
457 \\[comint-send-input] after the end of the process' output sends the text from
458 the end of process to the end of the current line.
459 \\[comint-send-input] before end of process output copies the current line minus the prompt to
460 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
461 \\[send-invisible] reads a line of text without echoing it, and sends it to
462 the shell. This is useful for entering passwords. Or, add the function
463 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
465 If you want to make multiple shell buffers, rename the `*shell*' buffer
466 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
468 If you want to make shell buffers limited in length, add the function
469 `comint-truncate-buffer' to `comint-output-filter-functions'.
471 If you accidentally suspend your process, use \\[comint-continue-subjob]
472 to continue it.
474 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
475 keep this buffer's default directory the same as the shell's working directory.
476 While directory tracking is enabled, the shell's working directory is displayed
477 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
478 \\[dirs] queries the shell and resyncs Emacs's idea of what the current
479 directory stack is.
480 \\[shell-dirtrack-mode] turns directory tracking on and off.
481 \(The `dirtrack' package provides an alternative implementation of this
482 feature - see the function `dirtrack-mode'.)
484 \\{shell-mode-map}
485 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
486 `shell-mode-hook' (in that order). Before each input, the hooks on
487 `comint-input-filter-functions' are run. After each shell output, the hooks
488 on `comint-output-filter-functions' are run.
490 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
491 and `shell-popd-regexp' are used to match their respective commands,
492 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
493 control the behavior of the relevant command.
495 Variables `comint-completion-autolist', `comint-completion-addsuffix',
496 `comint-completion-recexact' and `comint-completion-fignore' control the
497 behavior of file name, command name and variable name completion. Variable
498 `shell-completion-execonly' controls the behavior of command name completion.
499 Variable `shell-completion-fignore' is used to initialize the value of
500 `comint-completion-fignore'.
502 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
503 the initialization of the input ring history, and history expansion.
505 Variables `comint-output-filter-functions', a hook, and
506 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
507 control whether input and output cause the window to scroll to the end of the
508 buffer."
509 (setq comint-prompt-regexp shell-prompt-pattern)
510 (shell-completion-vars)
511 (set (make-local-variable 'paragraph-separate) "\\'")
512 (set (make-local-variable 'paragraph-start) comint-prompt-regexp)
513 (set (make-local-variable 'font-lock-defaults) '(shell-font-lock-keywords t))
514 (set (make-local-variable 'shell-dirstack) nil)
515 (set (make-local-variable 'shell-last-dir) nil)
516 (shell-dirtrack-mode 1)
518 ;; By default, ansi-color applies faces using overlays. This is
519 ;; very inefficient in Shell buffers (e.g. Bug#10835). We use a
520 ;; custom `ansi-color-apply-face-function' to convert color escape
521 ;; sequences into `font-lock-face' properties.
522 (set (make-local-variable 'ansi-color-apply-face-function)
523 (lambda (beg end face)
524 (when face
525 (put-text-property beg end 'font-lock-face face))))
527 ;; This is not really correct, since the shell buffer does not really
528 ;; edit this directory. But it is useful in the buffer list and menus.
529 (setq list-buffers-directory (expand-file-name default-directory))
530 ;; shell-dependent assignments.
531 (when (ring-empty-p comint-input-ring)
532 (let ((shell (file-name-nondirectory (car
533 (process-command (get-buffer-process (current-buffer))))))
534 (hsize (getenv "HISTSIZE")))
535 (and (stringp hsize)
536 (integerp (setq hsize (string-to-number hsize)))
537 (> hsize 0)
538 (set (make-local-variable 'comint-input-ring-size) hsize))
539 (setq comint-input-ring-file-name
540 (or (getenv "HISTFILE")
541 (cond ((string-equal shell "bash") "~/.bash_history")
542 ((string-equal shell "ksh") "~/.sh_history")
543 (t "~/.history"))))
544 (if (or (equal comint-input-ring-file-name "")
545 (equal (file-truename comint-input-ring-file-name)
546 (file-truename "/dev/null")))
547 (setq comint-input-ring-file-name nil))
548 ;; Arrange to write out the input ring on exit, if the shell doesn't
549 ;; do this itself.
550 (if (and comint-input-ring-file-name
551 (string-match shell-dumb-shell-regexp shell))
552 (set-process-sentinel (get-buffer-process (current-buffer))
553 #'shell-write-history-on-exit))
554 (setq shell-dirstack-query
555 (cond ((string-equal shell "sh") "pwd")
556 ((string-equal shell "ksh") "echo $PWD ~-")
557 (t "dirs")))
558 ;; Bypass a bug in certain versions of bash.
559 (when (string-equal shell "bash")
560 (add-hook 'comint-preoutput-filter-functions
561 'shell-filter-ctrl-a-ctrl-b nil t)))
562 (comint-read-input-ring t)))
564 (defun shell-filter-ctrl-a-ctrl-b (string)
565 "Remove `^A' and `^B' characters from comint output.
567 Bash uses these characters as internal quoting characters in its
568 prompt. Due to a bug in some bash versions (including 2.03,
569 2.04, and 2.05b), they may erroneously show up when bash is
570 started with the `--noediting' option and Select Graphic
571 Rendition (SGR) control sequences (formerly known as ANSI escape
572 sequences) are used to color the prompt.
574 This function can be put on `comint-preoutput-filter-functions'."
575 (if (string-match "[\C-a\C-b]" string)
576 (replace-regexp-in-string "[\C-a\C-b]" "" string t t)
577 string))
579 (defun shell-write-history-on-exit (process event)
580 "Called when the shell process is stopped.
582 Writes the input history to a history file
583 `comint-input-ring-file-name' using `comint-write-input-ring'
584 and inserts a short message in the shell buffer.
586 This function is a sentinel watching the shell interpreter process.
587 Sentinels will always get the two parameters PROCESS and EVENT."
588 ;; Write history.
589 (comint-write-input-ring)
590 (let ((buf (process-buffer process)))
591 (when (buffer-live-p buf)
592 (with-current-buffer buf
593 (insert (format "\nProcess %s %s\n" process event))))))
595 ;;;###autoload
596 (defun shell (&optional buffer)
597 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
598 Interactively, a prefix arg means to prompt for BUFFER.
599 If `default-directory' is a remote file name, it is also prompted
600 to change if called with a prefix arg.
602 If BUFFER exists but shell process is not running, make new shell.
603 If BUFFER exists and shell process is running, just switch to BUFFER.
604 Program used comes from variable `explicit-shell-file-name',
605 or (if that is nil) from the ESHELL environment variable,
606 or (if that is nil) from `shell-file-name'.
607 If a file `~/.emacs_SHELLNAME' exists, or `~/.emacs.d/init_SHELLNAME.sh',
608 it is given as initial input (but this may be lost, due to a timing
609 error, if the shell discards input when it starts up).
610 The buffer is put in Shell mode, giving commands for sending input
611 and controlling the subjobs of the shell. See `shell-mode'.
612 See also the variable `shell-prompt-pattern'.
614 To specify a coding system for converting non-ASCII characters
615 in the input and output to the shell, use \\[universal-coding-system-argument]
616 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
617 in the shell buffer, after you start the shell.
618 The default comes from `process-coding-system-alist' and
619 `default-process-coding-system'.
621 The shell file name (sans directories) is used to make a symbol name
622 such as `explicit-csh-args'. If that symbol is a variable,
623 its value is used as a list of arguments when invoking the shell.
624 Otherwise, one argument `-i' is passed to the shell.
626 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
627 (interactive
628 (list
629 (and current-prefix-arg
630 (prog1
631 (read-buffer "Shell buffer: "
632 (generate-new-buffer-name "*shell*"))
633 (if (file-remote-p default-directory)
634 ;; It must be possible to declare a local default-directory.
635 ;; FIXME: This can't be right: it changes the default-directory
636 ;; of the current-buffer rather than of the *shell* buffer.
637 (setq default-directory
638 (expand-file-name
639 (read-directory-name
640 "Default directory: " default-directory default-directory
641 t nil))))))))
642 (setq buffer (if (or buffer (not (derived-mode-p 'shell-mode))
643 (comint-check-proc (current-buffer)))
644 (get-buffer-create (or buffer "*shell*"))
645 ;; If the current buffer is a dead shell buffer, use it.
646 (current-buffer)))
648 ;; On remote hosts, the local `shell-file-name' might be useless.
649 (if (and (called-interactively-p 'any)
650 (file-remote-p default-directory)
651 (null explicit-shell-file-name)
652 (null (getenv "ESHELL")))
653 (with-current-buffer buffer
654 (set (make-local-variable 'explicit-shell-file-name)
655 (file-remote-p
656 (expand-file-name
657 (read-file-name
658 "Remote shell path: " default-directory shell-file-name
659 t shell-file-name))
660 'localname))))
662 ;; The buffer's window must be correctly set when we call comint (so
663 ;; that comint sets the COLUMNS env var properly).
664 (pop-to-buffer-same-window buffer)
665 (unless (comint-check-proc buffer)
666 (let* ((prog (or explicit-shell-file-name
667 (getenv "ESHELL") shell-file-name))
668 (name (file-name-nondirectory prog))
669 (startfile (concat "~/.emacs_" name))
670 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
671 (unless (file-exists-p startfile)
672 (setq startfile (concat user-emacs-directory "init_" name ".sh")))
673 (apply 'make-comint-in-buffer "shell" buffer prog
674 (if (file-exists-p startfile) startfile)
675 (if (and xargs-name (boundp xargs-name))
676 (symbol-value xargs-name)
677 '("-i")))
678 (shell-mode)))
679 buffer)
681 ;;; Directory tracking
683 ;; This code provides the shell mode input sentinel
684 ;; SHELL-DIRECTORY-TRACKER
685 ;; that tracks cd, pushd, and popd commands issued to the shell, and
686 ;; changes the current directory of the shell buffer accordingly.
688 ;; This is basically a fragile hack, although it's more accurate than
689 ;; the version in Emacs 18's shell.el. It has the following failings:
690 ;; 1. It doesn't know about the cdpath shell variable.
691 ;; 2. It cannot infallibly deal with command sequences, though it does well
692 ;; with these and with ignoring commands forked in another shell with ()s.
693 ;; 3. More generally, any complex command is going to throw it. Otherwise,
694 ;; you'd have to build an entire shell interpreter in Emacs Lisp. Failing
695 ;; that, there's no way to catch shell commands where cd's are buried
696 ;; inside conditional expressions, aliases, and so forth.
698 ;; The whole approach is a crock. Shell aliases mess it up. File sourcing
699 ;; messes it up. You run other processes under the shell; these each have
700 ;; separate working directories, and some have commands for manipulating
701 ;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
702 ;; commands that do *not* affect the current w.d. at all, but look like they
703 ;; do (e.g., the cd command in ftp). In shells that allow you job
704 ;; control, you can switch between jobs, all having different w.d.'s. So
705 ;; simply saying %3 can shift your w.d..
707 ;; The solution is to relax, not stress out about it, and settle for
708 ;; a hack that works pretty well in typical circumstances. Remember
709 ;; that a half-assed solution is more in keeping with the spirit of Unix,
710 ;; anyway. Blech.
712 ;; One good hack not implemented here for users of programmable shells
713 ;; is to program up the shell w.d. manipulation commands to output
714 ;; a coded command sequence to the tty. Something like
715 ;; ESC | <cwd> |
716 ;; where <cwd> is the new current working directory. Then trash the
717 ;; directory tracking machinery currently used in this package, and
718 ;; replace it with a process filter that watches for and strips out
719 ;; these messages.
721 (defun shell-directory-tracker (str)
722 "Tracks cd, pushd and popd commands issued to the shell.
723 This function is called on each input passed to the shell.
724 It watches for cd, pushd and popd commands and sets the buffer's
725 default directory to track these commands.
727 You may toggle this tracking on and off with \\[shell-dirtrack-mode].
728 If Emacs gets confused, you can resync with the shell with \\[dirs].
729 \(The `dirtrack' package provides an alternative implementation of this
730 feature - see the function `dirtrack-mode'.)
732 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
733 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
734 and `shell-pushd-dunique' control the behavior of the relevant command.
736 Environment variables are expanded, see function `substitute-in-file-name'."
737 (if shell-dirtrackp
738 ;; We fail gracefully if we think the command will fail in the shell.
739 (condition-case nil
740 (let ((start (progn (string-match
741 (concat "^" shell-command-separator-regexp)
742 str) ; skip whitespace
743 (match-end 0)))
744 (case-fold-search)
745 end cmd arg1)
746 (while (string-match shell-command-regexp str start)
747 (setq end (match-end 0)
748 cmd (comint-arguments (substring str start end) 0 0)
749 arg1 (comint-arguments (substring str start end) 1 1))
750 (if arg1
751 (setq arg1 (shell-unquote-argument arg1)))
752 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
753 "\\)\\($\\|[ \t]\\)")
754 cmd)
755 (shell-process-popd (comint-substitute-in-file-name arg1)))
756 ((string-match (concat "\\`\\(" shell-pushd-regexp
757 "\\)\\($\\|[ \t]\\)")
758 cmd)
759 (shell-process-pushd (comint-substitute-in-file-name arg1)))
760 ((string-match (concat "\\`\\(" shell-cd-regexp
761 "\\)\\($\\|[ \t]\\)")
762 cmd)
763 (shell-process-cd (comint-substitute-in-file-name arg1)))
764 ((and shell-chdrive-regexp
765 (string-match (concat "\\`\\(" shell-chdrive-regexp
766 "\\)\\($\\|[ \t]\\)")
767 cmd))
768 (shell-process-cd (comint-substitute-in-file-name cmd))))
769 (setq start (progn (string-match shell-command-separator-regexp
770 str end)
771 ;; skip again
772 (match-end 0)))))
773 (error "Couldn't cd"))))
775 (defun shell-unquote-argument (string)
776 "Remove all kinds of shell quoting from STRING."
777 (save-match-data
778 (let ((idx 0) next inside
779 (quote-chars
780 (if (string-match shell-dumb-shell-regexp
781 (file-name-nondirectory
782 (car (process-command (get-buffer-process (current-buffer))))))
783 "['`\"]"
784 "[\\'`\"]")))
785 (while (and (< idx (length string))
786 (setq next (string-match quote-chars string next)))
787 (cond ((= (aref string next) ?\\)
788 (setq string (replace-match "" nil nil string))
789 (setq next (1+ next)))
790 ((and inside (= (aref string next) inside))
791 (setq string (replace-match "" nil nil string))
792 (setq inside nil))
793 (inside
794 (setq next (1+ next)))
796 (setq inside (aref string next))
797 (setq string (replace-match "" nil nil string)))))
798 string)))
800 ;; popd [+n]
801 (defun shell-process-popd (arg)
802 (let ((num (or (shell-extract-num arg) 0)))
803 (cond ((and num (= num 0) shell-dirstack)
804 (shell-cd (shell-prefixed-directory-name (car shell-dirstack)))
805 (setq shell-dirstack (cdr shell-dirstack))
806 (shell-dirstack-message))
807 ((and num (> num 0) (<= num (length shell-dirstack)))
808 (let* ((ds (cons nil shell-dirstack))
809 (cell (nthcdr (1- num) ds)))
810 (rplacd cell (cdr (cdr cell)))
811 (setq shell-dirstack (cdr ds))
812 (shell-dirstack-message)))
814 (error "Couldn't popd")))))
816 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
817 (defun shell-prefixed-directory-name (dir)
818 (if (= (length comint-file-name-prefix) 0)
820 (if (file-name-absolute-p dir)
821 ;; The name is absolute, so prepend the prefix.
822 (concat comint-file-name-prefix dir)
823 ;; For relative name we assume default-directory already has the prefix.
824 (expand-file-name dir))))
826 ;; cd [dir]
827 (defun shell-process-cd (arg)
828 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
829 "~"))
830 ((string-equal "-" arg) shell-last-dir)
831 (t (shell-prefixed-directory-name arg)))))
832 (setq shell-last-dir default-directory)
833 (shell-cd new-dir)
834 (shell-dirstack-message)))
836 ;; pushd [+n | dir]
837 (defun shell-process-pushd (arg)
838 (let ((num (shell-extract-num arg)))
839 (cond ((zerop (length arg))
840 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
841 (cond (shell-pushd-tohome
842 (shell-process-pushd (concat comint-file-name-prefix "~")))
843 (shell-dirstack
844 (let ((old default-directory))
845 (shell-cd (car shell-dirstack))
846 (setq shell-dirstack (cons old (cdr shell-dirstack)))
847 (shell-dirstack-message)))
849 (message "Directory stack empty."))))
850 ((numberp num)
851 ;; pushd +n
852 (cond ((> num (length shell-dirstack))
853 (message "Directory stack not that deep."))
854 ((= num 0)
855 (error (message "Couldn't cd")))
856 (shell-pushd-dextract
857 (let ((dir (nth (1- num) shell-dirstack)))
858 (shell-process-popd arg)
859 (shell-process-pushd default-directory)
860 (shell-cd dir)
861 (shell-dirstack-message)))
863 (let* ((ds (cons default-directory shell-dirstack))
864 (dslen (length ds))
865 (front (nthcdr num ds))
866 (back (reverse (nthcdr (- dslen num) (reverse ds))))
867 (new-ds (append front back)))
868 (shell-cd (car new-ds))
869 (setq shell-dirstack (cdr new-ds))
870 (shell-dirstack-message)))))
872 ;; pushd <dir>
873 (let ((old-wd default-directory))
874 (shell-cd (shell-prefixed-directory-name arg))
875 (if (or (null shell-pushd-dunique)
876 (not (member old-wd shell-dirstack)))
877 (setq shell-dirstack (cons old-wd shell-dirstack)))
878 (shell-dirstack-message))))))
880 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
881 (defun shell-extract-num (str)
882 (and (string-match "^\\+[1-9][0-9]*$" str)
883 (string-to-number str)))
885 (defvaralias 'shell-dirtrack-mode 'shell-dirtrackp)
886 (define-minor-mode shell-dirtrack-mode
887 "Toggle directory tracking in this shell buffer (Shell Dirtrack mode).
888 With a prefix argument ARG, enable Shell Dirtrack mode if ARG is
889 positive, and disable it otherwise. If called from Lisp, enable
890 the mode if ARG is omitted or nil.
892 The `dirtrack' package provides an alternative implementation of
893 this feature; see the function `dirtrack-mode'."
894 nil nil nil
895 (setq list-buffers-directory (if shell-dirtrack-mode default-directory))
896 (if shell-dirtrack-mode
897 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
898 (remove-hook 'comint-input-filter-functions 'shell-directory-tracker t)))
900 (define-obsolete-function-alias 'shell-dirtrack-toggle 'shell-dirtrack-mode
901 "23.1")
903 (defun shell-cd (dir)
904 "Do normal `cd' to DIR, and set `list-buffers-directory'."
905 (cd dir)
906 (if shell-dirtrackp
907 (setq list-buffers-directory default-directory)))
909 (defun shell-resync-dirs ()
910 "Resync the buffer's idea of the current directory stack.
911 This command queries the shell with the command bound to
912 `shell-dirstack-query' (default \"dirs\"), reads the next
913 line output and parses it to form the new directory stack.
914 DON'T issue this command unless the buffer is at a shell prompt.
915 Also, note that if some other subprocess decides to do output
916 immediately after the query, its output will be taken as the
917 new directory stack -- you lose. If this happens, just do the
918 command again."
919 (interactive)
920 (let* ((proc (get-buffer-process (current-buffer)))
921 (pmark (process-mark proc))
922 (started-at-pmark (= (point) (marker-position pmark))))
923 (save-excursion
924 (goto-char pmark)
925 ;; If the process echoes commands, don't insert a fake command in
926 ;; the buffer or it will appear twice.
927 (unless comint-process-echoes
928 (insert shell-dirstack-query) (insert "\n"))
929 (sit-for 0) ; force redisplay
930 (comint-send-string proc shell-dirstack-query)
931 (comint-send-string proc "\n")
932 (set-marker pmark (point))
933 (let ((pt (point))
934 (regexp
935 (concat
936 (if comint-process-echoes
937 ;; Skip command echo if the process echoes
938 (concat "\\(" (regexp-quote shell-dirstack-query) "\n\\)")
939 "\\(\\)")
940 "\\(.+\n\\)")))
941 ;; This extra newline prevents the user's pending input from spoofing us.
942 (insert "\n") (backward-char 1)
943 ;; Wait for one line.
944 (while (not (looking-at regexp))
945 (accept-process-output proc)
946 (goto-char pt)))
947 (goto-char pmark) (delete-char 1) ; remove the extra newline
948 ;; That's the dirlist. grab it & parse it.
949 (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
950 (dl-len (length dl))
951 (ds '()) ; new dir stack
952 (i 0))
953 (while (< i dl-len)
954 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
955 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
956 (setq ds (cons (concat comint-file-name-prefix
957 (substring dl (match-beginning 1)
958 (match-end 1)))
959 ds))
960 (setq i (match-end 0)))
961 (let ((ds (nreverse ds)))
962 (condition-case nil
963 (progn (shell-cd (car ds))
964 (setq shell-dirstack (cdr ds)
965 shell-last-dir (car shell-dirstack))
966 (shell-dirstack-message))
967 (error (message "Couldn't cd"))))))
968 (if started-at-pmark (goto-char (marker-position pmark)))))
970 ;; For your typing convenience:
971 (defalias 'dirs 'shell-resync-dirs)
974 ;; Show the current dirstack on the message line.
975 ;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
976 ;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
977 ;; All the commands that mung the buffer's dirstack finish by calling
978 ;; this guy.
979 (defun shell-dirstack-message ()
980 (when shell-dirtrack-verbose
981 (let* ((msg "")
982 (ds (cons default-directory shell-dirstack))
983 (home (expand-file-name (concat comint-file-name-prefix "~/")))
984 (homelen (length home)))
985 (while ds
986 (let ((dir (car ds)))
987 (and (>= (length dir) homelen)
988 (string= home (substring dir 0 homelen))
989 (setq dir (concat "~/" (substring dir homelen))))
990 ;; Strip off comint-file-name-prefix if present.
991 (and comint-file-name-prefix
992 (>= (length dir) (length comint-file-name-prefix))
993 (string= comint-file-name-prefix
994 (substring dir 0 (length comint-file-name-prefix)))
995 (setq dir (substring dir (length comint-file-name-prefix)))
996 (setcar ds dir))
997 (setq msg (concat msg (directory-file-name dir) " "))
998 (setq ds (cdr ds))))
999 (message "%s" msg))))
1001 ;; This was mostly copied from shell-resync-dirs.
1002 (defun shell-snarf-envar (var)
1003 "Return as a string the shell's value of environment variable VAR."
1004 (let* ((cmd (format "printenv '%s'\n" var))
1005 (proc (get-buffer-process (current-buffer)))
1006 (pmark (process-mark proc)))
1007 (goto-char pmark)
1008 (insert cmd)
1009 (sit-for 0) ; force redisplay
1010 (comint-send-string proc cmd)
1011 (set-marker pmark (point))
1012 (let ((pt (point))) ; wait for 1 line
1013 ;; This extra newline prevents the user's pending input from spoofing us.
1014 (insert "\n") (backward-char 1)
1015 (while (not (looking-at ".+\n"))
1016 (accept-process-output proc)
1017 (goto-char pt)))
1018 (goto-char pmark) (delete-char 1) ; remove the extra newline
1019 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
1021 (defun shell-copy-environment-variable (variable)
1022 "Copy the environment variable VARIABLE from the subshell to Emacs.
1023 This command reads the value of the specified environment variable
1024 in the shell, and sets the same environment variable in Emacs
1025 \(what `getenv' in Emacs would return) to that value.
1026 That value will affect any new subprocesses that you subsequently start
1027 from Emacs."
1028 (interactive (list (read-envvar-name "\
1029 Copy Shell environment variable to Emacs: ")))
1030 (setenv variable (shell-snarf-envar variable)))
1032 (defun shell-forward-command (&optional arg)
1033 "Move forward across ARG shell command(s). Does not cross lines.
1034 See `shell-command-regexp'."
1035 (interactive "p")
1036 (let ((limit (line-end-position)))
1037 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
1038 limit 'move arg)
1039 (skip-syntax-backward " "))))
1042 (defun shell-backward-command (&optional arg)
1043 "Move backward across ARG shell command(s). Does not cross lines.
1044 See `shell-command-regexp'."
1045 (interactive "p")
1046 (let ((limit (save-excursion (comint-bol nil) (point))))
1047 (when (> limit (point))
1048 (setq limit (line-beginning-position)))
1049 (skip-syntax-backward " " limit)
1050 (if (re-search-backward
1051 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
1052 (progn (goto-char (match-beginning 1))
1053 (skip-chars-forward ";&|")))))
1055 (defun shell-dynamic-complete-command ()
1056 "Dynamically complete the command at point.
1057 This function is similar to `comint-dynamic-complete-filename', except that it
1058 searches `exec-path' (minus the trailing Emacs library path) for completion
1059 candidates. Note that this may not be the same as the shell's idea of the
1060 path.
1062 Completion is dependent on the value of `shell-completion-execonly', plus
1063 those that effect file completion.
1065 Returns t if successful."
1066 (interactive)
1067 (let ((data (shell-command-completion)))
1068 (if data
1069 (prog2 (unless (window-minibuffer-p (selected-window))
1070 (message "Completing command name..."))
1071 (apply #'completion-in-region data)))))
1073 (defun shell-command-completion ()
1074 "Return the completion data for the command at point, if any."
1075 (let ((filename (comint-match-partial-filename)))
1076 (if (and filename
1077 (save-match-data (not (string-match "[~/]" filename)))
1078 (eq (match-beginning 0)
1079 (save-excursion (shell-backward-command 1) (point))))
1080 (shell--command-completion-data))))
1082 (defun shell--command-completion-data ()
1083 "Return the completion data for the command at point."
1084 (let* ((filename (or (comint-match-partial-filename) ""))
1085 (start (if (zerop (length filename)) (point) (match-beginning 0)))
1086 (end (if (zerop (length filename)) (point) (match-end 0)))
1087 (filenondir (file-name-nondirectory filename))
1088 (path-dirs (cdr (reverse exec-path))) ;FIXME: Why `cdr'?
1089 (cwd (file-name-as-directory (expand-file-name default-directory)))
1090 (ignored-extensions
1091 (and comint-completion-fignore
1092 (mapconcat (function (lambda (x) (concat (regexp-quote x) "\\'")))
1093 comint-completion-fignore "\\|")))
1094 (dir "") (comps-in-dir ())
1095 (file "") (abs-file-name "") (completions ()))
1096 ;; Go thru each dir in the search path, finding completions.
1097 (while path-dirs
1098 (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
1099 comps-in-dir (and (file-accessible-directory-p dir)
1100 (file-name-all-completions filenondir dir)))
1101 ;; Go thru each completion found, to see whether it should be used.
1102 (while comps-in-dir
1103 (setq file (car comps-in-dir)
1104 abs-file-name (concat dir file))
1105 (if (and (not (member file completions))
1106 (not (and ignored-extensions
1107 (string-match ignored-extensions file)))
1108 (or (string-equal dir cwd)
1109 (not (file-directory-p abs-file-name)))
1110 (or (null shell-completion-execonly)
1111 (file-executable-p abs-file-name)))
1112 (setq completions (cons file completions)))
1113 (setq comps-in-dir (cdr comps-in-dir)))
1114 (setq path-dirs (cdr path-dirs)))
1115 ;; OK, we've got a list of completions.
1116 (list
1117 start end
1118 (lambda (string pred action)
1119 (if (string-match "/" string)
1120 (completion-file-name-table string pred action)
1121 (complete-with-action action completions string pred)))
1122 :exit-function
1123 (lambda (_string finished)
1124 (when (memq finished '(sole finished))
1125 (if (looking-at " ")
1126 (goto-char (match-end 0))
1127 (insert " ")))))))
1129 ;; (defun shell-dynamic-complete-as-command ()
1130 ;; "Dynamically complete at point as a command.
1131 ;; See `shell-dynamic-complete-filename'. Returns t if successful."
1132 ;; (apply #'completion-in-region shell--command-completion-data))
1134 (defun shell-dynamic-complete-filename ()
1135 "Dynamically complete the filename at point.
1136 This completes only if point is at a suitable position for a
1137 filename argument."
1138 (interactive)
1139 (let ((data (shell-filename-completion)))
1140 (if data (apply #'completion-in-region data))))
1142 (defun shell-filename-completion ()
1143 "Return the completion data for file name at point, if any."
1144 (let ((opoint (point))
1145 (beg (comint-line-beginning-position)))
1146 (when (save-excursion
1147 (goto-char (if (re-search-backward "[;|&]" beg t)
1148 (match-end 0)
1149 beg))
1150 (re-search-forward "[^ \t][ \t]" opoint t))
1151 (comint-filename-completion))))
1153 (defun shell-match-partial-variable ()
1154 "Return the shell variable at point, or nil if none is found."
1155 (save-excursion
1156 (if (re-search-backward "[^A-Za-z0-9_{(]" nil 'move)
1157 (or (looking-at "\\$") (forward-char 1)))
1158 (if (or (eolp) (looking-at "[^A-Za-z0-9_{($]"))
1160 (looking-at "\\$?[{(]?[A-Za-z0-9_]*[})]?")
1161 (buffer-substring (match-beginning 0) (match-end 0)))))
1163 (defun shell-dynamic-complete-environment-variable ()
1164 "Dynamically complete the environment variable at point.
1165 Completes if after a variable, i.e., if it starts with a \"$\".
1167 This function is similar to `comint-dynamic-complete-filename', except that it
1168 searches `process-environment' for completion candidates. Note that this may
1169 not be the same as the interpreter's idea of variable names. The main problem
1170 with this type of completion is that `process-environment' is the environment
1171 which Emacs started with. Emacs does not track changes to the environment made
1172 by the interpreter. Perhaps it would be more accurate if this function was
1173 called `shell-dynamic-complete-process-environment-variable'.
1175 Returns non-nil if successful."
1176 (interactive)
1177 (let ((data (shell-environment-variable-completion)))
1178 (if data
1179 (prog2 (unless (window-minibuffer-p (selected-window))
1180 (message "Completing variable name..."))
1181 (apply #'completion-in-region data)))))
1184 (defun shell-environment-variable-completion ()
1185 "Completion data for an environment variable at point, if any."
1186 (let* ((var (shell-match-partial-variable))
1187 (end (match-end 0)))
1188 (when (and (not (zerop (length var))) (eq (aref var 0) ?$))
1189 (let* ((start
1190 (save-excursion
1191 (goto-char (match-beginning 0))
1192 (looking-at "\\$?[({]*")
1193 (match-end 0)))
1194 (variables (mapcar (lambda (x)
1195 (substring x 0 (string-match "=" x)))
1196 process-environment))
1197 (suffix (case (char-before start) (?\{ "}") (?\( ")") (t ""))))
1198 (list start end variables
1199 :exit-function
1200 (lambda (s finished)
1201 (when (memq finished '(sole finished))
1202 (let ((suf (concat suffix
1203 (if (file-directory-p
1204 (comint-directory (getenv s)))
1205 "/"))))
1206 (if (looking-at (regexp-quote suf))
1207 (goto-char (match-end 0))
1208 (insert suf))))))))))
1211 (defun shell-c-a-p-replace-by-expanded-directory ()
1212 "Expand directory stack reference before point.
1213 For use on `completion-at-point-functions'."
1214 (when (comint-match-partial-filename)
1215 (save-excursion
1216 (goto-char (match-beginning 0))
1217 (let ((stack (cons default-directory shell-dirstack))
1218 (index (cond ((looking-at "=-/?")
1219 (length shell-dirstack))
1220 ((looking-at "=\\([0-9]+\\)/?")
1221 (string-to-number
1222 (buffer-substring
1223 (match-beginning 1) (match-end 1)))))))
1224 (when index
1225 (let ((start (match-beginning 0))
1226 (end (match-end 0))
1227 (replacement (file-name-as-directory (nth index stack))))
1228 (lambda ()
1229 (cond
1230 ((>= index (length stack))
1231 (error "Directory stack not that deep"))
1233 (save-excursion
1234 (goto-char start)
1235 (insert replacement)
1236 (delete-char (- end start)))
1237 (message "Directory item: %d" index)
1238 t)))))))))
1240 (defun shell-replace-by-expanded-directory ()
1241 "Expand directory stack reference before point.
1242 Directory stack references are of the form \"=digit\" or \"=-\".
1243 See `default-directory' and `shell-dirstack'.
1245 Returns t if successful."
1246 (interactive)
1247 (let ((f (shell-c-a-p-replace-by-expanded-directory)))
1248 (if f (funcall f))))
1250 (provide 'shell)
1252 ;;; shell.el ends here