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