1 ;;; shell.el --- specialized comint.el for running the shell.
3 ;; Copyright (C) 1988, 93, 94, 95, 96, 1997 Free Software Foundation, Inc.
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu> then
6 ;; Simon Marshall <simon@gnu.ai.mit.edu>
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; Please send me bug reports, bug fixes, and extensions, so that I can
30 ;; merge them into the master source.
31 ;; - Olin Shivers (shivers@cs.cmu.edu)
32 ;; - Simon Marshall (simon@gnu.ai.mit.edu)
34 ;; This file defines a a shell-in-a-buffer package (shell mode) built
35 ;; on top of comint mode. This is actually cmushell with things
36 ;; renamed to replace its counterpart in Emacs 18. cmushell is more
37 ;; featureful, robust, and uniform than the Emacs 18 version.
39 ;; Since this mode is built on top of the general command-interpreter-in-
40 ;; a-buffer mode (comint mode), it shares a common base functionality,
41 ;; and a common set of bindings, with all modes derived from comint mode.
42 ;; This makes these modes easier to use.
44 ;; For documentation on the functionality provided by comint mode, and
45 ;; the hooks available for customising it, see the file comint.el.
46 ;; For further information on shell mode, see the comments below.
49 ;; When sending text from a source file to a subprocess, the process-mark can
50 ;; move off the window, so you can lose sight of the process interactions.
51 ;; Maybe I should ensure the process mark is in the window when I send
52 ;; text to the process? Switch selectable?
55 ;;=============================================================================
56 ;; Some suggestions for your .emacs file.
58 ;; ;; Define M-# to run some strange command:
59 ;; (eval-after-load "shell"
60 ;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
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-s comint-next-matching-input Next input that matches
70 ;; m-c-l comint-show-output Show last batch of process output
71 ;; return comint-send-input
72 ;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
73 ;; c-c c-a comint-bol Beginning of line; skip prompt
74 ;; c-c c-u comint-kill-input ^u
75 ;; c-c c-w backward-kill-word ^w
76 ;; c-c c-c comint-interrupt-subjob ^c
77 ;; c-c c-z comint-stop-subjob ^z
78 ;; c-c c-\ comint-quit-subjob ^\
79 ;; c-c c-o comint-kill-output Delete last batch of process output
80 ;; c-c c-r comint-show-output Show last batch of process output
81 ;; c-c c-h comint-dynamic-list-input-ring List input history
82 ;; send-invisible Read line w/o echo & send to proc
83 ;; comint-continue-subjob Useful if you accidentally suspend
85 ;; comint-mode-hook is the comint mode hook.
87 ;; Shell Mode Commands:
88 ;; shell Fires up the shell process
89 ;; tab comint-dynamic-complete Complete filename/command/history
90 ;; m-? comint-dynamic-list-filename-completions
91 ;; List completions in help buffer
92 ;; m-c-f shell-forward-command Forward a shell command
93 ;; m-c-b shell-backward-command Backward a shell command
94 ;; dirs Resync the buffer's dir stack
95 ;; dirtrack-toggle Turn dir tracking on/off
96 ;; comint-strip-ctrl-m Remove trailing ^Ms from output
98 ;; The shell mode hook is shell-mode-hook
99 ;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
102 ;; Read the rest of this file for more information.
108 ;;; Customization and Buffer Variables
111 "Running shell from within Emacs buffers"
115 (defgroup shell-directories nil
116 "Directory support in shell mode"
119 (defgroup shell-faces nil
120 "Faces in shell buffers"
124 (defvar shell-prompt-pattern
"^[^#$%>\n]*[#$%>] *"
125 "Regexp to match prompts in the inferior shell.
126 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
127 This variable is used to initialise `comint-prompt-regexp' in the
130 The pattern should probably not match more than one line. If it does,
131 Shell mode may become confused trying to distinguish prompt from input
132 on lines which don't start with a prompt.
134 This is a fine thing to set in your `.emacs' file.")
136 (defcustom shell-completion-fignore nil
137 "*List of suffixes to be disregarded during file/command completion.
138 This variable is used to initialize `comint-completion-fignore' in the shell
139 buffer. The default is nil, for compatibility with most shells.
140 Some people like (\"~\" \"#\" \"%\").
142 This is a fine thing to set in your `.emacs' file."
143 :type
'(repeat (string :tag
"Suffix"))
146 (defvar shell-delimiter-argument-list
'(?\| ?
& ?
< ?
> ?\
( ?\
) ?\
;)
147 "List of characters to recognise as separate arguments.
148 This variable is used to initialize `comint-delimiter-argument-list' in the
149 shell buffer. The value may depend on the operating system or shell.
151 This is a fine thing to set in your `.emacs' file.")
153 (defvar shell-file-name-chars
154 (if (memq system-type
'(ms-dos windows-nt
))
155 "~/A-Za-z0-9_^$!#%&{}@`'.()-"
156 "~/A-Za-z0-9+@:_.$#%,={}-")
157 "String of characters valid in a file name.
158 This variable is used to initialize `comint-file-name-chars' in the
159 shell buffer. The value may depend on the operating system or shell.
161 This is a fine thing to set in your `.emacs' file.")
163 (defvar shell-file-name-quote-list
164 (if (memq system-type
'(ms-dos windows-nt
))
166 (append shell-delimiter-argument-list
'(?\ ?\
* ?\
! ?
\" ?
\' ?\
`)))
167 "List of characters to quote when in a file name.
168 This variable is used to initialize `comint-file-name-quote-list' in the
169 shell buffer. The value may depend on the operating system or shell.
171 This is a fine thing to set in your `.emacs' file.")
173 (defvar shell-dynamic-complete-functions
174 '(comint-replace-by-expanded-history
175 shell-dynamic-complete-environment-variable
176 shell-dynamic-complete-command
177 shell-replace-by-expanded-directory
178 comint-dynamic-complete-filename
)
179 "List of functions called to perform completion.
180 This variable is used to initialise `comint-dynamic-complete-functions' in the
183 This is a fine thing to set in your `.emacs' file.")
185 (defcustom shell-command-regexp
"[^;&|\n]+"
186 "*Regexp to match a single command within a pipeline.
187 This is used for directory tracking and does not do a perfect job."
191 (defcustom shell-completion-execonly t
192 "*If non-nil, use executable files only for completion candidates.
193 This mirrors the optional behavior of tcsh.
195 Detecting executability of files may slow command completion considerably."
199 (defcustom shell-popd-regexp
"popd"
200 "*Regexp to match subshell commands equivalent to popd."
202 :group
'shell-directories
)
204 (defcustom shell-pushd-regexp
"pushd"
205 "*Regexp to match subshell commands equivalent to pushd."
207 :group
'shell-directories
)
209 (defcustom shell-pushd-tohome nil
210 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
211 This mirrors the optional behavior of tcsh."
213 :group
'shell-directories
)
215 (defcustom shell-pushd-dextract nil
216 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
217 This mirrors the optional behavior of tcsh."
219 :group
'shell-directories
)
221 (defcustom shell-pushd-dunique nil
222 "*If non-nil, make pushd only add unique directories to the stack.
223 This mirrors the optional behavior of tcsh."
225 :group
'shell-directories
)
227 (defcustom shell-cd-regexp
"cd"
228 "*Regexp to match subshell commands equivalent to cd."
230 :group
'shell-directories
)
232 (defcustom shell-chdrive-regexp
233 (if (memq system-type
'(ms-dos windows-nt
))
234 ; NetWare allows the five chars between upper and lower alphabetics.
235 "[]a-zA-Z^_`\\[\\\\]:"
237 "*If non-nil, is regexp used to track drive changes."
238 :type
'(choice regexp
240 :group
'shell-directories
)
242 (defcustom explicit-shell-file-name nil
243 "*If non-nil, is file name to use for explicitly requested inferior shell."
244 :type
'(choice (const :tag
"None" nil
) file
)
247 (defcustom explicit-csh-args
248 (if (eq system-type
'hpux
)
249 ;; -T persuades HP's csh not to think it is smarter
250 ;; than us about what terminal modes to use.
253 "*Args passed to inferior shell by M-x shell, if the shell is csh.
254 Value is a list of strings, which may be nil."
255 :type
'(repeat (string :tag
"Argument"))
258 (defcustom shell-input-autoexpand
'history
259 "*If non-nil, expand input command history references on completion.
260 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
262 If the value is `input', then the expansion is seen on input.
263 If the value is `history', then the expansion is only when inserting
264 into the buffer's input ring. See also `comint-magic-space' and
265 `comint-dynamic-complete'.
267 This variable supplies a default for `comint-input-autoexpand',
268 for Shell mode only."
269 :type
'(choice (const nil
) (const input
) (const history
))
272 (defvar shell-dirstack nil
273 "List of directories saved by pushd in this buffer's shell.
274 Thus, this does not include the shell's current directory.")
276 (defvar shell-dirtrackp t
277 "Non-nil in a shell buffer means directory tracking is enabled.")
279 (defvar shell-last-dir nil
280 "Keep track of last directory for ksh `cd -' command.")
282 (defvar shell-dirstack-query nil
283 "Command used by `shell-resync-dir' to query the shell.")
285 (defvar shell-mode-map nil
)
286 (cond ((not shell-mode-map
)
287 (setq shell-mode-map
(nconc (make-sparse-keymap) comint-mode-map
))
288 (define-key shell-mode-map
"\C-c\C-f" 'shell-forward-command
)
289 (define-key shell-mode-map
"\C-c\C-b" 'shell-backward-command
)
290 (define-key shell-mode-map
"\t" 'comint-dynamic-complete
)
291 (define-key shell-mode-map
"\M-?"
292 'comint-dynamic-list-filename-completions
)
293 (define-key shell-mode-map
[menu-bar completion
]
294 (copy-keymap (lookup-key comint-mode-map
[menu-bar completion
])))
295 (define-key-after (lookup-key shell-mode-map
[menu-bar completion
])
296 [complete-env-variable
] '("Complete Env. Variable Name" .
297 shell-dynamic-complete-environment-variable
)
299 (define-key-after (lookup-key shell-mode-map
[menu-bar completion
])
300 [expand-directory
] '("Expand Directory Reference" .
301 shell-replace-by-expanded-directory
)
304 (defcustom shell-mode-hook
'()
305 "*Hook for customising Shell mode."
309 (defvar shell-font-lock-keywords
310 '((eval .
(cons shell-prompt-pattern
'font-lock-warning-face
))
311 ("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face
)
312 ("^[^ \t\n]+:.*" . font-lock-string-face
)
313 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face
))
314 "Additional expressions to highlight in Shell mode.")
318 (put 'shell-mode
'mode-class
'special
)
321 "Major mode for interacting with an inferior shell.
322 \\[comint-send-input] after the end of the process' output sends the text from
323 the end of process to the end of the current line.
324 \\[comint-send-input] before end of process output copies the current line minus the prompt to
325 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
326 \\[send-invisible] reads a line of text without echoing it, and sends it to
327 the shell. This is useful for entering passwords. Or, add the function
328 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
330 If you want to make multiple shell buffers, rename the `*shell*' buffer
331 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
333 If you want to make shell buffers limited in length, add the function
334 `comint-truncate-buffer' to `comint-output-filter-functions'.
336 If you accidentally suspend your process, use \\[comint-continue-subjob]
339 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
340 keep this buffer's default directory the same as the shell's working directory.
341 While directory tracking is enabled, the shell's working directory is displayed
342 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
343 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
345 \\[dirtrack-toggle] turns directory tracking on and off.
348 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
349 `shell-mode-hook' (in that order). Before each input, the hooks on
350 `comint-input-filter-functions' are run. After each shell output, the hooks
351 on `comint-output-filter-functions' are run.
353 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
354 and `shell-popd-regexp' are used to match their respective commands,
355 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
356 control the behavior of the relevant command.
358 Variables `comint-completion-autolist', `comint-completion-addsuffix',
359 `comint-completion-recexact' and `comint-completion-fignore' control the
360 behavior of file name, command name and variable name completion. Variable
361 `shell-completion-execonly' controls the behavior of command name completion.
362 Variable `shell-completion-fignore' is used to initialise the value of
363 `comint-completion-fignore'.
365 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
366 the initialisation of the input ring history, and history expansion.
368 Variables `comint-output-filter-functions', a hook, and
369 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
370 control whether input and output cause the window to scroll to the end of the
374 (setq major-mode
'shell-mode
)
375 (setq mode-name
"Shell")
376 (use-local-map shell-mode-map
)
377 (setq comint-prompt-regexp shell-prompt-pattern
)
378 (setq comint-completion-fignore shell-completion-fignore
)
379 (setq comint-delimiter-argument-list shell-delimiter-argument-list
)
380 (setq comint-file-name-chars shell-file-name-chars
)
381 (setq comint-file-name-quote-list shell-file-name-quote-list
)
382 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions
)
383 (make-local-variable 'paragraph-start
)
384 (setq paragraph-start comint-prompt-regexp
)
385 (make-local-variable 'font-lock-defaults
)
386 (setq font-lock-defaults
'(shell-font-lock-keywords t
))
387 (make-local-variable 'shell-dirstack
)
388 (setq shell-dirstack nil
)
389 (make-local-variable 'shell-last-dir
)
390 (setq shell-last-dir nil
)
391 (make-local-variable 'shell-dirtrackp
)
392 (setq shell-dirtrackp t
)
393 (add-hook 'comint-input-filter-functions
'shell-directory-tracker nil t
)
394 (setq comint-input-autoexpand shell-input-autoexpand
)
395 ;; This is not really correct, since the shell buffer does not really
396 ;; edit this directory. But it is useful in the buffer list and menus.
397 (make-local-variable 'list-buffers-directory
)
398 (setq list-buffers-directory
(expand-file-name default-directory
))
399 ;; shell-dependent assignments.
400 (let ((shell (file-name-nondirectory (car
401 (process-command (get-buffer-process (current-buffer)))))))
402 (setq comint-input-ring-file-name
403 (or (getenv "HISTFILE")
404 (cond ((string-equal shell
"bash") "~/.bash_history")
405 ((string-equal shell
"ksh") "~/.sh_history")
407 (if (or (equal comint-input-ring-file-name
"")
408 (equal (file-truename comint-input-ring-file-name
)
409 (file-truename "/dev/null")))
410 (setq comint-input-ring-file-name nil
))
411 (setq shell-dirstack-query
412 (cond ((string-equal shell
"sh") "pwd")
413 ((string-equal shell
"ksh") "echo $PWD ~-")
415 (run-hooks 'shell-mode-hook
)
416 (comint-read-input-ring t
))
420 "Run an inferior shell, with I/O through buffer *shell*.
421 If buffer exists but shell process is not running, make new shell.
422 If buffer exists and shell process is running, just switch to buffer `*shell*'.
423 Program used comes from variable `explicit-shell-file-name',
424 or (if that is nil) from the ESHELL environment variable,
425 or else from SHELL if there is no ESHELL.
426 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
427 (Note that this may lose due to a timing error if the shell
428 discards input when it starts up.)
429 The buffer is put in Shell mode, giving commands for sending input
430 and controlling the subjobs of the shell. See `shell-mode'.
431 See also the variable `shell-prompt-pattern'.
433 To specify a coding system for converting non-ASCII characters
434 in the input and output to the shell, use \\[universal-coding-system-argument]
435 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
436 in the shell buffer, after you start the shell.
437 The default comes from `process-coding-system-alist' and
438 `default-process-coding-system'.
440 The shell file name (sans directories) is used to make a symbol name
441 such as `explicit-csh-args'. If that symbol is a variable,
442 its value is used as a list of arguments when invoking the shell.
443 Otherwise, one argument `-i' is passed to the shell.
445 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
447 (if (not (comint-check-proc "*shell*"))
448 (let* ((prog (or explicit-shell-file-name
452 (name (file-name-nondirectory prog
))
453 (startfile (concat "~/.emacs_" name
))
454 (xargs-name (intern-soft (concat "explicit-" name
"-args")))
457 (set-buffer (apply 'make-comint
"shell" prog
458 (if (file-exists-p startfile
) startfile
)
459 (if (and xargs-name
(boundp xargs-name
))
460 (symbol-value xargs-name
)
462 (setq shell-buffer
(current-buffer))
464 (pop-to-buffer shell-buffer
))
465 (pop-to-buffer "*shell*")))
467 ;;; Don't do this when shell.el is loaded, only while dumping.
468 ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
470 ;;; Directory tracking
472 ;;; This code provides the shell mode input sentinel
473 ;;; SHELL-DIRECTORY-TRACKER
474 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
475 ;;; changes the current directory of the shell buffer accordingly.
477 ;;; This is basically a fragile hack, although it's more accurate than
478 ;;; the version in Emacs 18's shell.el. It has the following failings:
479 ;;; 1. It doesn't know about the cdpath shell variable.
480 ;;; 2. It cannot infallibly deal with command sequences, though it does well
481 ;;; with these and with ignoring commands forked in another shell with ()s.
482 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
483 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
484 ;;; that, there's no way to catch shell commands where cd's are buried
485 ;;; inside conditional expressions, aliases, and so forth.
487 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
488 ;;; messes it up. You run other processes under the shell; these each have
489 ;;; separate working directories, and some have commands for manipulating
490 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
491 ;;; commands that do *not* affect the current w.d. at all, but look like they
492 ;;; do (e.g., the cd command in ftp). In shells that allow you job
493 ;;; control, you can switch between jobs, all having different w.d.'s. So
494 ;;; simply saying %3 can shift your w.d..
496 ;;; The solution is to relax, not stress out about it, and settle for
497 ;;; a hack that works pretty well in typical circumstances. Remember
498 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
501 ;;; One good hack not implemented here for users of programmable shells
502 ;;; is to program up the shell w.d. manipulation commands to output
503 ;;; a coded command sequence to the tty. Something like
505 ;;; where <cwd> is the new current working directory. Then trash the
506 ;;; directory tracking machinery currently used in this package, and
507 ;;; replace it with a process filter that watches for and strips out
510 (defun shell-directory-tracker (str)
511 "Tracks cd, pushd and popd commands issued to the shell.
512 This function is called on each input passed to the shell.
513 It watches for cd, pushd and popd commands and sets the buffer's
514 default directory to track these commands.
516 You may toggle this tracking on and off with M-x dirtrack-toggle.
517 If emacs gets confused, you can resync with the shell with M-x dirs.
519 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
520 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
521 and `shell-pushd-dunique' control the behavior of the relevant command.
523 Environment variables are expanded, see function `substitute-in-file-name'."
525 ;; We fail gracefully if we think the command will fail in the shell.
526 (condition-case chdir-failure
527 (let ((start (progn (string-match "^[; \t]*" str
) ; skip whitespace
530 (while (string-match shell-command-regexp str start
)
531 (setq end
(match-end 0)
532 cmd
(comint-arguments (substring str start end
) 0 0)
533 arg1
(comint-arguments (substring str start end
) 1 1))
534 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
535 "\\)\\($\\|[ \t]\\)")
537 (shell-process-popd (comint-substitute-in-file-name arg1
)))
538 ((string-match (concat "\\`\\(" shell-pushd-regexp
539 "\\)\\($\\|[ \t]\\)")
541 (shell-process-pushd (comint-substitute-in-file-name arg1
)))
542 ((string-match (concat "\\`\\(" shell-cd-regexp
543 "\\)\\($\\|[ \t]\\)")
545 (shell-process-cd (comint-substitute-in-file-name arg1
)))
546 ((and shell-chdrive-regexp
547 (string-match (concat "\\`\\(" shell-chdrive-regexp
548 "\\)\\($\\|[ \t]\\)")
550 (shell-process-cd (comint-substitute-in-file-name cmd
))))
551 (setq start
(progn (string-match "[; \t]*" str end
) ; skip again
553 (error "Couldn't cd"))))
556 (defun shell-process-popd (arg)
557 (let ((num (or (shell-extract-num arg
) 0)))
558 (cond ((and num
(= num
0) shell-dirstack
)
559 (shell-cd (car shell-dirstack
))
560 (setq shell-dirstack
(cdr shell-dirstack
))
561 (shell-dirstack-message))
562 ((and num
(> num
0) (<= num
(length shell-dirstack
)))
563 (let* ((ds (cons nil shell-dirstack
))
564 (cell (nthcdr (1- num
) ds
)))
565 (rplacd cell
(cdr (cdr cell
)))
566 (setq shell-dirstack
(cdr ds
))
567 (shell-dirstack-message)))
569 (error "Couldn't popd")))))
571 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
572 (defun shell-prefixed-directory-name (dir)
573 (if (= (length comint-file-name-prefix
) 0)
575 (if (file-name-absolute-p dir
)
576 ;; The name is absolute, so prepend the prefix.
577 (concat comint-file-name-prefix dir
)
578 ;; For relative name we assume default-directory already has the prefix.
579 (expand-file-name dir
))))
582 (defun shell-process-cd (arg)
583 (let ((new-dir (cond ((zerop (length arg
)) (concat comint-file-name-prefix
585 ((string-equal "-" arg
) shell-last-dir
)
586 (t (shell-prefixed-directory-name arg
)))))
587 (setq shell-last-dir default-directory
)
589 (shell-dirstack-message)))
592 (defun shell-process-pushd (arg)
593 (let ((num (shell-extract-num arg
)))
594 (cond ((zerop (length arg
))
595 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
596 (cond (shell-pushd-tohome
597 (shell-process-pushd (concat comint-file-name-prefix
"~")))
599 (let ((old default-directory
))
600 (shell-cd (car shell-dirstack
))
601 (setq shell-dirstack
(cons old
(cdr shell-dirstack
)))
602 (shell-dirstack-message)))
604 (message "Directory stack empty."))))
607 (cond ((> num
(length shell-dirstack
))
608 (message "Directory stack not that deep."))
610 (error (message "Couldn't cd.")))
611 (shell-pushd-dextract
612 (let ((dir (nth (1- num
) shell-dirstack
)))
613 (shell-process-popd arg
)
614 (shell-process-pushd default-directory
)
616 (shell-dirstack-message)))
618 (let* ((ds (cons default-directory shell-dirstack
))
620 (front (nthcdr num ds
))
621 (back (reverse (nthcdr (- dslen num
) (reverse ds
))))
622 (new-ds (append front back
)))
623 (shell-cd (car new-ds
))
624 (setq shell-dirstack
(cdr new-ds
))
625 (shell-dirstack-message)))))
628 (let ((old-wd default-directory
))
629 (shell-cd (shell-prefixed-directory-name arg
))
630 (if (or (null shell-pushd-dunique
)
631 (not (member old-wd shell-dirstack
)))
632 (setq shell-dirstack
(cons old-wd shell-dirstack
)))
633 (shell-dirstack-message))))))
635 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
636 (defun shell-extract-num (str)
637 (and (string-match "^\\+[1-9][0-9]*$" str
)
638 (string-to-int str
)))
641 (defun shell-dirtrack-toggle ()
642 "Turn directory tracking on and off in a shell buffer."
644 (if (setq shell-dirtrackp
(not shell-dirtrackp
))
645 (setq list-buffers-directory default-directory
)
646 (setq list-buffers-directory nil
))
647 (message "Directory tracking %s" (if shell-dirtrackp
"ON" "OFF")))
649 ;;; For your typing convenience:
650 (defalias 'dirtrack-toggle
'shell-dirtrack-toggle
)
652 (defun shell-cd (dir)
653 "Do normal `cd' to DIR, and set `list-buffers-directory'."
655 (setq list-buffers-directory
(file-name-as-directory
656 (expand-file-name dir
))))
659 (defun shell-resync-dirs ()
660 "Resync the buffer's idea of the current directory stack.
661 This command queries the shell with the command bound to
662 `shell-dirstack-query' (default \"dirs\"), reads the next
663 line output and parses it to form the new directory stack.
664 DON'T issue this command unless the buffer is at a shell prompt.
665 Also, note that if some other subprocess decides to do output
666 immediately after the query, its output will be taken as the
667 new directory stack -- you lose. If this happens, just do the
670 (let* ((proc (get-buffer-process (current-buffer)))
671 (pmark (process-mark proc
)))
673 (insert shell-dirstack-query
) (insert "\n")
674 (sit-for 0) ; force redisplay
675 (comint-send-string proc shell-dirstack-query
)
676 (comint-send-string proc
"\n")
677 (set-marker pmark
(point))
678 (let ((pt (point))) ; wait for 1 line
679 ;; This extra newline prevents the user's pending input from spoofing us.
680 (insert "\n") (backward-char 1)
681 (while (not (looking-at ".+\n"))
682 (accept-process-output proc
)
684 (goto-char pmark
) (delete-char 1) ; remove the extra newline
685 ;; That's the dirlist. grab it & parse it.
686 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
688 (ds '()) ; new dir stack
691 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
692 (string-match "\\s *\\(\\S +\\)\\s *" dl i
) ; pick off next dir
693 (setq ds
(cons (concat comint-file-name-prefix
694 (substring dl
(match-beginning 1)
697 (setq i
(match-end 0)))
698 (let ((ds (nreverse ds
)))
700 (progn (shell-cd (car ds
))
701 (setq shell-dirstack
(cdr ds
)
702 shell-last-dir
(car shell-dirstack
))
703 (shell-dirstack-message))
704 (error (message "Couldn't cd.")))))))
706 ;;; For your typing convenience:
707 (defalias 'dirs
'shell-resync-dirs
)
710 ;;; Show the current dirstack on the message line.
711 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
712 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
713 ;;; All the commands that mung the buffer's dirstack finish by calling
715 (defun shell-dirstack-message ()
717 (ds (cons default-directory shell-dirstack
))
718 (home (expand-file-name (concat comint-file-name-prefix
"~/")))
719 (homelen (length home
)))
721 (let ((dir (car ds
)))
722 (and (>= (length dir
) homelen
) (string= home
(substring dir
0 homelen
))
723 (setq dir
(concat "~/" (substring dir homelen
))))
724 ;; Strip off comint-file-name-prefix if present.
725 (and comint-file-name-prefix
726 (>= (length dir
) (length comint-file-name-prefix
))
727 (string= comint-file-name-prefix
728 (substring dir
0 (length comint-file-name-prefix
)))
729 (setq dir
(substring dir
(length comint-file-name-prefix
)))
731 (setq msg
(concat msg
(directory-file-name dir
) " "))
735 ;; This was mostly copied from shell-resync-dirs.
736 (defun shell-snarf-envar (var)
737 "Return as a string the shell's value of environment variable VAR."
738 (let* ((cmd (format "printenv '%s'\n" var
))
739 (proc (get-buffer-process (current-buffer)))
740 (pmark (process-mark proc
)))
743 (sit-for 0) ; force redisplay
744 (comint-send-string proc cmd
)
745 (set-marker pmark
(point))
746 (let ((pt (point))) ; wait for 1 line
747 ;; This extra newline prevents the user's pending input from spoofing us.
748 (insert "\n") (backward-char 1)
749 (while (not (looking-at ".+\n"))
750 (accept-process-output proc
)
752 (goto-char pmark
) (delete-char 1) ; remove the extra newline
753 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
755 (defun shell-copy-environment-variable (variable)
756 "Copy the environment variable VARIABLE from the subshell to Emacs.
757 This command reads the value of the specified environment variable
758 in the shell, and sets the same environment variable in Emacs
759 \(what `getenv' in Emacvs would return) to that value.
760 That value will affect any new subprocesses that you subsequently start
762 (interactive (list (read-envvar-name "\
763 Copy Shell environment variable to Emacs: ")))
764 (setenv variable
(shell-snarf-envar variable
)))
766 (defun shell-forward-command (&optional arg
)
767 "Move forward across ARG shell command(s). Does not cross lines.
768 See `shell-command-regexp'."
770 (let ((limit (save-excursion (end-of-line nil
) (point))))
771 (if (re-search-forward (concat shell-command-regexp
"\\([;&|][\t ]*\\)+")
773 (skip-syntax-backward " "))))
776 (defun shell-backward-command (&optional arg
)
777 "Move backward across ARG shell command(s). Does not cross lines.
778 See `shell-command-regexp'."
780 (let ((limit (save-excursion (comint-bol nil
) (point))))
781 (if (> limit
(point))
782 (save-excursion (beginning-of-line) (setq limit
(point))))
783 (skip-syntax-backward " " limit
)
784 (if (re-search-backward
785 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp
) limit
'move arg
)
786 (progn (goto-char (match-beginning 1))
787 (skip-chars-forward ";&|")))))
790 (defun shell-dynamic-complete-command ()
791 "Dynamically complete the command at point.
792 This function is similar to `comint-dynamic-complete-filename', except that it
793 searches `exec-path' (minus the trailing emacs library path) for completion
794 candidates. Note that this may not be the same as the shell's idea of the
797 Completion is dependent on the value of `shell-completion-execonly', plus
798 those that effect file completion. See `shell-dynamic-complete-as-command'.
800 Returns t if successful."
802 (let ((filename (comint-match-partial-filename)))
804 (save-match-data (not (string-match "[~/]" filename
)))
805 (eq (match-beginning 0)
806 (save-excursion (shell-backward-command 1) (point))))
807 (prog2 (message "Completing command name...")
808 (shell-dynamic-complete-as-command)))))
811 (defun shell-dynamic-complete-as-command ()
812 "Dynamically complete at point as a command.
813 See `shell-dynamic-complete-filename'. Returns t if successful."
814 (let* ((filename (or (comint-match-partial-filename) ""))
815 (pathnondir (file-name-nondirectory filename
))
816 (paths (cdr (reverse exec-path
)))
817 (cwd (file-name-as-directory (expand-file-name default-directory
)))
819 (and comint-completion-fignore
820 (mapconcat (function (lambda (x) (concat (regexp-quote x
) "$")))
821 comint-completion-fignore
"\\|")))
822 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
823 ;; Go thru each path in the search path, finding completions.
825 (setq path
(file-name-as-directory (comint-directory (or (car paths
) ".")))
826 comps-in-path
(and (file-accessible-directory-p path
)
827 (file-name-all-completions pathnondir path
)))
828 ;; Go thru each completion found, to see whether it should be used.
830 (setq file
(car comps-in-path
)
831 filepath
(concat path file
))
832 (if (and (not (member file completions
))
833 (not (and ignored-extensions
834 (string-match ignored-extensions file
)))
835 (or (string-equal path cwd
)
836 (not (file-directory-p filepath
)))
837 (or (null shell-completion-execonly
)
838 (file-executable-p filepath
)))
839 (setq completions
(cons file completions
)))
840 (setq comps-in-path
(cdr comps-in-path
)))
841 (setq paths
(cdr paths
)))
842 ;; OK, we've got a list of completions.
843 (let ((success (let ((comint-completion-addsuffix nil
))
844 (comint-dynamic-simple-complete pathnondir completions
))))
845 (if (and (memq success
'(sole shortest
)) comint-completion-addsuffix
846 (not (file-directory-p (comint-match-partial-filename))))
851 (defun shell-match-partial-variable ()
852 "Return the shell variable at point, or nil if none is found."
854 (let ((limit (point)))
855 (if (re-search-backward "[^A-Za-z0-9_{}]" nil
'move
)
856 (or (looking-at "\\$") (forward-char 1)))
857 ;; Anchor the search forwards.
858 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
860 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit
)
861 (buffer-substring (match-beginning 0) (match-end 0))))))
864 (defun shell-dynamic-complete-environment-variable ()
865 "Dynamically complete the environment variable at point.
866 Completes if after a variable, i.e., if it starts with a \"$\".
867 See `shell-dynamic-complete-as-environment-variable'.
869 This function is similar to `comint-dynamic-complete-filename', except that it
870 searches `process-environment' for completion candidates. Note that this may
871 not be the same as the interpreter's idea of variable names. The main problem
872 with this type of completion is that `process-environment' is the environment
873 which Emacs started with. Emacs does not track changes to the environment made
874 by the interpreter. Perhaps it would be more accurate if this function was
875 called `shell-dynamic-complete-process-environment-variable'.
877 Returns non-nil if successful."
879 (let ((variable (shell-match-partial-variable)))
880 (if (and variable
(string-match "^\\$" variable
))
881 (prog2 (message "Completing variable name...")
882 (shell-dynamic-complete-as-environment-variable)))))
885 (defun shell-dynamic-complete-as-environment-variable ()
886 "Dynamically complete at point as an environment variable.
887 Used by `shell-dynamic-complete-environment-variable'.
888 Uses `comint-dynamic-simple-complete'."
889 (let* ((var (or (shell-match-partial-variable) ""))
890 (variable (substring var
(or (string-match "[^$({]\\|$" var
) 0)))
891 (variables (mapcar (function (lambda (x)
892 (substring x
0 (string-match "=" x
))))
893 process-environment
))
894 (addsuffix comint-completion-addsuffix
)
895 (comint-completion-addsuffix nil
)
896 (success (comint-dynamic-simple-complete variable variables
)))
897 (if (memq success
'(sole shortest
))
898 (let* ((var (shell-match-partial-variable))
899 (variable (substring var
(string-match "[^$({]" var
)))
900 (protection (cond ((string-match "{" var
) "}")
901 ((string-match "(" var
) ")")
903 (suffix (cond ((null addsuffix
) "")
905 (comint-directory (getenv variable
))) "/")
907 (insert protection suffix
)))
911 (defun shell-replace-by-expanded-directory ()
912 "Expand directory stack reference before point.
913 Directory stack references are of the form \"=digit\" or \"=-\".
914 See `default-directory' and `shell-dirstack'.
916 Returns t if successful."
918 (if (comint-match-partial-filename)
920 (goto-char (match-beginning 0))
921 (let ((stack (cons default-directory shell-dirstack
))
922 (index (cond ((looking-at "=-/?")
923 (length shell-dirstack
))
924 ((looking-at "=\\([0-9]+\\)")
927 (match-beginning 1) (match-end 1)))))))
930 ((>= index
(length stack
))
931 (error "Directory stack not that deep."))
933 (replace-match (file-name-as-directory (nth index stack
)) t t
)
934 (message "Directory item: %d" index
)
939 ;;; shell.el ends here