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