1 ;;; shell.el --- specialized comint.el for running the shell
3 ;; Copyright (C) 1988, 1993, 1994, 1995, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
6 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
7 ;; Simon Marshall <simon@gnu.org>
8 ;; Maintainer: FSF <emacs-devel@gnu.org>
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This file defines a shell-in-a-buffer package (shell mode) built on
29 ;; top of comint mode. This is actually cmushell with things renamed
30 ;; to replace its counterpart in Emacs 18. cmushell is more
31 ;; featureful, robust, and uniform than the Emacs 18 version.
33 ;; Since this mode is built on top of the general command-interpreter-in-
34 ;; a-buffer mode (comint mode), it shares a common base functionality,
35 ;; and a common set of bindings, with all modes derived from comint mode.
36 ;; This makes these modes easier to use.
38 ;; For documentation on the functionality provided by comint mode, and
39 ;; the hooks available for customising it, see the file comint.el.
40 ;; For further information on shell mode, see the comments below.
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?
49 ;;=============================================================================
50 ;; Some suggestions for your .emacs file.
52 ;; ;; Define M-# to run some strange command:
53 ;; (eval-after-load "shell"
54 ;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
56 ;; Brief Command Documentation:
57 ;;============================================================================
58 ;; Comint Mode Commands: (common to shell and all comint-derived modes)
60 ;; m-p comint-previous-input Cycle backwards in input history
61 ;; m-n comint-next-input Cycle forwards
62 ;; m-r comint-previous-matching-input Previous input matching a regexp
63 ;; m-s comint-next-matching-input Next input that matches
64 ;; m-c-l comint-show-output Show last batch of process output
65 ;; return comint-send-input
66 ;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
67 ;; c-c c-a comint-bol Beginning of line; skip prompt
68 ;; c-c c-u comint-kill-input ^u
69 ;; c-c c-w backward-kill-word ^w
70 ;; c-c c-c comint-interrupt-subjob ^c
71 ;; c-c c-z comint-stop-subjob ^z
72 ;; c-c c-\ comint-quit-subjob ^\
73 ;; c-c c-o comint-delete-output Delete last batch of process output
74 ;; c-c c-r comint-show-output Show last batch of process output
75 ;; c-c c-l comint-dynamic-list-input-ring List input history
76 ;; send-invisible Read line w/o echo & send to proc
77 ;; comint-continue-subjob Useful if you accidentally suspend
79 ;; comint-mode-hook is the comint mode hook.
81 ;; Shell Mode Commands:
82 ;; shell Fires up the shell process
83 ;; tab comint-dynamic-complete 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
92 ;; The shell mode hook is shell-mode-hook
93 ;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
96 ;; Read the rest of this file for more information.
102 ;;; Customization and Buffer Variables
105 "Running shell from within Emacs buffers."
109 (defgroup shell-directories nil
110 "Directory support in shell mode."
113 (defgroup shell-faces nil
114 "Faces in shell buffers."
118 (defcustom shell-dumb-shell-regexp (purecopy "cmd\\(proxy\\)?\\.exe")
119 "Regexp to match shells that don't save their command history, and
120 don't handle the backslash as a quote character. For shells that
121 match this regexp, Emacs will write out the command history when the
122 shell finishes, and won't remove backslashes when it unquotes shell
127 (defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
128 "Regexp to match prompts in the inferior shell.
129 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
130 This variable is used to initialize `comint-prompt-regexp' in the
133 If `comint-use-prompt-regexp' is nil, then this variable is only used
134 to determine paragraph boundaries. See Info node `Shell Prompts' for
135 how Shell mode treats paragraphs.
137 The pattern should probably not match more than one line. If it does,
138 Shell mode may become confused trying to distinguish prompt from input
139 on lines which don't start with a prompt.
141 This is a fine thing to set in your `.emacs' file."
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 (\"~\" \"#\" \"%\").
151 This is a fine thing to set in your `.emacs' file."
152 :type '(repeat (string :tag "Suffix"))
155 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
156 "List of characters to recognize as separate arguments.
157 This variable is used to initialize `comint-delimiter-argument-list' in the
158 shell buffer. The value may depend on the operating system or shell.
160 This is a fine thing to set in your `.emacs' file.")
162 (defvar shell-file-name-chars
163 (if (memq system-type '(ms-dos windows-nt cygwin))
164 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
165 "[]~/A-Za-z0-9+@:_.$#%,={}-")
166 "String of characters valid in a file name.
167 This variable is used to initialize `comint-file-name-chars' in the
168 shell buffer. The value may depend on the operating system or shell.
170 This is a fine thing to set in your `.emacs' file.")
172 (defvar shell-file-name-quote-list
173 (if (memq system-type '(ms-dos windows-nt))
175 (append shell-delimiter-argument-list '(?\s ?$ ?\* ?\! ?\" ?\' ?\` ?\# ?\\)))
176 "List of characters to quote when in a file name.
177 This variable is used to initialize `comint-file-name-quote-list' in the
178 shell buffer. The value may depend on the operating system or shell.
180 This is a fine thing to set in your `.emacs' file.")
182 (defvar shell-dynamic-complete-functions
183 '(comint-replace-by-expanded-history
184 shell-dynamic-complete-environment-variable
185 shell-dynamic-complete-command
186 shell-replace-by-expanded-directory
187 shell-dynamic-complete-filename
188 comint-dynamic-complete-filename)
189 "List of functions called to perform completion.
190 This variable is used to initialize `comint-dynamic-complete-functions' in the
193 This is a fine thing to set in your `.emacs' file.")
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."
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."
207 (defcustom shell-completion-execonly t
208 "If non-nil, use executable files only for completion candidates.
209 This mirrors the optional behavior of tcsh.
211 Detecting executability of files may slow command completion considerably."
215 (defcustom shell-popd-regexp "popd"
216 "Regexp to match subshell commands equivalent to popd."
218 :group 'shell-directories)
220 (defcustom shell-pushd-regexp "pushd"
221 "Regexp to match subshell commands equivalent to pushd."
223 :group 'shell-directories)
225 (defcustom shell-pushd-tohome nil
226 "If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
227 This mirrors the optional behavior of tcsh."
229 :group 'shell-directories)
231 (defcustom shell-pushd-dextract nil
232 "If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
233 This mirrors the optional behavior of tcsh."
235 :group 'shell-directories)
237 (defcustom shell-pushd-dunique nil
238 "If non-nil, make pushd only add unique directories to the stack.
239 This mirrors the optional behavior of tcsh."
241 :group 'shell-directories)
243 (defcustom shell-cd-regexp "cd"
244 "Regexp to match subshell commands equivalent to cd."
246 :group 'shell-directories)
248 (defcustom shell-chdrive-regexp
249 (if (memq system-type '(ms-dos windows-nt))
250 ; NetWare allows the five chars between upper and lower alphabetics.
251 "[]a-zA-Z^_`\\[\\\\]:"
253 "If non-nil, is regexp used to track drive changes."
254 :type '(choice regexp
256 :group 'shell-directories)
258 (defcustom shell-dirtrack-verbose t
259 "If non-nil, show the directory stack following directory change.
260 This is effective only if directory tracking is enabled.
261 The `dirtrack' package provides an alternative implementation of this feature -
262 see the function `dirtrack-mode'."
264 :group 'shell-directories)
266 (defcustom explicit-shell-file-name nil
267 "If non-nil, is file name to use for explicitly requested inferior shell."
268 :type '(choice (const :tag "None" nil) file)
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.
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"))
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 grook --noediting. Bash 1.x has -nolineediting, but
292 ;; process-send-eof cannot terminate bash if we use it.
293 (if (and (not purify-flag)
295 (file-executable-p prog)
296 (string-match "bad option"
297 (shell-command-to-string
298 (concat (shell-quote-argument prog)
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"))
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).
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'.
316 This variable supplies a default for `comint-input-autoexpand',
317 for Shell mode only."
318 :type '(choice (const :tag "off" nil)
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.")
328 (defvar shell-dirtrackp t
329 "Non-nil in a shell buffer means directory tracking is enabled.")
331 (defvar shell-last-dir nil
332 "Keep track of last directory for ksh `cd -' command.")
334 (defvar shell-dirstack-query nil
335 "Command used by `shell-resync-dirs' to query the shell.")
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" 'comint-dynamic-complete)
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]
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)
351 (define-key-after (lookup-key map [menu-bar completion])
352 [expand-directory] '("Expand Directory Reference" .
353 shell-replace-by-expanded-directory)
357 (defcustom shell-mode-hook '()
358 "Hook for customizing Shell mode."
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.")
370 (defcustom shell-dir-cookie-re nil
371 "Regexp matching your prompt, including some part of the current directory.
372 If your prompt includes the current directory or the last few elements of it,
373 set this to a pattern that matches your prompt and whose subgroup 1 matches
374 the directory part of it.
375 This is used by `shell-dir-cookie-watcher' to try and use this info
376 to track your current directory. It can be used instead of or in addition
379 :type '(choice (const nil) regexp))
381 (put 'shell-mode 'mode-class 'special)
383 (define-derived-mode shell-mode comint-mode "Shell"
384 "Major mode for interacting with an inferior shell.\\<shell-mode-map>
385 \\[comint-send-input] after the end of the process' output sends the text from
386 the end of process to the end of the current line.
387 \\[comint-send-input] before end of process output copies the current line minus the prompt to
388 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
389 \\[send-invisible] reads a line of text without echoing it, and sends it to
390 the shell. This is useful for entering passwords. Or, add the function
391 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
393 If you want to make multiple shell buffers, rename the `*shell*' buffer
394 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
396 If you want to make shell buffers limited in length, add the function
397 `comint-truncate-buffer' to `comint-output-filter-functions'.
399 If you accidentally suspend your process, use \\[comint-continue-subjob]
402 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
403 keep this buffer's default directory the same as the shell's working directory.
404 While directory tracking is enabled, the shell's working directory is displayed
405 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
406 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
408 \\[shell-dirtrack-mode] turns directory tracking on and off.
409 \(The `dirtrack' package provides an alternative implementation of this
410 feature - see the function `dirtrack-mode'.)
413 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
414 `shell-mode-hook' (in that order). Before each input, the hooks on
415 `comint-input-filter-functions' are run. After each shell output, the hooks
416 on `comint-output-filter-functions' are run.
418 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
419 and `shell-popd-regexp' are used to match their respective commands,
420 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
421 control the behavior of the relevant command.
423 Variables `comint-completion-autolist', `comint-completion-addsuffix',
424 `comint-completion-recexact' and `comint-completion-fignore' control the
425 behavior of file name, command name and variable name completion. Variable
426 `shell-completion-execonly' controls the behavior of command name completion.
427 Variable `shell-completion-fignore' is used to initialize the value of
428 `comint-completion-fignore'.
430 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
431 the initialization of the input ring history, and history expansion.
433 Variables `comint-output-filter-functions', a hook, and
434 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
435 control whether input and output cause the window to scroll to the end of the
437 (setq comint-prompt-regexp shell-prompt-pattern)
438 (setq comint-completion-fignore shell-completion-fignore)
439 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
440 (setq comint-file-name-chars shell-file-name-chars)
441 (setq comint-file-name-quote-list shell-file-name-quote-list)
442 (set (make-local-variable 'comint-dynamic-complete-functions)
443 shell-dynamic-complete-functions)
444 (set (make-local-variable 'paragraph-separate) "\\'")
445 (make-local-variable 'paragraph-start)
446 (setq paragraph-start comint-prompt-regexp)
447 (make-local-variable 'font-lock-defaults)
448 (setq font-lock-defaults '(shell-font-lock-keywords t))
449 (make-local-variable 'shell-dirstack)
450 (setq shell-dirstack nil)
451 (make-local-variable 'shell-last-dir)
452 (setq shell-last-dir nil)
453 (setq comint-input-autoexpand shell-input-autoexpand)
454 (shell-dirtrack-mode 1)
455 ;; This is not really correct, since the shell buffer does not really
456 ;; edit this directory. But it is useful in the buffer list and menus.
457 (setq list-buffers-directory (expand-file-name default-directory))
458 ;; shell-dependent assignments.
459 (when (ring-empty-p comint-input-ring)
460 (let ((shell (file-name-nondirectory (car
461 (process-command (get-buffer-process (current-buffer)))))))
462 (setq comint-input-ring-file-name
463 (or (getenv "HISTFILE")
464 (cond ((string-equal shell "bash") "~/.bash_history")
465 ((string-equal shell "ksh") "~/.sh_history")
467 (if (or (equal comint-input-ring-file-name "")
468 (equal (file-truename comint-input-ring-file-name)
469 (file-truename "/dev/null")))
470 (setq comint-input-ring-file-name nil))
471 ;; Arrange to write out the input ring on exit, if the shell doesn't
473 (if (and comint-input-ring-file-name
474 (string-match shell-dumb-shell-regexp shell))
475 (set-process-sentinel (get-buffer-process (current-buffer))
476 #'shell-write-history-on-exit))
477 (setq shell-dirstack-query
478 (cond ((string-equal shell "sh") "pwd")
479 ((string-equal shell "ksh") "echo $PWD ~-")
481 ;; Bypass a bug in certain versions of bash.
482 (when (string-equal shell "bash")
483 (add-hook 'comint-output-filter-functions
484 'shell-filter-ctrl-a-ctrl-b nil t)))
485 (when shell-dir-cookie-re
486 ;; Watch for magic cookies in the output to track the current dir.
487 (add-hook 'comint-output-filter-functions
488 'shell-dir-cookie-watcher nil t))
489 (comint-read-input-ring t)))
491 (defun shell-filter-ctrl-a-ctrl-b (string)
492 "Remove `^A' and `^B' characters from comint output.
494 Bash uses these characters as internal quoting characters in its
495 prompt. Due to a bug in some bash versions (including 2.03,
496 2.04, and 2.05b), they may erroneously show up when bash is
497 started with the `--noediting' option and Select Graphic
498 Rendition (SGR) control sequences (formerly known as ANSI escape
499 sequences) are used to color the prompt.
501 This function can be put on `comint-output-filter-functions'.
502 The argument STRING is ignored."
503 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
505 (goto-char (or (and (markerp comint-last-output-start)
506 (marker-position comint-last-output-start))
508 (while (re-search-forward "[\C-a\C-b]" pmark t)
509 (replace-match "")))))
511 (defun shell-write-history-on-exit (process event)
512 "Called when the shell process is stopped.
514 Writes the input history to a history file
515 `comint-input-ring-file-name' using `comint-write-input-ring'
516 and inserts a short message in the shell buffer.
518 This function is a sentinel watching the shell interpreter process.
519 Sentinels will always get the two parameters PROCESS and EVENT."
521 (comint-write-input-ring)
522 (let ((buf (process-buffer process)))
523 (when (buffer-live-p buf)
524 (with-current-buffer buf
525 (insert (format "\nProcess %s %s\n" process event))))))
528 (defun shell (&optional buffer)
529 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
530 Interactively, a prefix arg means to prompt for BUFFER.
531 If `default-directory' is a remote file name, it is also prompted
532 to change if called with a prefix arg.
534 If BUFFER exists but shell process is not running, make new shell.
535 If BUFFER exists and shell process is running, just switch to BUFFER.
536 Program used comes from variable `explicit-shell-file-name',
537 or (if that is nil) from the ESHELL environment variable,
538 or (if that is nil) from `shell-file-name'.
539 If a file `~/.emacs_SHELLNAME' exists, or `~/.emacs.d/init_SHELLNAME.sh',
540 it is given as initial input (but this may be lost, due to a timing
541 error, if the shell discards input when it starts up).
542 The buffer is put in Shell mode, giving commands for sending input
543 and controlling the subjobs of the shell. See `shell-mode'.
544 See also the variable `shell-prompt-pattern'.
546 To specify a coding system for converting non-ASCII characters
547 in the input and output to the shell, use \\[universal-coding-system-argument]
548 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
549 in the shell buffer, after you start the shell.
550 The default comes from `process-coding-system-alist' and
551 `default-process-coding-system'.
553 The shell file name (sans directories) is used to make a symbol name
554 such as `explicit-csh-args'. If that symbol is a variable,
555 its value is used as a list of arguments when invoking the shell.
556 Otherwise, one argument `-i' is passed to the shell.
558 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
561 (and current-prefix-arg
563 (read-buffer "Shell buffer: "
564 (generate-new-buffer-name "*shell*"))
565 (if (file-remote-p default-directory)
566 ;; It must be possible to declare a local default-directory.
567 ;; FIXME: This can't be right: it changes the default-directory
568 ;; of the current-buffer rather than of the *shell* buffer.
569 (setq default-directory
572 "Default directory: " default-directory default-directory
573 t nil 'file-directory-p))))))))
574 (require 'ansi-color)
575 (setq buffer (if (or buffer (not (derived-mode-p 'shell-mode))
576 (comint-check-proc (current-buffer)))
577 (get-buffer-create (or buffer "*shell*"))
578 ;; If the current buffer is a dead shell buffer, use it.
580 ;; Pop to buffer, so that the buffer's window will be correctly set
581 ;; when we call comint (so that comint sets the COLUMNS env var properly).
582 (pop-to-buffer buffer)
583 (unless (comint-check-proc buffer)
584 (let* ((prog (or explicit-shell-file-name
585 (getenv "ESHELL") shell-file-name))
586 (name (file-name-nondirectory prog))
587 (startfile (concat "~/.emacs_" name))
588 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
589 (unless (file-exists-p startfile)
590 (setq startfile (concat user-emacs-directory "init_" name ".sh")))
591 (apply 'make-comint-in-buffer "shell" buffer prog
592 (if (file-exists-p startfile) startfile)
593 (if (and xargs-name (boundp xargs-name))
594 (symbol-value xargs-name)
599 ;; Don't do this when shell.el is loaded, only while dumping.
600 ;;;###autoload (add-hook 'same-window-buffer-names (purecopy "*shell*"))
602 ;;; Directory tracking
604 ;; This code provides the shell mode input sentinel
605 ;; SHELL-DIRECTORY-TRACKER
606 ;; that tracks cd, pushd, and popd commands issued to the shell, and
607 ;; changes the current directory of the shell buffer accordingly.
609 ;; This is basically a fragile hack, although it's more accurate than
610 ;; the version in Emacs 18's shell.el. It has the following failings:
611 ;; 1. It doesn't know about the cdpath shell variable.
612 ;; 2. It cannot infallibly deal with command sequences, though it does well
613 ;; with these and with ignoring commands forked in another shell with ()s.
614 ;; 3. More generally, any complex command is going to throw it. Otherwise,
615 ;; you'd have to build an entire shell interpreter in Emacs Lisp. Failing
616 ;; that, there's no way to catch shell commands where cd's are buried
617 ;; inside conditional expressions, aliases, and so forth.
619 ;; The whole approach is a crock. Shell aliases mess it up. File sourcing
620 ;; messes it up. You run other processes under the shell; these each have
621 ;; separate working directories, and some have commands for manipulating
622 ;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
623 ;; commands that do *not* affect the current w.d. at all, but look like they
624 ;; do (e.g., the cd command in ftp). In shells that allow you job
625 ;; control, you can switch between jobs, all having different w.d.'s. So
626 ;; simply saying %3 can shift your w.d..
628 ;; The solution is to relax, not stress out about it, and settle for
629 ;; a hack that works pretty well in typical circumstances. Remember
630 ;; that a half-assed solution is more in keeping with the spirit of Unix,
633 ;; One good hack not implemented here for users of programmable shells
634 ;; is to program up the shell w.d. manipulation commands to output
635 ;; a coded command sequence to the tty. Something like
637 ;; where <cwd> is the new current working directory. Then trash the
638 ;; directory tracking machinery currently used in this package, and
639 ;; replace it with a process filter that watches for and strips out
642 (defun shell-dir-cookie-watcher (text)
643 ;; This is fragile: the TEXT could be split into several chunks and we'd
644 ;; miss it. Oh well. It's a best effort anyway. I'd expect that it's
645 ;; rather unusual to have the prompt split into several packets, but
646 ;; I'm sure Murphy will prove me wrong.
647 (when (and shell-dir-cookie-re (string-match shell-dir-cookie-re text))
648 (let ((dir (match-string 1 text)))
650 ((file-name-absolute-p dir) (shell-cd dir))
651 ;; Let's try and see if it seems to be up or down from where we were.
652 ((string-match "\\`\\(.*\\)\\(?:/.*\\)?\n\\(.*/\\)\\1\\(?:/.*\\)?\\'"
653 (setq text (concat dir "\n" default-directory)))
654 (shell-cd (concat (match-string 2 text) dir)))))))
656 (defun shell-directory-tracker (str)
657 "Tracks cd, pushd and popd commands issued to the shell.
658 This function is called on each input passed to the shell.
659 It watches for cd, pushd and popd commands and sets the buffer's
660 default directory to track these commands.
662 You may toggle this tracking on and off with \\[shell-dirtrack-mode].
663 If Emacs gets confused, you can resync with the shell with \\[dirs].
664 \(The `dirtrack' package provides an alternative implementation of this
665 feature - see the function `dirtrack-mode'.)
667 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
668 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
669 and `shell-pushd-dunique' control the behavior of the relevant command.
671 Environment variables are expanded, see function `substitute-in-file-name'."
673 ;; We fail gracefully if we think the command will fail in the shell.
674 (condition-case chdir-failure
675 (let ((start (progn (string-match
676 (concat "^" shell-command-separator-regexp)
677 str) ; skip whitespace
680 (while (string-match shell-command-regexp str start)
681 (setq end (match-end 0)
682 cmd (comint-arguments (substring str start end) 0 0)
683 arg1 (comint-arguments (substring str start end) 1 1))
685 (setq arg1 (shell-unquote-argument arg1)))
686 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
687 "\\)\\($\\|[ \t]\\)")
689 (shell-process-popd (comint-substitute-in-file-name arg1)))
690 ((string-match (concat "\\`\\(" shell-pushd-regexp
691 "\\)\\($\\|[ \t]\\)")
693 (shell-process-pushd (comint-substitute-in-file-name arg1)))
694 ((string-match (concat "\\`\\(" shell-cd-regexp
695 "\\)\\($\\|[ \t]\\)")
697 (shell-process-cd (comint-substitute-in-file-name arg1)))
698 ((and shell-chdrive-regexp
699 (string-match (concat "\\`\\(" shell-chdrive-regexp
700 "\\)\\($\\|[ \t]\\)")
702 (shell-process-cd (comint-substitute-in-file-name cmd))))
703 (setq start (progn (string-match shell-command-separator-regexp
707 (error "Couldn't cd"))))
709 (defun shell-unquote-argument (string)
710 "Remove all kinds of shell quoting from STRING."
712 (let ((idx 0) next inside
714 (if (string-match shell-dumb-shell-regexp
715 (file-name-nondirectory
716 (car (process-command (get-buffer-process (current-buffer))))))
719 (while (and (< idx (length string))
720 (setq next (string-match quote-chars string next)))
721 (cond ((= (aref string next) ?\\)
722 (setq string (replace-match "" nil nil string))
723 (setq next (1+ next)))
724 ((and inside (= (aref string next) inside))
725 (setq string (replace-match "" nil nil string))
728 (setq next (1+ next)))
730 (setq inside (aref string next))
731 (setq string (replace-match "" nil nil string)))))
735 (defun shell-process-popd (arg)
736 (let ((num (or (shell-extract-num arg) 0)))
737 (cond ((and num (= num 0) shell-dirstack)
738 (shell-cd (shell-prefixed-directory-name (car shell-dirstack)))
739 (setq shell-dirstack (cdr shell-dirstack))
740 (shell-dirstack-message))
741 ((and num (> num 0) (<= num (length shell-dirstack)))
742 (let* ((ds (cons nil shell-dirstack))
743 (cell (nthcdr (1- num) ds)))
744 (rplacd cell (cdr (cdr cell)))
745 (setq shell-dirstack (cdr ds))
746 (shell-dirstack-message)))
748 (error "Couldn't popd")))))
750 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
751 (defun shell-prefixed-directory-name (dir)
752 (if (= (length comint-file-name-prefix) 0)
754 (if (file-name-absolute-p dir)
755 ;; The name is absolute, so prepend the prefix.
756 (concat comint-file-name-prefix dir)
757 ;; For relative name we assume default-directory already has the prefix.
758 (expand-file-name dir))))
761 (defun shell-process-cd (arg)
762 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
764 ((string-equal "-" arg) shell-last-dir)
765 (t (shell-prefixed-directory-name arg)))))
766 (setq shell-last-dir default-directory)
768 (shell-dirstack-message)))
771 (defun shell-process-pushd (arg)
772 (let ((num (shell-extract-num arg)))
773 (cond ((zerop (length arg))
774 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
775 (cond (shell-pushd-tohome
776 (shell-process-pushd (concat comint-file-name-prefix "~")))
778 (let ((old default-directory))
779 (shell-cd (car shell-dirstack))
780 (setq shell-dirstack (cons old (cdr shell-dirstack)))
781 (shell-dirstack-message)))
783 (message "Directory stack empty."))))
786 (cond ((> num (length shell-dirstack))
787 (message "Directory stack not that deep."))
789 (error (message "Couldn't cd")))
790 (shell-pushd-dextract
791 (let ((dir (nth (1- num) shell-dirstack)))
792 (shell-process-popd arg)
793 (shell-process-pushd default-directory)
795 (shell-dirstack-message)))
797 (let* ((ds (cons default-directory shell-dirstack))
799 (front (nthcdr num ds))
800 (back (reverse (nthcdr (- dslen num) (reverse ds))))
801 (new-ds (append front back)))
802 (shell-cd (car new-ds))
803 (setq shell-dirstack (cdr new-ds))
804 (shell-dirstack-message)))))
807 (let ((old-wd default-directory))
808 (shell-cd (shell-prefixed-directory-name arg))
809 (if (or (null shell-pushd-dunique)
810 (not (member old-wd shell-dirstack)))
811 (setq shell-dirstack (cons old-wd shell-dirstack)))
812 (shell-dirstack-message))))))
814 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
815 (defun shell-extract-num (str)
816 (and (string-match "^\\+[1-9][0-9]*$" str)
817 (string-to-number str)))
819 (defvaralias 'shell-dirtrack-mode 'shell-dirtrackp)
820 (define-minor-mode shell-dirtrack-mode
821 "Turn directory tracking on and off in a shell buffer.
822 The `dirtrack' package provides an alternative implementation of this
823 feature - see the function `dirtrack-mode'."
825 (setq list-buffers-directory (if shell-dirtrack-mode default-directory))
826 (if shell-dirtrack-mode
827 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
828 (remove-hook 'comint-input-filter-functions 'shell-directory-tracker t)))
830 (define-obsolete-function-alias 'shell-dirtrack-toggle 'shell-dirtrack-mode
833 (defun shell-cd (dir)
834 "Do normal `cd' to DIR, and set `list-buffers-directory'."
837 (setq list-buffers-directory default-directory)))
839 (defun shell-resync-dirs ()
840 "Resync the buffer's idea of the current directory stack.
841 This command queries the shell with the command bound to
842 `shell-dirstack-query' (default \"dirs\"), reads the next
843 line output and parses it to form the new directory stack.
844 DON'T issue this command unless the buffer is at a shell prompt.
845 Also, note that if some other subprocess decides to do output
846 immediately after the query, its output will be taken as the
847 new directory stack -- you lose. If this happens, just do the
850 (let* ((proc (get-buffer-process (current-buffer)))
851 (pmark (process-mark proc))
852 (started-at-pmark (= (point) (marker-position pmark))))
855 ;; If the process echoes commands, don't insert a fake command in
856 ;; the buffer or it will appear twice.
857 (unless comint-process-echoes
858 (insert shell-dirstack-query) (insert "\n"))
859 (sit-for 0) ; force redisplay
860 (comint-send-string proc shell-dirstack-query)
861 (comint-send-string proc "\n")
862 (set-marker pmark (point))
866 (if comint-process-echoes
867 ;; Skip command echo if the process echoes
868 (concat "\\(" (regexp-quote shell-dirstack-query) "\n\\)")
871 ;; This extra newline prevents the user's pending input from spoofing us.
872 (insert "\n") (backward-char 1)
873 ;; Wait for one line.
874 (while (not (looking-at regexp))
875 (accept-process-output proc)
877 (goto-char pmark) (delete-char 1) ; remove the extra newline
878 ;; That's the dirlist. grab it & parse it.
879 (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
881 (ds '()) ; new dir stack
884 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
885 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
886 (setq ds (cons (concat comint-file-name-prefix
887 (substring dl (match-beginning 1)
890 (setq i (match-end 0)))
891 (let ((ds (nreverse ds)))
893 (progn (shell-cd (car ds))
894 (setq shell-dirstack (cdr ds)
895 shell-last-dir (car shell-dirstack))
896 (shell-dirstack-message))
897 (error (message "Couldn't cd"))))))
898 (if started-at-pmark (goto-char (marker-position pmark)))))
900 ;; For your typing convenience:
901 (defalias 'dirs 'shell-resync-dirs)
904 ;; Show the current dirstack on the message line.
905 ;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
906 ;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
907 ;; All the commands that mung the buffer's dirstack finish by calling
909 (defun shell-dirstack-message ()
910 (when shell-dirtrack-verbose
912 (ds (cons default-directory shell-dirstack))
913 (home (expand-file-name (concat comint-file-name-prefix "~/")))
914 (homelen (length home)))
916 (let ((dir (car ds)))
917 (and (>= (length dir) homelen)
918 (string= home (substring dir 0 homelen))
919 (setq dir (concat "~/" (substring dir homelen))))
920 ;; Strip off comint-file-name-prefix if present.
921 (and comint-file-name-prefix
922 (>= (length dir) (length comint-file-name-prefix))
923 (string= comint-file-name-prefix
924 (substring dir 0 (length comint-file-name-prefix)))
925 (setq dir (substring dir (length comint-file-name-prefix)))
927 (setq msg (concat msg (directory-file-name dir) " "))
929 (message "%s" msg))))
931 ;; This was mostly copied from shell-resync-dirs.
932 (defun shell-snarf-envar (var)
933 "Return as a string the shell's value of environment variable VAR."
934 (let* ((cmd (format "printenv '%s'\n" var))
935 (proc (get-buffer-process (current-buffer)))
936 (pmark (process-mark proc)))
939 (sit-for 0) ; force redisplay
940 (comint-send-string proc cmd)
941 (set-marker pmark (point))
942 (let ((pt (point))) ; wait for 1 line
943 ;; This extra newline prevents the user's pending input from spoofing us.
944 (insert "\n") (backward-char 1)
945 (while (not (looking-at ".+\n"))
946 (accept-process-output proc)
948 (goto-char pmark) (delete-char 1) ; remove the extra newline
949 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
951 (defun shell-copy-environment-variable (variable)
952 "Copy the environment variable VARIABLE from the subshell to Emacs.
953 This command reads the value of the specified environment variable
954 in the shell, and sets the same environment variable in Emacs
955 \(what `getenv' in Emacs would return) to that value.
956 That value will affect any new subprocesses that you subsequently start
958 (interactive (list (read-envvar-name "\
959 Copy Shell environment variable to Emacs: ")))
960 (setenv variable (shell-snarf-envar variable)))
962 (defun shell-forward-command (&optional arg)
963 "Move forward across ARG shell command(s). Does not cross lines.
964 See `shell-command-regexp'."
966 (let ((limit (line-end-position)))
967 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
969 (skip-syntax-backward " "))))
972 (defun shell-backward-command (&optional arg)
973 "Move backward across ARG shell command(s). Does not cross lines.
974 See `shell-command-regexp'."
976 (let ((limit (save-excursion (comint-bol nil) (point))))
977 (when (> limit (point))
978 (setq limit (line-beginning-position)))
979 (skip-syntax-backward " " limit)
980 (if (re-search-backward
981 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
982 (progn (goto-char (match-beginning 1))
983 (skip-chars-forward ";&|")))))
985 (defun shell-dynamic-complete-command ()
986 "Dynamically complete the command at point.
987 This function is similar to `comint-dynamic-complete-filename', except that it
988 searches `exec-path' (minus the trailing Emacs library path) for completion
989 candidates. Note that this may not be the same as the shell's idea of the
992 Completion is dependent on the value of `shell-completion-execonly', plus
993 those that effect file completion. See `shell-dynamic-complete-as-command'.
995 Returns t if successful."
997 (let ((filename (comint-match-partial-filename)))
999 (save-match-data (not (string-match "[~/]" filename)))
1000 (eq (match-beginning 0)
1001 (save-excursion (shell-backward-command 1) (point))))
1002 (prog2 (unless (window-minibuffer-p (selected-window))
1003 (message "Completing command name..."))
1004 (shell-dynamic-complete-as-command)))))
1007 (defun shell-dynamic-complete-as-command ()
1008 "Dynamically complete at point as a command.
1009 See `shell-dynamic-complete-filename'. Returns t if successful."
1010 (let* ((filename (or (comint-match-partial-filename) ""))
1011 (filenondir (file-name-nondirectory filename))
1012 (path-dirs (cdr (reverse exec-path)))
1013 (cwd (file-name-as-directory (expand-file-name default-directory)))
1015 (and comint-completion-fignore
1016 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
1017 comint-completion-fignore "\\|")))
1018 (dir "") (comps-in-dir ())
1019 (file "") (abs-file-name "") (completions ()))
1020 ;; Go thru each dir in the search path, finding completions.
1022 (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
1023 comps-in-dir (and (file-accessible-directory-p dir)
1024 (file-name-all-completions filenondir dir)))
1025 ;; Go thru each completion found, to see whether it should be used.
1027 (setq file (car comps-in-dir)
1028 abs-file-name (concat dir file))
1029 (if (and (not (member file completions))
1030 (not (and ignored-extensions
1031 (string-match ignored-extensions file)))
1032 (or (string-equal dir cwd)
1033 (not (file-directory-p abs-file-name)))
1034 (or (null shell-completion-execonly)
1035 (file-executable-p abs-file-name)))
1036 (setq completions (cons file completions)))
1037 (setq comps-in-dir (cdr comps-in-dir)))
1038 (setq path-dirs (cdr path-dirs)))
1039 ;; OK, we've got a list of completions.
1040 (let ((success (let ((comint-completion-addsuffix nil))
1041 (comint-dynamic-simple-complete filenondir completions))))
1042 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
1043 (not (file-directory-p (comint-match-partial-filename))))
1047 (defun shell-dynamic-complete-filename ()
1048 "Dynamically complete the filename at point.
1049 This completes only if point is at a suitable position for a
1052 (let ((opoint (point))
1053 (beg (comint-line-beginning-position)))
1054 (when (save-excursion
1055 (goto-char (if (re-search-backward "[;|&]" beg t)
1058 (re-search-forward "[^ \t][ \t]" opoint t))
1059 (comint-dynamic-complete-as-filename))))
1061 (defun shell-match-partial-variable ()
1062 "Return the shell variable at point, or nil if none is found."
1064 (let ((limit (point)))
1065 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
1066 (or (looking-at "\\$") (forward-char 1)))
1067 ;; Anchor the search forwards.
1068 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
1070 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
1071 (buffer-substring (match-beginning 0) (match-end 0))))))
1073 (defun shell-dynamic-complete-environment-variable ()
1074 "Dynamically complete the environment variable at point.
1075 Completes if after a variable, i.e., if it starts with a \"$\".
1076 See `shell-dynamic-complete-as-environment-variable'.
1078 This function is similar to `comint-dynamic-complete-filename', except that it
1079 searches `process-environment' for completion candidates. Note that this may
1080 not be the same as the interpreter's idea of variable names. The main problem
1081 with this type of completion is that `process-environment' is the environment
1082 which Emacs started with. Emacs does not track changes to the environment made
1083 by the interpreter. Perhaps it would be more accurate if this function was
1084 called `shell-dynamic-complete-process-environment-variable'.
1086 Returns non-nil if successful."
1088 (let ((variable (shell-match-partial-variable)))
1089 (if (and variable (string-match "^\\$" variable))
1090 (prog2 (unless (window-minibuffer-p (selected-window))
1091 (message "Completing variable name..."))
1092 (shell-dynamic-complete-as-environment-variable)))))
1095 (defun shell-dynamic-complete-as-environment-variable ()
1096 "Dynamically complete at point as an environment variable.
1097 Used by `shell-dynamic-complete-environment-variable'.
1098 Uses `comint-dynamic-simple-complete'."
1099 (let* ((var (or (shell-match-partial-variable) ""))
1100 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
1101 (variables (mapcar (function (lambda (x)
1102 (substring x 0 (string-match "=" x))))
1103 process-environment))
1104 (addsuffix comint-completion-addsuffix)
1105 (comint-completion-addsuffix nil)
1106 (success (comint-dynamic-simple-complete variable variables)))
1107 (if (memq success '(sole shortest))
1108 (let* ((var (shell-match-partial-variable))
1109 (variable (substring var (string-match "[^$({]" var)))
1110 (protection (cond ((string-match "{" var) "}")
1111 ((string-match "(" var) ")")
1113 (suffix (cond ((null addsuffix) "")
1115 (comint-directory (getenv variable))) "/")
1117 (insert protection suffix)))
1121 (defun shell-replace-by-expanded-directory ()
1122 "Expand directory stack reference before point.
1123 Directory stack references are of the form \"=digit\" or \"=-\".
1124 See `default-directory' and `shell-dirstack'.
1126 Returns t if successful."
1128 (if (comint-match-partial-filename)
1130 (goto-char (match-beginning 0))
1131 (let ((stack (cons default-directory shell-dirstack))
1132 (index (cond ((looking-at "=-/?")
1133 (length shell-dirstack))
1134 ((looking-at "=\\([0-9]+\\)/?")
1137 (match-beginning 1) (match-end 1)))))))
1140 ((>= index (length stack))
1141 (error "Directory stack not that deep"))
1143 (replace-match (file-name-as-directory (nth index stack)) t t)
1144 (message "Directory item: %d" index)
1149 ;;; shell.el ends here