1 ;;; shell.el --- specialized comint.el for running the shell
3 ;; Copyright (C) 1988, 93, 94, 95, 96, 1997, 2000 Free Software Foundation, Inc.
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
6 ;; Simon Marshall <simon@gnu.org>
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.org)
34 ;; This file defines a shell-in-a-buffer package (shell mode) built on
35 ;; top of comint mode. This is actually cmushell with things renamed
36 ;; 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-l 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-mode 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 (defcustom shell-dumb-shell-regexp
"cmd\\(proxy\\)?\\.exe"
125 "Regexp to match shells that don't save their command history, and
126 don't handle the backslash as a quote character. For shells that
127 match this regexp, Emacs will write out the command history when the
128 shell finishes, and won't remove backslashes when it unquotes shell
133 (defcustom shell-prompt-pattern
"^[^#$%>\n]*[#$%>] *"
134 "Regexp to match prompts in the inferior shell.
135 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
136 This variable is used to initialise `comint-prompt-regexp' in the
139 This variable is only used if the variable
140 `comint-use-prompt-regexp-instead-of-fields' is non-nil.
142 The pattern should probably not match more than one line. If it does,
143 Shell mode may become confused trying to distinguish prompt from input
144 on lines which don't start with a prompt.
146 This is a fine thing to set in your `.emacs' file."
150 (defcustom shell-completion-fignore nil
151 "*List of suffixes to be disregarded during file/command completion.
152 This variable is used to initialize `comint-completion-fignore' in the shell
153 buffer. The default is nil, for compatibility with most shells.
154 Some people like (\"~\" \"#\" \"%\").
156 This is a fine thing to set in your `.emacs' file."
157 :type
'(repeat (string :tag
"Suffix"))
160 (defvar shell-delimiter-argument-list
'(?\| ?
& ?
< ?
> ?\
( ?\
) ?\
;)
161 "List of characters to recognise as separate arguments.
162 This variable is used to initialize `comint-delimiter-argument-list' in the
163 shell buffer. The value may depend on the operating system or shell.
165 This is a fine thing to set in your `.emacs' file.")
167 (defvar shell-file-name-chars
168 (if (memq system-type
'(ms-dos windows-nt cygwin
))
169 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
170 "~/A-Za-z0-9+@:_.$#%,={}-")
171 "String of characters valid in a file name.
172 This variable is used to initialize `comint-file-name-chars' in the
173 shell buffer. The value may depend on the operating system or shell.
175 This is a fine thing to set in your `.emacs' file.")
177 (defvar shell-file-name-quote-list
178 (if (memq system-type
'(ms-dos windows-nt
))
180 (append shell-delimiter-argument-list
'(?\ ?\
* ?\
! ?
\" ?
\' ?\
` ?\
#)))
181 "List of characters to quote when in a file name.
182 This variable is used to initialize `comint-file-name-quote-list' in the
183 shell buffer. The value may depend on the operating system or shell.
185 This is a fine thing to set in your `.emacs' file.")
187 (defvar shell-dynamic-complete-functions
188 '(comint-replace-by-expanded-history
189 shell-dynamic-complete-environment-variable
190 shell-dynamic-complete-command
191 shell-replace-by-expanded-directory
192 comint-dynamic-complete-filename
)
193 "List of functions called to perform completion.
194 This variable is used to initialise `comint-dynamic-complete-functions' in the
197 This is a fine thing to set in your `.emacs' file.")
199 (defcustom shell-command-regexp
"[^;&|\n]+"
200 "*Regexp to match a single command within a pipeline.
201 This is used for directory tracking and does not do a perfect job."
205 (defcustom shell-completion-execonly t
206 "*If non-nil, use executable files only for completion candidates.
207 This mirrors the optional behavior of tcsh.
209 Detecting executability of files may slow command completion considerably."
213 (defcustom shell-popd-regexp
"popd"
214 "*Regexp to match subshell commands equivalent to popd."
216 :group
'shell-directories
)
218 (defcustom shell-pushd-regexp
"pushd"
219 "*Regexp to match subshell commands equivalent to pushd."
221 :group
'shell-directories
)
223 (defcustom shell-pushd-tohome nil
224 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
225 This mirrors the optional behavior of tcsh."
227 :group
'shell-directories
)
229 (defcustom shell-pushd-dextract nil
230 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
231 This mirrors the optional behavior of tcsh."
233 :group
'shell-directories
)
235 (defcustom shell-pushd-dunique nil
236 "*If non-nil, make pushd only add unique directories to the stack.
237 This mirrors the optional behavior of tcsh."
239 :group
'shell-directories
)
241 (defcustom shell-cd-regexp
"cd"
242 "*Regexp to match subshell commands equivalent to cd."
244 :group
'shell-directories
)
246 (defcustom shell-chdrive-regexp
247 (if (memq system-type
'(ms-dos windows-nt
))
248 ; NetWare allows the five chars between upper and lower alphabetics.
249 "[]a-zA-Z^_`\\[\\\\]:"
251 "*If non-nil, is regexp used to track drive changes."
252 :type
'(choice regexp
254 :group
'shell-directories
)
256 (defcustom shell-dirtrack-verbose t
257 "*If non-nil, show the directory stack following directory change.
258 This is effective only if directory tracking is enabled."
260 :group
'shell-directories
)
262 (defcustom explicit-shell-file-name nil
263 "*If non-nil, is file name to use for explicitly requested inferior shell."
264 :type
'(choice (const :tag
"None" nil
) file
)
267 (defcustom explicit-csh-args
268 (if (eq system-type
'hpux
)
269 ;; -T persuades HP's csh not to think it is smarter
270 ;; than us about what terminal modes to use.
273 "*Args passed to inferior shell by M-x shell, if the shell is csh.
274 Value is a list of strings, which may be nil."
275 :type
'(repeat (string :tag
"Argument"))
278 (defcustom explicit-bash-args
279 ;; Tell bash not to use readline, except for bash 1.x which doesn't grook --noediting.
280 ;; Bash 1.x has -nolineediting, but process-send-eof cannot terminate bash if we use it.
281 (let* ((prog (or (and (boundp 'explicit-shell-file-name
) explicit-shell-file-name
)
282 (getenv "ESHELL") shell-file-name
))
283 (name (file-name-nondirectory prog
)))
284 (if (and (not purify-flag
)
286 (file-executable-p prog
)
287 (string-match "bad option"
288 (shell-command-to-string (concat prog
" --noediting"))))
290 '("--noediting" "-i")))
291 "*Args passed to inferior shell by M-x shell, if the shell is bash.
292 Value is a list of strings, which may be nil."
293 :type
'(repeat (string :tag
"Argument"))
296 (defcustom shell-input-autoexpand
'history
297 "*If non-nil, expand input command history references on completion.
298 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
300 If the value is `input', then the expansion is seen on input.
301 If the value is `history', then the expansion is only when inserting
302 into the buffer's input ring. See also `comint-magic-space' and
303 `comint-dynamic-complete'.
305 This variable supplies a default for `comint-input-autoexpand',
306 for Shell mode only."
307 :type
'(choice (const :tag
"off" nil
)
313 (defvar shell-dirstack nil
314 "List of directories saved by pushd in this buffer's shell.
315 Thus, this does not include the shell's current directory.")
317 (defvar shell-dirtrackp t
318 "Non-nil in a shell buffer means directory tracking is enabled.")
320 (defvar shell-last-dir nil
321 "Keep track of last directory for ksh `cd -' command.")
323 (defvar shell-dirstack-query nil
324 "Command used by `shell-resync-dir' to query the shell.")
326 (defvar shell-mode-map nil
)
327 (cond ((not shell-mode-map
)
328 (setq shell-mode-map
(nconc (make-sparse-keymap) comint-mode-map
))
329 (define-key shell-mode-map
"\C-c\C-f" 'shell-forward-command
)
330 (define-key shell-mode-map
"\C-c\C-b" 'shell-backward-command
)
331 (define-key shell-mode-map
"\t" 'comint-dynamic-complete
)
332 (define-key shell-mode-map
"\M-?"
333 'comint-dynamic-list-filename-completions
)
334 (define-key shell-mode-map
[menu-bar completion
]
336 (copy-keymap (lookup-key comint-mode-map
[menu-bar completion
]))))
337 (define-key-after (lookup-key shell-mode-map
[menu-bar completion
])
338 [complete-env-variable
] '("Complete Env. Variable Name" .
339 shell-dynamic-complete-environment-variable
)
341 (define-key-after (lookup-key shell-mode-map
[menu-bar completion
])
342 [expand-directory
] '("Expand Directory Reference" .
343 shell-replace-by-expanded-directory
)
346 (defcustom shell-mode-hook
'()
347 "*Hook for customising Shell mode."
351 (defvar shell-font-lock-keywords
352 '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face
)
353 ("^[^ \t\n]+:.*" . font-lock-string-face
)
354 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face
))
355 "Additional expressions to highlight in Shell mode.")
359 (put 'shell-mode
'mode-class
'special
)
361 (define-derived-mode shell-mode comint-mode
"Shell"
362 "Major mode for interacting with an inferior shell.
363 \\[comint-send-input] after the end of the process' output sends the text from
364 the end of process to the end of the current line.
365 \\[comint-send-input] before end of process output copies the current line minus the prompt to
366 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
367 \\[send-invisible] reads a line of text without echoing it, and sends it to
368 the shell. This is useful for entering passwords. Or, add the function
369 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
371 If you want to make multiple shell buffers, rename the `*shell*' buffer
372 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
374 If you want to make shell buffers limited in length, add the function
375 `comint-truncate-buffer' to `comint-output-filter-functions'.
377 If you accidentally suspend your process, use \\[comint-continue-subjob]
380 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
381 keep this buffer's default directory the same as the shell's working directory.
382 While directory tracking is enabled, the shell's working directory is displayed
383 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
384 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
386 \\[dirtrack-mode] turns directory tracking on and off.
389 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
390 `shell-mode-hook' (in that order). Before each input, the hooks on
391 `comint-input-filter-functions' are run. After each shell output, the hooks
392 on `comint-output-filter-functions' are run.
394 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
395 and `shell-popd-regexp' are used to match their respective commands,
396 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
397 control the behavior of the relevant command.
399 Variables `comint-completion-autolist', `comint-completion-addsuffix',
400 `comint-completion-recexact' and `comint-completion-fignore' control the
401 behavior of file name, command name and variable name completion. Variable
402 `shell-completion-execonly' controls the behavior of command name completion.
403 Variable `shell-completion-fignore' is used to initialise the value of
404 `comint-completion-fignore'.
406 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
407 the initialisation of the input ring history, and history expansion.
409 Variables `comint-output-filter-functions', a hook, and
410 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
411 control whether input and output cause the window to scroll to the end of the
413 (setq comint-prompt-regexp shell-prompt-pattern
)
414 (setq comint-completion-fignore shell-completion-fignore
)
415 (setq comint-delimiter-argument-list shell-delimiter-argument-list
)
416 (setq comint-file-name-chars shell-file-name-chars
)
417 (setq comint-file-name-quote-list shell-file-name-quote-list
)
418 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions
)
419 (make-local-variable 'paragraph-start
)
420 (setq paragraph-start comint-prompt-regexp
)
421 (make-local-variable 'font-lock-defaults
)
422 (setq font-lock-defaults
'(shell-font-lock-keywords t
))
423 (make-local-variable 'shell-dirstack
)
424 (setq shell-dirstack nil
)
425 (make-local-variable 'shell-last-dir
)
426 (setq shell-last-dir nil
)
427 (make-local-variable 'shell-dirtrackp
)
428 (setq shell-dirtrackp t
)
429 (add-hook 'comint-input-filter-functions
'shell-directory-tracker nil t
)
430 (setq comint-input-autoexpand shell-input-autoexpand
)
431 ;; This is not really correct, since the shell buffer does not really
432 ;; edit this directory. But it is useful in the buffer list and menus.
433 (make-local-variable 'list-buffers-directory
)
434 (setq list-buffers-directory
(expand-file-name default-directory
))
435 ;; shell-dependent assignments.
436 (when (ring-empty-p comint-input-ring
)
437 (let ((shell (file-name-nondirectory (car
438 (process-command (get-buffer-process (current-buffer)))))))
439 (setq comint-input-ring-file-name
440 (or (getenv "HISTFILE")
441 (cond ((string-equal shell
"bash") "~/.bash_history")
442 ((string-equal shell
"ksh") "~/.sh_history")
444 (if (or (equal comint-input-ring-file-name
"")
445 (equal (file-truename comint-input-ring-file-name
)
446 (file-truename "/dev/null")))
447 (setq comint-input-ring-file-name nil
))
448 ;; Arrange to write out the input ring on exit, if the shell doesn't
450 (if (and comint-input-ring-file-name
451 (string-match shell-dumb-shell-regexp shell
))
452 (set-process-sentinel (get-buffer-process (current-buffer))
453 #'shell-write-history-on-exit
))
454 (setq shell-dirstack-query
455 (cond ((string-equal shell
"sh") "pwd")
456 ((string-equal shell
"ksh") "echo $PWD ~-")
458 (comint-read-input-ring t
)))
460 (defun shell-write-history-on-exit (process event
)
461 "Called when the shell process is stopped.
463 Writes the input history to a history file
464 `comint-input-ring-file-name' using `comint-write-input-ring'
465 and inserts a short message in the shell buffer.
467 This function is a sentinel watching the shell interpreter process.
468 Sentinels will always get the two parameters PROCESS and EVENT."
470 (comint-write-input-ring)
471 (let ((buf (process-buffer process
)))
472 (when (buffer-live-p buf
)
473 (with-current-buffer buf
474 (insert (format "\nProcess %s %s\n" process event
))))))
477 (defun shell (&optional buffer
)
478 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
479 Interactively, a prefix arg means to prompt for BUFFER.
480 If BUFFER exists but shell process is not running, make new shell.
481 If BUFFER exists and shell process is running, just switch to BUFFER.
482 Program used comes from variable `explicit-shell-file-name',
483 or (if that is nil) from the ESHELL environment variable,
484 or else from SHELL if there is no ESHELL.
485 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
486 (Note that this may lose due to a timing error if the shell
487 discards input when it starts up.)
488 The buffer is put in Shell mode, giving commands for sending input
489 and controlling the subjobs of the shell. See `shell-mode'.
490 See also the variable `shell-prompt-pattern'.
492 To specify a coding system for converting non-ASCII characters
493 in the input and output to the shell, use \\[universal-coding-system-argument]
494 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
495 in the shell buffer, after you start the shell.
496 The default comes from `process-coding-system-alist' and
497 `default-process-coding-system'.
499 The shell file name (sans directories) is used to make a symbol name
500 such as `explicit-csh-args'. If that symbol is a variable,
501 its value is used as a list of arguments when invoking the shell.
502 Otherwise, one argument `-i' is passed to the shell.
504 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
507 (and current-prefix-arg
508 (read-buffer "Shell buffer: " "*shell*"))))
509 (setq buffer
(get-buffer-create (or buffer
"*shell*")))
510 ;; Pop to buffer, so that the buffer's window will be correctly set
511 ;; when we call comint (so that comint sets the COLUMNS env var properly).
512 (pop-to-buffer buffer
)
513 (unless (comint-check-proc buffer
)
514 (let* ((prog (or explicit-shell-file-name
515 (getenv "ESHELL") shell-file-name
))
516 (name (file-name-nondirectory prog
))
517 (startfile (concat "~/.emacs_" name
))
518 (xargs-name (intern-soft (concat "explicit-" name
"-args"))))
519 (if (not (file-exists-p startfile
))
520 (setq startfile
(concat "~/.emacs.d/.emacs_" name
)))
521 (apply 'make-comint-in-buffer
"shell" buffer prog
522 (if (file-exists-p startfile
) startfile
)
523 (if (and xargs-name
(boundp xargs-name
))
524 (symbol-value xargs-name
)
529 ;;; Don't do this when shell.el is loaded, only while dumping.
530 ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
532 ;;; Directory tracking
534 ;;; This code provides the shell mode input sentinel
535 ;;; SHELL-DIRECTORY-TRACKER
536 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
537 ;;; changes the current directory of the shell buffer accordingly.
539 ;;; This is basically a fragile hack, although it's more accurate than
540 ;;; the version in Emacs 18's shell.el. It has the following failings:
541 ;;; 1. It doesn't know about the cdpath shell variable.
542 ;;; 2. It cannot infallibly deal with command sequences, though it does well
543 ;;; with these and with ignoring commands forked in another shell with ()s.
544 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
545 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
546 ;;; that, there's no way to catch shell commands where cd's are buried
547 ;;; inside conditional expressions, aliases, and so forth.
549 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
550 ;;; messes it up. You run other processes under the shell; these each have
551 ;;; separate working directories, and some have commands for manipulating
552 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
553 ;;; commands that do *not* affect the current w.d. at all, but look like they
554 ;;; do (e.g., the cd command in ftp). In shells that allow you job
555 ;;; control, you can switch between jobs, all having different w.d.'s. So
556 ;;; simply saying %3 can shift your w.d..
558 ;;; The solution is to relax, not stress out about it, and settle for
559 ;;; a hack that works pretty well in typical circumstances. Remember
560 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
563 ;;; One good hack not implemented here for users of programmable shells
564 ;;; is to program up the shell w.d. manipulation commands to output
565 ;;; a coded command sequence to the tty. Something like
567 ;;; where <cwd> is the new current working directory. Then trash the
568 ;;; directory tracking machinery currently used in this package, and
569 ;;; replace it with a process filter that watches for and strips out
572 (defun shell-directory-tracker (str)
573 "Tracks cd, pushd and popd commands issued to the shell.
574 This function is called on each input passed to the shell.
575 It watches for cd, pushd and popd commands and sets the buffer's
576 default directory to track these commands.
578 You may toggle this tracking on and off with M-x dirtrack-mode.
579 If emacs gets confused, you can resync with the shell with M-x dirs.
581 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
582 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
583 and `shell-pushd-dunique' control the behavior of the relevant command.
585 Environment variables are expanded, see function `substitute-in-file-name'."
587 ;; We fail gracefully if we think the command will fail in the shell.
588 (condition-case chdir-failure
589 (let ((start (progn (string-match "^[; \t]*" str
) ; skip whitespace
592 (while (string-match shell-command-regexp str start
)
593 (setq end
(match-end 0)
594 cmd
(comint-arguments (substring str start end
) 0 0)
595 arg1
(comint-arguments (substring str start end
) 1 1))
597 (setq arg1
(shell-unquote-argument arg1
)))
598 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
599 "\\)\\($\\|[ \t]\\)")
601 (shell-process-popd (comint-substitute-in-file-name arg1
)))
602 ((string-match (concat "\\`\\(" shell-pushd-regexp
603 "\\)\\($\\|[ \t]\\)")
605 (shell-process-pushd (comint-substitute-in-file-name arg1
)))
606 ((string-match (concat "\\`\\(" shell-cd-regexp
607 "\\)\\($\\|[ \t]\\)")
609 (shell-process-cd (comint-substitute-in-file-name arg1
)))
610 ((and shell-chdrive-regexp
611 (string-match (concat "\\`\\(" shell-chdrive-regexp
612 "\\)\\($\\|[ \t]\\)")
614 (shell-process-cd (comint-substitute-in-file-name cmd
))))
615 (setq start
(progn (string-match "[; \t]*" str end
) ; skip again
617 (error "Couldn't cd"))))
619 (defun shell-unquote-argument (string)
620 "Remove all kinds of shell quoting from STRING."
622 (let ((idx 0) next inside
624 (if (string-match shell-dumb-shell-regexp
625 (file-name-nondirectory
626 (car (process-command (get-buffer-process (current-buffer))))))
629 (while (and (< idx
(length string
))
630 (setq next
(string-match quote-chars string next
)))
631 (cond ((= (aref string next
) ?
\\)
632 (setq string
(replace-match "" nil nil string
))
633 (setq next
(1+ next
)))
634 ((and inside
(= (aref string next
) inside
))
635 (setq string
(replace-match "" nil nil string
))
638 (setq next
(1+ next
)))
640 (setq inside
(aref string next
))
641 (setq string
(replace-match "" nil nil string
)))))
645 (defun shell-process-popd (arg)
646 (let ((num (or (shell-extract-num arg
) 0)))
647 (cond ((and num
(= num
0) shell-dirstack
)
648 (shell-cd (car shell-dirstack
))
649 (setq shell-dirstack
(cdr shell-dirstack
))
650 (shell-dirstack-message))
651 ((and num
(> num
0) (<= num
(length shell-dirstack
)))
652 (let* ((ds (cons nil shell-dirstack
))
653 (cell (nthcdr (1- num
) ds
)))
654 (rplacd cell
(cdr (cdr cell
)))
655 (setq shell-dirstack
(cdr ds
))
656 (shell-dirstack-message)))
658 (error "Couldn't popd")))))
660 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
661 (defun shell-prefixed-directory-name (dir)
662 (if (= (length comint-file-name-prefix
) 0)
664 (if (file-name-absolute-p dir
)
665 ;; The name is absolute, so prepend the prefix.
666 (concat comint-file-name-prefix dir
)
667 ;; For relative name we assume default-directory already has the prefix.
668 (expand-file-name dir
))))
671 (defun shell-process-cd (arg)
672 (let ((new-dir (cond ((zerop (length arg
)) (concat comint-file-name-prefix
674 ((string-equal "-" arg
) shell-last-dir
)
675 (t (shell-prefixed-directory-name arg
)))))
676 (setq shell-last-dir default-directory
)
678 (shell-dirstack-message)))
681 (defun shell-process-pushd (arg)
682 (let ((num (shell-extract-num arg
)))
683 (cond ((zerop (length arg
))
684 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
685 (cond (shell-pushd-tohome
686 (shell-process-pushd (concat comint-file-name-prefix
"~")))
688 (let ((old default-directory
))
689 (shell-cd (car shell-dirstack
))
690 (setq shell-dirstack
(cons old
(cdr shell-dirstack
)))
691 (shell-dirstack-message)))
693 (message "Directory stack empty."))))
696 (cond ((> num
(length shell-dirstack
))
697 (message "Directory stack not that deep."))
699 (error (message "Couldn't cd")))
700 (shell-pushd-dextract
701 (let ((dir (nth (1- num
) shell-dirstack
)))
702 (shell-process-popd arg
)
703 (shell-process-pushd default-directory
)
705 (shell-dirstack-message)))
707 (let* ((ds (cons default-directory shell-dirstack
))
709 (front (nthcdr num ds
))
710 (back (reverse (nthcdr (- dslen num
) (reverse ds
))))
711 (new-ds (append front back
)))
712 (shell-cd (car new-ds
))
713 (setq shell-dirstack
(cdr new-ds
))
714 (shell-dirstack-message)))))
717 (let ((old-wd default-directory
))
718 (shell-cd (shell-prefixed-directory-name arg
))
719 (if (or (null shell-pushd-dunique
)
720 (not (member old-wd shell-dirstack
)))
721 (setq shell-dirstack
(cons old-wd shell-dirstack
)))
722 (shell-dirstack-message))))))
724 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
725 (defun shell-extract-num (str)
726 (and (string-match "^\\+[1-9][0-9]*$" str
)
727 (string-to-int str
)))
730 (defun shell-dirtrack-mode ()
731 "Turn directory tracking on and off in a shell buffer."
733 (if (setq shell-dirtrackp
(not shell-dirtrackp
))
734 (setq list-buffers-directory default-directory
)
735 (setq list-buffers-directory nil
))
736 (message "Directory tracking %s" (if shell-dirtrackp
"ON" "OFF")))
738 ;;; For your typing convenience:
739 (defalias 'shell-dirtrack-toggle
'shell-dirtrack-mode
)
740 (defalias 'dirtrack-toggle
'shell-dirtrack-mode
)
741 (defalias 'dirtrack-mode
'shell-dirtrack-mode
)
743 (defun shell-cd (dir)
744 "Do normal `cd' to DIR, and set `list-buffers-directory'."
746 (setq list-buffers-directory
(file-name-as-directory
747 (expand-file-name dir
))))
750 (defun shell-resync-dirs ()
751 "Resync the buffer's idea of the current directory stack.
752 This command queries the shell with the command bound to
753 `shell-dirstack-query' (default \"dirs\"), reads the next
754 line output and parses it to form the new directory stack.
755 DON'T issue this command unless the buffer is at a shell prompt.
756 Also, note that if some other subprocess decides to do output
757 immediately after the query, its output will be taken as the
758 new directory stack -- you lose. If this happens, just do the
761 (let* ((proc (get-buffer-process (current-buffer)))
762 (pmark (process-mark proc
)))
764 (insert shell-dirstack-query
) (insert "\n")
765 (sit-for 0) ; force redisplay
766 (comint-send-string proc shell-dirstack-query
)
767 (comint-send-string proc
"\n")
768 (set-marker pmark
(point))
769 (let ((pt (point))) ; wait for 1 line
770 ;; This extra newline prevents the user's pending input from spoofing us.
771 (insert "\n") (backward-char 1)
772 (while (not (looking-at ".+\n"))
773 (accept-process-output proc
)
775 (goto-char pmark
) (delete-char 1) ; remove the extra newline
776 ;; That's the dirlist. grab it & parse it.
777 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
779 (ds '()) ; new dir stack
782 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
783 (string-match "\\s *\\(\\S +\\)\\s *" dl i
) ; pick off next dir
784 (setq ds
(cons (concat comint-file-name-prefix
785 (substring dl
(match-beginning 1)
788 (setq i
(match-end 0)))
789 (let ((ds (nreverse ds
)))
791 (progn (shell-cd (car ds
))
792 (setq shell-dirstack
(cdr ds
)
793 shell-last-dir
(car shell-dirstack
))
794 (shell-dirstack-message))
795 (error (message "Couldn't cd")))))))
797 ;;; For your typing convenience:
798 (defalias 'dirs
'shell-resync-dirs
)
801 ;;; Show the current dirstack on the message line.
802 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
803 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
804 ;;; All the commands that mung the buffer's dirstack finish by calling
806 (defun shell-dirstack-message ()
807 (when shell-dirtrack-verbose
809 (ds (cons default-directory shell-dirstack
))
810 (home (expand-file-name (concat comint-file-name-prefix
"~/")))
811 (homelen (length home
)))
813 (let ((dir (car ds
)))
814 (and (>= (length dir
) homelen
)
815 (string= home
(substring dir
0 homelen
))
816 (setq dir
(concat "~/" (substring dir homelen
))))
817 ;; Strip off comint-file-name-prefix if present.
818 (and comint-file-name-prefix
819 (>= (length dir
) (length comint-file-name-prefix
))
820 (string= comint-file-name-prefix
821 (substring dir
0 (length comint-file-name-prefix
)))
822 (setq dir
(substring dir
(length comint-file-name-prefix
)))
824 (setq msg
(concat msg
(directory-file-name dir
) " "))
826 (message "%s" msg
))))
828 ;; This was mostly copied from shell-resync-dirs.
829 (defun shell-snarf-envar (var)
830 "Return as a string the shell's value of environment variable VAR."
831 (let* ((cmd (format "printenv '%s'\n" var
))
832 (proc (get-buffer-process (current-buffer)))
833 (pmark (process-mark proc
)))
836 (sit-for 0) ; force redisplay
837 (comint-send-string proc cmd
)
838 (set-marker pmark
(point))
839 (let ((pt (point))) ; wait for 1 line
840 ;; This extra newline prevents the user's pending input from spoofing us.
841 (insert "\n") (backward-char 1)
842 (while (not (looking-at ".+\n"))
843 (accept-process-output proc
)
845 (goto-char pmark
) (delete-char 1) ; remove the extra newline
846 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
848 (defun shell-copy-environment-variable (variable)
849 "Copy the environment variable VARIABLE from the subshell to Emacs.
850 This command reads the value of the specified environment variable
851 in the shell, and sets the same environment variable in Emacs
852 \(what `getenv' in Emacs would return) to that value.
853 That value will affect any new subprocesses that you subsequently start
855 (interactive (list (read-envvar-name "\
856 Copy Shell environment variable to Emacs: ")))
857 (setenv variable
(shell-snarf-envar variable
)))
859 (defun shell-forward-command (&optional arg
)
860 "Move forward across ARG shell command(s). Does not cross lines.
861 See `shell-command-regexp'."
863 (let ((limit (save-excursion (end-of-line nil
) (point))))
864 (if (re-search-forward (concat shell-command-regexp
"\\([;&|][\t ]*\\)+")
866 (skip-syntax-backward " "))))
869 (defun shell-backward-command (&optional arg
)
870 "Move backward across ARG shell command(s). Does not cross lines.
871 See `shell-command-regexp'."
873 (let ((limit (save-excursion (comint-bol nil
) (point))))
874 (when (> limit
(point))
875 (setq limit
(line-beginning-position)))
876 (skip-syntax-backward " " limit
)
877 (if (re-search-backward
878 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp
) limit
'move arg
)
879 (progn (goto-char (match-beginning 1))
880 (skip-chars-forward ";&|")))))
882 (defun shell-dynamic-complete-command ()
883 "Dynamically complete the command at point.
884 This function is similar to `comint-dynamic-complete-filename', except that it
885 searches `exec-path' (minus the trailing emacs library path) for completion
886 candidates. Note that this may not be the same as the shell's idea of the
889 Completion is dependent on the value of `shell-completion-execonly', plus
890 those that effect file completion. See `shell-dynamic-complete-as-command'.
892 Returns t if successful."
894 (let ((filename (comint-match-partial-filename)))
896 (save-match-data (not (string-match "[~/]" filename
)))
897 (eq (match-beginning 0)
898 (save-excursion (shell-backward-command 1) (point))))
899 (prog2 (message "Completing command name...")
900 (shell-dynamic-complete-as-command)))))
903 (defun shell-dynamic-complete-as-command ()
904 "Dynamically complete at point as a command.
905 See `shell-dynamic-complete-filename'. Returns t if successful."
906 (let* ((filename (or (comint-match-partial-filename) ""))
907 (pathnondir (file-name-nondirectory filename
))
908 (paths (cdr (reverse exec-path
)))
909 (cwd (file-name-as-directory (expand-file-name default-directory
)))
911 (and comint-completion-fignore
912 (mapconcat (function (lambda (x) (concat (regexp-quote x
) "$")))
913 comint-completion-fignore
"\\|")))
914 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
915 ;; Go thru each path in the search path, finding completions.
917 (setq path
(file-name-as-directory (comint-directory (or (car paths
) ".")))
918 comps-in-path
(and (file-accessible-directory-p path
)
919 (file-name-all-completions pathnondir path
)))
920 ;; Go thru each completion found, to see whether it should be used.
922 (setq file
(car comps-in-path
)
923 filepath
(concat path file
))
924 (if (and (not (member file completions
))
925 (not (and ignored-extensions
926 (string-match ignored-extensions file
)))
927 (or (string-equal path cwd
)
928 (not (file-directory-p filepath
)))
929 (or (null shell-completion-execonly
)
930 (file-executable-p filepath
)))
931 (setq completions
(cons file completions
)))
932 (setq comps-in-path
(cdr comps-in-path
)))
933 (setq paths
(cdr paths
)))
934 ;; OK, we've got a list of completions.
935 (let ((success (let ((comint-completion-addsuffix nil
))
936 (comint-dynamic-simple-complete pathnondir completions
))))
937 (if (and (memq success
'(sole shortest
)) comint-completion-addsuffix
938 (not (file-directory-p (comint-match-partial-filename))))
943 (defun shell-match-partial-variable ()
944 "Return the shell variable at point, or nil if none is found."
946 (let ((limit (point)))
947 (if (re-search-backward "[^A-Za-z0-9_{}]" nil
'move
)
948 (or (looking-at "\\$") (forward-char 1)))
949 ;; Anchor the search forwards.
950 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
952 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit
)
953 (buffer-substring (match-beginning 0) (match-end 0))))))
956 (defun shell-dynamic-complete-environment-variable ()
957 "Dynamically complete the environment variable at point.
958 Completes if after a variable, i.e., if it starts with a \"$\".
959 See `shell-dynamic-complete-as-environment-variable'.
961 This function is similar to `comint-dynamic-complete-filename', except that it
962 searches `process-environment' for completion candidates. Note that this may
963 not be the same as the interpreter's idea of variable names. The main problem
964 with this type of completion is that `process-environment' is the environment
965 which Emacs started with. Emacs does not track changes to the environment made
966 by the interpreter. Perhaps it would be more accurate if this function was
967 called `shell-dynamic-complete-process-environment-variable'.
969 Returns non-nil if successful."
971 (let ((variable (shell-match-partial-variable)))
972 (if (and variable
(string-match "^\\$" variable
))
973 (prog2 (message "Completing variable name...")
974 (shell-dynamic-complete-as-environment-variable)))))
977 (defun shell-dynamic-complete-as-environment-variable ()
978 "Dynamically complete at point as an environment variable.
979 Used by `shell-dynamic-complete-environment-variable'.
980 Uses `comint-dynamic-simple-complete'."
981 (let* ((var (or (shell-match-partial-variable) ""))
982 (variable (substring var
(or (string-match "[^$({]\\|$" var
) 0)))
983 (variables (mapcar (function (lambda (x)
984 (substring x
0 (string-match "=" x
))))
985 process-environment
))
986 (addsuffix comint-completion-addsuffix
)
987 (comint-completion-addsuffix nil
)
988 (success (comint-dynamic-simple-complete variable variables
)))
989 (if (memq success
'(sole shortest
))
990 (let* ((var (shell-match-partial-variable))
991 (variable (substring var
(string-match "[^$({]" var
)))
992 (protection (cond ((string-match "{" var
) "}")
993 ((string-match "(" var
) ")")
995 (suffix (cond ((null addsuffix
) "")
997 (comint-directory (getenv variable
))) "/")
999 (insert protection suffix
)))
1003 (defun shell-replace-by-expanded-directory ()
1004 "Expand directory stack reference before point.
1005 Directory stack references are of the form \"=digit\" or \"=-\".
1006 See `default-directory' and `shell-dirstack'.
1008 Returns t if successful."
1010 (if (comint-match-partial-filename)
1012 (goto-char (match-beginning 0))
1013 (let ((stack (cons default-directory shell-dirstack
))
1014 (index (cond ((looking-at "=-/?")
1015 (length shell-dirstack
))
1016 ((looking-at "=\\([0-9]+\\)/?")
1019 (match-beginning 1) (match-end 1)))))))
1022 ((>= index
(length stack
))
1023 (error "Directory stack not that deep"))
1025 (replace-match (file-name-as-directory (nth index stack
)) t t
)
1026 (message "Directory item: %d" index
)
1031 ;;; shell.el ends here