Show a patch for Mule-UCS to make it byte-compiled
[emacs.git] / lisp / shell.el
blob0f71d8d820558e1de65fba8b50a605de5a25afc2
1 ;;; shell.el --- specialized comint.el for running the shell
3 ;; Copyright (C) 1988, 1993, 1994, 1995, 1996, 1997, 2000,
4 ;; 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
6 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
7 ;; Simon Marshall <simon@gnu.org>
8 ;; Maintainer: FSF
9 ;; Keywords: processes
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
28 ;;; Commentary:
30 ;; Please send me bug reports, bug fixes, and extensions, so that I can
31 ;; merge them into the master source.
32 ;; - Olin Shivers (shivers@cs.cmu.edu)
33 ;; - Simon Marshall (simon@gnu.org)
35 ;; This file defines a shell-in-a-buffer package (shell mode) built on
36 ;; top of comint mode. This is actually cmushell with things renamed
37 ;; to replace its counterpart in Emacs 18. cmushell is more
38 ;; featureful, robust, and uniform than the Emacs 18 version.
40 ;; Since this mode is built on top of the general command-interpreter-in-
41 ;; a-buffer mode (comint mode), it shares a common base functionality,
42 ;; and a common set of bindings, with all modes derived from comint mode.
43 ;; This makes these modes easier to use.
45 ;; For documentation on the functionality provided by comint mode, and
46 ;; the hooks available for customising it, see the file comint.el.
47 ;; For further information on shell mode, see the comments below.
49 ;; Needs fixin:
50 ;; When sending text from a source file to a subprocess, the process-mark can
51 ;; move off the window, so you can lose sight of the process interactions.
52 ;; Maybe I should ensure the process mark is in the window when I send
53 ;; text to the process? Switch selectable?
55 ;; YOUR .EMACS FILE
56 ;;=============================================================================
57 ;; Some suggestions for your .emacs file.
59 ;; ;; Define M-# to run some strange command:
60 ;; (eval-after-load "shell"
61 ;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
63 ;; Brief Command Documentation:
64 ;;============================================================================
65 ;; Comint Mode Commands: (common to shell and all comint-derived modes)
67 ;; m-p comint-previous-input Cycle backwards in input history
68 ;; m-n comint-next-input Cycle forwards
69 ;; m-r comint-previous-matching-input Previous input matching a regexp
70 ;; m-s comint-next-matching-input Next input that matches
71 ;; m-c-l comint-show-output Show last batch of process output
72 ;; return comint-send-input
73 ;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
74 ;; c-c c-a comint-bol Beginning of line; skip prompt
75 ;; c-c c-u comint-kill-input ^u
76 ;; c-c c-w backward-kill-word ^w
77 ;; c-c c-c comint-interrupt-subjob ^c
78 ;; c-c c-z comint-stop-subjob ^z
79 ;; c-c c-\ comint-quit-subjob ^\
80 ;; c-c c-o comint-kill-output Delete last batch of process output
81 ;; c-c c-r comint-show-output Show last batch of process output
82 ;; c-c c-l comint-dynamic-list-input-ring List input history
83 ;; send-invisible Read line w/o echo & send to proc
84 ;; comint-continue-subjob Useful if you accidentally suspend
85 ;; top-level job
86 ;; comint-mode-hook is the comint mode hook.
88 ;; Shell Mode Commands:
89 ;; shell Fires up the shell process
90 ;; tab comint-dynamic-complete Complete filename/command/history
91 ;; m-? comint-dynamic-list-filename-completions
92 ;; List completions in help buffer
93 ;; m-c-f shell-forward-command Forward a shell command
94 ;; m-c-b shell-backward-command Backward a shell command
95 ;; dirs Resync the buffer's dir stack
96 ;; dirtrack-mode Turn dir tracking on/off
97 ;; comint-strip-ctrl-m Remove trailing ^Ms from output
99 ;; The shell mode hook is shell-mode-hook
100 ;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
101 ;; compatibility.
103 ;; Read the rest of this file for more information.
105 ;;; Code:
107 (require 'comint)
109 ;;; Customization and Buffer Variables
111 (defgroup shell nil
112 "Running shell from within Emacs buffers."
113 :group 'processes
114 :group 'unix)
116 (defgroup shell-directories nil
117 "Directory support in shell mode."
118 :group 'shell)
120 (defgroup shell-faces nil
121 "Faces in shell buffers."
122 :group 'shell)
124 ;;;###autoload
125 (defcustom shell-dumb-shell-regexp "cmd\\(proxy\\)?\\.exe"
126 "Regexp to match shells that don't save their command history, and
127 don't handle the backslash as a quote character. For shells that
128 match this regexp, Emacs will write out the command history when the
129 shell finishes, and won't remove backslashes when it unquotes shell
130 arguments."
131 :type 'regexp
132 :group 'shell)
134 (defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
135 "Regexp to match prompts in the inferior shell.
136 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
137 This variable is used to initialize `comint-prompt-regexp' in the
138 shell buffer.
140 If `comint-use-prompt-regexp' is nil, then this variable is only used
141 to determine paragraph boundaries. See Info node `Shell Prompts' for
142 how Shell mode treats paragraphs.
144 The pattern should probably not match more than one line. If it does,
145 Shell mode may become confused trying to distinguish prompt from input
146 on lines which don't start with a prompt.
148 This is a fine thing to set in your `.emacs' file."
149 :type 'regexp
150 :group 'shell)
152 (defcustom shell-completion-fignore nil
153 "*List of suffixes to be disregarded during file/command completion.
154 This variable is used to initialize `comint-completion-fignore' in the shell
155 buffer. The default is nil, for compatibility with most shells.
156 Some people like (\"~\" \"#\" \"%\").
158 This is a fine thing to set in your `.emacs' file."
159 :type '(repeat (string :tag "Suffix"))
160 :group 'shell)
162 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
163 "List of characters to recognize as separate arguments.
164 This variable is used to initialize `comint-delimiter-argument-list' in the
165 shell buffer. The value may depend on the operating system or shell.
167 This is a fine thing to set in your `.emacs' file.")
169 (defvar shell-file-name-chars
170 (if (memq system-type '(ms-dos windows-nt cygwin))
171 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
172 "[]~/A-Za-z0-9+@:_.$#%,={}-")
173 "String of characters valid in a file name.
174 This variable is used to initialize `comint-file-name-chars' in the
175 shell buffer. The value may depend on the operating system or shell.
177 This is a fine thing to set in your `.emacs' file.")
179 (defvar shell-file-name-quote-list
180 (if (memq system-type '(ms-dos windows-nt))
182 (append shell-delimiter-argument-list '(?\s ?\* ?\! ?\" ?\' ?\` ?\# ?\\)))
183 "List of characters to quote when in a file name.
184 This variable is used to initialize `comint-file-name-quote-list' in the
185 shell buffer. The value may depend on the operating system or shell.
187 This is a fine thing to set in your `.emacs' file.")
189 (defvar shell-dynamic-complete-functions
190 '(comint-replace-by-expanded-history
191 shell-dynamic-complete-environment-variable
192 shell-dynamic-complete-command
193 shell-replace-by-expanded-directory
194 comint-dynamic-complete-filename)
195 "List of functions called to perform completion.
196 This variable is used to initialize `comint-dynamic-complete-functions' in the
197 shell buffer.
199 This is a fine thing to set in your `.emacs' file.")
201 (defcustom shell-command-regexp "[^;&|\n]+"
202 "*Regexp to match a single command within a pipeline.
203 This is used for directory tracking and does not do a perfect job."
204 :type 'regexp
205 :group 'shell)
207 (defcustom shell-command-separator-regexp "[;&|\n \t]*"
208 "*Regexp to match a single command within a pipeline.
209 This is used for directory tracking and does not do a perfect job."
210 :type 'regexp
211 :group 'shell)
213 (defcustom shell-completion-execonly t
214 "*If non-nil, use executable files only for completion candidates.
215 This mirrors the optional behavior of tcsh.
217 Detecting executability of files may slow command completion considerably."
218 :type 'boolean
219 :group 'shell)
221 (defcustom shell-popd-regexp "popd"
222 "*Regexp to match subshell commands equivalent to popd."
223 :type 'regexp
224 :group 'shell-directories)
226 (defcustom shell-pushd-regexp "pushd"
227 "*Regexp to match subshell commands equivalent to pushd."
228 :type 'regexp
229 :group 'shell-directories)
231 (defcustom shell-pushd-tohome nil
232 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
233 This mirrors the optional behavior of tcsh."
234 :type 'boolean
235 :group 'shell-directories)
237 (defcustom shell-pushd-dextract nil
238 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
239 This mirrors the optional behavior of tcsh."
240 :type 'boolean
241 :group 'shell-directories)
243 (defcustom shell-pushd-dunique nil
244 "*If non-nil, make pushd only add unique directories to the stack.
245 This mirrors the optional behavior of tcsh."
246 :type 'boolean
247 :group 'shell-directories)
249 (defcustom shell-cd-regexp "cd"
250 "*Regexp to match subshell commands equivalent to cd."
251 :type 'regexp
252 :group 'shell-directories)
254 (defcustom shell-chdrive-regexp
255 (if (memq system-type '(ms-dos windows-nt))
256 ; NetWare allows the five chars between upper and lower alphabetics.
257 "[]a-zA-Z^_`\\[\\\\]:"
258 nil)
259 "*If non-nil, is regexp used to track drive changes."
260 :type '(choice regexp
261 (const nil))
262 :group 'shell-directories)
264 (defcustom shell-dirtrack-verbose t
265 "*If non-nil, show the directory stack following directory change.
266 This is effective only if directory tracking is enabled."
267 :type 'boolean
268 :group 'shell-directories)
270 (defcustom explicit-shell-file-name nil
271 "*If non-nil, is file name to use for explicitly requested inferior shell."
272 :type '(choice (const :tag "None" nil) file)
273 :group 'shell)
275 (defcustom explicit-csh-args
276 (if (eq system-type 'hpux)
277 ;; -T persuades HP's csh not to think it is smarter
278 ;; than us about what terminal modes to use.
279 '("-i" "-T")
280 '("-i"))
281 "*Args passed to inferior shell by M-x shell, if the shell is csh.
282 Value is a list of strings, which may be nil."
283 :type '(repeat (string :tag "Argument"))
284 :group 'shell)
286 (defcustom explicit-bash-args
287 ;; Tell bash not to use readline, except for bash 1.x which doesn't grook --noediting.
288 ;; Bash 1.x has -nolineediting, but process-send-eof cannot terminate bash if we use it.
289 (let* ((prog (or (and (boundp 'explicit-shell-file-name) explicit-shell-file-name)
290 (getenv "ESHELL") shell-file-name))
291 (name (file-name-nondirectory prog)))
292 (if (and (not purify-flag)
293 (equal name "bash")
294 (file-executable-p prog)
295 (string-match "bad option"
296 (shell-command-to-string (concat prog " --noediting"))))
297 '("-i")
298 '("--noediting" "-i")))
299 "*Args passed to inferior shell by M-x shell, if the shell is bash.
300 Value is a list of strings, which may be nil."
301 :type '(repeat (string :tag "Argument"))
302 :group 'shell)
304 (defcustom shell-input-autoexpand 'history
305 "*If non-nil, expand input command history references on completion.
306 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
308 If the value is `input', then the expansion is seen on input.
309 If the value is `history', then the expansion is only when inserting
310 into the buffer's input ring. See also `comint-magic-space' and
311 `comint-dynamic-complete'.
313 This variable supplies a default for `comint-input-autoexpand',
314 for Shell mode only."
315 :type '(choice (const :tag "off" nil)
316 (const input)
317 (const history)
318 (const :tag "on" t))
319 :group 'shell)
321 (defvar shell-dirstack nil
322 "List of directories saved by pushd in this buffer's shell.
323 Thus, this does not include the shell's current directory.")
325 (defvar shell-dirtrackp t
326 "Non-nil in a shell buffer means directory tracking is enabled.")
328 (defvar shell-last-dir nil
329 "Keep track of last directory for ksh `cd -' command.")
331 (defvar shell-dirstack-query nil
332 "Command used by `shell-resync-dir' to query the shell.")
334 (defvar shell-mode-map nil)
335 (cond ((not shell-mode-map)
336 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
337 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
338 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
339 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
340 (define-key shell-mode-map "\M-?"
341 'comint-dynamic-list-filename-completions)
342 (define-key shell-mode-map [menu-bar completion]
343 (cons "Complete"
344 (copy-keymap (lookup-key comint-mode-map [menu-bar completion]))))
345 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
346 [complete-env-variable] '("Complete Env. Variable Name" .
347 shell-dynamic-complete-environment-variable)
348 'complete-file)
349 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
350 [expand-directory] '("Expand Directory Reference" .
351 shell-replace-by-expanded-directory)
352 'complete-expand)))
354 (defcustom shell-mode-hook '()
355 "*Hook for customising Shell mode."
356 :type 'hook
357 :group 'shell)
359 (defvar shell-font-lock-keywords
360 '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
361 ("^[^ \t\n]+:.*" . font-lock-string-face)
362 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
363 "Additional expressions to highlight in Shell mode.")
365 ;;; Basic Procedures
367 (put 'shell-mode 'mode-class 'special)
369 (define-derived-mode shell-mode comint-mode "Shell"
370 "Major mode for interacting with an inferior shell.
371 \\[comint-send-input] after the end of the process' output sends the text from
372 the end of process to the end of the current line.
373 \\[comint-send-input] before end of process output copies the current line minus the prompt to
374 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
375 \\[send-invisible] reads a line of text without echoing it, and sends it to
376 the shell. This is useful for entering passwords. Or, add the function
377 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
379 If you want to make multiple shell buffers, rename the `*shell*' buffer
380 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
382 If you want to make shell buffers limited in length, add the function
383 `comint-truncate-buffer' to `comint-output-filter-functions'.
385 If you accidentally suspend your process, use \\[comint-continue-subjob]
386 to continue it.
388 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
389 keep this buffer's default directory the same as the shell's working directory.
390 While directory tracking is enabled, the shell's working directory is displayed
391 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
392 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
393 directory stack is.
394 \\[dirtrack-mode] turns directory tracking on and off.
396 \\{shell-mode-map}
397 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
398 `shell-mode-hook' (in that order). Before each input, the hooks on
399 `comint-input-filter-functions' are run. After each shell output, the hooks
400 on `comint-output-filter-functions' are run.
402 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
403 and `shell-popd-regexp' are used to match their respective commands,
404 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
405 control the behavior of the relevant command.
407 Variables `comint-completion-autolist', `comint-completion-addsuffix',
408 `comint-completion-recexact' and `comint-completion-fignore' control the
409 behavior of file name, command name and variable name completion. Variable
410 `shell-completion-execonly' controls the behavior of command name completion.
411 Variable `shell-completion-fignore' is used to initialize the value of
412 `comint-completion-fignore'.
414 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
415 the initialization of the input ring history, and history expansion.
417 Variables `comint-output-filter-functions', a hook, and
418 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
419 control whether input and output cause the window to scroll to the end of the
420 buffer."
421 (setq comint-prompt-regexp shell-prompt-pattern)
422 (setq comint-completion-fignore shell-completion-fignore)
423 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
424 (setq comint-file-name-chars shell-file-name-chars)
425 (setq comint-file-name-quote-list shell-file-name-quote-list)
426 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
427 (set (make-local-variable 'paragraph-separate) "\\'")
428 (make-local-variable 'paragraph-start)
429 (setq paragraph-start comint-prompt-regexp)
430 (make-local-variable 'font-lock-defaults)
431 (setq font-lock-defaults '(shell-font-lock-keywords t))
432 (make-local-variable 'shell-dirstack)
433 (setq shell-dirstack nil)
434 (make-local-variable 'shell-last-dir)
435 (setq shell-last-dir nil)
436 (make-local-variable 'shell-dirtrackp)
437 (setq shell-dirtrackp t)
438 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
439 (setq comint-input-autoexpand shell-input-autoexpand)
440 ;; This is not really correct, since the shell buffer does not really
441 ;; edit this directory. But it is useful in the buffer list and menus.
442 (make-local-variable 'list-buffers-directory)
443 (setq list-buffers-directory (expand-file-name default-directory))
444 ;; shell-dependent assignments.
445 (when (ring-empty-p comint-input-ring)
446 (let ((shell (file-name-nondirectory (car
447 (process-command (get-buffer-process (current-buffer)))))))
448 (setq comint-input-ring-file-name
449 (or (getenv "HISTFILE")
450 (cond ((string-equal shell "bash") "~/.bash_history")
451 ((string-equal shell "ksh") "~/.sh_history")
452 (t "~/.history"))))
453 (if (or (equal comint-input-ring-file-name "")
454 (equal (file-truename comint-input-ring-file-name)
455 (file-truename "/dev/null")))
456 (setq comint-input-ring-file-name nil))
457 ;; Arrange to write out the input ring on exit, if the shell doesn't
458 ;; do this itself.
459 (if (and comint-input-ring-file-name
460 (string-match shell-dumb-shell-regexp shell))
461 (set-process-sentinel (get-buffer-process (current-buffer))
462 #'shell-write-history-on-exit))
463 (setq shell-dirstack-query
464 (cond ((string-equal shell "sh") "pwd")
465 ((string-equal shell "ksh") "echo $PWD ~-")
466 (t "dirs")))
467 ;; Bypass a bug in certain versions of bash.
468 (when (string-equal shell "bash")
469 (add-hook 'comint-output-filter-functions
470 'shell-filter-ctrl-a-ctrl-b nil t)))
471 (comint-read-input-ring t)))
473 (defun shell-filter-ctrl-a-ctrl-b (string)
474 "Remove `^A' and `^B' characters from comint output.
476 Bash uses these characters as internal quoting characters in its
477 prompt. Due to a bug in some bash versions (including 2.03,
478 2.04, and 2.05b), they may erroneously show up when bash is
479 started with the `--noediting' option and Select Graphic
480 Rendition (SGR) control sequences (formerly known as ANSI escape
481 sequences) are used to color the prompt.
483 This function can be put on `comint-output-filter-functions'.
484 The argument STRING is ignored."
485 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
486 (save-excursion
487 (goto-char (or comint-last-output-start (point-min)))
488 (while (re-search-forward "[\C-a\C-b]" pmark t)
489 (replace-match "")))))
491 (defun shell-write-history-on-exit (process event)
492 "Called when the shell process is stopped.
494 Writes the input history to a history file
495 `comint-input-ring-file-name' using `comint-write-input-ring'
496 and inserts a short message in the shell buffer.
498 This function is a sentinel watching the shell interpreter process.
499 Sentinels will always get the two parameters PROCESS and EVENT."
500 ;; Write history.
501 (comint-write-input-ring)
502 (let ((buf (process-buffer process)))
503 (when (buffer-live-p buf)
504 (with-current-buffer buf
505 (insert (format "\nProcess %s %s\n" process event))))))
507 ;;;###autoload
508 (defun shell (&optional buffer)
509 "Run an inferior shell, with I/O through BUFFER (which defaults to `*shell*').
510 Interactively, a prefix arg means to prompt for BUFFER.
511 If BUFFER exists but shell process is not running, make new shell.
512 If BUFFER exists and shell process is running, just switch to BUFFER.
513 Program used comes from variable `explicit-shell-file-name',
514 or (if that is nil) from the ESHELL environment variable,
515 or else from SHELL if there is no ESHELL.
516 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
517 (Note that this may lose due to a timing error if the shell
518 discards input when it starts up.)
519 The buffer is put in Shell mode, giving commands for sending input
520 and controlling the subjobs of the shell. See `shell-mode'.
521 See also the variable `shell-prompt-pattern'.
523 To specify a coding system for converting non-ASCII characters
524 in the input and output to the shell, use \\[universal-coding-system-argument]
525 before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
526 in the shell buffer, after you start the shell.
527 The default comes from `process-coding-system-alist' and
528 `default-process-coding-system'.
530 The shell file name (sans directories) is used to make a symbol name
531 such as `explicit-csh-args'. If that symbol is a variable,
532 its value is used as a list of arguments when invoking the shell.
533 Otherwise, one argument `-i' is passed to the shell.
535 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
536 (interactive
537 (list
538 (and current-prefix-arg
539 (read-buffer "Shell buffer: "
540 (generate-new-buffer-name "*shell*")))))
541 (setq buffer (get-buffer-create (or buffer "*shell*")))
542 ;; Pop to buffer, so that the buffer's window will be correctly set
543 ;; when we call comint (so that comint sets the COLUMNS env var properly).
544 (pop-to-buffer buffer)
545 (unless (comint-check-proc buffer)
546 (let* ((prog (or explicit-shell-file-name
547 (getenv "ESHELL") shell-file-name))
548 (name (file-name-nondirectory prog))
549 (startfile (concat "~/.emacs_" name))
550 (xargs-name (intern-soft (concat "explicit-" name "-args"))))
551 (if (not (file-exists-p startfile))
552 (setq startfile (concat "~/.emacs.d/.emacs_" name)))
553 (apply 'make-comint-in-buffer "shell" buffer prog
554 (if (file-exists-p startfile) startfile)
555 (if (and xargs-name (boundp xargs-name))
556 (symbol-value xargs-name)
557 '("-i")))
558 (shell-mode)))
559 buffer)
561 ;;; Don't do this when shell.el is loaded, only while dumping.
562 ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
564 ;;; Directory tracking
566 ;;; This code provides the shell mode input sentinel
567 ;;; SHELL-DIRECTORY-TRACKER
568 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
569 ;;; changes the current directory of the shell buffer accordingly.
571 ;;; This is basically a fragile hack, although it's more accurate than
572 ;;; the version in Emacs 18's shell.el. It has the following failings:
573 ;;; 1. It doesn't know about the cdpath shell variable.
574 ;;; 2. It cannot infallibly deal with command sequences, though it does well
575 ;;; with these and with ignoring commands forked in another shell with ()s.
576 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
577 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
578 ;;; that, there's no way to catch shell commands where cd's are buried
579 ;;; inside conditional expressions, aliases, and so forth.
581 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
582 ;;; messes it up. You run other processes under the shell; these each have
583 ;;; separate working directories, and some have commands for manipulating
584 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
585 ;;; commands that do *not* affect the current w.d. at all, but look like they
586 ;;; do (e.g., the cd command in ftp). In shells that allow you job
587 ;;; control, you can switch between jobs, all having different w.d.'s. So
588 ;;; simply saying %3 can shift your w.d..
590 ;;; The solution is to relax, not stress out about it, and settle for
591 ;;; a hack that works pretty well in typical circumstances. Remember
592 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
593 ;;; anyway. Blech.
595 ;;; One good hack not implemented here for users of programmable shells
596 ;;; is to program up the shell w.d. manipulation commands to output
597 ;;; a coded command sequence to the tty. Something like
598 ;;; ESC | <cwd> |
599 ;;; where <cwd> is the new current working directory. Then trash the
600 ;;; directory tracking machinery currently used in this package, and
601 ;;; replace it with a process filter that watches for and strips out
602 ;;; these messages.
604 (defun shell-directory-tracker (str)
605 "Tracks cd, pushd and popd commands issued to the shell.
606 This function is called on each input passed to the shell.
607 It watches for cd, pushd and popd commands and sets the buffer's
608 default directory to track these commands.
610 You may toggle this tracking on and off with M-x dirtrack-mode.
611 If emacs gets confused, you can resync with the shell with M-x dirs.
613 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
614 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
615 and `shell-pushd-dunique' control the behavior of the relevant command.
617 Environment variables are expanded, see function `substitute-in-file-name'."
618 (if shell-dirtrackp
619 ;; We fail gracefully if we think the command will fail in the shell.
620 (condition-case chdir-failure
621 (let ((start (progn (string-match
622 (concat "^" shell-command-separator-regexp)
623 str) ; skip whitespace
624 (match-end 0)))
625 end cmd arg1)
626 (while (string-match shell-command-regexp str start)
627 (setq end (match-end 0)
628 cmd (comint-arguments (substring str start end) 0 0)
629 arg1 (comint-arguments (substring str start end) 1 1))
630 (if arg1
631 (setq arg1 (shell-unquote-argument arg1)))
632 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
633 "\\)\\($\\|[ \t]\\)")
634 cmd)
635 (shell-process-popd (comint-substitute-in-file-name arg1)))
636 ((string-match (concat "\\`\\(" shell-pushd-regexp
637 "\\)\\($\\|[ \t]\\)")
638 cmd)
639 (shell-process-pushd (comint-substitute-in-file-name arg1)))
640 ((string-match (concat "\\`\\(" shell-cd-regexp
641 "\\)\\($\\|[ \t]\\)")
642 cmd)
643 (shell-process-cd (comint-substitute-in-file-name arg1)))
644 ((and shell-chdrive-regexp
645 (string-match (concat "\\`\\(" shell-chdrive-regexp
646 "\\)\\($\\|[ \t]\\)")
647 cmd))
648 (shell-process-cd (comint-substitute-in-file-name cmd))))
649 (setq start (progn (string-match shell-command-separator-regexp
650 str end)
651 ;; skip again
652 (match-end 0)))))
653 (error "Couldn't cd"))))
655 (defun shell-unquote-argument (string)
656 "Remove all kinds of shell quoting from STRING."
657 (save-match-data
658 (let ((idx 0) next inside
659 (quote-chars
660 (if (string-match shell-dumb-shell-regexp
661 (file-name-nondirectory
662 (car (process-command (get-buffer-process (current-buffer))))))
663 "['`\"]"
664 "[\\'`\"]")))
665 (while (and (< idx (length string))
666 (setq next (string-match quote-chars string next)))
667 (cond ((= (aref string next) ?\\)
668 (setq string (replace-match "" nil nil string))
669 (setq next (1+ next)))
670 ((and inside (= (aref string next) inside))
671 (setq string (replace-match "" nil nil string))
672 (setq inside nil))
673 (inside
674 (setq next (1+ next)))
676 (setq inside (aref string next))
677 (setq string (replace-match "" nil nil string)))))
678 string)))
680 ;;; popd [+n]
681 (defun shell-process-popd (arg)
682 (let ((num (or (shell-extract-num arg) 0)))
683 (cond ((and num (= num 0) shell-dirstack)
684 (shell-cd (car shell-dirstack))
685 (setq shell-dirstack (cdr shell-dirstack))
686 (shell-dirstack-message))
687 ((and num (> num 0) (<= num (length shell-dirstack)))
688 (let* ((ds (cons nil shell-dirstack))
689 (cell (nthcdr (1- num) ds)))
690 (rplacd cell (cdr (cdr cell)))
691 (setq shell-dirstack (cdr ds))
692 (shell-dirstack-message)))
694 (error "Couldn't popd")))))
696 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
697 (defun shell-prefixed-directory-name (dir)
698 (if (= (length comint-file-name-prefix) 0)
700 (if (file-name-absolute-p dir)
701 ;; The name is absolute, so prepend the prefix.
702 (concat comint-file-name-prefix dir)
703 ;; For relative name we assume default-directory already has the prefix.
704 (expand-file-name dir))))
706 ;;; cd [dir]
707 (defun shell-process-cd (arg)
708 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
709 "~"))
710 ((string-equal "-" arg) shell-last-dir)
711 (t (shell-prefixed-directory-name arg)))))
712 (setq shell-last-dir default-directory)
713 (shell-cd new-dir)
714 (shell-dirstack-message)))
716 ;;; pushd [+n | dir]
717 (defun shell-process-pushd (arg)
718 (let ((num (shell-extract-num arg)))
719 (cond ((zerop (length arg))
720 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
721 (cond (shell-pushd-tohome
722 (shell-process-pushd (concat comint-file-name-prefix "~")))
723 (shell-dirstack
724 (let ((old default-directory))
725 (shell-cd (car shell-dirstack))
726 (setq shell-dirstack (cons old (cdr shell-dirstack)))
727 (shell-dirstack-message)))
729 (message "Directory stack empty."))))
730 ((numberp num)
731 ;; pushd +n
732 (cond ((> num (length shell-dirstack))
733 (message "Directory stack not that deep."))
734 ((= num 0)
735 (error (message "Couldn't cd")))
736 (shell-pushd-dextract
737 (let ((dir (nth (1- num) shell-dirstack)))
738 (shell-process-popd arg)
739 (shell-process-pushd default-directory)
740 (shell-cd dir)
741 (shell-dirstack-message)))
743 (let* ((ds (cons default-directory shell-dirstack))
744 (dslen (length ds))
745 (front (nthcdr num ds))
746 (back (reverse (nthcdr (- dslen num) (reverse ds))))
747 (new-ds (append front back)))
748 (shell-cd (car new-ds))
749 (setq shell-dirstack (cdr new-ds))
750 (shell-dirstack-message)))))
752 ;; pushd <dir>
753 (let ((old-wd default-directory))
754 (shell-cd (shell-prefixed-directory-name arg))
755 (if (or (null shell-pushd-dunique)
756 (not (member old-wd shell-dirstack)))
757 (setq shell-dirstack (cons old-wd shell-dirstack)))
758 (shell-dirstack-message))))))
760 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
761 (defun shell-extract-num (str)
762 (and (string-match "^\\+[1-9][0-9]*$" str)
763 (string-to-number str)))
766 (defun shell-dirtrack-mode ()
767 "Turn directory tracking on and off in a shell buffer."
768 (interactive)
769 (if (setq shell-dirtrackp (not shell-dirtrackp))
770 (setq list-buffers-directory default-directory)
771 (setq list-buffers-directory nil))
772 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
774 ;;; For your typing convenience:
775 (defalias 'shell-dirtrack-toggle 'shell-dirtrack-mode)
776 (defalias 'dirtrack-toggle 'shell-dirtrack-mode)
777 (defalias 'dirtrack-mode 'shell-dirtrack-mode)
779 (defun shell-cd (dir)
780 "Do normal `cd' to DIR, and set `list-buffers-directory'."
781 (if shell-dirtrackp
782 (setq list-buffers-directory (file-name-as-directory
783 (expand-file-name dir))))
784 (cd dir))
786 (defun shell-resync-dirs ()
787 "Resync the buffer's idea of the current directory stack.
788 This command queries the shell with the command bound to
789 `shell-dirstack-query' (default \"dirs\"), reads the next
790 line output and parses it to form the new directory stack.
791 DON'T issue this command unless the buffer is at a shell prompt.
792 Also, note that if some other subprocess decides to do output
793 immediately after the query, its output will be taken as the
794 new directory stack -- you lose. If this happens, just do the
795 command again."
796 (interactive)
797 (let* ((proc (get-buffer-process (current-buffer)))
798 (pmark (process-mark proc)))
799 (goto-char pmark)
800 (insert shell-dirstack-query) (insert "\n")
801 (sit-for 0) ; force redisplay
802 (comint-send-string proc shell-dirstack-query)
803 (comint-send-string proc "\n")
804 (set-marker pmark (point))
805 (let ((pt (point))) ; wait for 1 line
806 ;; This extra newline prevents the user's pending input from spoofing us.
807 (insert "\n") (backward-char 1)
808 (while (not (looking-at
809 (concat "\\(" ; skip literal echo in case of stty echo
810 (regexp-quote shell-dirstack-query)
811 "\n\\)?" ; skip if present
812 "\\(" ".+\n" "\\)")) ) ; what to actually look for
813 (accept-process-output proc)
814 (goto-char pt)))
815 (goto-char pmark) (delete-char 1) ; remove the extra newline
816 ;; That's the dirlist. grab it & parse it.
817 (let* ((dl (buffer-substring (match-beginning 2) (1- (match-end 2))))
818 (dl-len (length dl))
819 (ds '()) ; new dir stack
820 (i 0))
821 (while (< i dl-len)
822 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
823 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
824 (setq ds (cons (concat comint-file-name-prefix
825 (substring dl (match-beginning 1)
826 (match-end 1)))
827 ds))
828 (setq i (match-end 0)))
829 (let ((ds (nreverse ds)))
830 (condition-case nil
831 (progn (shell-cd (car ds))
832 (setq shell-dirstack (cdr ds)
833 shell-last-dir (car shell-dirstack))
834 (shell-dirstack-message))
835 (error (message "Couldn't cd")))))))
837 ;;; For your typing convenience:
838 (defalias 'dirs 'shell-resync-dirs)
841 ;;; Show the current dirstack on the message line.
842 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
843 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
844 ;;; All the commands that mung the buffer's dirstack finish by calling
845 ;;; this guy.
846 (defun shell-dirstack-message ()
847 (when shell-dirtrack-verbose
848 (let* ((msg "")
849 (ds (cons default-directory shell-dirstack))
850 (home (expand-file-name (concat comint-file-name-prefix "~/")))
851 (homelen (length home)))
852 (while ds
853 (let ((dir (car ds)))
854 (and (>= (length dir) homelen)
855 (string= home (substring dir 0 homelen))
856 (setq dir (concat "~/" (substring dir homelen))))
857 ;; Strip off comint-file-name-prefix if present.
858 (and comint-file-name-prefix
859 (>= (length dir) (length comint-file-name-prefix))
860 (string= comint-file-name-prefix
861 (substring dir 0 (length comint-file-name-prefix)))
862 (setq dir (substring dir (length comint-file-name-prefix)))
863 (setcar ds dir))
864 (setq msg (concat msg (directory-file-name dir) " "))
865 (setq ds (cdr ds))))
866 (message "%s" msg))))
868 ;; This was mostly copied from shell-resync-dirs.
869 (defun shell-snarf-envar (var)
870 "Return as a string the shell's value of environment variable VAR."
871 (let* ((cmd (format "printenv '%s'\n" var))
872 (proc (get-buffer-process (current-buffer)))
873 (pmark (process-mark proc)))
874 (goto-char pmark)
875 (insert cmd)
876 (sit-for 0) ; force redisplay
877 (comint-send-string proc cmd)
878 (set-marker pmark (point))
879 (let ((pt (point))) ; wait for 1 line
880 ;; This extra newline prevents the user's pending input from spoofing us.
881 (insert "\n") (backward-char 1)
882 (while (not (looking-at ".+\n"))
883 (accept-process-output proc)
884 (goto-char pt)))
885 (goto-char pmark) (delete-char 1) ; remove the extra newline
886 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
888 (defun shell-copy-environment-variable (variable)
889 "Copy the environment variable VARIABLE from the subshell to Emacs.
890 This command reads the value of the specified environment variable
891 in the shell, and sets the same environment variable in Emacs
892 \(what `getenv' in Emacs would return) to that value.
893 That value will affect any new subprocesses that you subsequently start
894 from Emacs."
895 (interactive (list (read-envvar-name "\
896 Copy Shell environment variable to Emacs: ")))
897 (setenv variable (shell-snarf-envar variable)))
899 (defun shell-forward-command (&optional arg)
900 "Move forward across ARG shell command(s). Does not cross lines.
901 See `shell-command-regexp'."
902 (interactive "p")
903 (let ((limit (save-excursion (end-of-line nil) (point))))
904 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
905 limit 'move arg)
906 (skip-syntax-backward " "))))
909 (defun shell-backward-command (&optional arg)
910 "Move backward across ARG shell command(s). Does not cross lines.
911 See `shell-command-regexp'."
912 (interactive "p")
913 (let ((limit (save-excursion (comint-bol nil) (point))))
914 (when (> limit (point))
915 (setq limit (line-beginning-position)))
916 (skip-syntax-backward " " limit)
917 (if (re-search-backward
918 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
919 (progn (goto-char (match-beginning 1))
920 (skip-chars-forward ";&|")))))
922 (defun shell-dynamic-complete-command ()
923 "Dynamically complete the command at point.
924 This function is similar to `comint-dynamic-complete-filename', except that it
925 searches `exec-path' (minus the trailing emacs library path) for completion
926 candidates. Note that this may not be the same as the shell's idea of the
927 path.
929 Completion is dependent on the value of `shell-completion-execonly', plus
930 those that effect file completion. See `shell-dynamic-complete-as-command'.
932 Returns t if successful."
933 (interactive)
934 (let ((filename (comint-match-partial-filename)))
935 (if (and filename
936 (save-match-data (not (string-match "[~/]" filename)))
937 (eq (match-beginning 0)
938 (save-excursion (shell-backward-command 1) (point))))
939 (prog2 (message "Completing command name...")
940 (shell-dynamic-complete-as-command)))))
943 (defun shell-dynamic-complete-as-command ()
944 "Dynamically complete at point as a command.
945 See `shell-dynamic-complete-filename'. Returns t if successful."
946 (let* ((filename (or (comint-match-partial-filename) ""))
947 (filenondir (file-name-nondirectory filename))
948 (path-dirs (cdr (reverse exec-path)))
949 (cwd (file-name-as-directory (expand-file-name default-directory)))
950 (ignored-extensions
951 (and comint-completion-fignore
952 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
953 comint-completion-fignore "\\|")))
954 (dir "") (comps-in-dir ())
955 (file "") (abs-file-name "") (completions ()))
956 ;; Go thru each dir in the search path, finding completions.
957 (while path-dirs
958 (setq dir (file-name-as-directory (comint-directory (or (car path-dirs) ".")))
959 comps-in-dir (and (file-accessible-directory-p dir)
960 (file-name-all-completions filenondir dir)))
961 ;; Go thru each completion found, to see whether it should be used.
962 (while comps-in-dir
963 (setq file (car comps-in-dir)
964 abs-file-name (concat dir file))
965 (if (and (not (member file completions))
966 (not (and ignored-extensions
967 (string-match ignored-extensions file)))
968 (or (string-equal dir cwd)
969 (not (file-directory-p abs-file-name)))
970 (or (null shell-completion-execonly)
971 (file-executable-p abs-file-name)))
972 (setq completions (cons file completions)))
973 (setq comps-in-dir (cdr comps-in-dir)))
974 (setq path-dirs (cdr path-dirs)))
975 ;; OK, we've got a list of completions.
976 (let ((success (let ((comint-completion-addsuffix nil))
977 (comint-dynamic-simple-complete filenondir completions))))
978 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
979 (not (file-directory-p (comint-match-partial-filename))))
980 (insert " "))
981 success)))
984 (defun shell-match-partial-variable ()
985 "Return the shell variable at point, or nil if none is found."
986 (save-excursion
987 (let ((limit (point)))
988 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
989 (or (looking-at "\\$") (forward-char 1)))
990 ;; Anchor the search forwards.
991 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
993 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
994 (buffer-substring (match-beginning 0) (match-end 0))))))
997 (defun shell-dynamic-complete-environment-variable ()
998 "Dynamically complete the environment variable at point.
999 Completes if after a variable, i.e., if it starts with a \"$\".
1000 See `shell-dynamic-complete-as-environment-variable'.
1002 This function is similar to `comint-dynamic-complete-filename', except that it
1003 searches `process-environment' for completion candidates. Note that this may
1004 not be the same as the interpreter's idea of variable names. The main problem
1005 with this type of completion is that `process-environment' is the environment
1006 which Emacs started with. Emacs does not track changes to the environment made
1007 by the interpreter. Perhaps it would be more accurate if this function was
1008 called `shell-dynamic-complete-process-environment-variable'.
1010 Returns non-nil if successful."
1011 (interactive)
1012 (let ((variable (shell-match-partial-variable)))
1013 (if (and variable (string-match "^\\$" variable))
1014 (prog2 (message "Completing variable name...")
1015 (shell-dynamic-complete-as-environment-variable)))))
1018 (defun shell-dynamic-complete-as-environment-variable ()
1019 "Dynamically complete at point as an environment variable.
1020 Used by `shell-dynamic-complete-environment-variable'.
1021 Uses `comint-dynamic-simple-complete'."
1022 (let* ((var (or (shell-match-partial-variable) ""))
1023 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
1024 (variables (mapcar (function (lambda (x)
1025 (substring x 0 (string-match "=" x))))
1026 process-environment))
1027 (addsuffix comint-completion-addsuffix)
1028 (comint-completion-addsuffix nil)
1029 (success (comint-dynamic-simple-complete variable variables)))
1030 (if (memq success '(sole shortest))
1031 (let* ((var (shell-match-partial-variable))
1032 (variable (substring var (string-match "[^$({]" var)))
1033 (protection (cond ((string-match "{" var) "}")
1034 ((string-match "(" var) ")")
1035 (t "")))
1036 (suffix (cond ((null addsuffix) "")
1037 ((file-directory-p
1038 (comint-directory (getenv variable))) "/")
1039 (t " "))))
1040 (insert protection suffix)))
1041 success))
1044 (defun shell-replace-by-expanded-directory ()
1045 "Expand directory stack reference before point.
1046 Directory stack references are of the form \"=digit\" or \"=-\".
1047 See `default-directory' and `shell-dirstack'.
1049 Returns t if successful."
1050 (interactive)
1051 (if (comint-match-partial-filename)
1052 (save-excursion
1053 (goto-char (match-beginning 0))
1054 (let ((stack (cons default-directory shell-dirstack))
1055 (index (cond ((looking-at "=-/?")
1056 (length shell-dirstack))
1057 ((looking-at "=\\([0-9]+\\)/?")
1058 (string-to-number
1059 (buffer-substring
1060 (match-beginning 1) (match-end 1)))))))
1061 (cond ((null index)
1062 nil)
1063 ((>= index (length stack))
1064 (error "Directory stack not that deep"))
1066 (replace-match (file-name-as-directory (nth index stack)) t t)
1067 (message "Directory item: %d" index)
1068 t))))))
1070 (provide 'shell)
1072 ;;; arch-tag: bcb5f12a-c1f4-4aea-a809-2504bd5bd797
1073 ;;; shell.el ends here