2007-08-19 Michael Kifer <kifer@cs.stonybrook.edu>
[emacs.git] / lisp / shell.el
blob03fbf46df67b41ab416277deed9794543441e691
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 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>
9 ;; Keywords: processes
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, or (at your option)
16 ;; 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; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
28 ;;; Commentary:
30 ;; This file defines a shell-in-a-buffer package (shell mode) built on
31 ;; top of comint mode. This is actually cmushell with things renamed
32 ;; to replace its counterpart in Emacs 18. cmushell is more
33 ;; featureful, robust, and uniform than the Emacs 18 version.
35 ;; Since this mode is built on top of the general command-interpreter-in-
36 ;; a-buffer mode (comint mode), it shares a common base functionality,
37 ;; and a common set of bindings, with all modes derived from comint mode.
38 ;; This makes these modes easier to use.
40 ;; For documentation on the functionality provided by comint mode, and
41 ;; the hooks available for customising it, see the file comint.el.
42 ;; For further information on shell mode, see the comments below.
44 ;; Needs fixin:
45 ;; When sending text from a source file to a subprocess, the process-mark can
46 ;; move off the window, so you can lose sight of the process interactions.
47 ;; Maybe I should ensure the process mark is in the window when I send
48 ;; text to the process? Switch selectable?
50 ;; YOUR .EMACS FILE
51 ;;=============================================================================
52 ;; Some suggestions for your .emacs file.
54 ;; ;; Define M-# to run some strange command:
55 ;; (eval-after-load "shell"
56 ;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
58 ;; Brief Command Documentation:
59 ;;============================================================================
60 ;; Comint Mode Commands: (common to shell and all comint-derived modes)
62 ;; m-p comint-previous-input Cycle backwards in input history
63 ;; m-n comint-next-input Cycle forwards
64 ;; m-r comint-previous-matching-input Previous input matching a regexp
65 ;; m-s comint-next-matching-input Next input that matches
66 ;; m-c-l comint-show-output Show last batch of process output
67 ;; return comint-send-input
68 ;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
69 ;; c-c c-a comint-bol Beginning of line; skip prompt
70 ;; c-c c-u comint-kill-input ^u
71 ;; c-c c-w backward-kill-word ^w
72 ;; c-c c-c comint-interrupt-subjob ^c
73 ;; c-c c-z comint-stop-subjob ^z
74 ;; c-c c-\ comint-quit-subjob ^\
75 ;; c-c c-o comint-kill-output Delete last batch of process output
76 ;; c-c c-r comint-show-output Show last batch of process output
77 ;; c-c c-l comint-dynamic-list-input-ring List input history
78 ;; send-invisible Read line w/o echo & send to proc
79 ;; comint-continue-subjob Useful if you accidentally suspend
80 ;; top-level job
81 ;; comint-mode-hook is the comint mode hook.
83 ;; Shell Mode Commands:
84 ;; shell Fires up the shell process
85 ;; tab comint-dynamic-complete Complete filename/command/history
86 ;; m-? comint-dynamic-list-filename-completions
87 ;; List completions in help buffer
88 ;; m-c-f shell-forward-command Forward a shell command
89 ;; m-c-b shell-backward-command Backward a shell command
90 ;; dirs Resync the buffer's dir stack
91 ;; dirtrack-mode Turn dir tracking on/off
92 ;; comint-strip-ctrl-m Remove trailing ^Ms from output
94 ;; The shell mode hook is shell-mode-hook
95 ;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
96 ;; compatibility.
98 ;; Read the rest of this file for more information.
100 ;;; Code:
102 (require 'comint)
104 ;;; Customization and Buffer Variables
106 (defgroup shell nil
107 "Running shell from within Emacs buffers."
108 :group 'processes
109 :group 'unix)
111 (defgroup shell-directories nil
112 "Directory support in shell mode."
113 :group 'shell)
115 (defgroup shell-faces nil
116 "Faces in shell buffers."
117 :group 'shell)
119 ;;;###autoload
120 (defcustom shell-dumb-shell-regexp "cmd\\(proxy\\)?\\.exe"
121 "Regexp to match shells that don't save their command history, and
122 don't handle the backslash as a quote character. For shells that
123 match this regexp, Emacs will write out the command history when the
124 shell finishes, and won't remove backslashes when it unquotes shell
125 arguments."
126 :type 'regexp
127 :group 'shell)
129 (defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
130 "Regexp to match prompts in the inferior shell.
131 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
132 This variable is used to initialize `comint-prompt-regexp' in the
133 shell buffer.
135 If `comint-use-prompt-regexp' is nil, then this variable is only used
136 to determine paragraph boundaries. See Info node `Shell Prompts' for
137 how Shell mode treats paragraphs.
139 The pattern should probably not match more than one line. If it does,
140 Shell mode may become confused trying to distinguish prompt from input
141 on lines which don't start with a prompt.
143 This is a fine thing to set in your `.emacs' file."
144 :type 'regexp
145 :group 'shell)
147 (defcustom shell-completion-fignore nil
148 "List of suffixes to be disregarded during file/command completion.
149 This variable is used to initialize `comint-completion-fignore' in the shell
150 buffer. The default is nil, for compatibility with most shells.
151 Some people like (\"~\" \"#\" \"%\").
153 This is a fine thing to set in your `.emacs' file."
154 :type '(repeat (string :tag "Suffix"))
155 :group 'shell)
157 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
158 "List of characters to recognize as separate arguments.
159 This variable is used to initialize `comint-delimiter-argument-list' in the
160 shell buffer. The value may depend on the operating system or shell.
162 This is a fine thing to set in your `.emacs' file.")
164 (defvar shell-file-name-chars
165 (if (memq system-type '(ms-dos windows-nt cygwin))
166 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
167 "[]~/A-Za-z0-9+@:_.$#%,={}-")
168 "String of characters valid in a file name.
169 This variable is used to initialize `comint-file-name-chars' in the
170 shell buffer. The value may depend on the operating system or shell.
172 This is a fine thing to set in your `.emacs' file.")
174 (defvar shell-file-name-quote-list
175 (if (memq system-type '(ms-dos windows-nt))
177 (append shell-delimiter-argument-list '(?\s ?\* ?\! ?\" ?\' ?\` ?\# ?\\)))
178 "List of characters to quote when in a file name.
179 This variable is used to initialize `comint-file-name-quote-list' in the
180 shell buffer. The value may depend on the operating system or shell.
182 This is a fine thing to set in your `.emacs' file.")
184 (defvar shell-dynamic-complete-functions
185 '(comint-replace-by-expanded-history
186 shell-dynamic-complete-environment-variable
187 shell-dynamic-complete-command
188 shell-replace-by-expanded-directory
189 comint-dynamic-complete-filename)
190 "List of functions called to perform completion.
191 This variable is used to initialize `comint-dynamic-complete-functions' in the
192 shell buffer.
194 This is a fine thing to set in your `.emacs' file.")
196 (defcustom shell-command-regexp "[^;&|\n]+"
197 "Regexp to match a single command within a pipeline.
198 This is used for directory tracking and does not do a perfect job."
199 :type 'regexp
200 :group 'shell)
202 (defcustom shell-command-separator-regexp "[;&|\n \t]*"
203 "Regexp to match a single command within a pipeline.
204 This is used for directory tracking and does not do a perfect job."
205 :type 'regexp
206 :group 'shell)
208 (defcustom shell-completion-execonly t
209 "If non-nil, use executable files only for completion candidates.
210 This mirrors the optional behavior of tcsh.
212 Detecting executability of files may slow command completion considerably."
213 :type 'boolean
214 :group 'shell)
216 (defcustom shell-popd-regexp "popd"
217 "Regexp to match subshell commands equivalent to popd."
218 :type 'regexp
219 :group 'shell-directories)
221 (defcustom shell-pushd-regexp "pushd"
222 "Regexp to match subshell commands equivalent to pushd."
223 :type 'regexp
224 :group 'shell-directories)
226 (defcustom shell-pushd-tohome nil
227 "If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
228 This mirrors the optional behavior of tcsh."
229 :type 'boolean
230 :group 'shell-directories)
232 (defcustom shell-pushd-dextract nil
233 "If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
234 This mirrors the optional behavior of tcsh."
235 :type 'boolean
236 :group 'shell-directories)
238 (defcustom shell-pushd-dunique nil
239 "If non-nil, make pushd only add unique directories to the stack.
240 This mirrors the optional behavior of tcsh."
241 :type 'boolean
242 :group 'shell-directories)
244 (defcustom shell-cd-regexp "cd"
245 "Regexp to match subshell commands equivalent to cd."
246 :type 'regexp
247 :group 'shell-directories)
249 (defcustom shell-chdrive-regexp
250 (if (memq system-type '(ms-dos windows-nt))
251 ; NetWare allows the five chars between upper and lower alphabetics.
252 "[]a-zA-Z^_`\\[\\\\]:"
253 nil)
254 "If non-nil, is regexp used to track drive changes."
255 :type '(choice regexp
256 (const nil))
257 :group 'shell-directories)
259 (defcustom shell-dirtrack-verbose t
260 "If non-nil, show the directory stack following directory change.
261 This is effective only if directory tracking is enabled."
262 :type 'boolean
263 :group 'shell-directories)
265 (defcustom explicit-shell-file-name nil
266 "If non-nil, is file name to use for explicitly requested inferior shell."
267 :type '(choice (const :tag "None" nil) file)
268 :group 'shell)
270 ;; Note: There are no explicit references to the variable `explicit-csh-args'.
271 ;; It is used implicitly by M-x shell when the shell is `csh'.
272 (defcustom explicit-csh-args
273 (if (eq system-type 'hpux)
274 ;; -T persuades HP's csh not to think it is smarter
275 ;; than us about what terminal modes to use.
276 '("-i" "-T")
277 '("-i"))
278 "Args passed to inferior shell by \\[shell], if the shell is csh.
279 Value is a list of strings, which may be nil."
280 :type '(repeat (string :tag "Argument"))
281 :group 'shell)
283 ;; Note: There are no explicit references to the variable `explicit-bash-args'.
284 ;; It is used implicitly by M-x shell when the interactive shell is `bash'.
285 (defcustom explicit-bash-args
286 (let* ((prog (or (and (boundp 'explicit-shell-file-name) explicit-shell-file-name)
287 (getenv "ESHELL") shell-file-name))
288 (name (file-name-nondirectory prog)))
289 ;; Tell bash not to use readline, except for bash 1.x which
290 ;; doesn't grook --noediting. Bash 1.x has -nolineediting, but
291 ;; process-send-eof cannot terminate bash if we use it.
292 (if (and (not purify-flag)
293 (equal name "bash")
294 (file-executable-p prog)
295 (string-match "bad option"
296 (shell-command-to-string
297 (concat (shell-quote-argument prog)
298 " --noediting"))))
299 '("-i")
300 '("--noediting" "-i")))
301 "Args passed to inferior shell by \\[shell], if the shell is bash.
302 Value is a list of strings, which may be nil."
303 :type '(repeat (string :tag "Argument"))
304 :group 'shell)
306 (defcustom shell-input-autoexpand 'history
307 "If non-nil, expand input command history references on completion.
308 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
310 If the value is `input', then the expansion is seen on input.
311 If the value is `history', then the expansion is only when inserting
312 into the buffer's input ring. See also `comint-magic-space' and
313 `comint-dynamic-complete'.
315 This variable supplies a default for `comint-input-autoexpand',
316 for Shell mode only."
317 :type '(choice (const :tag "off" nil)
318 (const input)
319 (const history)
320 (const :tag "on" t))
321 :group 'shell)
323 (defvar shell-dirstack nil
324 "List of directories saved by pushd in this buffer's shell.
325 Thus, this does not include the shell's current directory.")
327 (defvar shell-dirtrackp t
328 "Non-nil in a shell buffer means directory tracking is enabled.")
330 (defvar shell-last-dir nil
331 "Keep track of last directory for ksh `cd -' command.")
333 (defvar shell-dirstack-query nil
334 "Command used by `shell-resync-dirs' to query the shell.")
336 (defvar shell-mode-map nil)
337 (cond ((not shell-mode-map)
338 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
339 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
340 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
341 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
342 (define-key shell-mode-map "\M-?"
343 'comint-dynamic-list-filename-completions)
344 (define-key shell-mode-map [menu-bar completion]
345 (cons "Complete"
346 (copy-keymap (lookup-key comint-mode-map [menu-bar completion]))))
347 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
348 [complete-env-variable] '("Complete Env. Variable Name" .
349 shell-dynamic-complete-environment-variable)
350 'complete-file)
351 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
352 [expand-directory] '("Expand Directory Reference" .
353 shell-replace-by-expanded-directory)
354 'complete-expand)))
356 (defcustom shell-mode-hook '()
357 "*Hook for customising Shell mode."
358 :type 'hook
359 :group 'shell)
361 (defvar shell-font-lock-keywords
362 '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
363 ("^[^ \t\n]+:.*" . font-lock-string-face)
364 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
365 "Additional expressions to highlight in Shell mode.")
367 ;;; Basic Procedures
369 (put 'shell-mode 'mode-class 'special)
371 (define-derived-mode shell-mode comint-mode "Shell"
372 "Major mode for interacting with an inferior shell.\\<shell-mode-map>
373 \\[comint-send-input] after the end of the process' output sends the text from
374 the end of process to the end of the current line.
375 \\[comint-send-input] before end of process output copies the current line minus the prompt to
376 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
377 \\[send-invisible] reads a line of text without echoing it, and sends it to
378 the shell. This is useful for entering passwords. Or, add the function
379 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
381 If you want to make multiple shell buffers, rename the `*shell*' buffer
382 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
384 If you want to make shell buffers limited in length, add the function
385 `comint-truncate-buffer' to `comint-output-filter-functions'.
387 If you accidentally suspend your process, use \\[comint-continue-subjob]
388 to continue it.
390 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
391 keep this buffer's default directory the same as the shell's working directory.
392 While directory tracking is enabled, the shell's working directory is displayed
393 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
394 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
395 directory stack is.
396 \\[dirtrack-mode] turns directory tracking on and off.
398 \\{shell-mode-map}
399 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
400 `shell-mode-hook' (in that order). Before each input, the hooks on
401 `comint-input-filter-functions' are run. After each shell output, the hooks
402 on `comint-output-filter-functions' are run.
404 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
405 and `shell-popd-regexp' are used to match their respective commands,
406 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
407 control the behavior of the relevant command.
409 Variables `comint-completion-autolist', `comint-completion-addsuffix',
410 `comint-completion-recexact' and `comint-completion-fignore' control the
411 behavior of file name, command name and variable name completion. Variable
412 `shell-completion-execonly' controls the behavior of command name completion.
413 Variable `shell-completion-fignore' is used to initialize the value of
414 `comint-completion-fignore'.
416 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
417 the initialization of the input ring history, and history expansion.
419 Variables `comint-output-filter-functions', a hook, and
420 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
421 control whether input and output cause the window to scroll to the end of the
422 buffer."
423 (setq comint-prompt-regexp shell-prompt-pattern)
424 (setq comint-completion-fignore shell-completion-fignore)
425 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
426 (setq comint-file-name-chars shell-file-name-chars)
427 (setq comint-file-name-quote-list shell-file-name-quote-list)
428 (set (make-local-variable 'comint-dynamic-complete-functions)
429 shell-dynamic-complete-functions)
430 (set (make-local-variable 'paragraph-separate) "\\'")
431 (make-local-variable 'paragraph-start)
432 (setq paragraph-start comint-prompt-regexp)
433 (make-local-variable 'font-lock-defaults)
434 (setq font-lock-defaults '(shell-font-lock-keywords t))
435 (make-local-variable 'shell-dirstack)
436 (setq shell-dirstack nil)
437 (make-local-variable 'shell-last-dir)
438 (setq shell-last-dir nil)
439 (setq comint-input-autoexpand shell-input-autoexpand)
440 ;; This is not really correct, since the shell buffer does not really
441 ;; edit this directory. But it is useful in the buffer list and menus.
442 (make-local-variable 'list-buffers-directory)
443 (shell-dirtrack-mode 1)
444 (setq list-buffers-directory (expand-file-name default-directory))
445 ;; shell-dependent assignments.
446 (when (ring-empty-p comint-input-ring)
447 (let ((shell (file-name-nondirectory (car
448 (process-command (get-buffer-process (current-buffer)))))))
449 (setq comint-input-ring-file-name
450 (or (getenv "HISTFILE")
451 (cond ((string-equal shell "bash") "~/.bash_history")
452 ((string-equal shell "ksh") "~/.sh_history")
453 (t "~/.history"))))
454 (if (or (equal comint-input-ring-file-name "")
455 (equal (file-truename comint-input-ring-file-name)
456 (file-truename "/dev/null")))
457 (setq comint-input-ring-file-name nil))
458 ;; Arrange to write out the input ring on exit, if the shell doesn't
459 ;; do this itself.
460 (if (and comint-input-ring-file-name
461 (string-match shell-dumb-shell-regexp shell))
462 (set-process-sentinel (get-buffer-process (current-buffer))
463 #'shell-write-history-on-exit))
464 (setq shell-dirstack-query
465 (cond ((string-equal shell "sh") "pwd")
466 ((string-equal shell "ksh") "echo $PWD ~-")
467 (t "dirs")))
468 ;; Bypass a bug in certain versions of bash.
469 (when (string-equal shell "bash")
470 (add-hook 'comint-output-filter-functions
471 'shell-filter-ctrl-a-ctrl-b nil t)))
472 (comint-read-input-ring t)))
474 (defun shell-filter-ctrl-a-ctrl-b (string)
475 "Remove `^A' and `^B' characters from comint output.
477 Bash uses these characters as internal quoting characters in its
478 prompt. Due to a bug in some bash versions (including 2.03,
479 2.04, and 2.05b), they may erroneously show up when bash is
480 started with the `--noediting' option and Select Graphic
481 Rendition (SGR) control sequences (formerly known as ANSI escape
482 sequences) are used to color the prompt.
484 This function can be put on `comint-output-filter-functions'.
485 The argument STRING is ignored."
486 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
487 (save-excursion
488 (goto-char (or (and (markerp comint-last-output-start)
489 (marker-position comint-last-output-start))
490 (point-min)))
491 (while (re-search-forward "[\C-a\C-b]" pmark t)
492 (replace-match "")))))
494 (defun shell-write-history-on-exit (process event)
495 "Called when the shell process is stopped.
497 Writes the input history to a history file
498 `comint-input-ring-file-name' using `comint-write-input-ring'
499 and inserts a short message in the shell buffer.
501 This function is a sentinel watching the shell interpreter process.
502 Sentinels will always get the two parameters PROCESS and EVENT."
503 ;; Write history.
504 (comint-write-input-ring)
505 (let ((buf (process-buffer process)))
506 (when (buffer-live-p buf)
507 (with-current-buffer buf
508 (insert (format "\nProcess %s %s\n" process event))))))
510 ;;;###autoload
511 (defun shell (&optional buffer)
512 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
513 Interactively, a prefix arg means to prompt for BUFFER.
514 If BUFFER exists but shell process is not running, make new shell.
515 If BUFFER exists and shell process is running, just switch to BUFFER.
516 Program used comes from variable `explicit-shell-file-name',
517 or (if that is nil) from the ESHELL environment variable,
518 or (if that is nil) from `shell-file-name'.
519 If a file `~/.emacs_SHELLNAME' exists, or `~/.emacs.d/init_SHELLNAME.sh',
520 it is given as initial input (but this may be lost, due to a timing
521 error, if the shell discards input when it starts up).
522 The buffer is put in Shell mode, giving commands for sending input
523 and controlling the subjobs of the shell. See `shell-mode'.
524 See also the variable `shell-prompt-pattern'.
526 To specify a coding system for converting non-ASCII characters
527 in the input and output to the shell, use \\[universal-coding-system-argument]
528 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
529 in the shell buffer, after you start the shell.
530 The default comes from `process-coding-system-alist' and
531 `default-process-coding-system'.
533 The shell file name (sans directories) is used to make a symbol name
534 such as `explicit-csh-args'. If that symbol is a variable,
535 its value is used as a list of arguments when invoking the shell.
536 Otherwise, one argument `-i' is passed to the shell.
538 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
539 (interactive
540 (list
541 (and current-prefix-arg
542 (read-buffer "Shell buffer: "
543 (generate-new-buffer-name "*shell*")))))
544 (setq buffer (get-buffer-create (or buffer "*shell*")))
545 ;; Pop to buffer, so that the buffer's window will be correctly set
546 ;; when we call comint (so that comint sets the COLUMNS env var properly).
547 (pop-to-buffer buffer)
548 (unless (comint-check-proc buffer)
549 (let* ((prog (or explicit-shell-file-name
550 (getenv "ESHELL") shell-file-name))
551 (name (file-name-nondirectory prog))
552 (startfile (concat "~/.emacs_" name))
553 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
554 (unless (file-exists-p startfile)
555 (setq startfile (concat user-emacs-directory "init_" name ".sh")))
556 (apply 'make-comint-in-buffer "shell" buffer prog
557 (if (file-exists-p startfile) startfile)
558 (if (and xargs-name (boundp xargs-name))
559 (symbol-value xargs-name)
560 '("-i")))
561 (shell-mode)))
562 buffer)
564 ;; Don't do this when shell.el is loaded, only while dumping.
565 ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
567 ;;; Directory tracking
569 ;; This code provides the shell mode input sentinel
570 ;; SHELL-DIRECTORY-TRACKER
571 ;; that tracks cd, pushd, and popd commands issued to the shell, and
572 ;; changes the current directory of the shell buffer accordingly.
574 ;; This is basically a fragile hack, although it's more accurate than
575 ;; the version in Emacs 18's shell.el. It has the following failings:
576 ;; 1. It doesn't know about the cdpath shell variable.
577 ;; 2. It cannot infallibly deal with command sequences, though it does well
578 ;; with these and with ignoring commands forked in another shell with ()s.
579 ;; 3. More generally, any complex command is going to throw it. Otherwise,
580 ;; you'd have to build an entire shell interpreter in Emacs Lisp. Failing
581 ;; that, there's no way to catch shell commands where cd's are buried
582 ;; inside conditional expressions, aliases, and so forth.
584 ;; The whole approach is a crock. Shell aliases mess it up. File sourcing
585 ;; messes it up. You run other processes under the shell; these each have
586 ;; separate working directories, and some have commands for manipulating
587 ;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
588 ;; commands that do *not* affect the current w.d. at all, but look like they
589 ;; do (e.g., the cd command in ftp). In shells that allow you job
590 ;; control, you can switch between jobs, all having different w.d.'s. So
591 ;; simply saying %3 can shift your w.d..
593 ;; The solution is to relax, not stress out about it, and settle for
594 ;; a hack that works pretty well in typical circumstances. Remember
595 ;; that a half-assed solution is more in keeping with the spirit of Unix,
596 ;; anyway. Blech.
598 ;; One good hack not implemented here for users of programmable shells
599 ;; is to program up the shell w.d. manipulation commands to output
600 ;; a coded command sequence to the tty. Something like
601 ;; ESC | <cwd> |
602 ;; where <cwd> is the new current working directory. Then trash the
603 ;; directory tracking machinery currently used in this package, and
604 ;; replace it with a process filter that watches for and strips out
605 ;; these messages.
607 (defun shell-directory-tracker (str)
608 "Tracks cd, pushd and popd commands issued to the shell.
609 This function is called on each input passed to the shell.
610 It watches for cd, pushd and popd commands and sets the buffer's
611 default directory to track these commands.
613 You may toggle this tracking on and off with \\[dirtrack-mode].
614 If Emacs gets confused, you can resync with the shell with \\[dirs].
616 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
617 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
618 and `shell-pushd-dunique' control the behavior of the relevant command.
620 Environment variables are expanded, see function `substitute-in-file-name'."
621 (if shell-dirtrackp
622 ;; We fail gracefully if we think the command will fail in the shell.
623 (condition-case chdir-failure
624 (let ((start (progn (string-match
625 (concat "^" shell-command-separator-regexp)
626 str) ; skip whitespace
627 (match-end 0)))
628 end cmd arg1)
629 (while (string-match shell-command-regexp str start)
630 (setq end (match-end 0)
631 cmd (comint-arguments (substring str start end) 0 0)
632 arg1 (comint-arguments (substring str start end) 1 1))
633 (if arg1
634 (setq arg1 (shell-unquote-argument arg1)))
635 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
636 "\\)\\($\\|[ \t]\\)")
637 cmd)
638 (shell-process-popd (comint-substitute-in-file-name arg1)))
639 ((string-match (concat "\\`\\(" shell-pushd-regexp
640 "\\)\\($\\|[ \t]\\)")
641 cmd)
642 (shell-process-pushd (comint-substitute-in-file-name arg1)))
643 ((string-match (concat "\\`\\(" shell-cd-regexp
644 "\\)\\($\\|[ \t]\\)")
645 cmd)
646 (shell-process-cd (comint-substitute-in-file-name arg1)))
647 ((and shell-chdrive-regexp
648 (string-match (concat "\\`\\(" shell-chdrive-regexp
649 "\\)\\($\\|[ \t]\\)")
650 cmd))
651 (shell-process-cd (comint-substitute-in-file-name cmd))))
652 (setq start (progn (string-match shell-command-separator-regexp
653 str end)
654 ;; skip again
655 (match-end 0)))))
656 (error "Couldn't cd"))))
658 (defun shell-unquote-argument (string)
659 "Remove all kinds of shell quoting from STRING."
660 (save-match-data
661 (let ((idx 0) next inside
662 (quote-chars
663 (if (string-match shell-dumb-shell-regexp
664 (file-name-nondirectory
665 (car (process-command (get-buffer-process (current-buffer))))))
666 "['`\"]"
667 "[\\'`\"]")))
668 (while (and (< idx (length string))
669 (setq next (string-match quote-chars string next)))
670 (cond ((= (aref string next) ?\\)
671 (setq string (replace-match "" nil nil string))
672 (setq next (1+ next)))
673 ((and inside (= (aref string next) inside))
674 (setq string (replace-match "" nil nil string))
675 (setq inside nil))
676 (inside
677 (setq next (1+ next)))
679 (setq inside (aref string next))
680 (setq string (replace-match "" nil nil string)))))
681 string)))
683 ;; popd [+n]
684 (defun shell-process-popd (arg)
685 (let ((num (or (shell-extract-num arg) 0)))
686 (cond ((and num (= num 0) shell-dirstack)
687 (shell-cd (car shell-dirstack))
688 (setq shell-dirstack (cdr shell-dirstack))
689 (shell-dirstack-message))
690 ((and num (> num 0) (<= num (length shell-dirstack)))
691 (let* ((ds (cons nil shell-dirstack))
692 (cell (nthcdr (1- num) ds)))
693 (rplacd cell (cdr (cdr cell)))
694 (setq shell-dirstack (cdr ds))
695 (shell-dirstack-message)))
697 (error "Couldn't popd")))))
699 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
700 (defun shell-prefixed-directory-name (dir)
701 (if (= (length comint-file-name-prefix) 0)
703 (if (file-name-absolute-p dir)
704 ;; The name is absolute, so prepend the prefix.
705 (concat comint-file-name-prefix dir)
706 ;; For relative name we assume default-directory already has the prefix.
707 (expand-file-name dir))))
709 ;; cd [dir]
710 (defun shell-process-cd (arg)
711 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
712 "~"))
713 ((string-equal "-" arg) shell-last-dir)
714 (t (shell-prefixed-directory-name arg)))))
715 (setq shell-last-dir default-directory)
716 (shell-cd new-dir)
717 (shell-dirstack-message)))
719 ;; pushd [+n | dir]
720 (defun shell-process-pushd (arg)
721 (let ((num (shell-extract-num arg)))
722 (cond ((zerop (length arg))
723 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
724 (cond (shell-pushd-tohome
725 (shell-process-pushd (concat comint-file-name-prefix "~")))
726 (shell-dirstack
727 (let ((old default-directory))
728 (shell-cd (car shell-dirstack))
729 (setq shell-dirstack (cons old (cdr shell-dirstack)))
730 (shell-dirstack-message)))
732 (message "Directory stack empty."))))
733 ((numberp num)
734 ;; pushd +n
735 (cond ((> num (length shell-dirstack))
736 (message "Directory stack not that deep."))
737 ((= num 0)
738 (error (message "Couldn't cd")))
739 (shell-pushd-dextract
740 (let ((dir (nth (1- num) shell-dirstack)))
741 (shell-process-popd arg)
742 (shell-process-pushd default-directory)
743 (shell-cd dir)
744 (shell-dirstack-message)))
746 (let* ((ds (cons default-directory shell-dirstack))
747 (dslen (length ds))
748 (front (nthcdr num ds))
749 (back (reverse (nthcdr (- dslen num) (reverse ds))))
750 (new-ds (append front back)))
751 (shell-cd (car new-ds))
752 (setq shell-dirstack (cdr new-ds))
753 (shell-dirstack-message)))))
755 ;; pushd <dir>
756 (let ((old-wd default-directory))
757 (shell-cd (shell-prefixed-directory-name arg))
758 (if (or (null shell-pushd-dunique)
759 (not (member old-wd shell-dirstack)))
760 (setq shell-dirstack (cons old-wd shell-dirstack)))
761 (shell-dirstack-message))))))
763 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
764 (defun shell-extract-num (str)
765 (and (string-match "^\\+[1-9][0-9]*$" str)
766 (string-to-number str)))
768 (defvaralias 'shell-dirtrack-mode 'shell-dirtrackp)
769 (define-minor-mode shell-dirtrack-mode
770 "Turn directory tracking on and off in a shell buffer."
771 nil nil nil
772 (setq list-buffers-directory (if shell-dirtrack-mode default-directory))
773 (if shell-dirtrack-mode
774 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
775 (remove-hook 'comint-input-filter-functions 'shell-directory-tracker t)))
777 ;; For your typing convenience:
778 (defalias 'shell-dirtrack-toggle 'shell-dirtrack-mode) ;??Convenience??
779 (defalias 'dirtrack-toggle 'shell-dirtrack-mode)
780 (defalias 'dirtrack-mode 'shell-dirtrack-mode)
782 (defun shell-cd (dir)
783 "Do normal `cd' to DIR, and set `list-buffers-directory'."
784 (cd dir)
785 (if shell-dirtrackp
786 (setq list-buffers-directory default-directory)))
788 (defun shell-resync-dirs ()
789 "Resync the buffer's idea of the current directory stack.
790 This command queries the shell with the command bound to
791 `shell-dirstack-query' (default \"dirs\"), reads the next
792 line output and parses it to form the new directory stack.
793 DON'T issue this command unless the buffer is at a shell prompt.
794 Also, note that if some other subprocess decides to do output
795 immediately after the query, its output will be taken as the
796 new directory stack -- you lose. If this happens, just do the
797 command again."
798 (interactive)
799 (let* ((proc (get-buffer-process (current-buffer)))
800 (pmark (process-mark proc)))
801 (goto-char pmark)
802 ;; If the process echoes commands, don't insert a fake command in
803 ;; the buffer or it will appear twice.
804 (unless comint-process-echoes
805 (insert shell-dirstack-query) (insert "\n"))
806 (sit-for 0) ; force redisplay
807 (comint-send-string proc shell-dirstack-query)
808 (comint-send-string proc "\n")
809 (set-marker pmark (point))
810 (let ((pt (point))
811 (regexp
812 (concat
813 (if comint-process-echoes
814 ;; Skip command echo if the process echoes
815 (concat "\\(" (regexp-quote shell-dirstack-query) "\n\\)")
816 "\\(\\)")
817 "\\(.+\n\\)")))
818 ;; This extra newline prevents the user's pending input from spoofing us.
819 (insert "\n") (backward-char 1)
820 ;; Wait for one line.
821 (while (not (looking-at regexp))
822 (accept-process-output proc)
823 (goto-char pt)))
824 (goto-char pmark) (delete-char 1) ; remove the extra newline
825 ;; That's the dirlist. grab it & parse it.
826 (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
827 (dl-len (length dl))
828 (ds '()) ; new dir stack
829 (i 0))
830 (while (< i dl-len)
831 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
832 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
833 (setq ds (cons (concat comint-file-name-prefix
834 (substring dl (match-beginning 1)
835 (match-end 1)))
836 ds))
837 (setq i (match-end 0)))
838 (let ((ds (nreverse ds)))
839 (condition-case nil
840 (progn (shell-cd (car ds))
841 (setq shell-dirstack (cdr ds)
842 shell-last-dir (car shell-dirstack))
843 (shell-dirstack-message))
844 (error (message "Couldn't cd")))))))
846 ;; For your typing convenience:
847 (defalias 'dirs 'shell-resync-dirs)
850 ;; Show the current dirstack on the message line.
851 ;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
852 ;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
853 ;; All the commands that mung the buffer's dirstack finish by calling
854 ;; this guy.
855 (defun shell-dirstack-message ()
856 (when shell-dirtrack-verbose
857 (let* ((msg "")
858 (ds (cons default-directory shell-dirstack))
859 (home (expand-file-name (concat comint-file-name-prefix "~/")))
860 (homelen (length home)))
861 (while ds
862 (let ((dir (car ds)))
863 (and (>= (length dir) homelen)
864 (string= home (substring dir 0 homelen))
865 (setq dir (concat "~/" (substring dir homelen))))
866 ;; Strip off comint-file-name-prefix if present.
867 (and comint-file-name-prefix
868 (>= (length dir) (length comint-file-name-prefix))
869 (string= comint-file-name-prefix
870 (substring dir 0 (length comint-file-name-prefix)))
871 (setq dir (substring dir (length comint-file-name-prefix)))
872 (setcar ds dir))
873 (setq msg (concat msg (directory-file-name dir) " "))
874 (setq ds (cdr ds))))
875 (message "%s" msg))))
877 ;; This was mostly copied from shell-resync-dirs.
878 (defun shell-snarf-envar (var)
879 "Return as a string the shell's value of environment variable VAR."
880 (let* ((cmd (format "printenv '%s'\n" var))
881 (proc (get-buffer-process (current-buffer)))
882 (pmark (process-mark proc)))
883 (goto-char pmark)
884 (insert cmd)
885 (sit-for 0) ; force redisplay
886 (comint-send-string proc cmd)
887 (set-marker pmark (point))
888 (let ((pt (point))) ; wait for 1 line
889 ;; This extra newline prevents the user's pending input from spoofing us.
890 (insert "\n") (backward-char 1)
891 (while (not (looking-at ".+\n"))
892 (accept-process-output proc)
893 (goto-char pt)))
894 (goto-char pmark) (delete-char 1) ; remove the extra newline
895 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
897 (defun shell-copy-environment-variable (variable)
898 "Copy the environment variable VARIABLE from the subshell to Emacs.
899 This command reads the value of the specified environment variable
900 in the shell, and sets the same environment variable in Emacs
901 \(what `getenv' in Emacs would return) to that value.
902 That value will affect any new subprocesses that you subsequently start
903 from Emacs."
904 (interactive (list (read-envvar-name "\
905 Copy Shell environment variable to Emacs: ")))
906 (setenv variable (shell-snarf-envar variable)))
908 (defun shell-forward-command (&optional arg)
909 "Move forward across ARG shell command(s). Does not cross lines.
910 See `shell-command-regexp'."
911 (interactive "p")
912 (let ((limit (save-excursion (end-of-line nil) (point))))
913 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
914 limit 'move arg)
915 (skip-syntax-backward " "))))
918 (defun shell-backward-command (&optional arg)
919 "Move backward across ARG shell command(s). Does not cross lines.
920 See `shell-command-regexp'."
921 (interactive "p")
922 (let ((limit (save-excursion (comint-bol nil) (point))))
923 (when (> limit (point))
924 (setq limit (line-beginning-position)))
925 (skip-syntax-backward " " limit)
926 (if (re-search-backward
927 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
928 (progn (goto-char (match-beginning 1))
929 (skip-chars-forward ";&|")))))
931 (defun shell-dynamic-complete-command ()
932 "Dynamically complete the command at point.
933 This function is similar to `comint-dynamic-complete-filename', except that it
934 searches `exec-path' (minus the trailing Emacs library path) for completion
935 candidates. Note that this may not be the same as the shell's idea of the
936 path.
938 Completion is dependent on the value of `shell-completion-execonly', plus
939 those that effect file completion. See `shell-dynamic-complete-as-command'.
941 Returns t if successful."
942 (interactive)
943 (let ((filename (comint-match-partial-filename)))
944 (if (and filename
945 (save-match-data (not (string-match "[~/]" filename)))
946 (eq (match-beginning 0)
947 (save-excursion (shell-backward-command 1) (point))))
948 (prog2 (message "Completing command name...")
949 (shell-dynamic-complete-as-command)))))
952 (defun shell-dynamic-complete-as-command ()
953 "Dynamically complete at point as a command.
954 See `shell-dynamic-complete-filename'. Returns t if successful."
955 (let* ((filename (or (comint-match-partial-filename) ""))
956 (filenondir (file-name-nondirectory filename))
957 (path-dirs (cdr (reverse exec-path)))
958 (cwd (file-name-as-directory (expand-file-name default-directory)))
959 (ignored-extensions
960 (and comint-completion-fignore
961 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
962 comint-completion-fignore "\\|")))
963 (dir "") (comps-in-dir ())
964 (file "") (abs-file-name "") (completions ()))
965 ;; Go thru each dir in the search path, finding completions.
966 (while path-dirs
967 (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
968 comps-in-dir (and (file-accessible-directory-p dir)
969 (file-name-all-completions filenondir dir)))
970 ;; Go thru each completion found, to see whether it should be used.
971 (while comps-in-dir
972 (setq file (car comps-in-dir)
973 abs-file-name (concat dir file))
974 (if (and (not (member file completions))
975 (not (and ignored-extensions
976 (string-match ignored-extensions file)))
977 (or (string-equal dir cwd)
978 (not (file-directory-p abs-file-name)))
979 (or (null shell-completion-execonly)
980 (file-executable-p abs-file-name)))
981 (setq completions (cons file completions)))
982 (setq comps-in-dir (cdr comps-in-dir)))
983 (setq path-dirs (cdr path-dirs)))
984 ;; OK, we've got a list of completions.
985 (let ((success (let ((comint-completion-addsuffix nil))
986 (comint-dynamic-simple-complete filenondir completions))))
987 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
988 (not (file-directory-p (comint-match-partial-filename))))
989 (insert " "))
990 success)))
993 (defun shell-match-partial-variable ()
994 "Return the shell variable at point, or nil if none is found."
995 (save-excursion
996 (let ((limit (point)))
997 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
998 (or (looking-at "\\$") (forward-char 1)))
999 ;; Anchor the search forwards.
1000 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
1002 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
1003 (buffer-substring (match-beginning 0) (match-end 0))))))
1006 (defun shell-dynamic-complete-environment-variable ()
1007 "Dynamically complete the environment variable at point.
1008 Completes if after a variable, i.e., if it starts with a \"$\".
1009 See `shell-dynamic-complete-as-environment-variable'.
1011 This function is similar to `comint-dynamic-complete-filename', except that it
1012 searches `process-environment' for completion candidates. Note that this may
1013 not be the same as the interpreter's idea of variable names. The main problem
1014 with this type of completion is that `process-environment' is the environment
1015 which Emacs started with. Emacs does not track changes to the environment made
1016 by the interpreter. Perhaps it would be more accurate if this function was
1017 called `shell-dynamic-complete-process-environment-variable'.
1019 Returns non-nil if successful."
1020 (interactive)
1021 (let ((variable (shell-match-partial-variable)))
1022 (if (and variable (string-match "^\\$" variable))
1023 (prog2 (message "Completing variable name...")
1024 (shell-dynamic-complete-as-environment-variable)))))
1027 (defun shell-dynamic-complete-as-environment-variable ()
1028 "Dynamically complete at point as an environment variable.
1029 Used by `shell-dynamic-complete-environment-variable'.
1030 Uses `comint-dynamic-simple-complete'."
1031 (let* ((var (or (shell-match-partial-variable) ""))
1032 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
1033 (variables (mapcar (function (lambda (x)
1034 (substring x 0 (string-match "=" x))))
1035 process-environment))
1036 (addsuffix comint-completion-addsuffix)
1037 (comint-completion-addsuffix nil)
1038 (success (comint-dynamic-simple-complete variable variables)))
1039 (if (memq success '(sole shortest))
1040 (let* ((var (shell-match-partial-variable))
1041 (variable (substring var (string-match "[^$({]" var)))
1042 (protection (cond ((string-match "{" var) "}")
1043 ((string-match "(" var) ")")
1044 (t "")))
1045 (suffix (cond ((null addsuffix) "")
1046 ((file-directory-p
1047 (comint-directory (getenv variable))) "/")
1048 (t " "))))
1049 (insert protection suffix)))
1050 success))
1053 (defun shell-replace-by-expanded-directory ()
1054 "Expand directory stack reference before point.
1055 Directory stack references are of the form \"=digit\" or \"=-\".
1056 See `default-directory' and `shell-dirstack'.
1058 Returns t if successful."
1059 (interactive)
1060 (if (comint-match-partial-filename)
1061 (save-excursion
1062 (goto-char (match-beginning 0))
1063 (let ((stack (cons default-directory shell-dirstack))
1064 (index (cond ((looking-at "=-/?")
1065 (length shell-dirstack))
1066 ((looking-at "=\\([0-9]+\\)/?")
1067 (string-to-number
1068 (buffer-substring
1069 (match-beginning 1) (match-end 1)))))))
1070 (cond ((null index)
1071 nil)
1072 ((>= index (length stack))
1073 (error "Directory stack not that deep"))
1075 (replace-match (file-name-as-directory (nth index stack)) t t)
1076 (message "Directory item: %d" index)
1077 t))))))
1079 (provide 'shell)
1081 ;; arch-tag: bcb5f12a-c1f4-4aea-a809-2504bd5bd797
1082 ;;; shell.el ends here