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