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