]> code.delx.au - gnu-emacs/blob - lisp/shell.el
(shell): If we create a new shell buffer,
[gnu-emacs] / lisp / shell.el
1 ;;; shell.el --- specialized comint.el for running the shell.
2
3 ;; Copyright (C) 1988, 1993, 1994 Free Software Foundation, Inc.
4
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
6 ;; Maintainer: Simon Marshall <simon@gnu.ai.mit.edu>
7 ;; Keywords: processes
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to
23 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
24
25 ;;; Commentary:
26
27 ;;; Please send me bug reports, bug fixes, and extensions, so that I can
28 ;;; merge them into the master source.
29 ;;; - Olin Shivers (shivers@cs.cmu.edu)
30 ;;; - Simon Marshall (simon@gnu.ai.mit.edu)
31
32 ;;; This file defines a a shell-in-a-buffer package (shell mode) built
33 ;;; on top of comint mode. This is actually cmushell with things
34 ;;; renamed to replace its counterpart in Emacs 18. cmushell is more
35 ;;; featureful, robust, and uniform than the Emacs 18 version.
36
37 ;;; Since this mode is built on top of the general command-interpreter-in-
38 ;;; a-buffer mode (comint mode), it shares a common base functionality,
39 ;;; and a common set of bindings, with all modes derived from comint mode.
40 ;;; This makes these modes easier to use.
41
42 ;;; For documentation on the functionality provided by comint mode, and
43 ;;; the hooks available for customising it, see the file comint.el.
44 ;;; For further information on shell mode, see the comments below.
45
46 ;;; Needs fixin:
47 ;;; When sending text from a source file to a subprocess, the process-mark can
48 ;;; move off the window, so you can lose sight of the process interactions.
49 ;;; Maybe I should ensure the process mark is in the window when I send
50 ;;; text to the process? Switch selectable?
51
52 ;; YOUR .EMACS FILE
53 ;;=============================================================================
54 ;; Some suggestions for your .emacs file.
55 ;;
56 ;; ;; Define C-c t to run my favorite command in shell mode:
57 ;; (setq shell-mode-hook
58 ;; '((lambda ()
59 ;; (define-key shell-mode-map "\C-ct" 'favorite-cmd))))
60
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-R comint-previous-matching-input-from-input -"- matching input
70 ;;; m-s comint-next-matching-input Next input that matches
71 ;;; m-S comint-next-matching-input-from-input -"- matching input
72 ;;; m-c-l comint-show-output Show last batch of process output
73 ;;; return comint-send-input
74 ;;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
75 ;;; c-c c-a comint-bol Beginning of line; skip prompt
76 ;;; c-c c-u comint-kill-input ^u
77 ;;; c-c c-w backward-kill-word ^w
78 ;;; c-c c-c comint-interrupt-subjob ^c
79 ;;; c-c c-z comint-stop-subjob ^z
80 ;;; c-c c-\ comint-quit-subjob ^\
81 ;;; c-c c-o comint-kill-output Delete last batch of process output
82 ;;; c-c c-r comint-show-output Show last batch of process output
83 ;;; c-c c-h comint-dynamic-list-input-ring List input history
84 ;;; send-invisible Read line w/o echo & send to proc
85 ;;; comint-continue-subjob Useful if you accidentally suspend
86 ;;; top-level job
87 ;;; comint-mode-hook is the comint mode hook.
88
89 ;;; Shell Mode Commands:
90 ;;; shell Fires up the shell process
91 ;;; tab comint-dynamic-complete Complete filename/command/history
92 ;;; m-? comint-dynamic-list-filename-completions List completions in help buffer
93 ;;; m-c-f shell-forward-command Forward a shell command
94 ;;; m-c-b shell-backward-command Backward a shell command
95 ;;; dirs Resync the buffer's dir stack
96 ;;; dirtrack-toggle Turn dir tracking on/off
97 ;;; shell-strip-ctrl-m Remove trailing ^Ms from output
98 ;;;
99 ;;; The shell mode hook is shell-mode-hook
100 ;;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
101 ;;; compatibility.
102
103 ;;; Read the rest of this file for more information.
104 \f
105 ;;; Customization and Buffer Variables
106 ;;; ===========================================================================
107 ;;;
108
109 ;;; Code:
110
111 (require 'comint)
112
113 ;;;###autoload
114 (defvar shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
115 "Regexp to match prompts in the inferior shell.
116 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
117 This variable is used to initialise `comint-prompt-regexp' in the
118 shell buffer.
119
120 The pattern should probably not match more than one line. If it does,
121 shell-mode may become confused trying to distinguish prompt from input
122 on lines which don't start with a prompt.
123
124 This is a fine thing to set in your `.emacs' file.")
125
126 (defvar shell-completion-fignore nil
127 "*List of suffixes to be disregarded during file/command completion.
128 This variable is used to initialize `comint-completion-fignore' in the shell
129 buffer. The default is nil, for compatibility with most shells.
130 Some people like (\"~\" \"#\" \"%\").
131
132 This is a fine thing to set in your `.emacs' file.")
133
134 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
135 "List of characters to recognise as separate arguments.
136 This variable is used to initialize `comint-delimiter-argument-list' in the
137 shell buffer. The default is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
138
139 This is a fine thing to set in your `.emacs' file.")
140
141 (defvar shell-dynamic-complete-functions
142 '(comint-replace-by-expanded-history
143 shell-dynamic-complete-environment-variable
144 shell-dynamic-complete-command
145 shell-replace-by-expanded-directory
146 comint-dynamic-complete-filename)
147 "List of functions called to perform completion.
148 This variable is used to initialise `comint-dynamic-complete-functions' in the
149 shell buffer.
150
151 This is a fine thing to set in your `.emacs' file.")
152
153 (defvar shell-command-regexp "[^;&|\n]+"
154 "*Regexp to match a single command within a pipeline.
155 This is used for directory tracking and does not do a perfect job.")
156
157 (defvar shell-completion-execonly t
158 "*If non-nil, use executable files only for completion candidates.
159 This mirrors the optional behavior of tcsh.
160
161 Detecting executability of files may slow command completion considerably.")
162
163 (defvar shell-popd-regexp "popd"
164 "*Regexp to match subshell commands equivalent to popd.")
165
166 (defvar shell-pushd-regexp "pushd"
167 "*Regexp to match subshell commands equivalent to pushd.")
168
169 (defvar shell-pushd-tohome nil
170 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
171 This mirrors the optional behavior of tcsh.")
172
173 (defvar shell-pushd-dextract nil
174 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
175 This mirrors the optional behavior of tcsh.")
176
177 (defvar shell-pushd-dunique nil
178 "*If non-nil, make pushd only add unique directories to the stack.
179 This mirrors the optional behavior of tcsh.")
180
181 (defvar shell-cd-regexp "cd"
182 "*Regexp to match subshell commands equivalent to cd.")
183
184 (defvar explicit-shell-file-name nil
185 "*If non-nil, is file name to use for explicitly requested inferior shell.")
186
187 (defvar explicit-csh-args
188 (if (eq system-type 'hpux)
189 ;; -T persuades HP's csh not to think it is smarter
190 ;; than us about what terminal modes to use.
191 '("-i" "-T")
192 '("-i"))
193 "*Args passed to inferior shell by M-x shell, if the shell is csh.
194 Value is a list of strings, which may be nil.")
195
196 (defvar shell-input-autoexpand 'history
197 "*If non-nil, expand input command history references on completion.
198 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
199
200 If the value is `input', then the expansion is seen on input.
201 If the value is `history', then the expansion is only when inserting
202 into the buffer's input ring. See also `comint-magic-space' and
203 `comint-dynamic-complete'.
204
205 This variable supplies a default for `comint-input-autoexpand',
206 for Shell mode only.")
207
208 (defvar shell-dirstack nil
209 "List of directories saved by pushd in this buffer's shell.
210 Thus, this does not include the shell's current directory.")
211
212 (defvar shell-dirtrackp t
213 "Non-nil in a shell buffer means directory tracking is enabled.")
214
215 (defvar shell-last-dir nil
216 "Keep track of last directory for ksh `cd -' command.")
217
218 (defvar shell-dirstack-query nil
219 "Command used by `shell-resync-dir' to query the shell.")
220
221 (defvar shell-mode-map nil)
222 (cond ((not shell-mode-map)
223 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
224 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
225 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
226 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
227 (define-key shell-mode-map "\M-?"
228 'comint-dynamic-list-filename-completions)
229 (define-key shell-mode-map [menu-bar completion]
230 (copy-keymap (lookup-key comint-mode-map [menu-bar completion])))
231 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
232 [complete-env-variable] '("Complete Env. Variable Name" .
233 shell-dynamic-complete-environment-variable)
234 'complete-file)
235 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
236 [expand-directory] '("Expand Directory Reference" .
237 shell-replace-by-expanded-directory)
238 'complete-expand)))
239
240 (defvar shell-mode-hook '()
241 "*Hook for customising Shell mode.")
242
243 (defvar shell-font-lock-keywords
244 (list (cons shell-prompt-pattern 'font-lock-keyword-face)
245 '("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
246 '("^[^ \t\n]+:.*$" . font-lock-string-face)
247 '("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
248 "Additional expressions to highlight in Shell mode.")
249 \f
250 ;;; Basic Procedures
251 ;;; ===========================================================================
252 ;;;
253
254 (defun shell-mode ()
255 "Major mode for interacting with an inferior shell.
256 Return after the end of the process' output sends the text from the
257 end of process to the end of the current line.
258 Return before end of process output copies the current line (except
259 for the prompt) to the end of the buffer and sends it.
260 \\[send-invisible] reads a line of text without echoing it, and sends it to
261 the shell. This is useful for entering passwords. Or, add the function
262 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
263
264 If you want to make multiple shell buffers, rename the `*shell*' buffer
265 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
266
267 If you accidentally suspend your process, use \\[comint-continue-subjob]
268 to continue it.
269
270 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
271 keep this buffer's default directory the same as the shell's working directory.
272 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
273 directory stack is.
274 \\[dirtrack-toggle] turns directory tracking on and off.
275
276 \\{shell-mode-map}
277 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
278 `shell-mode-hook' (in that order). Before each input, the hooks on
279 `comint-input-filter-functions' are run. After each shell output, the hooks
280 on `comint-output-filter-functions' are run.
281
282 Variables `shell-cd-regexp', `shell-pushd-regexp' and `shell-popd-regexp'
283 are used to match their respective commands, while `shell-pushd-tohome',
284 `shell-pushd-dextract' and `shell-pushd-dunique' control the behavior of the
285 relevant command.
286
287 Variables `comint-completion-autolist', `comint-completion-addsuffix',
288 `comint-completion-recexact' and `comint-completion-fignore' control the
289 behavior of file name, command name and variable name completion. Variable
290 `shell-completion-execonly' controls the behavior of command name completion.
291 Variable `shell-completion-fignore' is used to initialise the value of
292 `comint-completion-fignore'.
293
294 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
295 the initialisation of the input ring history, and history expansion.
296
297 Variables `comint-output-filter-functions', a hook, and
298 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
299 control whether input and output cause the window to scroll to the end of the
300 buffer."
301 (interactive)
302 (comint-mode)
303 (setq major-mode 'shell-mode)
304 (setq mode-name "Shell")
305 (use-local-map shell-mode-map)
306 (setq comint-prompt-regexp shell-prompt-pattern)
307 (setq comint-completion-fignore shell-completion-fignore)
308 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
309 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
310 (make-local-variable 'paragraph-start)
311 (setq paragraph-start comint-prompt-regexp)
312 (make-local-variable 'font-lock-defaults)
313 (setq font-lock-defaults '(shell-font-lock-keywords t))
314 (make-local-variable 'shell-dirstack)
315 (setq shell-dirstack nil)
316 (setq shell-last-dir nil)
317 (make-local-variable 'shell-dirtrackp)
318 (setq shell-dirtrackp t)
319 (add-hook 'comint-input-filter-functions 'shell-directory-tracker)
320 (setq comint-input-autoexpand shell-input-autoexpand)
321 ;; shell-dependent assignments.
322 (let ((shell (file-name-nondirectory (car
323 (process-command (get-buffer-process (current-buffer)))))))
324 (setq comint-input-ring-file-name
325 (or (getenv "HISTFILE")
326 (cond ((string-equal shell "bash") "~/.bash_history")
327 ((string-equal shell "ksh") "~/.sh_history")
328 (t "~/.history"))))
329 (if (equal (file-truename comint-input-ring-file-name) "/dev/null")
330 (setq comint-input-ring-file-name nil))
331 (setq shell-dirstack-query
332 (if (string-match "^k?sh$" shell) "pwd" "dirs")))
333 (run-hooks 'shell-mode-hook)
334 (comint-read-input-ring t))
335 \f
336 ;;;###autoload
337 (defun shell ()
338 "Run an inferior shell, with I/O through buffer *shell*.
339 If buffer exists but shell process is not running, make new shell.
340 If buffer exists and shell process is running, just switch to buffer `*shell*'.
341 Program used comes from variable `explicit-shell-file-name',
342 or (if that is nil) from the ESHELL environment variable,
343 or else from SHELL if there is no ESHELL.
344 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
345 (Note that this may lose due to a timing error if the shell
346 discards input when it starts up.)
347 The buffer is put in Shell mode, giving commands for sending input
348 and controlling the subjobs of the shell. See `shell-mode'.
349 See also the variable `shell-prompt-pattern'.
350
351 The shell file name (sans directories) is used to make a symbol name
352 such as `explicit-csh-args'. If that symbol is a variable,
353 its value is used as a list of arguments when invoking the shell.
354 Otherwise, one argument `-i' is passed to the shell.
355
356 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
357 (interactive)
358 (if (not (comint-check-proc "*shell*"))
359 (let* ((prog (or explicit-shell-file-name
360 (getenv "ESHELL")
361 (getenv "SHELL")
362 "/bin/sh"))
363 (name (file-name-nondirectory prog))
364 (startfile (concat "~/.emacs_" name))
365 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
366 (set-buffer (apply 'make-comint "shell" prog
367 (if (file-exists-p startfile) startfile)
368 (if (and xargs-name (boundp xargs-name))
369 (symbol-value xargs-name)
370 '("-i"))))
371 (shell-mode)
372 (switch-to-buffer (current-buffer)))
373 (switch-to-buffer "*shell*")))
374 \f
375 ;;; Directory tracking
376 ;;; ===========================================================================
377 ;;; This code provides the shell mode input sentinel
378 ;;; SHELL-DIRECTORY-TRACKER
379 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
380 ;;; changes the current directory of the shell buffer accordingly.
381 ;;;
382 ;;; This is basically a fragile hack, although it's more accurate than
383 ;;; the version in Emacs 18's shell.el. It has the following failings:
384 ;;; 1. It doesn't know about the cdpath shell variable.
385 ;;; 2. It cannot infallibly deal with command sequences, though it does well
386 ;;; with these and with ignoring commands forked in another shell with ()s.
387 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
388 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
389 ;;; that, there's no way to catch shell commands where cd's are buried
390 ;;; inside conditional expressions, aliases, and so forth.
391 ;;;
392 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
393 ;;; messes it up. You run other processes under the shell; these each have
394 ;;; separate working directories, and some have commands for manipulating
395 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
396 ;;; commands that do *not* affect the current w.d. at all, but look like they
397 ;;; do (e.g., the cd command in ftp). In shells that allow you job
398 ;;; control, you can switch between jobs, all having different w.d.'s. So
399 ;;; simply saying %3 can shift your w.d..
400 ;;;
401 ;;; The solution is to relax, not stress out about it, and settle for
402 ;;; a hack that works pretty well in typical circumstances. Remember
403 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
404 ;;; anyway. Blech.
405 ;;;
406 ;;; One good hack not implemented here for users of programmable shells
407 ;;; is to program up the shell w.d. manipulation commands to output
408 ;;; a coded command sequence to the tty. Something like
409 ;;; ESC | <cwd> |
410 ;;; where <cwd> is the new current working directory. Then trash the
411 ;;; directory tracking machinery currently used in this package, and
412 ;;; replace it with a process filter that watches for and strips out
413 ;;; these messages.
414
415 (defun shell-directory-tracker (str)
416 "Tracks cd, pushd and popd commands issued to the shell.
417 This function is called on each input passed to the shell.
418 It watches for cd, pushd and popd commands and sets the buffer's
419 default directory to track these commands.
420
421 You may toggle this tracking on and off with M-x dirtrack-toggle.
422 If emacs gets confused, you can resync with the shell with M-x dirs.
423
424 See variables `shell-cd-regexp', `shell-pushd-regexp', and `shell-popd-regexp',
425 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
426 control the behavior of the relevant command.
427
428 Environment variables are expanded, see function `substitute-in-file-name'."
429 (if shell-dirtrackp
430 ;; We fail gracefully if we think the command will fail in the shell.
431 (condition-case chdir-failure
432 (let ((start (progn (string-match "^[;\\s ]*" str) ; skip whitespace
433 (match-end 0)))
434 end cmd arg1)
435 (while (string-match shell-command-regexp str start)
436 (setq end (match-end 0)
437 cmd (comint-arguments (substring str start end) 0 0)
438 arg1 (comint-arguments (substring str start end) 1 1))
439 (cond ((eq (string-match shell-popd-regexp cmd) 0)
440 (shell-process-popd (substitute-in-file-name arg1)))
441 ((eq (string-match shell-pushd-regexp cmd) 0)
442 (shell-process-pushd (substitute-in-file-name arg1)))
443 ((eq (string-match shell-cd-regexp cmd) 0)
444 (shell-process-cd (substitute-in-file-name arg1))))
445 (setq start (progn (string-match "[;\\s ]*" str end) ; skip again
446 (match-end 0)))))
447 (error "Couldn't cd"))))
448
449 ;;; popd [+n]
450 (defun shell-process-popd (arg)
451 (let ((num (or (shell-extract-num arg) 0)))
452 (cond ((and num (= num 0) shell-dirstack)
453 (cd (car shell-dirstack))
454 (setq shell-dirstack (cdr shell-dirstack))
455 (shell-dirstack-message))
456 ((and num (> num 0) (<= num (length shell-dirstack)))
457 (let* ((ds (cons nil shell-dirstack))
458 (cell (nthcdr (1- num) ds)))
459 (rplacd cell (cdr (cdr cell)))
460 (setq shell-dirstack (cdr ds))
461 (shell-dirstack-message)))
462 (t
463 (error "Couldn't popd")))))
464
465 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
466 (defun shell-prefixed-directory-name (dir)
467 (if (= (length comint-file-name-prefix) 0)
468 dir
469 (if (file-name-absolute-p dir)
470 ;; The name is absolute, so prepend the prefix.
471 (concat comint-file-name-prefix dir)
472 ;; For a relative name we assume default-directory already has the prefix.
473 (expand-file-name dir))))
474
475 ;;; cd [dir]
476 (defun shell-process-cd (arg)
477 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
478 "~"))
479 ((string-equal "-" arg) shell-last-dir)
480 (t (shell-prefixed-directory-name arg)))))
481 (setq shell-last-dir default-directory)
482 (cd new-dir)
483 (shell-dirstack-message)))
484
485 ;;; pushd [+n | dir]
486 (defun shell-process-pushd (arg)
487 (let ((num (shell-extract-num arg)))
488 (cond ((zerop (length arg))
489 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
490 (cond (shell-pushd-tohome
491 (shell-process-pushd (concat comint-file-name-prefix "~")))
492 (shell-dirstack
493 (let ((old default-directory))
494 (cd (car shell-dirstack))
495 (setq shell-dirstack
496 (cons old (cdr shell-dirstack)))
497 (shell-dirstack-message)))
498 (t
499 (message "Directory stack empty."))))
500 ((numberp num)
501 ;; pushd +n
502 (cond ((> num (length shell-dirstack))
503 (message "Directory stack not that deep."))
504 ((= num 0)
505 (error (message "Couldn't cd.")))
506 (shell-pushd-dextract
507 (let ((dir (nth (1- num) shell-dirstack)))
508 (shell-process-popd arg)
509 (shell-process-pushd default-directory)
510 (cd dir)
511 (shell-dirstack-message)))
512 (t
513 (let* ((ds (cons default-directory shell-dirstack))
514 (dslen (length ds))
515 (front (nthcdr num ds))
516 (back (reverse (nthcdr (- dslen num) (reverse ds))))
517 (new-ds (append front back)))
518 (cd (car new-ds))
519 (setq shell-dirstack (cdr new-ds))
520 (shell-dirstack-message)))))
521 (t
522 ;; pushd <dir>
523 (let ((old-wd default-directory))
524 (cd (shell-prefixed-directory-name arg))
525 (if (or (null shell-pushd-dunique)
526 (not (member old-wd shell-dirstack)))
527 (setq shell-dirstack (cons old-wd shell-dirstack)))
528 (shell-dirstack-message))))))
529
530 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
531 (defun shell-extract-num (str)
532 (and (string-match "^\\+[1-9][0-9]*$" str)
533 (string-to-int str)))
534
535
536 (defun shell-dirtrack-toggle ()
537 "Turn directory tracking on and off in a shell buffer."
538 (interactive)
539 (setq shell-dirtrackp (not shell-dirtrackp))
540 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
541
542 ;;; For your typing convenience:
543 (defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
544
545
546 (defun shell-resync-dirs ()
547 "Resync the buffer's idea of the current directory stack.
548 This command queries the shell with the command bound to
549 `shell-dirstack-query' (default \"dirs\"), reads the next
550 line output and parses it to form the new directory stack.
551 DON'T issue this command unless the buffer is at a shell prompt.
552 Also, note that if some other subprocess decides to do output
553 immediately after the query, its output will be taken as the
554 new directory stack -- you lose. If this happens, just do the
555 command again."
556 (interactive)
557 (let* ((proc (get-buffer-process (current-buffer)))
558 (pmark (process-mark proc)))
559 (goto-char pmark)
560 (insert shell-dirstack-query) (insert "\n")
561 (sit-for 0) ; force redisplay
562 (comint-send-string proc shell-dirstack-query)
563 (comint-send-string proc "\n")
564 (set-marker pmark (point))
565 (let ((pt (point))) ; wait for 1 line
566 ;; This extra newline prevents the user's pending input from spoofing us.
567 (insert "\n") (backward-char 1)
568 (while (not (looking-at ".+\n"))
569 (accept-process-output proc)
570 (goto-char pt)))
571 (goto-char pmark) (delete-char 1) ; remove the extra newline
572 ;; That's the dirlist. grab it & parse it.
573 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
574 (dl-len (length dl))
575 (ds '()) ; new dir stack
576 (i 0))
577 (while (< i dl-len)
578 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
579 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
580 (setq ds (cons (concat comint-file-name-prefix
581 (substring dl (match-beginning 1)
582 (match-end 1)))
583 ds))
584 (setq i (match-end 0)))
585 (let ((ds (nreverse ds)))
586 (condition-case nil
587 (progn (cd (car ds))
588 (setq shell-dirstack (cdr ds))
589 (shell-dirstack-message))
590 (error (message "Couldn't cd.")))))))
591
592 ;;; For your typing convenience:
593 (defalias 'dirs 'shell-resync-dirs)
594
595
596 ;;; Show the current dirstack on the message line.
597 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
598 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
599 ;;; All the commands that mung the buffer's dirstack finish by calling
600 ;;; this guy.
601 (defun shell-dirstack-message ()
602 (let* ((msg "")
603 (ds (cons default-directory shell-dirstack))
604 (home (expand-file-name (concat comint-file-name-prefix "~/")))
605 (homelen (length home)))
606 (while ds
607 (let ((dir (car ds)))
608 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
609 (setq dir (concat "~/" (substring dir homelen))))
610 ;; Strip off comint-file-name-prefix if present.
611 (and comint-file-name-prefix
612 (>= (length dir) (length comint-file-name-prefix))
613 (string= comint-file-name-prefix
614 (substring dir 0 (length comint-file-name-prefix)))
615 (setq dir (substring dir (length comint-file-name-prefix)))
616 (setcar ds dir))
617 (setq msg (concat msg (directory-file-name dir) " "))
618 (setq ds (cdr ds))))
619 (message msg)))
620 \f
621 (defun shell-forward-command (&optional arg)
622 "Move forward across ARG shell command(s). Does not cross lines.
623 See `shell-command-regexp'."
624 (interactive "p")
625 (let ((limit (save-excursion (end-of-line nil) (point))))
626 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
627 limit 'move arg)
628 (skip-syntax-backward " "))))
629
630
631 (defun shell-backward-command (&optional arg)
632 "Move backward across ARG shell command(s). Does not cross lines.
633 See `shell-command-regexp'."
634 (interactive "p")
635 (let ((limit (save-excursion (comint-bol nil) (point))))
636 (if (> limit (point))
637 (save-excursion (beginning-of-line) (setq limit (point))))
638 (skip-syntax-backward " " limit)
639 (if (re-search-backward
640 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
641 (progn (goto-char (match-beginning 1))
642 (skip-chars-forward ";&|")))))
643
644
645 (defun shell-dynamic-complete-command ()
646 "Dynamically complete the command at point.
647 This function is similar to `comint-dynamic-complete-filename', except that it
648 searches `exec-path' (minus the trailing emacs library path) for completion
649 candidates. Note that this may not be the same as the shell's idea of the
650 path.
651
652 Completion is dependent on the value of `shell-completion-execonly', plus
653 those that effect file completion. See `shell-dynamic-complete-as-command'.
654
655 Returns t if successful."
656 (interactive)
657 (let ((filename (comint-match-partial-filename)))
658 (if (and filename
659 (save-match-data (not (string-match "[~/]" filename)))
660 (eq (match-beginning 0)
661 (save-excursion (shell-backward-command 1) (point))))
662 (prog2 (message "Completing command name...")
663 (shell-dynamic-complete-as-command)))))
664
665
666 (defun shell-dynamic-complete-as-command ()
667 "Dynamically complete at point as a command.
668 See `shell-dynamic-complete-filename'. Returns t if successful."
669 (let* ((filename (or (comint-match-partial-filename) ""))
670 (pathnondir (file-name-nondirectory filename))
671 (paths (cdr (reverse exec-path)))
672 (cwd (file-name-as-directory (expand-file-name default-directory)))
673 (ignored-extensions
674 (and comint-completion-fignore
675 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
676 comint-completion-fignore "\\|")))
677 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
678 ;; Go thru each path in the search path, finding completions.
679 (while paths
680 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
681 comps-in-path (and (file-accessible-directory-p path)
682 (file-name-all-completions pathnondir path)))
683 ;; Go thru each completion found, to see whether it should be used.
684 (while comps-in-path
685 (setq file (car comps-in-path)
686 filepath (concat path file))
687 (if (and (not (member file completions))
688 (not (and ignored-extensions
689 (string-match ignored-extensions file)))
690 (or (string-equal path cwd)
691 (not (file-directory-p filepath)))
692 (or (null shell-completion-execonly)
693 (file-executable-p filepath)))
694 (setq completions (cons file completions)))
695 (setq comps-in-path (cdr comps-in-path)))
696 (setq paths (cdr paths)))
697 ;; OK, we've got a list of completions.
698 (let ((success (let ((comint-completion-addsuffix nil))
699 (comint-dynamic-simple-complete pathnondir completions))))
700 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
701 (not (file-directory-p (comint-match-partial-filename))))
702 (insert " "))
703 success)))
704
705
706 (defun shell-match-partial-variable ()
707 "Return the variable at point, or nil if non is found."
708 (save-excursion
709 (let ((limit (point)))
710 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
711 (or (looking-at "\\$") (forward-char 1)))
712 ;; Anchor the search forwards.
713 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
714 nil
715 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
716 (buffer-substring (match-beginning 0) (match-end 0))))))
717
718
719 (defun shell-dynamic-complete-environment-variable ()
720 "Dynamically complete the environment variable at point.
721 Completes if after a variable, i.e., if it starts with a \"$\".
722 See `shell-dynamic-complete-as-environment-variable'.
723
724 This function is similar to `comint-dynamic-complete-filename', except that it
725 searches `process-environment' for completion candidates. Note that this may
726 not be the same as the interpreter's idea of variable names. The main problem
727 with this type of completion is that `process-environment' is the environment
728 which Emacs started with. Emacs does not track changes to the environment made
729 by the interpreter. Perhaps it would be more accurate if this function was
730 called `shell-dynamic-complete-process-environment-variable'.
731
732 Returns non-nil if successful."
733 (interactive)
734 (let ((variable (shell-match-partial-variable)))
735 (if (and variable (string-match "^\\$" variable))
736 (prog2 (message "Completing variable name...")
737 (shell-dynamic-complete-as-environment-variable)))))
738
739
740 (defun shell-dynamic-complete-as-environment-variable ()
741 "Dynamically complete at point as an environment variable.
742 Used by `shell-dynamic-complete-environment-variable'.
743 Uses `comint-dynamic-simple-complete'."
744 (let* ((var (or (shell-match-partial-variable) ""))
745 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
746 (variables (mapcar (function (lambda (x)
747 (substring x 0 (string-match "=" x))))
748 process-environment))
749 (addsuffix comint-completion-addsuffix)
750 (comint-completion-addsuffix nil)
751 (success (comint-dynamic-simple-complete variable variables)))
752 (if (memq success '(sole shortest))
753 (let* ((var (shell-match-partial-variable))
754 (variable (substring var (string-match "[^$({]" var)))
755 (protection (cond ((string-match "{" var) "}")
756 ((string-match "(" var) ")")
757 (t "")))
758 (suffix (cond ((null addsuffix) "")
759 ((file-directory-p
760 (comint-directory (getenv variable))) "/")
761 (t " "))))
762 (insert protection suffix)))
763 success))
764
765
766 (defun shell-replace-by-expanded-directory ()
767 "Expand directory stack reference before point.
768 Directory stack references are of the form \"=digit\" or \"=-\".
769 See `default-directory' and `shell-dirstack'.
770
771 Returns t if successful."
772 (interactive)
773 (if (comint-match-partial-filename)
774 (save-excursion
775 (goto-char (match-beginning 0))
776 (let ((stack (cons default-directory shell-dirstack))
777 (index (cond ((looking-at "=-/?")
778 (length shell-dirstack))
779 ((looking-at "=\\([0-9]+\\)")
780 (string-to-number
781 (buffer-substring
782 (match-beginning 1) (match-end 1)))))))
783 (cond ((null index)
784 nil)
785 ((>= index (length stack))
786 (error "Directory stack not that deep."))
787 (t
788 (replace-match (file-name-as-directory (nth index stack)) t t)
789 (message "Directory item: %d" index)
790 t))))))
791 \f
792 (provide 'shell)
793
794 ;;; shell.el ends here