1 ;;; shell.el --- specialized comint.el for running the shell.
3 ;; Copyright (C) 1988, 1993, 1994 Free Software Foundation, Inc.
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
6 ;; Maintainer: Simon Marshall <s.marshall@dcs.hull.ac.uk>
9 ;; This file is part of GNU Emacs.
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)
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.
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.
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 (s.marshall@dcs.hull.ac.uk)
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.
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.
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.
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?
53 ;;=============================================================================
54 ;; Some suggestions for your .emacs file.
56 ;; ;; Define C-c t to run my favorite command in shell mode:
57 ;; (setq shell-mode-hook
59 ;; (define-key shell-mode-map "\C-ct" 'favorite-cmd))))
62 ;;; Brief Command Documentation:
63 ;;;============================================================================
64 ;;; Comint Mode Commands: (common to shell and all comint-derived modes)
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
87 ;;; comint-mode-hook is the comint mode hook.
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
99 ;;; The shell mode hook is shell-mode-hook
100 ;;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
103 ;;; Read the rest of this file for more information.
105 ;;; Customization and Buffer Variables
106 ;;; ===========================================================================
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
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.
124 This is a fine thing to set in your `.emacs' file.")
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 (\"~\" \"#\" \"%\").
132 This is a fine thing to set in your `.emacs' file.")
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 (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
139 This is a fine thing to set in your `.emacs' file.")
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
151 This is a fine thing to set in your `.emacs' file.")
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.")
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.
161 Detecting executability of files may slow command completion considerably.")
163 (defvar shell-popd-regexp
"popd"
164 "*Regexp to match subshell commands equivalent to popd.")
166 (defvar shell-pushd-regexp
"pushd"
167 "*Regexp to match subshell commands equivalent to pushd.")
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.")
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.")
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.")
181 (defvar shell-cd-regexp
"cd"
182 "*Regexp to match subshell commands equivalent to cd.")
184 (defvar explicit-shell-file-name nil
185 "*If non-nil, is file name to use for explicitly requested inferior shell.")
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.
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.")
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).
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'.
205 This variable supplies a default for `comint-input-autoexpand',
206 for Shell mode only.")
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.")
212 (defvar shell-dirtrackp t
213 "Non-nil in a shell buffer means directory tracking is enabled.")
215 (defvar shell-last-dir nil
216 "Keep track of last directory for ksh `cd -' command.")
218 (defvar shell-dirstack-query nil
219 "Command used by `shell-resync-dir' to query the shell.")
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
)
235 (define-key-after (lookup-key shell-mode-map
[menu-bar completion
])
236 [expand-directory
] '("Expand Directory Reference" .
237 shell-replace-by-expanded-directory
)
240 (defvar shell-mode-hook
'()
241 "*Hook for customising Shell mode.")
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.")
251 ;;; ===========================================================================
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 M-x 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'.
264 If you accidentally suspend your process, use \\[comint-continue-subjob]
267 cd, pushd and popd commands given to the shell are watched by Emacs to keep
268 this buffer's default directory the same as the shell's working directory.
269 M-x dirs queries the shell and resyncs Emacs' idea of what the current
271 M-x dirtrack-toggle turns directory tracking on and off.
274 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
275 `shell-mode-hook' (in that order). Before each input, the hooks on
276 `comint-input-filter-functions' are run. After each shell output, the hooks
277 on `comint-output-filter-functions' are run.
279 Variables `shell-cd-regexp', `shell-pushd-regexp' and `shell-popd-regexp'
280 are used to match their respective commands, while `shell-pushd-tohome',
281 `shell-pushd-dextract' and `shell-pushd-dunique' control the behavior of the
284 Variables `comint-completion-autolist', `comint-completion-addsuffix',
285 `comint-completion-recexact' and `comint-completion-fignore' control the
286 behavior of file name, command name and variable name completion. Variable
287 `shell-completion-execonly' controls the behavior of command name completion.
288 Variable `shell-completion-fignore' is used to initialise the value of
289 `comint-completion-fignore'.
291 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
292 the initialisation of the input ring history, and history expansion.
294 Variables `comint-output-filter-functions', a hook, and
295 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
296 control whether input and output cause the window to scroll to the end of the
300 (setq major-mode
'shell-mode
)
301 (setq mode-name
"Shell")
302 (use-local-map shell-mode-map
)
303 (setq comint-prompt-regexp shell-prompt-pattern
)
304 (setq comint-completion-fignore shell-completion-fignore
)
305 (setq comint-delimiter-argument-list shell-delimiter-argument-list
)
306 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions
)
307 (make-local-variable 'paragraph-start
)
308 (setq paragraph-start comint-prompt-regexp
)
309 (make-local-variable 'font-lock-defaults
)
310 (setq font-lock-defaults
'(shell-font-lock-keywords t
))
311 (make-local-variable 'shell-dirstack
)
312 (setq shell-dirstack nil
)
313 (setq shell-last-dir nil
)
314 (make-local-variable 'shell-dirtrackp
)
315 (setq shell-dirtrackp t
)
316 (add-hook 'comint-input-filter-functions
'shell-directory-tracker
)
317 (setq comint-input-autoexpand shell-input-autoexpand
)
318 ;; shell-dependent assignments.
319 (let ((shell (file-name-nondirectory (car
320 (process-command (get-buffer-process (current-buffer)))))))
321 (setq comint-input-ring-file-name
322 (or (getenv "HISTFILE")
323 (cond ((string-equal shell
"bash") "~/.bash_history")
324 ((string-equal shell
"ksh") "~/.sh_history")
326 (if (equal (file-truename comint-input-ring-file-name
) "/dev/null")
327 (setq comint-input-ring-file-name nil
))
328 (setq shell-dirstack-query
329 (if (string-match "^k?sh$" shell
) "pwd" "dirs")))
330 (run-hooks 'shell-mode-hook
)
331 (comint-read-input-ring t
))
335 "Run an inferior shell, with I/O through buffer *shell*.
336 If buffer exists but shell process is not running, make new shell.
337 If buffer exists and shell process is running, just switch to buffer `*shell*'.
338 Program used comes from variable `explicit-shell-file-name',
339 or (if that is nil) from the ESHELL environment variable,
340 or else from SHELL if there is no ESHELL.
341 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
342 (Note that this may lose due to a timing error if the shell
343 discards input when it starts up.)
344 The buffer is put in Shell mode, giving commands for sending input
345 and controlling the subjobs of the shell. See `shell-mode'.
346 See also the variable `shell-prompt-pattern'.
348 The shell file name (sans directories) is used to make a symbol name
349 such as `explicit-csh-args'. If that symbol is a variable,
350 its value is used as a list of arguments when invoking the shell.
351 Otherwise, one argument `-i' is passed to the shell.
353 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
355 (if (not (comint-check-proc "*shell*"))
356 (let* ((prog (or explicit-shell-file-name
360 (name (file-name-nondirectory prog
))
361 (startfile (concat "~/.emacs_" name
))
362 (xargs-name (intern-soft (concat "explicit-" name
"-args"))))
363 (set-buffer (apply 'make-comint
"shell" prog
364 (if (file-exists-p startfile
) startfile
)
365 (if (and xargs-name
(boundp xargs-name
))
366 (symbol-value xargs-name
)
369 (switch-to-buffer "*shell*"))
371 ;;; Directory tracking
372 ;;; ===========================================================================
373 ;;; This code provides the shell mode input sentinel
374 ;;; SHELL-DIRECTORY-TRACKER
375 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
376 ;;; changes the current directory of the shell buffer accordingly.
378 ;;; This is basically a fragile hack, although it's more accurate than
379 ;;; the version in Emacs 18's shell.el. It has the following failings:
380 ;;; 1. It doesn't know about the cdpath shell variable.
381 ;;; 2. It cannot infallibly deal with command sequences, though it does well
382 ;;; with these and with ignoring commands forked in another shell with ()s.
383 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
384 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
385 ;;; that, there's no way to catch shell commands where cd's are buried
386 ;;; inside conditional expressions, aliases, and so forth.
388 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
389 ;;; messes it up. You run other processes under the shell; these each have
390 ;;; separate working directories, and some have commands for manipulating
391 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
392 ;;; commands that do *not* affect the current w.d. at all, but look like they
393 ;;; do (e.g., the cd command in ftp). In shells that allow you job
394 ;;; control, you can switch between jobs, all having different w.d.'s. So
395 ;;; simply saying %3 can shift your w.d..
397 ;;; The solution is to relax, not stress out about it, and settle for
398 ;;; a hack that works pretty well in typical circumstances. Remember
399 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
402 ;;; One good hack not implemented here for users of programmable shells
403 ;;; is to program up the shell w.d. manipulation commands to output
404 ;;; a coded command sequence to the tty. Something like
406 ;;; where <cwd> is the new current working directory. Then trash the
407 ;;; directory tracking machinery currently used in this package, and
408 ;;; replace it with a process filter that watches for and strips out
411 (defun shell-directory-tracker (str)
412 "Tracks cd, pushd and popd commands issued to the shell.
413 This function is called on each input passed to the shell.
414 It watches for cd, pushd and popd commands and sets the buffer's
415 default directory to track these commands.
417 You may toggle this tracking on and off with M-x dirtrack-toggle.
418 If emacs gets confused, you can resync with the shell with M-x dirs.
420 See variables `shell-cd-regexp', `shell-pushd-regexp', and `shell-popd-regexp',
421 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
422 control the behavior of the relevant command.
424 Environment variables are expanded, see function `substitute-in-file-name'."
426 ;; We fail gracefully if we think the command will fail in the shell.
427 (condition-case chdir-failure
428 (let ((start (progn (string-match "^[;\\s ]*" str
) ; skip whitespace
431 (while (string-match shell-command-regexp str start
)
432 (setq end
(match-end 0)
433 cmd
(comint-arguments (substring str start end
) 0 0)
434 arg1
(comint-arguments (substring str start end
) 1 1))
435 (cond ((eq (string-match shell-popd-regexp cmd
) 0)
436 (shell-process-popd (substitute-in-file-name arg1
)))
437 ((eq (string-match shell-pushd-regexp cmd
) 0)
438 (shell-process-pushd (substitute-in-file-name arg1
)))
439 ((eq (string-match shell-cd-regexp cmd
) 0)
440 (shell-process-cd (substitute-in-file-name arg1
))))
441 (setq start
(progn (string-match "[;\\s ]*" str end
) ; skip again
443 (error "Couldn't cd"))))
446 (defun shell-process-popd (arg)
447 (let ((num (or (shell-extract-num arg
) 0)))
448 (cond ((and num
(= num
0) shell-dirstack
)
449 (cd (car shell-dirstack
))
450 (setq shell-dirstack
(cdr shell-dirstack
))
451 (shell-dirstack-message))
452 ((and num
(> num
0) (<= num
(length shell-dirstack
)))
453 (let* ((ds (cons nil shell-dirstack
))
454 (cell (nthcdr (1- num
) ds
)))
455 (rplacd cell
(cdr (cdr cell
)))
456 (setq shell-dirstack
(cdr ds
))
457 (shell-dirstack-message)))
459 (error "Couldn't popd")))))
461 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
462 (defun shell-prefixed-directory-name (dir)
463 (if (= (length comint-file-name-prefix
) 0)
465 (if (file-name-absolute-p dir
)
466 ;; The name is absolute, so prepend the prefix.
467 (concat comint-file-name-prefix dir
)
468 ;; For a relative name we assume default-directory already has the prefix.
469 (expand-file-name dir
))))
472 (defun shell-process-cd (arg)
473 (let ((new-dir (cond ((zerop (length arg
)) (concat comint-file-name-prefix
475 ((string-equal "-" arg
) shell-last-dir
)
476 (t (shell-prefixed-directory-name arg
)))))
477 (setq shell-last-dir default-directory
)
479 (shell-dirstack-message)))
482 (defun shell-process-pushd (arg)
483 (let ((num (shell-extract-num arg
)))
484 (cond ((zerop (length arg
))
485 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
486 (cond (shell-pushd-tohome
487 (shell-process-pushd (concat comint-file-name-prefix
"~")))
489 (let ((old default-directory
))
490 (cd (car shell-dirstack
))
492 (cons old
(cdr shell-dirstack
)))
493 (shell-dirstack-message)))
495 (message "Directory stack empty."))))
498 (cond ((> num
(length shell-dirstack
))
499 (message "Directory stack not that deep."))
501 (error (message "Couldn't cd.")))
502 (shell-pushd-dextract
503 (let ((dir (nth (1- num
) shell-dirstack
)))
504 (shell-process-popd arg
)
505 (shell-process-pushd default-directory
)
507 (shell-dirstack-message)))
509 (let* ((ds (cons default-directory shell-dirstack
))
511 (front (nthcdr num ds
))
512 (back (reverse (nthcdr (- dslen num
) (reverse ds
))))
513 (new-ds (append front back
)))
515 (setq shell-dirstack
(cdr new-ds
))
516 (shell-dirstack-message)))))
519 (let ((old-wd default-directory
))
520 (cd (shell-prefixed-directory-name arg
))
521 (if (or (null shell-pushd-dunique
)
522 (not (member old-wd shell-dirstack
)))
523 (setq shell-dirstack
(cons old-wd shell-dirstack
)))
524 (shell-dirstack-message))))))
526 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
527 (defun shell-extract-num (str)
528 (and (string-match "^\\+[1-9][0-9]*$" str
)
529 (string-to-int str
)))
532 (defun shell-dirtrack-toggle ()
533 "Turn directory tracking on and off in a shell buffer."
535 (setq shell-dirtrackp
(not shell-dirtrackp
))
536 (message "Directory tracking %s" (if shell-dirtrackp
"ON" "OFF")))
538 ;;; For your typing convenience:
539 (defalias 'dirtrack-toggle
'shell-dirtrack-toggle
)
542 (defun shell-resync-dirs ()
543 "Resync the buffer's idea of the current directory stack.
544 This command queries the shell with the command bound to
545 `shell-dirstack-query' (default \"dirs\"), reads the next
546 line output and parses it to form the new directory stack.
547 DON'T issue this command unless the buffer is at a shell prompt.
548 Also, note that if some other subprocess decides to do output
549 immediately after the query, its output will be taken as the
550 new directory stack -- you lose. If this happens, just do the
553 (let* ((proc (get-buffer-process (current-buffer)))
554 (pmark (process-mark proc
)))
556 (insert shell-dirstack-query
) (insert "\n")
557 (sit-for 0) ; force redisplay
558 (comint-send-string proc shell-dirstack-query
)
559 (comint-send-string proc
"\n")
560 (set-marker pmark
(point))
561 (let ((pt (point))) ; wait for 1 line
562 ;; This extra newline prevents the user's pending input from spoofing us.
563 (insert "\n") (backward-char 1)
564 (while (not (looking-at ".+\n"))
565 (accept-process-output proc
)
567 (goto-char pmark
) (delete-char 1) ; remove the extra newline
568 ;; That's the dirlist. grab it & parse it.
569 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
571 (ds '()) ; new dir stack
574 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
575 (string-match "\\s *\\(\\S +\\)\\s *" dl i
) ; pick off next dir
576 (setq ds
(cons (concat comint-file-name-prefix
577 (substring dl
(match-beginning 1)
580 (setq i
(match-end 0)))
581 (let ((ds (nreverse ds
)))
584 (setq shell-dirstack
(cdr ds
))
585 (shell-dirstack-message))
586 (error (message "Couldn't cd.")))))))
588 ;;; For your typing convenience:
589 (defalias 'dirs
'shell-resync-dirs
)
592 ;;; Show the current dirstack on the message line.
593 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
594 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
595 ;;; All the commands that mung the buffer's dirstack finish by calling
597 (defun shell-dirstack-message ()
599 (ds (cons default-directory shell-dirstack
))
600 (home (expand-file-name (concat comint-file-name-prefix
"~/")))
601 (homelen (length home
)))
603 (let ((dir (car ds
)))
604 (and (>= (length dir
) homelen
) (string= home
(substring dir
0 homelen
))
605 (setq dir
(concat "~/" (substring dir homelen
))))
606 ;; Strip off comint-file-name-prefix if present.
607 (and comint-file-name-prefix
608 (>= (length dir
) (length comint-file-name-prefix
))
609 (string= comint-file-name-prefix
610 (substring dir
0 (length comint-file-name-prefix
)))
611 (setq dir
(substring dir
(length comint-file-name-prefix
)))
613 (setq msg
(concat msg
(directory-file-name dir
) " "))
617 (defun shell-forward-command (&optional arg
)
618 "Move forward across ARG shell command(s). Does not cross lines.
619 See `shell-command-regexp'."
621 (let ((limit (save-excursion (end-of-line nil
) (point))))
622 (if (re-search-forward (concat shell-command-regexp
"\\([;&|][\t ]*\\)+")
624 (skip-syntax-backward " "))))
627 (defun shell-backward-command (&optional arg
)
628 "Move backward across ARG shell command(s). Does not cross lines.
629 See `shell-command-regexp'."
631 (let ((limit (save-excursion (comint-bol nil
) (point))))
632 (if (> limit
(point))
633 (save-excursion (beginning-of-line) (setq limit
(point))))
634 (skip-syntax-backward " " limit
)
635 (if (re-search-backward
636 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp
) limit
'move arg
)
637 (progn (goto-char (match-beginning 1))
638 (skip-chars-forward ";&|")))))
641 (defun shell-dynamic-complete-command ()
642 "Dynamically complete the command at point.
643 This function is similar to `comint-dynamic-complete-filename', except that it
644 searches `exec-path' (minus the trailing emacs library path) for completion
645 candidates. Note that this may not be the same as the shell's idea of the
648 Completion is dependent on the value of `shell-completion-execonly', plus
649 those that effect file completion. See `shell-dynamic-complete-as-command'.
651 Returns t if successful."
653 (let ((filename (comint-match-partial-filename)))
655 (save-match-data (not (string-match "[~/]" filename
)))
656 (eq (match-beginning 0)
657 (save-excursion (shell-backward-command 1) (point))))
658 (prog2 (message "Completing command name...")
659 (shell-dynamic-complete-as-command)))))
662 (defun shell-dynamic-complete-as-command ()
663 "Dynamically complete at point as a command.
664 See `shell-dynamic-complete-filename'. Returns t if successful."
665 (let* ((filename (or (comint-match-partial-filename) ""))
666 (pathnondir (file-name-nondirectory filename
))
667 (paths (cdr (reverse exec-path
)))
668 (cwd (file-name-as-directory (expand-file-name default-directory
)))
670 (and comint-completion-fignore
671 (mapconcat (function (lambda (x) (concat (regexp-quote x
) "$")))
672 comint-completion-fignore
"\\|")))
673 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
674 ;; Go thru each path in the search path, finding completions.
676 (setq path
(file-name-as-directory (comint-directory (or (car paths
) ".")))
677 comps-in-path
(and (file-accessible-directory-p path
)
678 (file-name-all-completions pathnondir path
)))
679 ;; Go thru each completion found, to see whether it should be used.
681 (setq file
(car comps-in-path
)
682 filepath
(concat path file
))
683 (if (and (not (member file completions
))
684 (not (and ignored-extensions
685 (string-match ignored-extensions file
)))
686 (or (string-equal path cwd
)
687 (not (file-directory-p filepath
)))
688 (or (null shell-completion-execonly
)
689 (file-executable-p filepath
)))
690 (setq completions
(cons file completions
)))
691 (setq comps-in-path
(cdr comps-in-path
)))
692 (setq paths
(cdr paths
)))
693 ;; OK, we've got a list of completions.
694 (let ((success (let ((comint-completion-addsuffix nil
))
695 (comint-dynamic-simple-complete pathnondir completions
))))
696 (if (and (memq success
'(sole shortest
)) comint-completion-addsuffix
697 (not (file-directory-p (comint-match-partial-filename))))
702 (defun shell-match-partial-variable ()
703 "Return the variable at point, or nil if non is found."
705 (let ((limit (point)))
706 (if (re-search-backward "[^A-Za-z0-9_{}]" nil
'move
)
707 (or (looking-at "\\$") (forward-char 1)))
708 ;; Anchor the search forwards.
709 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
711 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit
)
712 (buffer-substring (match-beginning 0) (match-end 0))))))
715 (defun shell-dynamic-complete-environment-variable ()
716 "Dynamically complete the environment variable at point.
717 Completes if after a variable, i.e., if it starts with a \"$\".
718 See `shell-dynamic-complete-as-environment-variable'.
720 This function is similar to `comint-dynamic-complete-filename', except that it
721 searches `process-environment' for completion candidates. Note that this may
722 not be the same as the interpreter's idea of variable names. The main problem
723 with this type of completion is that `process-environment' is the environment
724 which Emacs started with. Emacs does not track changes to the environment made
725 by the interpreter. Perhaps it would be more accurate if this function was
726 called `shell-dynamic-complete-process-environment-variable'.
728 Returns non-nil if successful."
730 (let ((variable (shell-match-partial-variable)))
731 (if (and variable
(string-match "^\\$" variable
))
732 (prog2 (message "Completing variable name...")
733 (shell-dynamic-complete-as-environment-variable)))))
736 (defun shell-dynamic-complete-as-environment-variable ()
737 "Dynamically complete at point as an environment variable.
738 Used by `shell-dynamic-complete-environment-variable'.
739 Uses `comint-dynamic-simple-complete'."
740 (let* ((var (or (shell-match-partial-variable) ""))
741 (variable (substring var
(or (string-match "[^$({]\\|$" var
) 0)))
742 (variables (mapcar (function (lambda (x)
743 (substring x
0 (string-match "=" x
))))
744 process-environment
))
745 (addsuffix comint-completion-addsuffix
)
746 (comint-completion-addsuffix nil
)
747 (success (comint-dynamic-simple-complete variable variables
)))
748 (if (memq success
'(sole shortest
))
749 (let* ((var (shell-match-partial-variable))
750 (variable (substring var
(string-match "[^$({]" var
)))
751 (protection (cond ((string-match "{" var
) "}")
752 ((string-match "(" var
) ")")
754 (suffix (cond ((null addsuffix
) "")
756 (comint-directory (getenv variable
))) "/")
758 (insert protection suffix
)))
762 (defun shell-replace-by-expanded-directory ()
763 "Expand directory stack reference before point.
764 Directory stack references are of the form \"=digit\" or \"=-\".
765 See `default-directory' and `shell-dirstack'.
767 Returns t if successful."
769 (if (comint-match-partial-filename)
771 (goto-char (match-beginning 0))
772 (let ((stack (cons default-directory shell-dirstack
))
773 (index (cond ((looking-at "=-/?")
774 (length shell-dirstack
))
775 ((looking-at "=\\([0-9]+\\)")
778 (match-beginning 1) (match-end 1)))))))
781 ((>= index
(length stack
))
782 (error "Directory stack not that deep."))
784 (replace-match (file-name-as-directory (nth index stack
)) t t
)
785 (message "Directory item: %d" index
)
790 ;;; shell.el ends here