1 ;;; shell.el --- specialized comint.el for running the shell.
2 ;;; Copyright (C) 1988, 1993 Free Software Foundation, Inc.
4 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
5 ;; Adapted-by: Simon Marshall <s.marshall@dcs.hull.ac.uk>
8 ;;; This file is part of GNU Emacs.
10 ;;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;;; it under the terms of the GNU General Public License as published by
12 ;;; the Free Software Foundation; either version 2, or (at your option)
13 ;;; any later version.
15 ;;; GNU Emacs is distributed in the hope that it will be useful,
16 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;;; GNU General Public License for more details.
20 ;;; You should have received a copy of the GNU General Public License
21 ;;; along with GNU Emacs; see the file COPYING. If not, write to
22 ;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
26 ;;; Please send me bug reports, bug fixes, and extensions, so that I can
27 ;;; merge them into the master source.
28 ;;; - Olin Shivers (shivers@cs.cmu.edu)
29 ;;; - Simon Marshall (s.marshall@dcs.hull.ac.uk)
31 ;;; This file defines a a shell-in-a-buffer package (shell mode) built
32 ;;; on top of comint mode. This is actually cmushell with things
33 ;;; renamed to replace its counterpart in Emacs 18. cmushell is more
34 ;;; featureful, robust, and uniform than the Emacs 18 version.
36 ;;; Since this mode is built on top of the general command-interpreter-in-
37 ;;; a-buffer mode (comint mode), it shares a common base functionality,
38 ;;; and a common set of bindings, with all modes derived from comint mode.
39 ;;; This makes these modes easier to use.
41 ;;; For documentation on the functionality provided by comint mode, and
42 ;;; the hooks available for customising it, see the file comint.el.
43 ;;; For further information on shell mode, see the comments below.
46 ;;; When sending text from a source file to a subprocess, the process-mark can
47 ;;; move off the window, so you can lose sight of the process interactions.
48 ;;; Maybe I should ensure the process mark is in the window when I send
49 ;;; text to the process? Switch selectable?
52 ;;=============================================================================
53 ;; Some suggestions for your .emacs file.
55 ;; ; If shell lives in some non-standard directory, you must tell emacs
56 ;; ; where to get it. This may or may not be necessary.
57 ;; (setq load-path (cons (expand-file-name "~jones/lib/emacs") load-path))
59 ;; ; Autoload shell from file shell.el
60 ;; (autoload 'shell "shell"
61 ;; "Run an inferior shell process."
64 ;; ; Define C-c t to run my favorite command in shell mode:
65 ;; (setq shell-mode-hook
67 ;; (define-key shell-mode-map "\C-ct" 'favorite-cmd))))
70 ;;; Brief Command Documentation:
71 ;;;============================================================================
72 ;;; Comint Mode Commands: (common to shell and all comint-derived modes)
74 ;;; m-p comint-previous-input Cycle backwards in input history
75 ;;; m-n comint-next-input Cycle forwards
76 ;;; m-r comint-previous-matching-input Previous input matching a regexp
77 ;;; m-R comint-previous-matching-input-from-input -"- matching input
78 ;;; m-s comint-next-matching-input Next input that matches
79 ;;; m-S comint-next-matching-input-from-input -"- matching input
80 ;;; m-c-r comint-previous-input-matching Search backwards in input history
81 ;;; return comint-send-input
82 ;;; c-a comint-bol Beginning of line; skip prompt
83 ;;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
84 ;;; c-c c-u comint-kill-input ^u
85 ;;; c-c c-w backward-kill-word ^w
86 ;;; c-c c-c comint-interrupt-subjob ^c
87 ;;; c-c c-z comint-stop-subjob ^z
88 ;;; c-c c-\ comint-quit-subjob ^\
89 ;;; c-c c-o comint-kill-output Delete last batch of process output
90 ;;; c-c c-r comint-show-output Show last batch of process output
91 ;;; c-c c-h comint-dynamic-list-input-ring List input history
92 ;;; send-invisible Read line w/o echo & send to proc
93 ;;; comint-continue-subjob Useful if you accidentally suspend
95 ;;; comint-mode-hook is the comint mode hook.
97 ;;; Shell Mode Commands:
98 ;;; shell Fires up the shell process
99 ;;; tab comint-dynamic-complete Complete filename/command/history
100 ;;; m-? comint-dynamic-list-filename-completions List completions in help buffer
101 ;;; m-c-f shell-forward-command Forward a shell command
102 ;;; m-c-b shell-backward-command Backward a shell command
103 ;;; dirs Resync the buffer's dir stack
104 ;;; dirtrack-toggle Turn dir tracking on/off
106 ;;; The shell mode hook is shell-mode-hook
107 ;;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
110 ;;; Read the rest of this file for more information.
112 ;;; SHELL.EL COMPATIBILITY
113 ;;; Notes from when this was called cmushell, and was not the standard emacs
115 ;;;============================================================================
116 ;;; In brief: this package should have no trouble coexisting with shell.el.
118 ;;; Most customising variables -- e.g., explicit-shell-file-name -- are the
119 ;;; same, so the users shouldn't have much trouble. Hooks have different
120 ;;; names, however, so you can customise shell mode differently from cmushell
121 ;;; mode. You basically just have to remember to type M-x cmushell instead of
124 ;;; It would be nice if this file was completely plug-compatible with the old
125 ;;; shell package -- if you could just name this file shell.el, and have it
126 ;;; transparently replace the old one. But you can't. Several other packages
127 ;;; (tex-mode, background, dbx, gdb, kermit, monkey, prolog, telnet) are also
128 ;;; clients of shell mode. These packages assume detailed knowledge of shell
129 ;;; mode internals in ways that are incompatible with cmushell mode (mostly
130 ;;; because of cmushell mode's greater functionality). So, unless we are
131 ;;; willing to port all of these packages, we can't have this file be a
132 ;;; complete replacement for shell.el -- that is, we can't name this file
133 ;;; shell.el, and its main entry point (shell), because dbx.el will break
134 ;;; when it loads it in and tries to use it.
136 ;;; There are two ways to fix this. One: rewrite these other modes to use the
137 ;;; new package. This is a win, but can't be assumed. The other, backwards
138 ;;; compatible route, is to make this package non-conflict with shell.el, so
139 ;;; both files can be loaded in at the same time. And *that* is why some
140 ;;; functions and variables have different names: (cmushell),
141 ;;; cmushell-mode-map, that sort of thing. All the names have been carefully
142 ;;; chosen so that shell.el and cmushell.el won't tromp on each other.
144 ;;; Customization and Buffer Variables
145 ;;; ===========================================================================
153 (defvar shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
154 "Regexp to match prompts in the inferior shell.
155 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
156 This variable is used to initialise `comint-prompt-regexp' in the
159 The pattern should probably not match more than one line. If it does,
160 shell-mode may become confused trying to distinguish prompt from input
161 on lines which don't start with a prompt.
163 This is a fine thing to set in your `.emacs' file.")
165 (defvar shell-delimiter-argument-list '("|" "&" "<" ">" "(" ")" ";")
166 "List of characters to recognise as separate arguments.
167 Defaults to \(\"|\" \"&\" \"\(\" \")\" \";\"), which works pretty well.
168 This variable is used to initialise `comint-delimiter-argument-list' in the
171 This is a fine thing to set in your `.emacs' file.")
173 (defvar shell-command-regexp "\\((.*)\\|[^;&|]\\)+"
174 "*Regexp to match shell commands.
175 Elements of pipes are considered as separate commands, forks and redirections
176 as part of one command.")
178 (defvar shell-completion-execonly t
179 "*If non-nil, use executable files only for completion candidates.
180 This mirrors the optional behavior of tcsh.
182 Detecting executability of files may slow command completion considerably.")
184 (defvar shell-popd-regexp "popd"
185 "*Regexp to match subshell commands equivalent to popd.")
187 (defvar shell-pushd-regexp "pushd"
188 "*Regexp to match subshell commands equivalent to pushd.")
190 (defvar shell-pushd-tohome nil
191 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
192 This mirrors the optional behavior of tcsh.")
194 (defvar shell-pushd-dextract nil
195 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
196 This mirrors the optional behavior of tcsh.")
198 (defvar shell-pushd-dunique nil
199 "*If non-nil, make pushd only add unique directories to the stack.
200 This mirrors the optional behavior of tcsh.")
202 (defvar shell-cd-regexp "cd"
203 "*Regexp to match subshell commands equivalent to cd.")
205 (defvar explicit-shell-file-name nil
206 "*If non-nil, is file name to use for explicitly requested inferior shell.")
208 (defvar explicit-csh-args
209 (if (eq system-type 'hpux)
210 ;; -T persuades HP's csh not to think it is smarter
211 ;; than us about what terminal modes to use.
214 "*Args passed to inferior shell by M-x shell, if the shell is csh.
215 Value is a list of strings, which may be nil.")
217 ;;; All the above vars aren't prefixed "cmushell-" to make them
218 ;;; backwards compatible w/shell.el and old .emacs files.
220 (defvar shell-dirstack nil
221 "List of directories saved by pushd in this buffer's shell.
222 Thus, this does not include the shell's current directory.")
224 (defvar shell-last-dir nil
225 "Keep track of last directory for ksh `cd -' command.")
227 (defvar shell-dirstack-query "dirs"
228 "Command used by `shell-resync-dir' to query the shell.")
230 (defvar shell-mode-map '())
231 (cond ((not shell-mode-map)
232 (setq shell-mode-map (full-copy-sparse-keymap comint-mode-map))
233 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
234 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
235 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
236 (define-key shell-mode-map "\M-?"
237 'comint-dynamic-list-filename-completions)))
239 (defvar shell-mode-hook '()
240 "*Hook for customising Shell mode.")
244 ;;; ===========================================================================
248 "Major mode for interacting with an inferior shell.
249 Return after the end of the process' output sends the text from the
250 end of process to the end of the current line.
251 Return before end of process output copies the current line (except
252 for the prompt) to the end of the buffer and sends it.
253 M-x send-invisible reads a line of text without echoing it, and sends it to
254 the shell. This is useful for entering passwords.
256 If you accidentally suspend your process, use \\[comint-continue-subjob]
259 cd, pushd and popd commands given to the shell are watched by Emacs to keep
260 this buffer's default directory the same as the shell's working directory.
261 M-x dirs queries the shell and resyncs Emacs' idea of what the current
263 M-x dirtrack-toggle turns directory tracking on and off.
266 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
267 `shell-mode-hook' (in that order). After each shell output, the hooks on
268 `comint-output-filter-functions' are run.
270 Variables `shell-cd-regexp', `shell-pushd-regexp' and `shell-popd-regexp'
271 are used to match their respective commands, while `shell-pushd-tohome',
272 `shell-pushd-dextract' and `shell-pushd-dunique' control the behavior of the
275 Variables `comint-completion-autolist', `comint-completion-addsuffix' and
276 `comint-completion-recexact' control the behavior of file name, command name
277 and variable name completion. Variable `shell-completion-execonly' controls
278 the behavior of command name completion.
280 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
281 the initialisation of the input ring history, and history expansion.
283 Variables `comint-output-filter-functions', `comint-scroll-to-bottom-on-input',
284 and `comint-scroll-to-bottom-on-output' control whether input and output
285 cause the window to scroll to the end of the buffer."
288 (setq major-mode 'shell-mode)
289 (setq mode-name "Shell")
290 (use-local-map shell-mode-map)
291 (setq comint-prompt-regexp shell-prompt-pattern)
292 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
293 (setq comint-after-partial-filename-command 'shell-after-partial-filename)
294 (setq comint-get-current-command 'shell-get-current-command)
295 (setq comint-dynamic-complete-command-command 'shell-dynamic-complete-command)
296 (make-local-variable 'paragraph-start)
297 (setq paragraph-start comint-prompt-regexp)
298 (make-local-variable 'shell-dirstack)
299 (setq shell-dirstack nil)
300 (setq shell-last-dir nil)
301 (make-local-variable 'shell-dirtrackp)
302 (setq shell-dirtrackp t)
303 (setq comint-input-sentinel 'shell-directory-tracker)
304 ;; shell-dependent assignments.
305 (let ((shell (car (process-command (get-buffer-process (current-buffer))))))
306 (setq comint-input-ring-file-name
307 (or (getenv "HISTFILE")
308 (cond ((string-match "csh$" shell) "~/.history")
309 ((string-match "bash$" shell) "~/.bash_history")
310 ((string-match "ksh$" shell) "~/.sh_history")
312 (run-hooks 'shell-mode-hook)
313 (comint-read-input-ring)
314 (shell-dirstack-message))
318 "Run an inferior shell, with I/O through buffer *shell*.
319 If buffer exists but shell process is not running, make new shell.
320 If buffer exists and shell process is running, just switch to buffer `*shell*'.
321 Program used comes from variable `explicit-shell-file-name',
322 or (if that is nil) from the ESHELL environment variable,
323 or else from SHELL if there is no ESHELL.
324 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
325 (Note that this may lose due to a timing error if the shell
326 discards input when it starts up.)
327 The buffer is put in Shell mode, giving commands for sending input
328 and controlling the subjobs of the shell. See `shell-mode'.
329 See also the variable `shell-prompt-pattern'.
331 The shell file name (sans directories) is used to make a symbol name
332 such as `explicit-csh-args'. If that symbol is a variable,
333 its value is used as a list of arguments when invoking the shell.
334 Otherwise, one argument `-i' is passed to the shell.
336 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
338 (if (not (comint-check-proc "*shell*"))
339 (let* ((prog (or explicit-shell-file-name
343 (name (file-name-nondirectory prog))
344 (startfile (concat "~/.emacs_" name))
345 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
346 (set-buffer (apply 'make-comint "shell" prog
347 (if (file-exists-p startfile) startfile)
348 (if (and xargs-name (boundp xargs-name))
349 (symbol-value xargs-name)
352 (switch-to-buffer "*shell*"))
354 ;;; Directory tracking
355 ;;; ===========================================================================
356 ;;; This code provides the shell mode input sentinel
357 ;;; SHELL-DIRECTORY-TRACKER
358 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
359 ;;; changes the current directory of the shell buffer accordingly.
361 ;;; This is basically a fragile hack, although it's more accurate than
362 ;;; the version in Emacs 18's shell.el. It has the following failings:
363 ;;; 1. It doesn't know about the cdpath shell variable.
364 ;;; 2. It cannot infallibly deal with command sequences, though it does well
365 ;;; with these and with ignoring commands forked in another shell with ()s.
366 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
367 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
368 ;;; that, there's no way to catch shell commands where cd's are buried
369 ;;; inside conditional expressions, aliases, and so forth.
371 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
372 ;;; messes it up. You run other processes under the shell; these each have
373 ;;; separate working directories, and some have commands for manipulating
374 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
375 ;;; commands that do *not* affect the current w.d. at all, but look like they
376 ;;; do (e.g., the cd command in ftp). In shells that allow you job
377 ;;; control, you can switch between jobs, all having different w.d.'s. So
378 ;;; simply saying %3 can shift your w.d..
380 ;;; The solution is to relax, not stress out about it, and settle for
381 ;;; a hack that works pretty well in typical circumstances. Remember
382 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
385 ;;; One good hack not implemented here for users of programmable shells
386 ;;; is to program up the shell w.d. manipulation commands to output
387 ;;; a coded command sequence to the tty. Something like
389 ;;; where <cwd> is the new current working directory. Then trash the
390 ;;; directory tracking machinery currently used in this package, and
391 ;;; replace it with a process filter that watches for and strips out
394 (defun shell-directory-tracker (str)
395 "Tracks cd, pushd and popd commands issued to the shell.
396 This function is called on each input passed to the shell.
397 It watches for cd, pushd and popd commands and sets the buffer's
398 default directory to track these commands.
400 You may toggle this tracking on and off with M-x dirtrack-toggle.
401 If emacs gets confused, you can resync with the shell with M-x dirs.
403 See variables `shell-cd-regexp', `shell-pushd-regexp', and `shell-popd-regexp',
404 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
405 control the behavior of the relevant command.
407 Environment variables are expanded, see function `substitute-in-file-name'."
409 ;; We fail gracefully if we think the command will fail in the shell.
410 (condition-case chdir-failure
411 (let ((start (progn (string-match "^[;\\s ]*" str) ; skip whitespace
414 (while (string-match shell-command-regexp str start)
415 (setq end (match-end 0)
416 cmd (comint-arguments (substring str start end) 0 0)
417 arg1 (comint-arguments (substring str start end) 1 1))
418 (cond ((eq (string-match shell-popd-regexp cmd) 0)
419 (shell-process-popd (substitute-in-file-name arg1)))
420 ((eq (string-match shell-pushd-regexp cmd) 0)
421 (shell-process-pushd (substitute-in-file-name arg1)))
422 ((eq (string-match shell-cd-regexp cmd) 0)
423 (shell-process-cd (substitute-in-file-name arg1))))
424 (setq start (progn (string-match "[;\\s ]*" str end) ; skip again
426 (error (message "Couldn't cd")))))
429 ;; Like `cd', but prepends comint-file-name-prefix to absolute names.
430 (defsubst shell-cd (directory)
431 (if (file-name-absolute-p directory)
432 (cd-absolute (concat comint-file-name-prefix directory))
436 (defun shell-process-popd (arg)
437 (let ((num (or (shell-extract-num arg) 0)))
438 (cond ((and num (= num 0) shell-dirstack)
439 (shell-cd (car shell-dirstack))
440 (setq shell-dirstack (cdr shell-dirstack))
441 (shell-dirstack-message))
442 ((and num (> num 0) (<= num (length shell-dirstack)))
443 (let* ((ds (cons nil shell-dirstack))
444 (cell (nthcdr (1- num) ds)))
445 (rplacd cell (cdr (cdr cell)))
446 (setq shell-dirstack (cdr ds))
447 (shell-dirstack-message)))
449 (error (message "Couldn't popd."))))))
452 (defun shell-process-cd (arg)
453 (let ((new-dir (cond ((zerop (length arg)) (getenv "HOME"))
454 ((string-equal "-" arg) shell-last-dir)
456 (setq shell-last-dir default-directory)
458 (shell-dirstack-message)))
461 (defun shell-process-pushd (arg)
462 (let ((num (shell-extract-num arg)))
463 (cond ((zerop (length arg))
464 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
465 (cond (shell-pushd-tohome
466 (shell-process-pushd "~"))
468 (let ((old default-directory))
469 (shell-cd (car shell-dirstack))
471 (cons old (cdr shell-dirstack)))
472 (shell-dirstack-message)))
474 (message "Directory stack empty."))))
477 (cond ((> num (length shell-dirstack))
478 (message "Directory stack not that deep."))
480 (error (message "Couldn't cd.")))
481 (shell-pushd-dextract
482 (let ((dir (nth (1- num) shell-dirstack)))
483 (shell-process-popd arg)
484 (shell-process-pushd default-directory)
486 (shell-dirstack-message)))
488 (let* ((ds (cons default-directory shell-dirstack))
490 (front (nthcdr num ds))
491 (back (reverse (nthcdr (- dslen num) (reverse ds))))
492 (new-ds (append front back)))
493 (shell-cd (car new-ds))
494 (setq shell-dirstack (cdr new-ds))
495 (shell-dirstack-message)))))
498 (let ((old-wd default-directory))
500 (if (or (null shell-pushd-dunique)
501 (not (member old-wd shell-dirstack)))
502 (setq shell-dirstack (cons old-wd shell-dirstack)))
503 (shell-dirstack-message))))))
505 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
506 (defun shell-extract-num (str)
507 (and (string-match "^\\+[1-9][0-9]*$" str)
508 (string-to-int str)))
511 (defun shell-dirtrack-toggle ()
512 "Turn directory tracking on and off in a shell buffer."
514 (setq shell-dirtrackp (not shell-dirtrackp))
515 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
517 ;;; For your typing convenience:
518 (defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
521 (defun shell-resync-dirs ()
522 "Resync the buffer's idea of the current directory stack.
523 This command queries the shell with the command bound to
524 `shell-dirstack-query' (default \"dirs\"), reads the next
525 line output and parses it to form the new directory stack.
526 DON'T issue this command unless the buffer is at a shell prompt.
527 Also, note that if some other subprocess decides to do output
528 immediately after the query, its output will be taken as the
529 new directory stack -- you lose. If this happens, just do the
532 (let* ((proc (get-buffer-process (current-buffer)))
533 (pmark (process-mark proc)))
535 (insert shell-dirstack-query) (insert "\n")
536 (sit-for 0) ; force redisplay
537 (comint-send-string proc shell-dirstack-query)
538 (comint-send-string proc "\n")
539 (set-marker pmark (point))
540 (let ((pt (point))) ; wait for 1 line
541 ;; This extra newline prevents the user's pending input from spoofing us.
542 (insert "\n") (backward-char 1)
543 (while (not (looking-at ".+\n"))
544 (accept-process-output proc)
546 (goto-char pmark) (delete-char 1) ; remove the extra newline
547 ;; That's the dirlist. grab it & parse it.
548 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
550 (ds '()) ; new dir stack
553 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
554 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
555 (setq ds (cons (substring dl (match-beginning 1) (match-end 1))
557 (setq i (match-end 0)))
558 (let ((ds (reverse ds)))
561 (setq shell-dirstack (cdr ds))
562 (shell-dirstack-message))
563 (error (message "Couldn't cd.")))))))
565 ;;; For your typing convenience:
566 (defalias 'dirs 'shell-resync-dirs)
569 ;;; Show the current dirstack on the message line.
570 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
571 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
572 ;;; All the commands that mung the buffer's dirstack finish by calling
574 (defun shell-dirstack-message ()
576 (ds (cons default-directory shell-dirstack))
577 (home (expand-file-name (concat comint-file-name-prefix "~/")))
578 (homelen (length home)))
580 (let ((dir (car ds)))
581 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
582 (setq dir (concat "~/" (substring dir homelen))))
583 ;; Strip off comint-file-name-prefix if present.
584 (and comint-file-name-prefix
585 (>= (length dir) (length comint-file-name-prefix))
586 (string= comint-file-name-prefix
587 (substring dir 0 (length comint-file-name-prefix)))
588 (setq dir (substring dir (length comint-file-name-prefix)))
590 (setq msg (concat msg (directory-file-name dir) " "))
594 (defun shell-forward-command (&optional arg)
595 "Move forward across ARG shell command(s). Does not cross lines.
596 See `shell-command-regexp'."
598 (let ((limit (save-excursion (end-of-line nil) (point))))
599 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\\s ]*\\)+")
601 (skip-syntax-backward "^\\s "))))
604 (defun shell-backward-command (&optional arg)
605 "Move backward across ARG shell command(s). Does not cross lines.
606 See `shell-command-regexp'."
608 (let ((limit (save-excursion (comint-bol nil) (point))))
609 (skip-syntax-backward "\\s " limit)
610 (if (re-search-backward
611 (format "[;&|]+[\\s ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
612 (progn (goto-char (match-beginning 1))
613 (skip-syntax-backward "^\\s ")))))
616 (defun shell-get-current-command ()
617 "Function that returns the current command including arguments."
619 (if (looking-at "\\s *[^;&|]")
620 (goto-char (match-end 0)))
622 (progn (shell-backward-command 1) (point))
623 (progn (shell-forward-command 1) (if (eolp) (point) (match-end 1))))))
626 (defun shell-after-partial-filename ()
627 "Returns t if point is after a file name.
628 File names are assumed to contain `/'s or not be the first item in the command.
630 See also `shell-backward-command'."
631 (let ((filename (comint-match-partial-filename)))
632 (or (save-match-data (string-match "/" filename))
633 (not (eq (match-beginning 0)
634 (save-excursion (shell-backward-command 1) (point)))))))
637 (defun shell-dynamic-complete-command ()
638 "Dynamically complete the command at point.
639 This function is similar to `comint-dynamic-complete-filename', except that it
640 searches `exec-path' (minus the trailing emacs library path) for completion
641 candidates. Note that this may not be the same as the shell's idea of the
644 Completion is dependent on the value of `shell-completion-execonly', plus
645 those that effect file completion. See `comint-dynamic-complete-filename'."
647 (let* ((completion-ignore-case nil)
648 (filename (comint-match-partial-filename))
649 (pathnondir (file-name-nondirectory filename))
650 (paths (cdr (reverse exec-path)))
651 (cwd (file-name-as-directory (expand-file-name default-directory)))
653 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
654 completion-ignored-extensions "\\|"))
655 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
656 ;; Go thru each path in the search path, finding completions.
658 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
659 comps-in-path (and (file-accessible-directory-p path)
660 (file-name-all-completions pathnondir path)))
661 ;; Go thru each completion found, to see whether it should be used.
663 (setq file (car comps-in-path)
664 filepath (concat path file))
665 (if (and (not (member file completions))
666 (not (string-match ignored-extensions file))
667 (or (string-equal path cwd)
668 (not (file-directory-p filepath)))
669 (or (null shell-completion-execonly)
670 (file-executable-p filepath)))
671 (setq completions (cons file completions)))
672 (setq comps-in-path (cdr comps-in-path)))
673 (setq paths (cdr paths)))
674 ;; OK, we've got a list of completions.
675 (cond ((null completions)
676 (message "No completions of %s" filename)
678 ((= 1 (length completions)) ; Gotcha!
679 (let ((completion (car completions)))
680 (if (string-equal completion pathnondir)
681 (message "Sole completion")
682 (insert (substring (directory-file-name completion)
683 (length pathnondir)))
684 (message "Completed"))
685 (if comint-completion-addsuffix
686 (insert (if (file-directory-p completion) "/" " ")))))
687 (t ; There's no unique completion.
689 (try-completion pathnondir (mapcar (function (lambda (x)
692 ;; Insert the longest substring.
693 (insert (substring (directory-file-name completion)
694 (length pathnondir)))
695 (cond ((and comint-completion-recexact comint-completion-addsuffix
696 (string-equal pathnondir completion)
697 (member completion completions))
698 ;; It's not unique, but user wants shortest match.
699 (insert (if (file-directory-p completion) "/" " "))
700 (message "Completed shortest"))
701 ((or comint-completion-autolist
702 (string-equal pathnondir completion))
703 ;; It's not unique, list possible completions.
704 (comint-dynamic-list-completions completions))
706 (message "Partially completed"))))))))
708 ;;; Do the user's customization...
710 ;;; Isn't this what eval-after-load is for?
711 ;;;(defvar shell-load-hook nil
712 ;;; "This hook is run when shell is loaded in.
713 ;;;This is a good place to put keybindings.")
715 ;;;(run-hooks 'shell-load-hook)
719 ;;; shell.el ends here