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 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-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
))
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 shell-input-autoexpand
'history
279 "*If non-nil, expand input command history references on completion.
280 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
282 If the value is `input', then the expansion is seen on input.
283 If the value is `history', then the expansion is only when inserting
284 into the buffer's input ring. See also `comint-magic-space' and
285 `comint-dynamic-complete'.
287 This variable supplies a default for `comint-input-autoexpand',
288 for Shell mode only."
289 :type
'(choice (const :tag
"off" nil
)
295 (defvar shell-dirstack nil
296 "List of directories saved by pushd in this buffer's shell.
297 Thus, this does not include the shell's current directory.")
299 (defvar shell-dirtrackp t
300 "Non-nil in a shell buffer means directory tracking is enabled.")
302 (defvar shell-last-dir nil
303 "Keep track of last directory for ksh `cd -' command.")
305 (defvar shell-dirstack-query nil
306 "Command used by `shell-resync-dir' to query the shell.")
308 (defvar shell-mode-map nil
)
309 (cond ((not shell-mode-map
)
310 (setq shell-mode-map
(nconc (make-sparse-keymap) comint-mode-map
))
311 (define-key shell-mode-map
"\C-c\C-f" 'shell-forward-command
)
312 (define-key shell-mode-map
"\C-c\C-b" 'shell-backward-command
)
313 (define-key shell-mode-map
"\t" 'comint-dynamic-complete
)
314 (define-key shell-mode-map
"\M-?"
315 'comint-dynamic-list-filename-completions
)
316 (define-key shell-mode-map
[menu-bar completion
]
318 (copy-keymap (lookup-key comint-mode-map
[menu-bar completion
]))))
319 (define-key-after (lookup-key shell-mode-map
[menu-bar completion
])
320 [complete-env-variable
] '("Complete Env. Variable Name" .
321 shell-dynamic-complete-environment-variable
)
323 (define-key-after (lookup-key shell-mode-map
[menu-bar completion
])
324 [expand-directory
] '("Expand Directory Reference" .
325 shell-replace-by-expanded-directory
)
328 (defcustom shell-mode-hook
'()
329 "*Hook for customising Shell mode."
333 (defvar shell-font-lock-keywords
334 '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face
)
335 ("^[^ \t\n]+:.*" . font-lock-string-face
)
336 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face
))
337 "Additional expressions to highlight in Shell mode.")
341 (put 'shell-mode
'mode-class
'special
)
343 (define-derived-mode shell-mode comint-mode
"Shell"
344 "Major mode for interacting with an inferior shell.
345 \\[comint-send-input] after the end of the process' output sends the text from
346 the end of process to the end of the current line.
347 \\[comint-send-input] before end of process output copies the current line minus the prompt to
348 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
349 \\[send-invisible] reads a line of text without echoing it, and sends it to
350 the shell. This is useful for entering passwords. Or, add the function
351 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
353 If you want to make multiple shell buffers, rename the `*shell*' buffer
354 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
356 If you want to make shell buffers limited in length, add the function
357 `comint-truncate-buffer' to `comint-output-filter-functions'.
359 If you accidentally suspend your process, use \\[comint-continue-subjob]
362 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
363 keep this buffer's default directory the same as the shell's working directory.
364 While directory tracking is enabled, the shell's working directory is displayed
365 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
366 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
368 \\[dirtrack-mode] turns directory tracking on and off.
371 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
372 `shell-mode-hook' (in that order). Before each input, the hooks on
373 `comint-input-filter-functions' are run. After each shell output, the hooks
374 on `comint-output-filter-functions' are run.
376 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
377 and `shell-popd-regexp' are used to match their respective commands,
378 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
379 control the behavior of the relevant command.
381 Variables `comint-completion-autolist', `comint-completion-addsuffix',
382 `comint-completion-recexact' and `comint-completion-fignore' control the
383 behavior of file name, command name and variable name completion. Variable
384 `shell-completion-execonly' controls the behavior of command name completion.
385 Variable `shell-completion-fignore' is used to initialise the value of
386 `comint-completion-fignore'.
388 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
389 the initialisation of the input ring history, and history expansion.
391 Variables `comint-output-filter-functions', a hook, and
392 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
393 control whether input and output cause the window to scroll to the end of the
395 (setq comint-prompt-regexp shell-prompt-pattern
)
396 (setq comint-completion-fignore shell-completion-fignore
)
397 (setq comint-delimiter-argument-list shell-delimiter-argument-list
)
398 (setq comint-file-name-chars shell-file-name-chars
)
399 (setq comint-file-name-quote-list shell-file-name-quote-list
)
400 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions
)
401 (make-local-variable 'paragraph-start
)
402 (setq paragraph-start comint-prompt-regexp
)
403 (make-local-variable 'font-lock-defaults
)
404 (setq font-lock-defaults
'(shell-font-lock-keywords t
))
405 (make-local-variable 'shell-dirstack
)
406 (setq shell-dirstack nil
)
407 (make-local-variable 'shell-last-dir
)
408 (setq shell-last-dir nil
)
409 (make-local-variable 'shell-dirtrackp
)
410 (setq shell-dirtrackp t
)
411 (add-hook 'comint-input-filter-functions
'shell-directory-tracker nil t
)
412 (setq comint-input-autoexpand shell-input-autoexpand
)
413 ;; This is not really correct, since the shell buffer does not really
414 ;; edit this directory. But it is useful in the buffer list and menus.
415 (make-local-variable 'list-buffers-directory
)
416 (setq list-buffers-directory
(expand-file-name default-directory
))
417 ;; shell-dependent assignments.
418 (unless comint-input-ring
419 (let ((shell (file-name-nondirectory (car
420 (process-command (get-buffer-process (current-buffer)))))))
421 (setq comint-input-ring-file-name
422 (or (getenv "HISTFILE")
423 (cond ((string-equal shell
"bash") "~/.bash_history")
424 ((string-equal shell
"ksh") "~/.sh_history")
426 (if (or (equal comint-input-ring-file-name
"")
427 (equal (file-truename comint-input-ring-file-name
)
428 (file-truename "/dev/null")))
429 (setq comint-input-ring-file-name nil
))
430 ;; Arrange to write out the input ring on exit, if the shell doesn't
432 (if (and comint-input-ring-file-name
433 (string-match shell-dumb-shell-regexp shell
))
434 (set-process-sentinel (get-buffer-process (current-buffer))
435 #'shell-write-history-on-exit
))
436 (setq shell-dirstack-query
437 (cond ((string-equal shell
"sh") "pwd")
438 ((string-equal shell
"ksh") "echo $PWD ~-")
440 (comint-read-input-ring t
)))
442 (defun shell-write-history-on-exit (process event
)
443 "Called when the shell process is stopped.
445 Writes the input history to a history file
446 `comint-input-ring-file-name' using `comint-write-input-ring'
447 and inserts a short message in the shell buffer.
449 This function is a sentinel watching the shell interpreter process.
450 Sentinels will always get the two parameters PROCESS and EVENT."
452 (comint-write-input-ring)
453 (let ((buf (process-buffer process
)))
454 (when (buffer-live-p buf
)
455 (with-current-buffer buf
456 (insert (format "\nProcess %s %s\n" process event
))))))
459 (defun shell (&optional buffer
)
460 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
461 Interactively, a prefix arg means to prompt for BUFFER.
462 If BUFFER exists but shell process is not running, make new shell.
463 If BUFFER exists and shell process is running, just switch to BUFFER.
464 Program used comes from variable `explicit-shell-file-name',
465 or (if that is nil) from the ESHELL environment variable,
466 or else from SHELL if there is no ESHELL.
467 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
468 (Note that this may lose due to a timing error if the shell
469 discards input when it starts up.)
470 The buffer is put in Shell mode, giving commands for sending input
471 and controlling the subjobs of the shell. See `shell-mode'.
472 See also the variable `shell-prompt-pattern'.
474 To specify a coding system for converting non-ASCII characters
475 in the input and output to the shell, use \\[universal-coding-system-argument]
476 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
477 in the shell buffer, after you start the shell.
478 The default comes from `process-coding-system-alist' and
479 `default-process-coding-system'.
481 The shell file name (sans directories) is used to make a symbol name
482 such as `explicit-csh-args'. If that symbol is a variable,
483 its value is used as a list of arguments when invoking the shell.
484 Otherwise, one argument `-i' is passed to the shell.
486 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
489 (and current-prefix-arg
490 (read-buffer "Shell buffer: " "*shell*"))))
491 (setq buffer
(get-buffer-create (or buffer
"*shell*")))
492 ;; Pop to buffer, so that the buffer's window will be correctly set
493 ;; when we call comint (so that comint sets the COLUMNS env var properly).
494 (pop-to-buffer buffer
)
495 (unless (comint-check-proc buffer
)
496 (let* ((prog (or explicit-shell-file-name
497 (getenv "ESHELL") shell-file-name
))
498 (name (file-name-nondirectory prog
))
499 (startfile (concat "~/.emacs_" name
))
500 (xargs-name (intern-soft (concat "explicit-" name
"-args"))))
501 (apply 'make-comint-in-buffer
"shell" buffer prog
502 (if (file-exists-p startfile
) startfile
)
503 (if (and xargs-name
(boundp xargs-name
))
504 (symbol-value xargs-name
)
509 ;;; Don't do this when shell.el is loaded, only while dumping.
510 ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
512 ;;; Directory tracking
514 ;;; This code provides the shell mode input sentinel
515 ;;; SHELL-DIRECTORY-TRACKER
516 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
517 ;;; changes the current directory of the shell buffer accordingly.
519 ;;; This is basically a fragile hack, although it's more accurate than
520 ;;; the version in Emacs 18's shell.el. It has the following failings:
521 ;;; 1. It doesn't know about the cdpath shell variable.
522 ;;; 2. It cannot infallibly deal with command sequences, though it does well
523 ;;; with these and with ignoring commands forked in another shell with ()s.
524 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
525 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
526 ;;; that, there's no way to catch shell commands where cd's are buried
527 ;;; inside conditional expressions, aliases, and so forth.
529 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
530 ;;; messes it up. You run other processes under the shell; these each have
531 ;;; separate working directories, and some have commands for manipulating
532 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
533 ;;; commands that do *not* affect the current w.d. at all, but look like they
534 ;;; do (e.g., the cd command in ftp). In shells that allow you job
535 ;;; control, you can switch between jobs, all having different w.d.'s. So
536 ;;; simply saying %3 can shift your w.d..
538 ;;; The solution is to relax, not stress out about it, and settle for
539 ;;; a hack that works pretty well in typical circumstances. Remember
540 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
543 ;;; One good hack not implemented here for users of programmable shells
544 ;;; is to program up the shell w.d. manipulation commands to output
545 ;;; a coded command sequence to the tty. Something like
547 ;;; where <cwd> is the new current working directory. Then trash the
548 ;;; directory tracking machinery currently used in this package, and
549 ;;; replace it with a process filter that watches for and strips out
552 (defun shell-directory-tracker (str)
553 "Tracks cd, pushd and popd commands issued to the shell.
554 This function is called on each input passed to the shell.
555 It watches for cd, pushd and popd commands and sets the buffer's
556 default directory to track these commands.
558 You may toggle this tracking on and off with M-x dirtrack-mode.
559 If emacs gets confused, you can resync with the shell with M-x dirs.
561 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
562 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
563 and `shell-pushd-dunique' control the behavior of the relevant command.
565 Environment variables are expanded, see function `substitute-in-file-name'."
567 ;; We fail gracefully if we think the command will fail in the shell.
568 (condition-case chdir-failure
569 (let ((start (progn (string-match "^[; \t]*" str
) ; skip whitespace
572 (while (string-match shell-command-regexp str start
)
573 (setq end
(match-end 0)
574 cmd
(comint-arguments (substring str start end
) 0 0)
575 arg1
(comint-arguments (substring str start end
) 1 1))
577 (setq arg1
(shell-unquote-argument arg1
)))
578 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
579 "\\)\\($\\|[ \t]\\)")
581 (shell-process-popd (comint-substitute-in-file-name arg1
)))
582 ((string-match (concat "\\`\\(" shell-pushd-regexp
583 "\\)\\($\\|[ \t]\\)")
585 (shell-process-pushd (comint-substitute-in-file-name arg1
)))
586 ((string-match (concat "\\`\\(" shell-cd-regexp
587 "\\)\\($\\|[ \t]\\)")
589 (shell-process-cd (comint-substitute-in-file-name arg1
)))
590 ((and shell-chdrive-regexp
591 (string-match (concat "\\`\\(" shell-chdrive-regexp
592 "\\)\\($\\|[ \t]\\)")
594 (shell-process-cd (comint-substitute-in-file-name cmd
))))
595 (setq start
(progn (string-match "[; \t]*" str end
) ; skip again
597 (error "Couldn't cd"))))
599 (defun shell-unquote-argument (string)
600 "Remove all kinds of shell quoting from STRING."
602 (let ((idx 0) next inside
604 (if (string-match shell-dumb-shell-regexp
605 (file-name-nondirectory
606 (car (process-command (get-buffer-process (current-buffer))))))
609 (while (and (< idx
(length string
))
610 (setq next
(string-match quote-chars string next
)))
611 (cond ((= (aref string next
) ?
\\)
612 (setq string
(replace-match "" nil nil string
))
613 (setq next
(1+ next
)))
614 ((and inside
(= (aref string next
) inside
))
615 (setq string
(replace-match "" nil nil string
))
618 (setq next
(1+ next
)))
620 (setq inside
(aref string next
))
621 (setq string
(replace-match "" nil nil string
)))))
625 (defun shell-process-popd (arg)
626 (let ((num (or (shell-extract-num arg
) 0)))
627 (cond ((and num
(= num
0) shell-dirstack
)
628 (shell-cd (car shell-dirstack
))
629 (setq shell-dirstack
(cdr shell-dirstack
))
630 (shell-dirstack-message))
631 ((and num
(> num
0) (<= num
(length shell-dirstack
)))
632 (let* ((ds (cons nil shell-dirstack
))
633 (cell (nthcdr (1- num
) ds
)))
634 (rplacd cell
(cdr (cdr cell
)))
635 (setq shell-dirstack
(cdr ds
))
636 (shell-dirstack-message)))
638 (error "Couldn't popd")))))
640 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
641 (defun shell-prefixed-directory-name (dir)
642 (if (= (length comint-file-name-prefix
) 0)
644 (if (file-name-absolute-p dir
)
645 ;; The name is absolute, so prepend the prefix.
646 (concat comint-file-name-prefix dir
)
647 ;; For relative name we assume default-directory already has the prefix.
648 (expand-file-name dir
))))
651 (defun shell-process-cd (arg)
652 (let ((new-dir (cond ((zerop (length arg
)) (concat comint-file-name-prefix
654 ((string-equal "-" arg
) shell-last-dir
)
655 (t (shell-prefixed-directory-name arg
)))))
656 (setq shell-last-dir default-directory
)
658 (shell-dirstack-message)))
661 (defun shell-process-pushd (arg)
662 (let ((num (shell-extract-num arg
)))
663 (cond ((zerop (length arg
))
664 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
665 (cond (shell-pushd-tohome
666 (shell-process-pushd (concat comint-file-name-prefix
"~")))
668 (let ((old default-directory
))
669 (shell-cd (car shell-dirstack
))
670 (setq shell-dirstack
(cons old
(cdr shell-dirstack
)))
671 (shell-dirstack-message)))
673 (message "Directory stack empty."))))
676 (cond ((> num
(length shell-dirstack
))
677 (message "Directory stack not that deep."))
679 (error (message "Couldn't cd")))
680 (shell-pushd-dextract
681 (let ((dir (nth (1- num
) shell-dirstack
)))
682 (shell-process-popd arg
)
683 (shell-process-pushd default-directory
)
685 (shell-dirstack-message)))
687 (let* ((ds (cons default-directory shell-dirstack
))
689 (front (nthcdr num ds
))
690 (back (reverse (nthcdr (- dslen num
) (reverse ds
))))
691 (new-ds (append front back
)))
692 (shell-cd (car new-ds
))
693 (setq shell-dirstack
(cdr new-ds
))
694 (shell-dirstack-message)))))
697 (let ((old-wd default-directory
))
698 (shell-cd (shell-prefixed-directory-name arg
))
699 (if (or (null shell-pushd-dunique
)
700 (not (member old-wd shell-dirstack
)))
701 (setq shell-dirstack
(cons old-wd shell-dirstack
)))
702 (shell-dirstack-message))))))
704 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
705 (defun shell-extract-num (str)
706 (and (string-match "^\\+[1-9][0-9]*$" str
)
707 (string-to-int str
)))
710 (defun shell-dirtrack-mode ()
711 "Turn directory tracking on and off in a shell buffer."
713 (if (setq shell-dirtrackp
(not shell-dirtrackp
))
714 (setq list-buffers-directory default-directory
)
715 (setq list-buffers-directory nil
))
716 (message "Directory tracking %s" (if shell-dirtrackp
"ON" "OFF")))
718 ;;; For your typing convenience:
719 (defalias 'shell-dirtrack-toggle
'shell-dirtrack-mode
)
720 (defalias 'dirtrack-toggle
'shell-dirtrack-mode
)
721 (defalias 'dirtrack-mode
'shell-dirtrack-mode
)
723 (defun shell-cd (dir)
724 "Do normal `cd' to DIR, and set `list-buffers-directory'."
726 (setq list-buffers-directory
(file-name-as-directory
727 (expand-file-name dir
))))
730 (defun shell-resync-dirs ()
731 "Resync the buffer's idea of the current directory stack.
732 This command queries the shell with the command bound to
733 `shell-dirstack-query' (default \"dirs\"), reads the next
734 line output and parses it to form the new directory stack.
735 DON'T issue this command unless the buffer is at a shell prompt.
736 Also, note that if some other subprocess decides to do output
737 immediately after the query, its output will be taken as the
738 new directory stack -- you lose. If this happens, just do the
741 (let* ((proc (get-buffer-process (current-buffer)))
742 (pmark (process-mark proc
)))
744 (insert shell-dirstack-query
) (insert "\n")
745 (sit-for 0) ; force redisplay
746 (comint-send-string proc shell-dirstack-query
)
747 (comint-send-string proc
"\n")
748 (set-marker pmark
(point))
749 (let ((pt (point))) ; wait for 1 line
750 ;; This extra newline prevents the user's pending input from spoofing us.
751 (insert "\n") (backward-char 1)
752 (while (not (looking-at ".+\n"))
753 (accept-process-output proc
)
755 (goto-char pmark
) (delete-char 1) ; remove the extra newline
756 ;; That's the dirlist. grab it & parse it.
757 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
759 (ds '()) ; new dir stack
762 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
763 (string-match "\\s *\\(\\S +\\)\\s *" dl i
) ; pick off next dir
764 (setq ds
(cons (concat comint-file-name-prefix
765 (substring dl
(match-beginning 1)
768 (setq i
(match-end 0)))
769 (let ((ds (nreverse ds
)))
771 (progn (shell-cd (car ds
))
772 (setq shell-dirstack
(cdr ds
)
773 shell-last-dir
(car shell-dirstack
))
774 (shell-dirstack-message))
775 (error (message "Couldn't cd")))))))
777 ;;; For your typing convenience:
778 (defalias 'dirs
'shell-resync-dirs
)
781 ;;; Show the current dirstack on the message line.
782 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
783 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
784 ;;; All the commands that mung the buffer's dirstack finish by calling
786 (defun shell-dirstack-message ()
787 (when shell-dirtrack-verbose
789 (ds (cons default-directory shell-dirstack
))
790 (home (expand-file-name (concat comint-file-name-prefix
"~/")))
791 (homelen (length home
)))
793 (let ((dir (car ds
)))
794 (and (>= (length dir
) homelen
)
795 (string= home
(substring dir
0 homelen
))
796 (setq dir
(concat "~/" (substring dir homelen
))))
797 ;; Strip off comint-file-name-prefix if present.
798 (and comint-file-name-prefix
799 (>= (length dir
) (length comint-file-name-prefix
))
800 (string= comint-file-name-prefix
801 (substring dir
0 (length comint-file-name-prefix
)))
802 (setq dir
(substring dir
(length comint-file-name-prefix
)))
804 (setq msg
(concat msg
(directory-file-name dir
) " "))
806 (message "%s" msg
))))
808 ;; This was mostly copied from shell-resync-dirs.
809 (defun shell-snarf-envar (var)
810 "Return as a string the shell's value of environment variable VAR."
811 (let* ((cmd (format "printenv '%s'\n" var
))
812 (proc (get-buffer-process (current-buffer)))
813 (pmark (process-mark proc
)))
816 (sit-for 0) ; force redisplay
817 (comint-send-string proc cmd
)
818 (set-marker pmark
(point))
819 (let ((pt (point))) ; wait for 1 line
820 ;; This extra newline prevents the user's pending input from spoofing us.
821 (insert "\n") (backward-char 1)
822 (while (not (looking-at ".+\n"))
823 (accept-process-output proc
)
825 (goto-char pmark
) (delete-char 1) ; remove the extra newline
826 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
828 (defun shell-copy-environment-variable (variable)
829 "Copy the environment variable VARIABLE from the subshell to Emacs.
830 This command reads the value of the specified environment variable
831 in the shell, and sets the same environment variable in Emacs
832 \(what `getenv' in Emacs would return) to that value.
833 That value will affect any new subprocesses that you subsequently start
835 (interactive (list (read-envvar-name "\
836 Copy Shell environment variable to Emacs: ")))
837 (setenv variable
(shell-snarf-envar variable
)))
839 (defun shell-forward-command (&optional arg
)
840 "Move forward across ARG shell command(s). Does not cross lines.
841 See `shell-command-regexp'."
843 (let ((limit (save-excursion (end-of-line nil
) (point))))
844 (if (re-search-forward (concat shell-command-regexp
"\\([;&|][\t ]*\\)+")
846 (skip-syntax-backward " "))))
849 (defun shell-backward-command (&optional arg
)
850 "Move backward across ARG shell command(s). Does not cross lines.
851 See `shell-command-regexp'."
853 (let ((limit (save-excursion (comint-bol nil
) (point))))
854 (when (> limit
(point))
855 (setq limit
(line-beginning-position)))
856 (skip-syntax-backward " " limit
)
857 (if (re-search-backward
858 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp
) limit
'move arg
)
859 (progn (goto-char (match-beginning 1))
860 (skip-chars-forward ";&|")))))
862 (defun shell-dynamic-complete-command ()
863 "Dynamically complete the command at point.
864 This function is similar to `comint-dynamic-complete-filename', except that it
865 searches `exec-path' (minus the trailing emacs library path) for completion
866 candidates. Note that this may not be the same as the shell's idea of the
869 Completion is dependent on the value of `shell-completion-execonly', plus
870 those that effect file completion. See `shell-dynamic-complete-as-command'.
872 Returns t if successful."
874 (let ((filename (comint-match-partial-filename)))
876 (save-match-data (not (string-match "[~/]" filename
)))
877 (eq (match-beginning 0)
878 (save-excursion (shell-backward-command 1) (point))))
879 (prog2 (message "Completing command name...")
880 (shell-dynamic-complete-as-command)))))
883 (defun shell-dynamic-complete-as-command ()
884 "Dynamically complete at point as a command.
885 See `shell-dynamic-complete-filename'. Returns t if successful."
886 (let* ((filename (or (comint-match-partial-filename) ""))
887 (pathnondir (file-name-nondirectory filename
))
888 (paths (cdr (reverse exec-path
)))
889 (cwd (file-name-as-directory (expand-file-name default-directory
)))
891 (and comint-completion-fignore
892 (mapconcat (function (lambda (x) (concat (regexp-quote x
) "$")))
893 comint-completion-fignore
"\\|")))
894 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
895 ;; Go thru each path in the search path, finding completions.
897 (setq path
(file-name-as-directory (comint-directory (or (car paths
) ".")))
898 comps-in-path
(and (file-accessible-directory-p path
)
899 (file-name-all-completions pathnondir path
)))
900 ;; Go thru each completion found, to see whether it should be used.
902 (setq file
(car comps-in-path
)
903 filepath
(concat path file
))
904 (if (and (not (member file completions
))
905 (not (and ignored-extensions
906 (string-match ignored-extensions file
)))
907 (or (string-equal path cwd
)
908 (not (file-directory-p filepath
)))
909 (or (null shell-completion-execonly
)
910 (file-executable-p filepath
)))
911 (setq completions
(cons file completions
)))
912 (setq comps-in-path
(cdr comps-in-path
)))
913 (setq paths
(cdr paths
)))
914 ;; OK, we've got a list of completions.
915 (let ((success (let ((comint-completion-addsuffix nil
))
916 (comint-dynamic-simple-complete pathnondir completions
))))
917 (if (and (memq success
'(sole shortest
)) comint-completion-addsuffix
918 (not (file-directory-p (comint-match-partial-filename))))
923 (defun shell-match-partial-variable ()
924 "Return the shell variable at point, or nil if none is found."
926 (let ((limit (point)))
927 (if (re-search-backward "[^A-Za-z0-9_{}]" nil
'move
)
928 (or (looking-at "\\$") (forward-char 1)))
929 ;; Anchor the search forwards.
930 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
932 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit
)
933 (buffer-substring (match-beginning 0) (match-end 0))))))
936 (defun shell-dynamic-complete-environment-variable ()
937 "Dynamically complete the environment variable at point.
938 Completes if after a variable, i.e., if it starts with a \"$\".
939 See `shell-dynamic-complete-as-environment-variable'.
941 This function is similar to `comint-dynamic-complete-filename', except that it
942 searches `process-environment' for completion candidates. Note that this may
943 not be the same as the interpreter's idea of variable names. The main problem
944 with this type of completion is that `process-environment' is the environment
945 which Emacs started with. Emacs does not track changes to the environment made
946 by the interpreter. Perhaps it would be more accurate if this function was
947 called `shell-dynamic-complete-process-environment-variable'.
949 Returns non-nil if successful."
951 (let ((variable (shell-match-partial-variable)))
952 (if (and variable
(string-match "^\\$" variable
))
953 (prog2 (message "Completing variable name...")
954 (shell-dynamic-complete-as-environment-variable)))))
957 (defun shell-dynamic-complete-as-environment-variable ()
958 "Dynamically complete at point as an environment variable.
959 Used by `shell-dynamic-complete-environment-variable'.
960 Uses `comint-dynamic-simple-complete'."
961 (let* ((var (or (shell-match-partial-variable) ""))
962 (variable (substring var
(or (string-match "[^$({]\\|$" var
) 0)))
963 (variables (mapcar (function (lambda (x)
964 (substring x
0 (string-match "=" x
))))
965 process-environment
))
966 (addsuffix comint-completion-addsuffix
)
967 (comint-completion-addsuffix nil
)
968 (success (comint-dynamic-simple-complete variable variables
)))
969 (if (memq success
'(sole shortest
))
970 (let* ((var (shell-match-partial-variable))
971 (variable (substring var
(string-match "[^$({]" var
)))
972 (protection (cond ((string-match "{" var
) "}")
973 ((string-match "(" var
) ")")
975 (suffix (cond ((null addsuffix
) "")
977 (comint-directory (getenv variable
))) "/")
979 (insert protection suffix
)))
983 (defun shell-replace-by-expanded-directory ()
984 "Expand directory stack reference before point.
985 Directory stack references are of the form \"=digit\" or \"=-\".
986 See `default-directory' and `shell-dirstack'.
988 Returns t if successful."
990 (if (comint-match-partial-filename)
992 (goto-char (match-beginning 0))
993 (let ((stack (cons default-directory shell-dirstack
))
994 (index (cond ((looking-at "=-/?")
995 (length shell-dirstack
))
996 ((looking-at "=\\([0-9]+\\)")
999 (match-beginning 1) (match-end 1)))))))
1002 ((>= index
(length stack
))
1003 (error "Directory stack not that deep"))
1005 (replace-match (file-name-as-directory (nth index stack
)) t t
)
1006 (message "Directory item: %d" index
)
1011 ;;; shell.el ends here