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