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