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