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