(unload-feature): Typo.
[emacs.git] / lisp / shell.el
blobb93fe57402f3cdcf0bcda4632939e3430aa4d87a
1 ;;; shell.el --- specialized comint.el for running the shell.
3 ;; Copyright (C) 1988, 93, 94, 95, 96, 1997 Free Software Foundation, Inc.
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu> then
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 a shell-in-a-buffer package (shell mode) built
35 ;; on top of comint mode. This is actually cmushell with things
36 ;; renamed 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-prompt-pattern "^[^#$%>\n]*[#$%>] *"
125 "Regexp to match prompts in the inferior shell.
126 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
127 This variable is used to initialise `comint-prompt-regexp' in the
128 shell buffer.
130 This variable is only used if the variable
131 `comint-use-prompt-regexp-instead-of-fields' is non-nil.
133 The pattern should probably not match more than one line. If it does,
134 Shell mode may become confused trying to distinguish prompt from input
135 on lines which don't start with a prompt.
137 This is a fine thing to set in your `.emacs' file."
138 :type 'regexp
139 :group 'shell)
141 (defcustom shell-completion-fignore nil
142 "*List of suffixes to be disregarded during file/command completion.
143 This variable is used to initialize `comint-completion-fignore' in the shell
144 buffer. The default is nil, for compatibility with most shells.
145 Some people like (\"~\" \"#\" \"%\").
147 This is a fine thing to set in your `.emacs' file."
148 :type '(repeat (string :tag "Suffix"))
149 :group 'shell)
151 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
152 "List of characters to recognise as separate arguments.
153 This variable is used to initialize `comint-delimiter-argument-list' in the
154 shell buffer. The value may depend on the operating system or shell.
156 This is a fine thing to set in your `.emacs' file.")
158 (defvar shell-file-name-chars
159 (if (memq system-type '(ms-dos windows-nt))
160 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
161 "~/A-Za-z0-9+@:_.$#%,={}-")
162 "String of characters valid in a file name.
163 This variable is used to initialize `comint-file-name-chars' in the
164 shell buffer. The value may depend on the operating system or shell.
166 This is a fine thing to set in your `.emacs' file.")
168 (defvar shell-file-name-quote-list
169 (if (memq system-type '(ms-dos windows-nt))
171 (append shell-delimiter-argument-list '(?\ ?\* ?\! ?\" ?\' ?\` ?\#)))
172 "List of characters to quote when in a file name.
173 This variable is used to initialize `comint-file-name-quote-list' in the
174 shell buffer. The value may depend on the operating system or shell.
176 This is a fine thing to set in your `.emacs' file.")
178 (defvar shell-dynamic-complete-functions
179 '(comint-replace-by-expanded-history
180 shell-dynamic-complete-environment-variable
181 shell-dynamic-complete-command
182 shell-replace-by-expanded-directory
183 comint-dynamic-complete-filename)
184 "List of functions called to perform completion.
185 This variable is used to initialise `comint-dynamic-complete-functions' in the
186 shell buffer.
188 This is a fine thing to set in your `.emacs' file.")
190 (defcustom shell-command-regexp "[^;&|\n]+"
191 "*Regexp to match a single command within a pipeline.
192 This is used for directory tracking and does not do a perfect job."
193 :type 'regexp
194 :group 'shell)
196 (defcustom shell-completion-execonly t
197 "*If non-nil, use executable files only for completion candidates.
198 This mirrors the optional behavior of tcsh.
200 Detecting executability of files may slow command completion considerably."
201 :type 'boolean
202 :group 'shell)
204 (defcustom shell-popd-regexp "popd"
205 "*Regexp to match subshell commands equivalent to popd."
206 :type 'regexp
207 :group 'shell-directories)
209 (defcustom shell-pushd-regexp "pushd"
210 "*Regexp to match subshell commands equivalent to pushd."
211 :type 'regexp
212 :group 'shell-directories)
214 (defcustom shell-pushd-tohome nil
215 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
216 This mirrors the optional behavior of tcsh."
217 :type 'boolean
218 :group 'shell-directories)
220 (defcustom shell-pushd-dextract nil
221 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
222 This mirrors the optional behavior of tcsh."
223 :type 'boolean
224 :group 'shell-directories)
226 (defcustom shell-pushd-dunique nil
227 "*If non-nil, make pushd only add unique directories to the stack.
228 This mirrors the optional behavior of tcsh."
229 :type 'boolean
230 :group 'shell-directories)
232 (defcustom shell-cd-regexp "cd"
233 "*Regexp to match subshell commands equivalent to cd."
234 :type 'regexp
235 :group 'shell-directories)
237 (defcustom shell-chdrive-regexp
238 (if (memq system-type '(ms-dos windows-nt))
239 ; NetWare allows the five chars between upper and lower alphabetics.
240 "[]a-zA-Z^_`\\[\\\\]:"
241 nil)
242 "*If non-nil, is regexp used to track drive changes."
243 :type '(choice regexp
244 (const nil))
245 :group 'shell-directories)
247 (defcustom shell-dirtrack-verbose t
248 "*If non-nil, show the directory stack following directory change.
249 This is effective only if directory tracking is enabled."
250 :type 'boolean
251 :group 'shell-directories)
253 (defcustom explicit-shell-file-name nil
254 "*If non-nil, is file name to use for explicitly requested inferior shell."
255 :type '(choice (const :tag "None" nil) file)
256 :group 'shell)
258 (defcustom explicit-csh-args
259 (if (eq system-type 'hpux)
260 ;; -T persuades HP's csh not to think it is smarter
261 ;; than us about what terminal modes to use.
262 '("-i" "-T")
263 '("-i"))
264 "*Args passed to inferior shell by M-x shell, if the shell is csh.
265 Value is a list of strings, which may be nil."
266 :type '(repeat (string :tag "Argument"))
267 :group 'shell)
269 (defcustom shell-input-autoexpand 'history
270 "*If non-nil, expand input command history references on completion.
271 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
273 If the value is `input', then the expansion is seen on input.
274 If the value is `history', then the expansion is only when inserting
275 into the buffer's input ring. See also `comint-magic-space' and
276 `comint-dynamic-complete'.
278 This variable supplies a default for `comint-input-autoexpand',
279 for Shell mode only."
280 :type '(choice (const :tag "off" nil)
281 (const input)
282 (const history)
283 (const :tag "on" t))
284 :group 'shell)
286 (defvar shell-dirstack nil
287 "List of directories saved by pushd in this buffer's shell.
288 Thus, this does not include the shell's current directory.")
290 (defvar shell-dirtrackp t
291 "Non-nil in a shell buffer means directory tracking is enabled.")
293 (defvar shell-last-dir nil
294 "Keep track of last directory for ksh `cd -' command.")
296 (defvar shell-dirstack-query nil
297 "Command used by `shell-resync-dir' to query the shell.")
299 (defvar shell-mode-map nil)
300 (cond ((not shell-mode-map)
301 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
302 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
303 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
304 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
305 (define-key shell-mode-map "\M-?"
306 'comint-dynamic-list-filename-completions)
307 (define-key shell-mode-map [menu-bar completion]
308 (copy-keymap (lookup-key comint-mode-map [menu-bar completion])))
309 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
310 [complete-env-variable] '("Complete Env. Variable Name" .
311 shell-dynamic-complete-environment-variable)
312 'complete-file)
313 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
314 [expand-directory] '("Expand Directory Reference" .
315 shell-replace-by-expanded-directory)
316 'complete-expand)))
318 (defcustom shell-mode-hook '()
319 "*Hook for customising Shell mode."
320 :type 'hook
321 :group 'shell)
323 (defvar shell-font-lock-keywords
324 '((eval . (cons shell-prompt-pattern 'font-lock-warning-face))
325 ("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
326 ("^[^ \t\n]+:.*" . font-lock-string-face)
327 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
328 "Additional expressions to highlight in Shell mode.")
330 ;;; Basic Procedures
332 (put 'shell-mode 'mode-class 'special)
334 (defun shell-mode ()
335 "Major mode for interacting with an inferior shell.
336 \\[comint-send-input] after the end of the process' output sends the text from
337 the end of process to the end of the current line.
338 \\[comint-send-input] before end of process output copies the current line minus the prompt to
339 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
340 \\[send-invisible] reads a line of text without echoing it, and sends it to
341 the shell. This is useful for entering passwords. Or, add the function
342 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
344 If you want to make multiple shell buffers, rename the `*shell*' buffer
345 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
347 If you want to make shell buffers limited in length, add the function
348 `comint-truncate-buffer' to `comint-output-filter-functions'.
350 If you accidentally suspend your process, use \\[comint-continue-subjob]
351 to continue it.
353 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
354 keep this buffer's default directory the same as the shell's working directory.
355 While directory tracking is enabled, the shell's working directory is displayed
356 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
357 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
358 directory stack is.
359 \\[dirtrack-mode] turns directory tracking on and off.
361 \\{shell-mode-map}
362 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
363 `shell-mode-hook' (in that order). Before each input, the hooks on
364 `comint-input-filter-functions' are run. After each shell output, the hooks
365 on `comint-output-filter-functions' are run.
367 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
368 and `shell-popd-regexp' are used to match their respective commands,
369 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
370 control the behavior of the relevant command.
372 Variables `comint-completion-autolist', `comint-completion-addsuffix',
373 `comint-completion-recexact' and `comint-completion-fignore' control the
374 behavior of file name, command name and variable name completion. Variable
375 `shell-completion-execonly' controls the behavior of command name completion.
376 Variable `shell-completion-fignore' is used to initialise the value of
377 `comint-completion-fignore'.
379 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
380 the initialisation of the input ring history, and history expansion.
382 Variables `comint-output-filter-functions', a hook, and
383 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
384 control whether input and output cause the window to scroll to the end of the
385 buffer."
386 (interactive)
387 (comint-mode)
388 (setq major-mode 'shell-mode)
389 (setq mode-name "Shell")
390 (use-local-map shell-mode-map)
391 (setq comint-prompt-regexp shell-prompt-pattern)
392 (setq comint-completion-fignore shell-completion-fignore)
393 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
394 (setq comint-file-name-chars shell-file-name-chars)
395 (setq comint-file-name-quote-list shell-file-name-quote-list)
396 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
397 (make-local-variable 'paragraph-start)
398 (setq paragraph-start comint-prompt-regexp)
399 (make-local-variable 'font-lock-defaults)
400 (setq font-lock-defaults '(shell-font-lock-keywords t))
401 (make-local-variable 'shell-dirstack)
402 (setq shell-dirstack nil)
403 (make-local-variable 'shell-last-dir)
404 (setq shell-last-dir nil)
405 (make-local-variable 'shell-dirtrackp)
406 (setq shell-dirtrackp t)
407 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
408 (setq comint-input-autoexpand shell-input-autoexpand)
409 ;; This is not really correct, since the shell buffer does not really
410 ;; edit this directory. But it is useful in the buffer list and menus.
411 (make-local-variable 'list-buffers-directory)
412 (setq list-buffers-directory (expand-file-name default-directory))
413 ;; shell-dependent assignments.
414 (let ((shell (file-name-nondirectory (car
415 (process-command (get-buffer-process (current-buffer)))))))
416 (setq comint-input-ring-file-name
417 (or (getenv "HISTFILE")
418 (cond ((string-equal shell "bash") "~/.bash_history")
419 ((string-equal shell "ksh") "~/.sh_history")
420 (t "~/.history"))))
421 (if (or (equal comint-input-ring-file-name "")
422 (equal (file-truename comint-input-ring-file-name)
423 (file-truename "/dev/null")))
424 (setq comint-input-ring-file-name nil))
425 (setq shell-dirstack-query
426 (cond ((string-equal shell "sh") "pwd")
427 ((string-equal shell "ksh") "echo $PWD ~-")
428 (t "dirs"))))
429 (run-hooks 'shell-mode-hook)
430 (comint-read-input-ring t))
432 ;;;###autoload
433 (defun shell ()
434 "Run an inferior shell, with I/O through buffer *shell*.
435 If buffer exists but shell process is not running, make new shell.
436 If buffer exists and shell process is running, just switch to buffer `*shell*'.
437 Program used comes from variable `explicit-shell-file-name',
438 or (if that is nil) from the ESHELL environment variable,
439 or else from SHELL if there is no ESHELL.
440 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
441 (Note that this may lose due to a timing error if the shell
442 discards input when it starts up.)
443 The buffer is put in Shell mode, giving commands for sending input
444 and controlling the subjobs of the shell. See `shell-mode'.
445 See also the variable `shell-prompt-pattern'.
447 To specify a coding system for converting non-ASCII characters
448 in the input and output to the shell, use \\[universal-coding-system-argument]
449 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
450 in the shell buffer, after you start the shell.
451 The default comes from `process-coding-system-alist' and
452 `default-process-coding-system'.
454 The shell file name (sans directories) is used to make a symbol name
455 such as `explicit-csh-args'. If that symbol is a variable,
456 its value is used as a list of arguments when invoking the shell.
457 Otherwise, one argument `-i' is passed to the shell.
459 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
460 (interactive)
461 (if (not (comint-check-proc "*shell*"))
462 (let* ((prog (or explicit-shell-file-name
463 (getenv "ESHELL")
464 (getenv "SHELL")
465 "/bin/sh"))
466 (name (file-name-nondirectory prog))
467 (startfile (concat "~/.emacs_" name))
468 (xargs-name (intern-soft (concat "explicit-" name "-args")))
469 shell-buffer)
470 (save-excursion
471 (set-buffer (apply 'make-comint "shell" prog
472 (if (file-exists-p startfile) startfile)
473 (if (and xargs-name (boundp xargs-name))
474 (symbol-value xargs-name)
475 '("-i"))))
476 (setq shell-buffer (current-buffer))
477 (shell-mode))
478 (pop-to-buffer shell-buffer))
479 (pop-to-buffer "*shell*")))
481 ;;; Don't do this when shell.el is loaded, only while dumping.
482 ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
484 ;;; Directory tracking
486 ;;; This code provides the shell mode input sentinel
487 ;;; SHELL-DIRECTORY-TRACKER
488 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
489 ;;; changes the current directory of the shell buffer accordingly.
491 ;;; This is basically a fragile hack, although it's more accurate than
492 ;;; the version in Emacs 18's shell.el. It has the following failings:
493 ;;; 1. It doesn't know about the cdpath shell variable.
494 ;;; 2. It cannot infallibly deal with command sequences, though it does well
495 ;;; with these and with ignoring commands forked in another shell with ()s.
496 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
497 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
498 ;;; that, there's no way to catch shell commands where cd's are buried
499 ;;; inside conditional expressions, aliases, and so forth.
501 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
502 ;;; messes it up. You run other processes under the shell; these each have
503 ;;; separate working directories, and some have commands for manipulating
504 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
505 ;;; commands that do *not* affect the current w.d. at all, but look like they
506 ;;; do (e.g., the cd command in ftp). In shells that allow you job
507 ;;; control, you can switch between jobs, all having different w.d.'s. So
508 ;;; simply saying %3 can shift your w.d..
510 ;;; The solution is to relax, not stress out about it, and settle for
511 ;;; a hack that works pretty well in typical circumstances. Remember
512 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
513 ;;; anyway. Blech.
515 ;;; One good hack not implemented here for users of programmable shells
516 ;;; is to program up the shell w.d. manipulation commands to output
517 ;;; a coded command sequence to the tty. Something like
518 ;;; ESC | <cwd> |
519 ;;; where <cwd> is the new current working directory. Then trash the
520 ;;; directory tracking machinery currently used in this package, and
521 ;;; replace it with a process filter that watches for and strips out
522 ;;; these messages.
524 (defun shell-directory-tracker (str)
525 "Tracks cd, pushd and popd commands issued to the shell.
526 This function is called on each input passed to the shell.
527 It watches for cd, pushd and popd commands and sets the buffer's
528 default directory to track these commands.
530 You may toggle this tracking on and off with M-x dirtrack-mode.
531 If emacs gets confused, you can resync with the shell with M-x dirs.
533 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
534 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
535 and `shell-pushd-dunique' control the behavior of the relevant command.
537 Environment variables are expanded, see function `substitute-in-file-name'."
538 (if shell-dirtrackp
539 ;; We fail gracefully if we think the command will fail in the shell.
540 (condition-case chdir-failure
541 (let ((start (progn (string-match "^[; \t]*" str) ; skip whitespace
542 (match-end 0)))
543 end cmd arg1)
544 (while (string-match shell-command-regexp str start)
545 (setq end (match-end 0)
546 cmd (comint-arguments (substring str start end) 0 0)
547 arg1 (comint-arguments (substring str start end) 1 1))
548 (if arg1
549 (setq arg1 (shell-unquote-argument arg1)))
550 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
551 "\\)\\($\\|[ \t]\\)")
552 cmd)
553 (shell-process-popd (comint-substitute-in-file-name arg1)))
554 ((string-match (concat "\\`\\(" shell-pushd-regexp
555 "\\)\\($\\|[ \t]\\)")
556 cmd)
557 (shell-process-pushd (comint-substitute-in-file-name arg1)))
558 ((string-match (concat "\\`\\(" shell-cd-regexp
559 "\\)\\($\\|[ \t]\\)")
560 cmd)
561 (shell-process-cd (comint-substitute-in-file-name arg1)))
562 ((and shell-chdrive-regexp
563 (string-match (concat "\\`\\(" shell-chdrive-regexp
564 "\\)\\($\\|[ \t]\\)")
565 cmd))
566 (shell-process-cd (comint-substitute-in-file-name cmd))))
567 (setq start (progn (string-match "[; \t]*" str end) ; skip again
568 (match-end 0)))))
569 (error "Couldn't cd"))))
571 (defun shell-unquote-argument (string)
572 "Remove all kinds of shell quoting from STRING."
573 (save-match-data
574 (let ((idx 0) next inside)
575 (while (and (< idx (length string))
576 (setq next (string-match "[\\'`\"]" string next)))
577 (cond ((= (aref string next) ?\\)
578 (setq string (replace-match "" nil nil string))
579 (setq next (1+ next)))
580 ((and inside (= (aref string next) inside))
581 (setq string (replace-match "" nil nil string))
582 (setq inside nil))
583 (inside
584 (setq next (1+ next)))
586 (setq inside (aref string next))
587 (setq string (replace-match "" nil nil string)))))
588 string)))
590 ;;; popd [+n]
591 (defun shell-process-popd (arg)
592 (let ((num (or (shell-extract-num arg) 0)))
593 (cond ((and num (= num 0) shell-dirstack)
594 (shell-cd (car shell-dirstack))
595 (setq shell-dirstack (cdr shell-dirstack))
596 (shell-dirstack-message))
597 ((and num (> num 0) (<= num (length shell-dirstack)))
598 (let* ((ds (cons nil shell-dirstack))
599 (cell (nthcdr (1- num) ds)))
600 (rplacd cell (cdr (cdr cell)))
601 (setq shell-dirstack (cdr ds))
602 (shell-dirstack-message)))
604 (error "Couldn't popd")))))
606 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
607 (defun shell-prefixed-directory-name (dir)
608 (if (= (length comint-file-name-prefix) 0)
610 (if (file-name-absolute-p dir)
611 ;; The name is absolute, so prepend the prefix.
612 (concat comint-file-name-prefix dir)
613 ;; For relative name we assume default-directory already has the prefix.
614 (expand-file-name dir))))
616 ;;; cd [dir]
617 (defun shell-process-cd (arg)
618 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
619 "~"))
620 ((string-equal "-" arg) shell-last-dir)
621 (t (shell-prefixed-directory-name arg)))))
622 (setq shell-last-dir default-directory)
623 (shell-cd new-dir)
624 (shell-dirstack-message)))
626 ;;; pushd [+n | dir]
627 (defun shell-process-pushd (arg)
628 (let ((num (shell-extract-num arg)))
629 (cond ((zerop (length arg))
630 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
631 (cond (shell-pushd-tohome
632 (shell-process-pushd (concat comint-file-name-prefix "~")))
633 (shell-dirstack
634 (let ((old default-directory))
635 (shell-cd (car shell-dirstack))
636 (setq shell-dirstack (cons old (cdr shell-dirstack)))
637 (shell-dirstack-message)))
639 (message "Directory stack empty."))))
640 ((numberp num)
641 ;; pushd +n
642 (cond ((> num (length shell-dirstack))
643 (message "Directory stack not that deep."))
644 ((= num 0)
645 (error (message "Couldn't cd.")))
646 (shell-pushd-dextract
647 (let ((dir (nth (1- num) shell-dirstack)))
648 (shell-process-popd arg)
649 (shell-process-pushd default-directory)
650 (shell-cd dir)
651 (shell-dirstack-message)))
653 (let* ((ds (cons default-directory shell-dirstack))
654 (dslen (length ds))
655 (front (nthcdr num ds))
656 (back (reverse (nthcdr (- dslen num) (reverse ds))))
657 (new-ds (append front back)))
658 (shell-cd (car new-ds))
659 (setq shell-dirstack (cdr new-ds))
660 (shell-dirstack-message)))))
662 ;; pushd <dir>
663 (let ((old-wd default-directory))
664 (shell-cd (shell-prefixed-directory-name arg))
665 (if (or (null shell-pushd-dunique)
666 (not (member old-wd shell-dirstack)))
667 (setq shell-dirstack (cons old-wd shell-dirstack)))
668 (shell-dirstack-message))))))
670 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
671 (defun shell-extract-num (str)
672 (and (string-match "^\\+[1-9][0-9]*$" str)
673 (string-to-int str)))
676 (defun shell-dirtrack-mode ()
677 "Turn directory tracking on and off in a shell buffer."
678 (interactive)
679 (if (setq shell-dirtrackp (not shell-dirtrackp))
680 (setq list-buffers-directory default-directory)
681 (setq list-buffers-directory nil))
682 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
684 ;;; For your typing convenience:
685 (defalias 'shell-dirtrack-toggle 'shell-dirtrack-mode)
686 (defalias 'dirtrack-toggle 'shell-dirtrack-mode)
687 (defalias 'dirtrack-mode 'shell-dirtrack-mode)
689 (defun shell-cd (dir)
690 "Do normal `cd' to DIR, and set `list-buffers-directory'."
691 (if shell-dirtrackp
692 (setq list-buffers-directory (file-name-as-directory
693 (expand-file-name dir))))
694 (cd dir))
696 (defun shell-resync-dirs ()
697 "Resync the buffer's idea of the current directory stack.
698 This command queries the shell with the command bound to
699 `shell-dirstack-query' (default \"dirs\"), reads the next
700 line output and parses it to form the new directory stack.
701 DON'T issue this command unless the buffer is at a shell prompt.
702 Also, note that if some other subprocess decides to do output
703 immediately after the query, its output will be taken as the
704 new directory stack -- you lose. If this happens, just do the
705 command again."
706 (interactive)
707 (let* ((proc (get-buffer-process (current-buffer)))
708 (pmark (process-mark proc)))
709 (goto-char pmark)
710 (insert shell-dirstack-query) (insert "\n")
711 (sit-for 0) ; force redisplay
712 (comint-send-string proc shell-dirstack-query)
713 (comint-send-string proc "\n")
714 (set-marker pmark (point))
715 (let ((pt (point))) ; wait for 1 line
716 ;; This extra newline prevents the user's pending input from spoofing us.
717 (insert "\n") (backward-char 1)
718 (while (not (looking-at ".+\n"))
719 (accept-process-output proc)
720 (goto-char pt)))
721 (goto-char pmark) (delete-char 1) ; remove the extra newline
722 ;; That's the dirlist. grab it & parse it.
723 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
724 (dl-len (length dl))
725 (ds '()) ; new dir stack
726 (i 0))
727 (while (< i dl-len)
728 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
729 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
730 (setq ds (cons (concat comint-file-name-prefix
731 (substring dl (match-beginning 1)
732 (match-end 1)))
733 ds))
734 (setq i (match-end 0)))
735 (let ((ds (nreverse ds)))
736 (condition-case nil
737 (progn (shell-cd (car ds))
738 (setq shell-dirstack (cdr ds)
739 shell-last-dir (car shell-dirstack))
740 (shell-dirstack-message))
741 (error (message "Couldn't cd.")))))))
743 ;;; For your typing convenience:
744 (defalias 'dirs 'shell-resync-dirs)
747 ;;; Show the current dirstack on the message line.
748 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
749 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
750 ;;; All the commands that mung the buffer's dirstack finish by calling
751 ;;; this guy.
752 (defun shell-dirstack-message ()
753 (when shell-dirtrack-verbose
754 (let* ((msg "")
755 (ds (cons default-directory shell-dirstack))
756 (home (expand-file-name (concat comint-file-name-prefix "~/")))
757 (homelen (length home)))
758 (while ds
759 (let ((dir (car ds)))
760 (and (>= (length dir) homelen)
761 (string= home (substring dir 0 homelen))
762 (setq dir (concat "~/" (substring dir homelen))))
763 ;; Strip off comint-file-name-prefix if present.
764 (and comint-file-name-prefix
765 (>= (length dir) (length comint-file-name-prefix))
766 (string= comint-file-name-prefix
767 (substring dir 0 (length comint-file-name-prefix)))
768 (setq dir (substring dir (length comint-file-name-prefix)))
769 (setcar ds dir))
770 (setq msg (concat msg (directory-file-name dir) " "))
771 (setq ds (cdr ds))))
772 (message "%s" msg))))
774 ;; This was mostly copied from shell-resync-dirs.
775 (defun shell-snarf-envar (var)
776 "Return as a string the shell's value of environment variable VAR."
777 (let* ((cmd (format "printenv '%s'\n" var))
778 (proc (get-buffer-process (current-buffer)))
779 (pmark (process-mark proc)))
780 (goto-char pmark)
781 (insert cmd)
782 (sit-for 0) ; force redisplay
783 (comint-send-string proc cmd)
784 (set-marker pmark (point))
785 (let ((pt (point))) ; wait for 1 line
786 ;; This extra newline prevents the user's pending input from spoofing us.
787 (insert "\n") (backward-char 1)
788 (while (not (looking-at ".+\n"))
789 (accept-process-output proc)
790 (goto-char pt)))
791 (goto-char pmark) (delete-char 1) ; remove the extra newline
792 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
794 (defun shell-copy-environment-variable (variable)
795 "Copy the environment variable VARIABLE from the subshell to Emacs.
796 This command reads the value of the specified environment variable
797 in the shell, and sets the same environment variable in Emacs
798 \(what `getenv' in Emacs would return) to that value.
799 That value will affect any new subprocesses that you subsequently start
800 from Emacs."
801 (interactive (list (read-envvar-name "\
802 Copy Shell environment variable to Emacs: ")))
803 (setenv variable (shell-snarf-envar variable)))
805 (defun shell-forward-command (&optional arg)
806 "Move forward across ARG shell command(s). Does not cross lines.
807 See `shell-command-regexp'."
808 (interactive "p")
809 (let ((limit (save-excursion (end-of-line nil) (point))))
810 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
811 limit 'move arg)
812 (skip-syntax-backward " "))))
815 (defun shell-backward-command (&optional arg)
816 "Move backward across ARG shell command(s). Does not cross lines.
817 See `shell-command-regexp'."
818 (interactive "p")
819 (let ((limit (save-excursion (comint-bol nil) (point))))
820 (when (> limit (point))
821 (setq limit (line-beginning-position)))
822 (skip-syntax-backward " " limit)
823 (if (re-search-backward
824 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
825 (progn (goto-char (match-beginning 1))
826 (skip-chars-forward ";&|")))))
829 (defun shell-dynamic-complete-command ()
830 "Dynamically complete the command at point.
831 This function is similar to `comint-dynamic-complete-filename', except that it
832 searches `exec-path' (minus the trailing emacs library path) for completion
833 candidates. Note that this may not be the same as the shell's idea of the
834 path.
836 Completion is dependent on the value of `shell-completion-execonly', plus
837 those that effect file completion. See `shell-dynamic-complete-as-command'.
839 Returns t if successful."
840 (interactive)
841 (let ((filename (comint-match-partial-filename)))
842 (if (and filename
843 (save-match-data (not (string-match "[~/]" filename)))
844 (eq (match-beginning 0)
845 (save-excursion (shell-backward-command 1) (point))))
846 (prog2 (message "Completing command name...")
847 (shell-dynamic-complete-as-command)))))
850 (defun shell-dynamic-complete-as-command ()
851 "Dynamically complete at point as a command.
852 See `shell-dynamic-complete-filename'. Returns t if successful."
853 (let* ((filename (or (comint-match-partial-filename) ""))
854 (pathnondir (file-name-nondirectory filename))
855 (paths (cdr (reverse exec-path)))
856 (cwd (file-name-as-directory (expand-file-name default-directory)))
857 (ignored-extensions
858 (and comint-completion-fignore
859 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
860 comint-completion-fignore "\\|")))
861 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
862 ;; Go thru each path in the search path, finding completions.
863 (while paths
864 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
865 comps-in-path (and (file-accessible-directory-p path)
866 (file-name-all-completions pathnondir path)))
867 ;; Go thru each completion found, to see whether it should be used.
868 (while comps-in-path
869 (setq file (car comps-in-path)
870 filepath (concat path file))
871 (if (and (not (member file completions))
872 (not (and ignored-extensions
873 (string-match ignored-extensions file)))
874 (or (string-equal path cwd)
875 (not (file-directory-p filepath)))
876 (or (null shell-completion-execonly)
877 (file-executable-p filepath)))
878 (setq completions (cons file completions)))
879 (setq comps-in-path (cdr comps-in-path)))
880 (setq paths (cdr paths)))
881 ;; OK, we've got a list of completions.
882 (let ((success (let ((comint-completion-addsuffix nil))
883 (comint-dynamic-simple-complete pathnondir completions))))
884 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
885 (not (file-directory-p (comint-match-partial-filename))))
886 (insert " "))
887 success)))
890 (defun shell-match-partial-variable ()
891 "Return the shell variable at point, or nil if none is found."
892 (save-excursion
893 (let ((limit (point)))
894 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
895 (or (looking-at "\\$") (forward-char 1)))
896 ;; Anchor the search forwards.
897 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
899 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
900 (buffer-substring (match-beginning 0) (match-end 0))))))
903 (defun shell-dynamic-complete-environment-variable ()
904 "Dynamically complete the environment variable at point.
905 Completes if after a variable, i.e., if it starts with a \"$\".
906 See `shell-dynamic-complete-as-environment-variable'.
908 This function is similar to `comint-dynamic-complete-filename', except that it
909 searches `process-environment' for completion candidates. Note that this may
910 not be the same as the interpreter's idea of variable names. The main problem
911 with this type of completion is that `process-environment' is the environment
912 which Emacs started with. Emacs does not track changes to the environment made
913 by the interpreter. Perhaps it would be more accurate if this function was
914 called `shell-dynamic-complete-process-environment-variable'.
916 Returns non-nil if successful."
917 (interactive)
918 (let ((variable (shell-match-partial-variable)))
919 (if (and variable (string-match "^\\$" variable))
920 (prog2 (message "Completing variable name...")
921 (shell-dynamic-complete-as-environment-variable)))))
924 (defun shell-dynamic-complete-as-environment-variable ()
925 "Dynamically complete at point as an environment variable.
926 Used by `shell-dynamic-complete-environment-variable'.
927 Uses `comint-dynamic-simple-complete'."
928 (let* ((var (or (shell-match-partial-variable) ""))
929 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
930 (variables (mapcar (function (lambda (x)
931 (substring x 0 (string-match "=" x))))
932 process-environment))
933 (addsuffix comint-completion-addsuffix)
934 (comint-completion-addsuffix nil)
935 (success (comint-dynamic-simple-complete variable variables)))
936 (if (memq success '(sole shortest))
937 (let* ((var (shell-match-partial-variable))
938 (variable (substring var (string-match "[^$({]" var)))
939 (protection (cond ((string-match "{" var) "}")
940 ((string-match "(" var) ")")
941 (t "")))
942 (suffix (cond ((null addsuffix) "")
943 ((file-directory-p
944 (comint-directory (getenv variable))) "/")
945 (t " "))))
946 (insert protection suffix)))
947 success))
950 (defun shell-replace-by-expanded-directory ()
951 "Expand directory stack reference before point.
952 Directory stack references are of the form \"=digit\" or \"=-\".
953 See `default-directory' and `shell-dirstack'.
955 Returns t if successful."
956 (interactive)
957 (if (comint-match-partial-filename)
958 (save-excursion
959 (goto-char (match-beginning 0))
960 (let ((stack (cons default-directory shell-dirstack))
961 (index (cond ((looking-at "=-/?")
962 (length shell-dirstack))
963 ((looking-at "=\\([0-9]+\\)")
964 (string-to-number
965 (buffer-substring
966 (match-beginning 1) (match-end 1)))))))
967 (cond ((null index)
968 nil)
969 ((>= index (length stack))
970 (error "Directory stack not that deep."))
972 (replace-match (file-name-as-directory (nth index stack)) t t)
973 (message "Directory item: %d" index)
974 t))))))
976 (provide 'shell)
978 ;;; shell.el ends here