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