(follow-mode): Don't run hooks twice. Use `when'.
[bpt/emacs.git] / lisp / shell.el
1 ;;; shell.el --- specialized comint.el for running the shell
2
3 ;; Copyright (C) 1988, 1993, 1994, 1995, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
7 ;; Simon Marshall <simon@gnu.org>
8 ;; Maintainer: FSF <emacs-devel@gnu.org>
9 ;; Keywords: processes
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, 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 ;; 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.
34
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.
39
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.
43
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?
49
50 ;; YOUR .EMACS FILE
51 ;;=============================================================================
52 ;; Some suggestions for your .emacs file.
53 ;;
54 ;; ;; Define M-# to run some strange command:
55 ;; (eval-after-load "shell"
56 ;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
57
58 ;; Brief Command Documentation:
59 ;;============================================================================
60 ;; Comint Mode Commands: (common to shell and all comint-derived modes)
61 ;;
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.
82
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
93 ;;
94 ;; The shell mode hook is shell-mode-hook
95 ;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
96 ;; compatibility.
97
98 ;; Read the rest of this file for more information.
99
100 ;;; Code:
101
102 (require 'comint)
103
104 ;;; Customization and Buffer Variables
105
106 (defgroup shell nil
107 "Running shell from within Emacs buffers."
108 :group 'processes
109 :group 'unix)
110
111 (defgroup shell-directories nil
112 "Directory support in shell mode."
113 :group 'shell)
114
115 (defgroup shell-faces nil
116 "Faces in shell buffers."
117 :group 'shell)
118
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)
128
129 (defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
130 "Regexp to match prompts in the inferior shell.
131 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
132 This variable is used to initialize `comint-prompt-regexp' in the
133 shell buffer.
134
135 If `comint-use-prompt-regexp' is nil, then this variable is only used
136 to determine paragraph boundaries. See Info node `Shell Prompts' for
137 how Shell mode treats paragraphs.
138
139 The pattern should probably not match more than one line. If it does,
140 Shell mode may become confused trying to distinguish prompt from input
141 on lines which don't start with a prompt.
142
143 This is a fine thing to set in your `.emacs' file."
144 :type 'regexp
145 :group 'shell)
146
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 (\"~\" \"#\" \"%\").
152
153 This is a fine thing to set in your `.emacs' file."
154 :type '(repeat (string :tag "Suffix"))
155 :group 'shell)
156
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.
161
162 This is a fine thing to set in your `.emacs' file.")
163
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.
171
172 This is a fine thing to set in your `.emacs' file.")
173
174 (defvar shell-file-name-quote-list
175 (if (memq system-type '(ms-dos windows-nt))
176 nil
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.
181
182 This is a fine thing to set in your `.emacs' file.")
183
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.
193
194 This is a fine thing to set in your `.emacs' file.")
195
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)
201
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)
207
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.
211
212 Detecting executability of files may slow command completion considerably."
213 :type 'boolean
214 :group 'shell)
215
216 (defcustom shell-popd-regexp "popd"
217 "Regexp to match subshell commands equivalent to popd."
218 :type 'regexp
219 :group 'shell-directories)
220
221 (defcustom shell-pushd-regexp "pushd"
222 "Regexp to match subshell commands equivalent to pushd."
223 :type 'regexp
224 :group 'shell-directories)
225
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)
231
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)
237
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)
243
244 (defcustom shell-cd-regexp "cd"
245 "Regexp to match subshell commands equivalent to cd."
246 :type 'regexp
247 :group 'shell-directories)
248
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)
258
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)
264
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)
269
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)
282
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)
305
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).
309
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'.
314
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)
322
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.")
326
327 (defvar shell-dirtrackp t
328 "Non-nil in a shell buffer means directory tracking is enabled.")
329
330 (defvar shell-last-dir nil
331 "Keep track of last directory for ksh `cd -' command.")
332
333 (defvar shell-dirstack-query nil
334 "Command used by `shell-resync-dirs' to query the shell.")
335
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)))
355
356 (defcustom shell-mode-hook '()
357 "*Hook for customising Shell mode."
358 :type 'hook
359 :group 'shell)
360
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.")
366
367 ;;; Basic Procedures
368
369 (put 'shell-mode 'mode-class 'special)
370
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'.
380
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.
383
384 If you want to make shell buffers limited in length, add the function
385 `comint-truncate-buffer' to `comint-output-filter-functions'.
386
387 If you accidentally suspend your process, use \\[comint-continue-subjob]
388 to continue it.
389
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.
397
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.
403
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.
408
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'.
415
416 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
417 the initialization of the input ring history, and history expansion.
418
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)))
473
474 (defun shell-filter-ctrl-a-ctrl-b (string)
475 "Remove `^A' and `^B' characters from comint output.
476
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.
483
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 "")))))
493
494 (defun shell-write-history-on-exit (process event)
495 "Called when the shell process is stopped.
496
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.
500
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))))))
509
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 `default-directory' is a remote file name, it is also prompted
515 to change if called with a prefix arg.
516
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 (if that is nil) from `shell-file-name'.
522 If a file `~/.emacs_SHELLNAME' exists, or `~/.emacs.d/init_SHELLNAME.sh',
523 it is given as initial input (but this may be lost, due to a timing
524 error, if the shell 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 (prog1
546 (read-buffer "Shell buffer: "
547 (generate-new-buffer-name "*shell*"))
548 (if (file-remote-p default-directory)
549 ;; It must be possible to declare a local default-directory.
550 (setq default-directory
551 (expand-file-name
552 (read-file-name
553 "Default directory: " default-directory default-directory
554 t nil 'file-directory-p))))))))
555 (setq buffer (get-buffer-create (or buffer "*shell*")))
556 ;; Pop to buffer, so that the buffer's window will be correctly set
557 ;; when we call comint (so that comint sets the COLUMNS env var properly).
558 (pop-to-buffer buffer)
559 (unless (comint-check-proc buffer)
560 (let* ((prog (or explicit-shell-file-name
561 (getenv "ESHELL") shell-file-name))
562 (name (file-name-nondirectory prog))
563 (startfile (concat "~/.emacs_" name))
564 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
565 (unless (file-exists-p startfile)
566 (setq startfile (concat user-emacs-directory "init_" name ".sh")))
567 (apply 'make-comint-in-buffer "shell" buffer prog
568 (if (file-exists-p startfile) startfile)
569 (if (and xargs-name (boundp xargs-name))
570 (symbol-value xargs-name)
571 '("-i")))
572 (shell-mode)))
573 buffer)
574
575 ;; Don't do this when shell.el is loaded, only while dumping.
576 ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
577
578 ;;; Directory tracking
579 ;;
580 ;; This code provides the shell mode input sentinel
581 ;; SHELL-DIRECTORY-TRACKER
582 ;; that tracks cd, pushd, and popd commands issued to the shell, and
583 ;; changes the current directory of the shell buffer accordingly.
584 ;;
585 ;; This is basically a fragile hack, although it's more accurate than
586 ;; the version in Emacs 18's shell.el. It has the following failings:
587 ;; 1. It doesn't know about the cdpath shell variable.
588 ;; 2. It cannot infallibly deal with command sequences, though it does well
589 ;; with these and with ignoring commands forked in another shell with ()s.
590 ;; 3. More generally, any complex command is going to throw it. Otherwise,
591 ;; you'd have to build an entire shell interpreter in Emacs Lisp. Failing
592 ;; that, there's no way to catch shell commands where cd's are buried
593 ;; inside conditional expressions, aliases, and so forth.
594 ;;
595 ;; The whole approach is a crock. Shell aliases mess it up. File sourcing
596 ;; messes it up. You run other processes under the shell; these each have
597 ;; separate working directories, and some have commands for manipulating
598 ;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
599 ;; commands that do *not* affect the current w.d. at all, but look like they
600 ;; do (e.g., the cd command in ftp). In shells that allow you job
601 ;; control, you can switch between jobs, all having different w.d.'s. So
602 ;; simply saying %3 can shift your w.d..
603 ;;
604 ;; The solution is to relax, not stress out about it, and settle for
605 ;; a hack that works pretty well in typical circumstances. Remember
606 ;; that a half-assed solution is more in keeping with the spirit of Unix,
607 ;; anyway. Blech.
608 ;;
609 ;; One good hack not implemented here for users of programmable shells
610 ;; is to program up the shell w.d. manipulation commands to output
611 ;; a coded command sequence to the tty. Something like
612 ;; ESC | <cwd> |
613 ;; where <cwd> is the new current working directory. Then trash the
614 ;; directory tracking machinery currently used in this package, and
615 ;; replace it with a process filter that watches for and strips out
616 ;; these messages.
617
618 (defun shell-directory-tracker (str)
619 "Tracks cd, pushd and popd commands issued to the shell.
620 This function is called on each input passed to the shell.
621 It watches for cd, pushd and popd commands and sets the buffer's
622 default directory to track these commands.
623
624 You may toggle this tracking on and off with \\[dirtrack-mode].
625 If Emacs gets confused, you can resync with the shell with \\[dirs].
626
627 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
628 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
629 and `shell-pushd-dunique' control the behavior of the relevant command.
630
631 Environment variables are expanded, see function `substitute-in-file-name'."
632 (if shell-dirtrackp
633 ;; We fail gracefully if we think the command will fail in the shell.
634 (condition-case chdir-failure
635 (let ((start (progn (string-match
636 (concat "^" shell-command-separator-regexp)
637 str) ; skip whitespace
638 (match-end 0)))
639 end cmd arg1)
640 (while (string-match shell-command-regexp str start)
641 (setq end (match-end 0)
642 cmd (comint-arguments (substring str start end) 0 0)
643 arg1 (comint-arguments (substring str start end) 1 1))
644 (if arg1
645 (setq arg1 (shell-unquote-argument arg1)))
646 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
647 "\\)\\($\\|[ \t]\\)")
648 cmd)
649 (shell-process-popd (comint-substitute-in-file-name arg1)))
650 ((string-match (concat "\\`\\(" shell-pushd-regexp
651 "\\)\\($\\|[ \t]\\)")
652 cmd)
653 (shell-process-pushd (comint-substitute-in-file-name arg1)))
654 ((string-match (concat "\\`\\(" shell-cd-regexp
655 "\\)\\($\\|[ \t]\\)")
656 cmd)
657 (shell-process-cd (comint-substitute-in-file-name arg1)))
658 ((and shell-chdrive-regexp
659 (string-match (concat "\\`\\(" shell-chdrive-regexp
660 "\\)\\($\\|[ \t]\\)")
661 cmd))
662 (shell-process-cd (comint-substitute-in-file-name cmd))))
663 (setq start (progn (string-match shell-command-separator-regexp
664 str end)
665 ;; skip again
666 (match-end 0)))))
667 (error "Couldn't cd"))))
668
669 (defun shell-unquote-argument (string)
670 "Remove all kinds of shell quoting from STRING."
671 (save-match-data
672 (let ((idx 0) next inside
673 (quote-chars
674 (if (string-match shell-dumb-shell-regexp
675 (file-name-nondirectory
676 (car (process-command (get-buffer-process (current-buffer))))))
677 "['`\"]"
678 "[\\'`\"]")))
679 (while (and (< idx (length string))
680 (setq next (string-match quote-chars string next)))
681 (cond ((= (aref string next) ?\\)
682 (setq string (replace-match "" nil nil string))
683 (setq next (1+ next)))
684 ((and inside (= (aref string next) inside))
685 (setq string (replace-match "" nil nil string))
686 (setq inside nil))
687 (inside
688 (setq next (1+ next)))
689 (t
690 (setq inside (aref string next))
691 (setq string (replace-match "" nil nil string)))))
692 string)))
693
694 ;; popd [+n]
695 (defun shell-process-popd (arg)
696 (let ((num (or (shell-extract-num arg) 0)))
697 (cond ((and num (= num 0) shell-dirstack)
698 (shell-cd (car shell-dirstack))
699 (setq shell-dirstack (cdr shell-dirstack))
700 (shell-dirstack-message))
701 ((and num (> num 0) (<= num (length shell-dirstack)))
702 (let* ((ds (cons nil shell-dirstack))
703 (cell (nthcdr (1- num) ds)))
704 (rplacd cell (cdr (cdr cell)))
705 (setq shell-dirstack (cdr ds))
706 (shell-dirstack-message)))
707 (t
708 (error "Couldn't popd")))))
709
710 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
711 (defun shell-prefixed-directory-name (dir)
712 (if (= (length comint-file-name-prefix) 0)
713 dir
714 (if (file-name-absolute-p dir)
715 ;; The name is absolute, so prepend the prefix.
716 (concat comint-file-name-prefix dir)
717 ;; For relative name we assume default-directory already has the prefix.
718 (expand-file-name dir))))
719
720 ;; cd [dir]
721 (defun shell-process-cd (arg)
722 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
723 "~"))
724 ((string-equal "-" arg) shell-last-dir)
725 (t (shell-prefixed-directory-name arg)))))
726 (setq shell-last-dir default-directory)
727 (shell-cd new-dir)
728 (shell-dirstack-message)))
729
730 ;; pushd [+n | dir]
731 (defun shell-process-pushd (arg)
732 (let ((num (shell-extract-num arg)))
733 (cond ((zerop (length arg))
734 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
735 (cond (shell-pushd-tohome
736 (shell-process-pushd (concat comint-file-name-prefix "~")))
737 (shell-dirstack
738 (let ((old default-directory))
739 (shell-cd (car shell-dirstack))
740 (setq shell-dirstack (cons old (cdr shell-dirstack)))
741 (shell-dirstack-message)))
742 (t
743 (message "Directory stack empty."))))
744 ((numberp num)
745 ;; pushd +n
746 (cond ((> num (length shell-dirstack))
747 (message "Directory stack not that deep."))
748 ((= num 0)
749 (error (message "Couldn't cd")))
750 (shell-pushd-dextract
751 (let ((dir (nth (1- num) shell-dirstack)))
752 (shell-process-popd arg)
753 (shell-process-pushd default-directory)
754 (shell-cd dir)
755 (shell-dirstack-message)))
756 (t
757 (let* ((ds (cons default-directory shell-dirstack))
758 (dslen (length ds))
759 (front (nthcdr num ds))
760 (back (reverse (nthcdr (- dslen num) (reverse ds))))
761 (new-ds (append front back)))
762 (shell-cd (car new-ds))
763 (setq shell-dirstack (cdr new-ds))
764 (shell-dirstack-message)))))
765 (t
766 ;; pushd <dir>
767 (let ((old-wd default-directory))
768 (shell-cd (shell-prefixed-directory-name arg))
769 (if (or (null shell-pushd-dunique)
770 (not (member old-wd shell-dirstack)))
771 (setq shell-dirstack (cons old-wd shell-dirstack)))
772 (shell-dirstack-message))))))
773
774 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
775 (defun shell-extract-num (str)
776 (and (string-match "^\\+[1-9][0-9]*$" str)
777 (string-to-number str)))
778
779 (defvaralias 'shell-dirtrack-mode 'shell-dirtrackp)
780 (define-minor-mode shell-dirtrack-mode
781 "Turn directory tracking on and off in a shell buffer."
782 nil nil nil
783 (setq list-buffers-directory (if shell-dirtrack-mode default-directory))
784 (if shell-dirtrack-mode
785 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
786 (remove-hook 'comint-input-filter-functions 'shell-directory-tracker t)))
787
788 ;; For your typing convenience:
789 (defalias 'shell-dirtrack-toggle 'shell-dirtrack-mode) ;??Convenience??
790 (defalias 'dirtrack-toggle 'shell-dirtrack-mode)
791 (defalias 'dirtrack-mode 'shell-dirtrack-mode)
792
793 (defun shell-cd (dir)
794 "Do normal `cd' to DIR, and set `list-buffers-directory'."
795 (cd dir)
796 (if shell-dirtrackp
797 (setq list-buffers-directory default-directory)))
798
799 (defun shell-resync-dirs ()
800 "Resync the buffer's idea of the current directory stack.
801 This command queries the shell with the command bound to
802 `shell-dirstack-query' (default \"dirs\"), reads the next
803 line output and parses it to form the new directory stack.
804 DON'T issue this command unless the buffer is at a shell prompt.
805 Also, note that if some other subprocess decides to do output
806 immediately after the query, its output will be taken as the
807 new directory stack -- you lose. If this happens, just do the
808 command again."
809 (interactive)
810 (let* ((proc (get-buffer-process (current-buffer)))
811 (pmark (process-mark proc))
812 (started-at-pmark (= (point) (marker-position pmark))))
813 (save-excursion
814 (goto-char pmark)
815 ;; If the process echoes commands, don't insert a fake command in
816 ;; the buffer or it will appear twice.
817 (unless comint-process-echoes
818 (insert shell-dirstack-query) (insert "\n"))
819 (sit-for 0) ; force redisplay
820 (comint-send-string proc shell-dirstack-query)
821 (comint-send-string proc "\n")
822 (set-marker pmark (point))
823 (let ((pt (point))
824 (regexp
825 (concat
826 (if comint-process-echoes
827 ;; Skip command echo if the process echoes
828 (concat "\\(" (regexp-quote shell-dirstack-query) "\n\\)")
829 "\\(\\)")
830 "\\(.+\n\\)")))
831 ;; This extra newline prevents the user's pending input from spoofing us.
832 (insert "\n") (backward-char 1)
833 ;; Wait for one line.
834 (while (not (looking-at regexp))
835 (accept-process-output proc)
836 (goto-char pt)))
837 (goto-char pmark) (delete-char 1) ; remove the extra newline
838 ;; That's the dirlist. grab it & parse it.
839 (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
840 (dl-len (length dl))
841 (ds '()) ; new dir stack
842 (i 0))
843 (while (< i dl-len)
844 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
845 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
846 (setq ds (cons (concat comint-file-name-prefix
847 (substring dl (match-beginning 1)
848 (match-end 1)))
849 ds))
850 (setq i (match-end 0)))
851 (let ((ds (nreverse ds)))
852 (condition-case nil
853 (progn (shell-cd (car ds))
854 (setq shell-dirstack (cdr ds)
855 shell-last-dir (car shell-dirstack))
856 (shell-dirstack-message))
857 (error (message "Couldn't cd"))))))
858 (if started-at-pmark (goto-char (marker-position pmark)))))
859
860 ;; For your typing convenience:
861 (defalias 'dirs 'shell-resync-dirs)
862
863
864 ;; Show the current dirstack on the message line.
865 ;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
866 ;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
867 ;; All the commands that mung the buffer's dirstack finish by calling
868 ;; this guy.
869 (defun shell-dirstack-message ()
870 (when shell-dirtrack-verbose
871 (let* ((msg "")
872 (ds (cons default-directory shell-dirstack))
873 (home (expand-file-name (concat comint-file-name-prefix "~/")))
874 (homelen (length home)))
875 (while ds
876 (let ((dir (car ds)))
877 (and (>= (length dir) homelen)
878 (string= home (substring dir 0 homelen))
879 (setq dir (concat "~/" (substring dir homelen))))
880 ;; Strip off comint-file-name-prefix if present.
881 (and comint-file-name-prefix
882 (>= (length dir) (length comint-file-name-prefix))
883 (string= comint-file-name-prefix
884 (substring dir 0 (length comint-file-name-prefix)))
885 (setq dir (substring dir (length comint-file-name-prefix)))
886 (setcar ds dir))
887 (setq msg (concat msg (directory-file-name dir) " "))
888 (setq ds (cdr ds))))
889 (message "%s" msg))))
890
891 ;; This was mostly copied from shell-resync-dirs.
892 (defun shell-snarf-envar (var)
893 "Return as a string the shell's value of environment variable VAR."
894 (let* ((cmd (format "printenv '%s'\n" var))
895 (proc (get-buffer-process (current-buffer)))
896 (pmark (process-mark proc)))
897 (goto-char pmark)
898 (insert cmd)
899 (sit-for 0) ; force redisplay
900 (comint-send-string proc cmd)
901 (set-marker pmark (point))
902 (let ((pt (point))) ; wait for 1 line
903 ;; This extra newline prevents the user's pending input from spoofing us.
904 (insert "\n") (backward-char 1)
905 (while (not (looking-at ".+\n"))
906 (accept-process-output proc)
907 (goto-char pt)))
908 (goto-char pmark) (delete-char 1) ; remove the extra newline
909 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
910
911 (defun shell-copy-environment-variable (variable)
912 "Copy the environment variable VARIABLE from the subshell to Emacs.
913 This command reads the value of the specified environment variable
914 in the shell, and sets the same environment variable in Emacs
915 \(what `getenv' in Emacs would return) to that value.
916 That value will affect any new subprocesses that you subsequently start
917 from Emacs."
918 (interactive (list (read-envvar-name "\
919 Copy Shell environment variable to Emacs: ")))
920 (setenv variable (shell-snarf-envar variable)))
921
922 (defun shell-forward-command (&optional arg)
923 "Move forward across ARG shell command(s). Does not cross lines.
924 See `shell-command-regexp'."
925 (interactive "p")
926 (let ((limit (save-excursion (end-of-line nil) (point))))
927 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
928 limit 'move arg)
929 (skip-syntax-backward " "))))
930
931
932 (defun shell-backward-command (&optional arg)
933 "Move backward across ARG shell command(s). Does not cross lines.
934 See `shell-command-regexp'."
935 (interactive "p")
936 (let ((limit (save-excursion (comint-bol nil) (point))))
937 (when (> limit (point))
938 (setq limit (line-beginning-position)))
939 (skip-syntax-backward " " limit)
940 (if (re-search-backward
941 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
942 (progn (goto-char (match-beginning 1))
943 (skip-chars-forward ";&|")))))
944
945 (defun shell-dynamic-complete-command ()
946 "Dynamically complete the command at point.
947 This function is similar to `comint-dynamic-complete-filename', except that it
948 searches `exec-path' (minus the trailing Emacs library path) for completion
949 candidates. Note that this may not be the same as the shell's idea of the
950 path.
951
952 Completion is dependent on the value of `shell-completion-execonly', plus
953 those that effect file completion. See `shell-dynamic-complete-as-command'.
954
955 Returns t if successful."
956 (interactive)
957 (let ((filename (comint-match-partial-filename)))
958 (if (and filename
959 (save-match-data (not (string-match "[~/]" filename)))
960 (eq (match-beginning 0)
961 (save-excursion (shell-backward-command 1) (point))))
962 (prog2 (message "Completing command name...")
963 (shell-dynamic-complete-as-command)))))
964
965
966 (defun shell-dynamic-complete-as-command ()
967 "Dynamically complete at point as a command.
968 See `shell-dynamic-complete-filename'. Returns t if successful."
969 (let* ((filename (or (comint-match-partial-filename) ""))
970 (filenondir (file-name-nondirectory filename))
971 (path-dirs (cdr (reverse exec-path)))
972 (cwd (file-name-as-directory (expand-file-name default-directory)))
973 (ignored-extensions
974 (and comint-completion-fignore
975 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
976 comint-completion-fignore "\\|")))
977 (dir "") (comps-in-dir ())
978 (file "") (abs-file-name "") (completions ()))
979 ;; Go thru each dir in the search path, finding completions.
980 (while path-dirs
981 (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
982 comps-in-dir (and (file-accessible-directory-p dir)
983 (file-name-all-completions filenondir dir)))
984 ;; Go thru each completion found, to see whether it should be used.
985 (while comps-in-dir
986 (setq file (car comps-in-dir)
987 abs-file-name (concat dir file))
988 (if (and (not (member file completions))
989 (not (and ignored-extensions
990 (string-match ignored-extensions file)))
991 (or (string-equal dir cwd)
992 (not (file-directory-p abs-file-name)))
993 (or (null shell-completion-execonly)
994 (file-executable-p abs-file-name)))
995 (setq completions (cons file completions)))
996 (setq comps-in-dir (cdr comps-in-dir)))
997 (setq path-dirs (cdr path-dirs)))
998 ;; OK, we've got a list of completions.
999 (let ((success (let ((comint-completion-addsuffix nil))
1000 (comint-dynamic-simple-complete filenondir completions))))
1001 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
1002 (not (file-directory-p (comint-match-partial-filename))))
1003 (insert " "))
1004 success)))
1005
1006
1007 (defun shell-match-partial-variable ()
1008 "Return the shell variable at point, or nil if none is found."
1009 (save-excursion
1010 (let ((limit (point)))
1011 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
1012 (or (looking-at "\\$") (forward-char 1)))
1013 ;; Anchor the search forwards.
1014 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
1015 nil
1016 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
1017 (buffer-substring (match-beginning 0) (match-end 0))))))
1018
1019
1020 (defun shell-dynamic-complete-environment-variable ()
1021 "Dynamically complete the environment variable at point.
1022 Completes if after a variable, i.e., if it starts with a \"$\".
1023 See `shell-dynamic-complete-as-environment-variable'.
1024
1025 This function is similar to `comint-dynamic-complete-filename', except that it
1026 searches `process-environment' for completion candidates. Note that this may
1027 not be the same as the interpreter's idea of variable names. The main problem
1028 with this type of completion is that `process-environment' is the environment
1029 which Emacs started with. Emacs does not track changes to the environment made
1030 by the interpreter. Perhaps it would be more accurate if this function was
1031 called `shell-dynamic-complete-process-environment-variable'.
1032
1033 Returns non-nil if successful."
1034 (interactive)
1035 (let ((variable (shell-match-partial-variable)))
1036 (if (and variable (string-match "^\\$" variable))
1037 (prog2 (message "Completing variable name...")
1038 (shell-dynamic-complete-as-environment-variable)))))
1039
1040
1041 (defun shell-dynamic-complete-as-environment-variable ()
1042 "Dynamically complete at point as an environment variable.
1043 Used by `shell-dynamic-complete-environment-variable'.
1044 Uses `comint-dynamic-simple-complete'."
1045 (let* ((var (or (shell-match-partial-variable) ""))
1046 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
1047 (variables (mapcar (function (lambda (x)
1048 (substring x 0 (string-match "=" x))))
1049 process-environment))
1050 (addsuffix comint-completion-addsuffix)
1051 (comint-completion-addsuffix nil)
1052 (success (comint-dynamic-simple-complete variable variables)))
1053 (if (memq success '(sole shortest))
1054 (let* ((var (shell-match-partial-variable))
1055 (variable (substring var (string-match "[^$({]" var)))
1056 (protection (cond ((string-match "{" var) "}")
1057 ((string-match "(" var) ")")
1058 (t "")))
1059 (suffix (cond ((null addsuffix) "")
1060 ((file-directory-p
1061 (comint-directory (getenv variable))) "/")
1062 (t " "))))
1063 (insert protection suffix)))
1064 success))
1065
1066
1067 (defun shell-replace-by-expanded-directory ()
1068 "Expand directory stack reference before point.
1069 Directory stack references are of the form \"=digit\" or \"=-\".
1070 See `default-directory' and `shell-dirstack'.
1071
1072 Returns t if successful."
1073 (interactive)
1074 (if (comint-match-partial-filename)
1075 (save-excursion
1076 (goto-char (match-beginning 0))
1077 (let ((stack (cons default-directory shell-dirstack))
1078 (index (cond ((looking-at "=-/?")
1079 (length shell-dirstack))
1080 ((looking-at "=\\([0-9]+\\)/?")
1081 (string-to-number
1082 (buffer-substring
1083 (match-beginning 1) (match-end 1)))))))
1084 (cond ((null index)
1085 nil)
1086 ((>= index (length stack))
1087 (error "Directory stack not that deep"))
1088 (t
1089 (replace-match (file-name-as-directory (nth index stack)) t t)
1090 (message "Directory item: %d" index)
1091 t))))))
1092
1093 (provide 'shell)
1094
1095 ;; arch-tag: bcb5f12a-c1f4-4aea-a809-2504bd5bd797
1096 ;;; shell.el ends here