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