1 ;;; shell.el --- specialized comint.el for running the shell.
3 ;; Copyright (C) 1988, 1993, 1994, 1995 Free Software Foundation, Inc.
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
6 ;; Maintainer: Simon Marshall <simon@gnu.ai.mit.edu>
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 (simon@gnu.ai.mit.edu)
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 M-# to run some strange command:
57 ;; (eval-after-load "shell"
58 ;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
60 ;;; Brief Command Documentation:
61 ;;;============================================================================
62 ;;; Comint Mode Commands: (common to shell and all comint-derived modes)
64 ;;; m-p comint-previous-input Cycle backwards in input history
65 ;;; m-n comint-next-input Cycle forwards
66 ;;; m-r comint-previous-matching-input Previous input matching a regexp
67 ;;; m-s comint-next-matching-input Next input that matches
68 ;;; m-c-l comint-show-output Show last batch of process output
69 ;;; return comint-send-input
70 ;;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
71 ;;; c-c c-a comint-bol Beginning of line; skip prompt
72 ;;; c-c c-u comint-kill-input ^u
73 ;;; c-c c-w backward-kill-word ^w
74 ;;; c-c c-c comint-interrupt-subjob ^c
75 ;;; c-c c-z comint-stop-subjob ^z
76 ;;; c-c c-\ comint-quit-subjob ^\
77 ;;; c-c c-o comint-kill-output Delete last batch of process output
78 ;;; c-c c-r comint-show-output Show last batch of process output
79 ;;; c-c c-h comint-dynamic-list-input-ring List input history
80 ;;; send-invisible Read line w/o echo & send to proc
81 ;;; comint-continue-subjob Useful if you accidentally suspend
83 ;;; comint-mode-hook is the comint mode hook.
85 ;;; Shell Mode Commands:
86 ;;; shell Fires up the shell process
87 ;;; tab comint-dynamic-complete Complete filename/command/history
88 ;;; m-? comint-dynamic-list-filename-completions List completions in help buffer
89 ;;; m-c-f shell-forward-command Forward a shell command
90 ;;; m-c-b shell-backward-command Backward a shell command
91 ;;; dirs Resync the buffer's dir stack
92 ;;; dirtrack-toggle Turn dir tracking on/off
93 ;;; shell-strip-ctrl-m Remove trailing ^Ms from output
95 ;;; The shell mode hook is shell-mode-hook
96 ;;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
99 ;;; Read the rest of this file for more information.
101 ;;; Customization and Buffer Variables
102 ;;; ===========================================================================
110 (defvar shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
111 "Regexp to match prompts in the inferior shell.
112 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
113 This variable is used to initialise `comint-prompt-regexp' in the
116 The pattern should probably not match more than one line. If it does,
117 shell-mode may become confused trying to distinguish prompt from input
118 on lines which don't start with a prompt.
120 This is a fine thing to set in your `.emacs' file.")
122 (defvar shell-completion-fignore nil
123 "*List of suffixes to be disregarded during file/command completion.
124 This variable is used to initialize `comint-completion-fignore' in the shell
125 buffer. The default is nil, for compatibility with most shells.
126 Some people like (\"~\" \"#\" \"%\").
128 This is a fine thing to set in your `.emacs' file.")
130 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
131 "List of characters to recognise as separate arguments.
132 This variable is used to initialize `comint-delimiter-argument-list' in the
133 shell buffer. The default is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
135 This is a fine thing to set in your `.emacs' file.")
137 (defvar shell-dynamic-complete-functions
138 '(comint-replace-by-expanded-history
139 shell-dynamic-complete-environment-variable
140 shell-dynamic-complete-command
141 shell-replace-by-expanded-directory
142 comint-dynamic-complete-filename)
143 "List of functions called to perform completion.
144 This variable is used to initialise `comint-dynamic-complete-functions' in the
147 This is a fine thing to set in your `.emacs' file.")
149 (defvar shell-command-regexp "[^;&|\n]+"
150 "*Regexp to match a single command within a pipeline.
151 This is used for directory tracking and does not do a perfect job.")
153 (defvar shell-completion-execonly t
154 "*If non-nil, use executable files only for completion candidates.
155 This mirrors the optional behavior of tcsh.
157 Detecting executability of files may slow command completion considerably.")
159 (defvar shell-popd-regexp "popd"
160 "*Regexp to match subshell commands equivalent to popd.")
162 (defvar shell-pushd-regexp "pushd"
163 "*Regexp to match subshell commands equivalent to pushd.")
165 (defvar shell-pushd-tohome nil
166 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
167 This mirrors the optional behavior of tcsh.")
169 (defvar shell-pushd-dextract nil
170 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
171 This mirrors the optional behavior of tcsh.")
173 (defvar shell-pushd-dunique nil
174 "*If non-nil, make pushd only add unique directories to the stack.
175 This mirrors the optional behavior of tcsh.")
177 (defvar shell-cd-regexp "cd"
178 "*Regexp to match subshell commands equivalent to cd.")
180 (defvar explicit-shell-file-name nil
181 "*If non-nil, is file name to use for explicitly requested inferior shell.")
183 (defvar explicit-csh-args
184 (if (eq system-type 'hpux)
185 ;; -T persuades HP's csh not to think it is smarter
186 ;; than us about what terminal modes to use.
189 "*Args passed to inferior shell by M-x shell, if the shell is csh.
190 Value is a list of strings, which may be nil.")
192 (defvar shell-input-autoexpand 'history
193 "*If non-nil, expand input command history references on completion.
194 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
196 If the value is `input', then the expansion is seen on input.
197 If the value is `history', then the expansion is only when inserting
198 into the buffer's input ring. See also `comint-magic-space' and
199 `comint-dynamic-complete'.
201 This variable supplies a default for `comint-input-autoexpand',
202 for Shell mode only.")
204 (defvar shell-dirstack nil
205 "List of directories saved by pushd in this buffer's shell.
206 Thus, this does not include the shell's current directory.")
208 (defvar shell-dirtrackp t
209 "Non-nil in a shell buffer means directory tracking is enabled.")
211 (defvar shell-last-dir nil
212 "Keep track of last directory for ksh `cd -' command.")
214 (defvar shell-dirstack-query nil
215 "Command used by `shell-resync-dir' to query the shell.")
217 (defvar shell-mode-map nil)
218 (cond ((not shell-mode-map)
219 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
220 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
221 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
222 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
223 (define-key shell-mode-map "\M-?"
224 'comint-dynamic-list-filename-completions)
225 (define-key shell-mode-map [menu-bar completion]
226 (copy-keymap (lookup-key comint-mode-map [menu-bar completion])))
227 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
228 [complete-env-variable] '("Complete Env. Variable Name" .
229 shell-dynamic-complete-environment-variable)
231 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
232 [expand-directory] '("Expand Directory Reference" .
233 shell-replace-by-expanded-directory)
236 (defvar shell-mode-hook '()
237 "*Hook for customising Shell mode.")
239 (defvar shell-font-lock-keywords
240 (list (cons shell-prompt-pattern 'font-lock-keyword-face)
241 '("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
242 '("^[^ \t\n]+:.*$" . font-lock-string-face)
243 '("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
244 "Additional expressions to highlight in Shell mode.")
247 ;;; ===========================================================================
251 "Major mode for interacting with an inferior shell.
252 \\[comint-send-input] after the end of the process' output sends the text from
253 the end of process to the end of the current line.
254 \\[comint-send-input] before end of process output copies the current line minus the prompt to
255 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
256 \\[send-invisible] reads a line of text without echoing it, and sends it to
257 the shell. This is useful for entering passwords. Or, add the function
258 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
260 If you want to make multiple shell buffers, rename the `*shell*' buffer
261 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
263 If you want to make shell buffers limited in length, add the function
264 `comint-truncate-buffer' to `comint-output-filter-functions'.
266 If you accidentally suspend your process, use \\[comint-continue-subjob]
269 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
270 keep this buffer's default directory the same as the shell's working directory.
271 While directory tracking is enabled, the shell's working directory is displayed
272 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
273 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
275 \\[dirtrack-toggle] turns directory tracking on and off.
278 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
279 `shell-mode-hook' (in that order). Before each input, the hooks on
280 `comint-input-filter-functions' are run. After each shell output, the hooks
281 on `comint-output-filter-functions' are run.
283 Variables `shell-cd-regexp', `shell-pushd-regexp' and `shell-popd-regexp'
284 are used to match their respective commands, while `shell-pushd-tohome',
285 `shell-pushd-dextract' and `shell-pushd-dunique' control the behavior of the
288 Variables `comint-completion-autolist', `comint-completion-addsuffix',
289 `comint-completion-recexact' and `comint-completion-fignore' control the
290 behavior of file name, command name and variable name completion. Variable
291 `shell-completion-execonly' controls the behavior of command name completion.
292 Variable `shell-completion-fignore' is used to initialise the value of
293 `comint-completion-fignore'.
295 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
296 the initialisation of the input ring history, and history expansion.
298 Variables `comint-output-filter-functions', a hook, and
299 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
300 control whether input and output cause the window to scroll to the end of the
304 (setq major-mode 'shell-mode)
305 (setq mode-name "Shell")
306 (use-local-map shell-mode-map)
307 (setq comint-prompt-regexp shell-prompt-pattern)
308 (setq comint-completion-fignore shell-completion-fignore)
309 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
310 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
311 (make-local-variable 'paragraph-start)
312 (setq paragraph-start comint-prompt-regexp)
313 (make-local-variable 'font-lock-defaults)
314 (setq font-lock-defaults '(shell-font-lock-keywords t))
315 (make-local-variable 'shell-dirstack)
316 (setq shell-dirstack nil)
317 (setq shell-last-dir nil)
318 (make-local-variable 'shell-dirtrackp)
319 (setq shell-dirtrackp t)
320 (add-hook 'comint-input-filter-functions 'shell-directory-tracker)
321 (setq comint-input-autoexpand shell-input-autoexpand)
322 (make-local-variable 'list-buffers-directory)
323 (setq list-buffers-directory (expand-file-name default-directory))
324 ;; shell-dependent assignments.
325 (let ((shell (file-name-nondirectory (car
326 (process-command (get-buffer-process (current-buffer)))))))
327 (setq comint-input-ring-file-name
328 (or (getenv "HISTFILE")
329 (cond ((string-equal shell "bash") "~/.bash_history")
330 ((string-equal shell "ksh") "~/.sh_history")
332 (if (equal (file-truename comint-input-ring-file-name) "/dev/null")
333 (setq comint-input-ring-file-name nil))
334 (setq shell-dirstack-query
335 (if (string-match "^k?sh$" shell) "pwd" "dirs")))
336 (run-hooks 'shell-mode-hook)
337 (comint-read-input-ring t))
341 "Run an inferior shell, with I/O through buffer *shell*.
342 If buffer exists but shell process is not running, make new shell.
343 If buffer exists and shell process is running, just switch to buffer `*shell*'.
344 Program used comes from variable `explicit-shell-file-name',
345 or (if that is nil) from the ESHELL environment variable,
346 or else from SHELL if there is no ESHELL.
347 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
348 (Note that this may lose due to a timing error if the shell
349 discards input when it starts up.)
350 The buffer is put in Shell mode, giving commands for sending input
351 and controlling the subjobs of the shell. See `shell-mode'.
352 See also the variable `shell-prompt-pattern'.
354 The shell file name (sans directories) is used to make a symbol name
355 such as `explicit-csh-args'. If that symbol is a variable,
356 its value is used as a list of arguments when invoking the shell.
357 Otherwise, one argument `-i' is passed to the shell.
359 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
361 (if (not (comint-check-proc "*shell*"))
362 (let* ((prog (or explicit-shell-file-name
366 (name (file-name-nondirectory prog))
367 (startfile (concat "~/.emacs_" name))
368 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
369 (set-buffer (apply 'make-comint "shell" prog
370 (if (file-exists-p startfile) startfile)
371 (if (and xargs-name (boundp xargs-name))
372 (symbol-value xargs-name)
375 (switch-to-buffer (current-buffer)))
376 (switch-to-buffer "*shell*")))
378 ;;; Directory tracking
379 ;;; ===========================================================================
380 ;;; This code provides the shell mode input sentinel
381 ;;; SHELL-DIRECTORY-TRACKER
382 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
383 ;;; changes the current directory of the shell buffer accordingly.
385 ;;; This is basically a fragile hack, although it's more accurate than
386 ;;; the version in Emacs 18's shell.el. It has the following failings:
387 ;;; 1. It doesn't know about the cdpath shell variable.
388 ;;; 2. It cannot infallibly deal with command sequences, though it does well
389 ;;; with these and with ignoring commands forked in another shell with ()s.
390 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
391 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
392 ;;; that, there's no way to catch shell commands where cd's are buried
393 ;;; inside conditional expressions, aliases, and so forth.
395 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
396 ;;; messes it up. You run other processes under the shell; these each have
397 ;;; separate working directories, and some have commands for manipulating
398 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
399 ;;; commands that do *not* affect the current w.d. at all, but look like they
400 ;;; do (e.g., the cd command in ftp). In shells that allow you job
401 ;;; control, you can switch between jobs, all having different w.d.'s. So
402 ;;; simply saying %3 can shift your w.d..
404 ;;; The solution is to relax, not stress out about it, and settle for
405 ;;; a hack that works pretty well in typical circumstances. Remember
406 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
409 ;;; One good hack not implemented here for users of programmable shells
410 ;;; is to program up the shell w.d. manipulation commands to output
411 ;;; a coded command sequence to the tty. Something like
413 ;;; where <cwd> is the new current working directory. Then trash the
414 ;;; directory tracking machinery currently used in this package, and
415 ;;; replace it with a process filter that watches for and strips out
418 (defun shell-directory-tracker (str)
419 "Tracks cd, pushd and popd commands issued to the shell.
420 This function is called on each input passed to the shell.
421 It watches for cd, pushd and popd commands and sets the buffer's
422 default directory to track these commands.
424 You may toggle this tracking on and off with M-x dirtrack-toggle.
425 If emacs gets confused, you can resync with the shell with M-x dirs.
427 See variables `shell-cd-regexp', `shell-pushd-regexp', and `shell-popd-regexp',
428 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
429 control the behavior of the relevant command.
431 Environment variables are expanded, see function `substitute-in-file-name'."
433 ;; We fail gracefully if we think the command will fail in the shell.
434 (condition-case chdir-failure
435 (let ((start (progn (string-match "^[;\\s ]*" str) ; skip whitespace
438 (while (string-match shell-command-regexp str start)
439 (setq end (match-end 0)
440 cmd (comint-arguments (substring str start end) 0 0)
441 arg1 (comint-arguments (substring str start end) 1 1))
442 (cond ((eq (string-match shell-popd-regexp cmd) 0)
443 (shell-process-popd (substitute-in-file-name arg1)))
444 ((eq (string-match shell-pushd-regexp cmd) 0)
445 (shell-process-pushd (substitute-in-file-name arg1)))
446 ((eq (string-match shell-cd-regexp cmd) 0)
447 (shell-process-cd (substitute-in-file-name arg1))))
448 (setq start (progn (string-match "[;\\s ]*" str end) ; skip again
450 (error "Couldn't cd"))))
453 (defun shell-process-popd (arg)
454 (let ((num (or (shell-extract-num arg) 0)))
455 (cond ((and num (= num 0) shell-dirstack)
456 (shell-cd (car shell-dirstack))
457 (setq shell-dirstack (cdr shell-dirstack))
458 (shell-dirstack-message))
459 ((and num (> num 0) (<= num (length shell-dirstack)))
460 (let* ((ds (cons nil shell-dirstack))
461 (cell (nthcdr (1- num) ds)))
462 (rplacd cell (cdr (cdr cell)))
463 (setq shell-dirstack (cdr ds))
464 (shell-dirstack-message)))
466 (error "Couldn't popd")))))
468 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
469 (defun shell-prefixed-directory-name (dir)
470 (if (= (length comint-file-name-prefix) 0)
472 (if (file-name-absolute-p dir)
473 ;; The name is absolute, so prepend the prefix.
474 (concat comint-file-name-prefix dir)
475 ;; For relative name we assume default-directory already has the prefix.
476 (expand-file-name dir))))
479 (defun shell-process-cd (arg)
480 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
482 ((string-equal "-" arg) shell-last-dir)
483 (t (shell-prefixed-directory-name arg)))))
484 (setq shell-last-dir default-directory)
486 (shell-dirstack-message)))
489 (defun shell-process-pushd (arg)
490 (let ((num (shell-extract-num arg)))
491 (cond ((zerop (length arg))
492 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
493 (cond (shell-pushd-tohome
494 (shell-process-pushd (concat comint-file-name-prefix "~")))
496 (let ((old default-directory))
497 (shell-cd (car shell-dirstack))
499 (cons old (cdr shell-dirstack)))
500 (shell-dirstack-message)))
502 (message "Directory stack empty."))))
505 (cond ((> num (length shell-dirstack))
506 (message "Directory stack not that deep."))
508 (error (message "Couldn't cd.")))
509 (shell-pushd-dextract
510 (let ((dir (nth (1- num) shell-dirstack)))
511 (shell-process-popd arg)
512 (shell-process-pushd default-directory)
514 (shell-dirstack-message)))
516 (let* ((ds (cons default-directory shell-dirstack))
518 (front (nthcdr num ds))
519 (back (reverse (nthcdr (- dslen num) (reverse ds))))
520 (new-ds (append front back)))
521 (shell-cd (car new-ds))
522 (setq shell-dirstack (cdr new-ds))
523 (shell-dirstack-message)))))
526 (let ((old-wd default-directory))
527 (shell-cd (shell-prefixed-directory-name arg))
528 (if (or (null shell-pushd-dunique)
529 (not (member old-wd shell-dirstack)))
530 (setq shell-dirstack (cons old-wd shell-dirstack)))
531 (shell-dirstack-message))))))
533 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
534 (defun shell-extract-num (str)
535 (and (string-match "^\\+[1-9][0-9]*$" str)
536 (string-to-int str)))
539 (defun shell-dirtrack-toggle ()
540 "Turn directory tracking on and off in a shell buffer."
542 (if (setq shell-dirtrackp (not shell-dirtrackp))
543 (setq list-buffers-directory default-directory)
544 (setq list-buffers-directory nil))
545 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
547 ;;; For your typing convenience:
548 (defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
550 (defun shell-cd (dir)
551 "Do normal `cd' to DIR, and set `list-buffers-directory'."
553 (setq list-buffers-directory (file-name-as-directory
554 (expand-file-name dir))))
557 (defun shell-resync-dirs ()
558 "Resync the buffer's idea of the current directory stack.
559 This command queries the shell with the command bound to
560 `shell-dirstack-query' (default \"dirs\"), reads the next
561 line output and parses it to form the new directory stack.
562 DON'T issue this command unless the buffer is at a shell prompt.
563 Also, note that if some other subprocess decides to do output
564 immediately after the query, its output will be taken as the
565 new directory stack -- you lose. If this happens, just do the
568 (let* ((proc (get-buffer-process (current-buffer)))
569 (pmark (process-mark proc)))
571 (insert shell-dirstack-query) (insert "\n")
572 (sit-for 0) ; force redisplay
573 (comint-send-string proc shell-dirstack-query)
574 (comint-send-string proc "\n")
575 (set-marker pmark (point))
576 (let ((pt (point))) ; wait for 1 line
577 ;; This extra newline prevents the user's pending input from spoofing us.
578 (insert "\n") (backward-char 1)
579 (while (not (looking-at ".+\n"))
580 (accept-process-output proc)
582 (goto-char pmark) (delete-char 1) ; remove the extra newline
583 ;; That's the dirlist. grab it & parse it.
584 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
586 (ds '()) ; new dir stack
589 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
590 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
591 (setq ds (cons (concat comint-file-name-prefix
592 (substring dl (match-beginning 1)
595 (setq i (match-end 0)))
596 (let ((ds (nreverse ds)))
598 (progn (shell-cd (car ds))
599 (setq shell-dirstack (cdr ds))
600 (shell-dirstack-message))
601 (error (message "Couldn't cd.")))))))
603 ;;; For your typing convenience:
604 (defalias 'dirs 'shell-resync-dirs)
607 ;;; Show the current dirstack on the message line.
608 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
609 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
610 ;;; All the commands that mung the buffer's dirstack finish by calling
612 (defun shell-dirstack-message ()
614 (ds (cons default-directory shell-dirstack))
615 (home (expand-file-name (concat comint-file-name-prefix "~/")))
616 (homelen (length home)))
618 (let ((dir (car ds)))
619 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
620 (setq dir (concat "~/" (substring dir homelen))))
621 ;; Strip off comint-file-name-prefix if present.
622 (and comint-file-name-prefix
623 (>= (length dir) (length comint-file-name-prefix))
624 (string= comint-file-name-prefix
625 (substring dir 0 (length comint-file-name-prefix)))
626 (setq dir (substring dir (length comint-file-name-prefix)))
628 (setq msg (concat msg (directory-file-name dir) " "))
632 (defun shell-forward-command (&optional arg)
633 "Move forward across ARG shell command(s). Does not cross lines.
634 See `shell-command-regexp'."
636 (let ((limit (save-excursion (end-of-line nil) (point))))
637 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
639 (skip-syntax-backward " "))))
642 (defun shell-backward-command (&optional arg)
643 "Move backward across ARG shell command(s). Does not cross lines.
644 See `shell-command-regexp'."
646 (let ((limit (save-excursion (comint-bol nil) (point))))
647 (if (> limit (point))
648 (save-excursion (beginning-of-line) (setq limit (point))))
649 (skip-syntax-backward " " limit)
650 (if (re-search-backward
651 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
652 (progn (goto-char (match-beginning 1))
653 (skip-chars-forward ";&|")))))
656 (defun shell-dynamic-complete-command ()
657 "Dynamically complete the command at point.
658 This function is similar to `comint-dynamic-complete-filename', except that it
659 searches `exec-path' (minus the trailing emacs library path) for completion
660 candidates. Note that this may not be the same as the shell's idea of the
663 Completion is dependent on the value of `shell-completion-execonly', plus
664 those that effect file completion. See `shell-dynamic-complete-as-command'.
666 Returns t if successful."
668 (let ((filename (comint-match-partial-filename)))
670 (save-match-data (not (string-match "[~/]" filename)))
671 (eq (match-beginning 0)
672 (save-excursion (shell-backward-command 1) (point))))
673 (prog2 (message "Completing command name...")
674 (shell-dynamic-complete-as-command)))))
677 (defun shell-dynamic-complete-as-command ()
678 "Dynamically complete at point as a command.
679 See `shell-dynamic-complete-filename'. Returns t if successful."
680 (let* ((filename (or (comint-match-partial-filename) ""))
681 (pathnondir (file-name-nondirectory filename))
682 (paths (cdr (reverse exec-path)))
683 (cwd (file-name-as-directory (expand-file-name default-directory)))
685 (and comint-completion-fignore
686 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
687 comint-completion-fignore "\\|")))
688 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
689 ;; Go thru each path in the search path, finding completions.
691 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
692 comps-in-path (and (file-accessible-directory-p path)
693 (file-name-all-completions pathnondir path)))
694 ;; Go thru each completion found, to see whether it should be used.
696 (setq file (car comps-in-path)
697 filepath (concat path file))
698 (if (and (not (member file completions))
699 (not (and ignored-extensions
700 (string-match ignored-extensions file)))
701 (or (string-equal path cwd)
702 (not (file-directory-p filepath)))
703 (or (null shell-completion-execonly)
704 (file-executable-p filepath)))
705 (setq completions (cons file completions)))
706 (setq comps-in-path (cdr comps-in-path)))
707 (setq paths (cdr paths)))
708 ;; OK, we've got a list of completions.
709 (let ((success (let ((comint-completion-addsuffix nil))
710 (comint-dynamic-simple-complete pathnondir completions))))
711 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
712 (not (file-directory-p (comint-match-partial-filename))))
717 (defun shell-match-partial-variable ()
718 "Return the variable at point, or nil if non is found."
720 (let ((limit (point)))
721 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
722 (or (looking-at "\\$") (forward-char 1)))
723 ;; Anchor the search forwards.
724 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
726 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
727 (buffer-substring (match-beginning 0) (match-end 0))))))
730 (defun shell-dynamic-complete-environment-variable ()
731 "Dynamically complete the environment variable at point.
732 Completes if after a variable, i.e., if it starts with a \"$\".
733 See `shell-dynamic-complete-as-environment-variable'.
735 This function is similar to `comint-dynamic-complete-filename', except that it
736 searches `process-environment' for completion candidates. Note that this may
737 not be the same as the interpreter's idea of variable names. The main problem
738 with this type of completion is that `process-environment' is the environment
739 which Emacs started with. Emacs does not track changes to the environment made
740 by the interpreter. Perhaps it would be more accurate if this function was
741 called `shell-dynamic-complete-process-environment-variable'.
743 Returns non-nil if successful."
745 (let ((variable (shell-match-partial-variable)))
746 (if (and variable (string-match "^\\$" variable))
747 (prog2 (message "Completing variable name...")
748 (shell-dynamic-complete-as-environment-variable)))))
751 (defun shell-dynamic-complete-as-environment-variable ()
752 "Dynamically complete at point as an environment variable.
753 Used by `shell-dynamic-complete-environment-variable'.
754 Uses `comint-dynamic-simple-complete'."
755 (let* ((var (or (shell-match-partial-variable) ""))
756 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
757 (variables (mapcar (function (lambda (x)
758 (substring x 0 (string-match "=" x))))
759 process-environment))
760 (addsuffix comint-completion-addsuffix)
761 (comint-completion-addsuffix nil)
762 (success (comint-dynamic-simple-complete variable variables)))
763 (if (memq success '(sole shortest))
764 (let* ((var (shell-match-partial-variable))
765 (variable (substring var (string-match "[^$({]" var)))
766 (protection (cond ((string-match "{" var) "}")
767 ((string-match "(" var) ")")
769 (suffix (cond ((null addsuffix) "")
771 (comint-directory (getenv variable))) "/")
773 (insert protection suffix)))
777 (defun shell-replace-by-expanded-directory ()
778 "Expand directory stack reference before point.
779 Directory stack references are of the form \"=digit\" or \"=-\".
780 See `default-directory' and `shell-dirstack'.
782 Returns t if successful."
784 (if (comint-match-partial-filename)
786 (goto-char (match-beginning 0))
787 (let ((stack (cons default-directory shell-dirstack))
788 (index (cond ((looking-at "=-/?")
789 (length shell-dirstack))
790 ((looking-at "=\\([0-9]+\\)")
793 (match-beginning 1) (match-end 1)))))))
796 ((>= index (length stack))
797 (error "Directory stack not that deep."))
799 (replace-match (file-name-as-directory (nth index stack)) t t)
800 (message "Directory item: %d" index)
805 ;;; shell.el ends here