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