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