(log-edit-menu): New menu.
[emacs.git] / lisp / shell.el
blob966afc0a6600f45d12b6e9dc10d4a3ed9208c32f
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> then
6 ;; Simon Marshall <simon@gnu.org>
7 ;; Maintainer: FSF
8 ;; Keywords: processes
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)
15 ;; any later version.
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.
27 ;;; Commentary:
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.
48 ;; Needs fixin:
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?
54 ;; YOUR .EMACS FILE
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
84 ;; top-level job
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
100 ;; compatibility.
102 ;; Read the rest of this file for more information.
104 ;;; Code:
106 (require 'comint)
108 ;;; Customization and Buffer Variables
110 (defgroup shell nil
111 "Running shell from within Emacs buffers"
112 :group 'processes
113 :group 'unix)
115 (defgroup shell-directories nil
116 "Directory support in shell mode"
117 :group 'shell)
119 (defgroup shell-faces nil
120 "Faces in shell buffers"
121 :group 'shell)
123 ;;;###autoload
124 (defcustom shell-dumb-shell-regexp "cmd\\(proxy\\)?\\.exe"
125 "Regexp to match shells that don't save their command history.
126 For shells that match this regexp, Emacs will write out the
127 command history when the shell finishes."
128 :type 'regexp
129 :group 'shell)
131 (defcustom shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
132 "Regexp to match prompts in the inferior shell.
133 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
134 This variable is used to initialise `comint-prompt-regexp' in the
135 shell buffer.
137 This variable is only used if the variable
138 `comint-use-prompt-regexp-instead-of-fields' is non-nil.
140 The pattern should probably not match more than one line. If it does,
141 Shell mode may become confused trying to distinguish prompt from input
142 on lines which don't start with a prompt.
144 This is a fine thing to set in your `.emacs' file."
145 :type 'regexp
146 :group 'shell)
148 (defcustom shell-completion-fignore nil
149 "*List of suffixes to be disregarded during file/command completion.
150 This variable is used to initialize `comint-completion-fignore' in the shell
151 buffer. The default is nil, for compatibility with most shells.
152 Some people like (\"~\" \"#\" \"%\").
154 This is a fine thing to set in your `.emacs' file."
155 :type '(repeat (string :tag "Suffix"))
156 :group 'shell)
158 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
159 "List of characters to recognise as separate arguments.
160 This variable is used to initialize `comint-delimiter-argument-list' in the
161 shell buffer. The value may depend on the operating system or shell.
163 This is a fine thing to set in your `.emacs' file.")
165 (defvar shell-file-name-chars
166 (if (memq system-type '(ms-dos windows-nt))
167 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
168 "~/A-Za-z0-9+@:_.$#%,={}-")
169 "String of characters valid in a file name.
170 This variable is used to initialize `comint-file-name-chars' in the
171 shell buffer. The value may depend on the operating system or shell.
173 This is a fine thing to set in your `.emacs' file.")
175 (defvar shell-file-name-quote-list
176 (if (memq system-type '(ms-dos windows-nt))
178 (append shell-delimiter-argument-list '(?\ ?\* ?\! ?\" ?\' ?\` ?\#)))
179 "List of characters to quote when in a file name.
180 This variable is used to initialize `comint-file-name-quote-list' in the
181 shell buffer. The value may depend on the operating system or shell.
183 This is a fine thing to set in your `.emacs' file.")
185 (defvar shell-dynamic-complete-functions
186 '(comint-replace-by-expanded-history
187 shell-dynamic-complete-environment-variable
188 shell-dynamic-complete-command
189 shell-replace-by-expanded-directory
190 comint-dynamic-complete-filename)
191 "List of functions called to perform completion.
192 This variable is used to initialise `comint-dynamic-complete-functions' in the
193 shell buffer.
195 This is a fine thing to set in your `.emacs' file.")
197 (defcustom shell-command-regexp "[^;&|\n]+"
198 "*Regexp to match a single command within a pipeline.
199 This is used for directory tracking and does not do a perfect job."
200 :type 'regexp
201 :group 'shell)
203 (defcustom shell-completion-execonly t
204 "*If non-nil, use executable files only for completion candidates.
205 This mirrors the optional behavior of tcsh.
207 Detecting executability of files may slow command completion considerably."
208 :type 'boolean
209 :group 'shell)
211 (defcustom shell-popd-regexp "popd"
212 "*Regexp to match subshell commands equivalent to popd."
213 :type 'regexp
214 :group 'shell-directories)
216 (defcustom shell-pushd-regexp "pushd"
217 "*Regexp to match subshell commands equivalent to pushd."
218 :type 'regexp
219 :group 'shell-directories)
221 (defcustom shell-pushd-tohome nil
222 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
223 This mirrors the optional behavior of tcsh."
224 :type 'boolean
225 :group 'shell-directories)
227 (defcustom shell-pushd-dextract nil
228 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
229 This mirrors the optional behavior of tcsh."
230 :type 'boolean
231 :group 'shell-directories)
233 (defcustom shell-pushd-dunique nil
234 "*If non-nil, make pushd only add unique directories to the stack.
235 This mirrors the optional behavior of tcsh."
236 :type 'boolean
237 :group 'shell-directories)
239 (defcustom shell-cd-regexp "cd"
240 "*Regexp to match subshell commands equivalent to cd."
241 :type 'regexp
242 :group 'shell-directories)
244 (defcustom shell-chdrive-regexp
245 (if (memq system-type '(ms-dos windows-nt))
246 ; NetWare allows the five chars between upper and lower alphabetics.
247 "[]a-zA-Z^_`\\[\\\\]:"
248 nil)
249 "*If non-nil, is regexp used to track drive changes."
250 :type '(choice regexp
251 (const nil))
252 :group 'shell-directories)
254 (defcustom shell-dirtrack-verbose t
255 "*If non-nil, show the directory stack following directory change.
256 This is effective only if directory tracking is enabled."
257 :type 'boolean
258 :group 'shell-directories)
260 (defcustom explicit-shell-file-name nil
261 "*If non-nil, is file name to use for explicitly requested inferior shell."
262 :type '(choice (const :tag "None" nil) file)
263 :group 'shell)
265 (defcustom explicit-csh-args
266 (if (eq system-type 'hpux)
267 ;; -T persuades HP's csh not to think it is smarter
268 ;; than us about what terminal modes to use.
269 '("-i" "-T")
270 '("-i"))
271 "*Args passed to inferior shell by M-x shell, if the shell is csh.
272 Value is a list of strings, which may be nil."
273 :type '(repeat (string :tag "Argument"))
274 :group 'shell)
276 (defcustom shell-input-autoexpand 'history
277 "*If non-nil, expand input command history references on completion.
278 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
280 If the value is `input', then the expansion is seen on input.
281 If the value is `history', then the expansion is only when inserting
282 into the buffer's input ring. See also `comint-magic-space' and
283 `comint-dynamic-complete'.
285 This variable supplies a default for `comint-input-autoexpand',
286 for Shell mode only."
287 :type '(choice (const :tag "off" nil)
288 (const input)
289 (const history)
290 (const :tag "on" t))
291 :group 'shell)
293 (defvar shell-dirstack nil
294 "List of directories saved by pushd in this buffer's shell.
295 Thus, this does not include the shell's current directory.")
297 (defvar shell-dirtrackp t
298 "Non-nil in a shell buffer means directory tracking is enabled.")
300 (defvar shell-last-dir nil
301 "Keep track of last directory for ksh `cd -' command.")
303 (defvar shell-dirstack-query nil
304 "Command used by `shell-resync-dir' to query the shell.")
306 (defvar shell-mode-map nil)
307 (cond ((not shell-mode-map)
308 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
309 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
310 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
311 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
312 (define-key shell-mode-map "\M-?"
313 'comint-dynamic-list-filename-completions)
314 (define-key shell-mode-map [menu-bar completion]
315 (copy-keymap (lookup-key comint-mode-map [menu-bar completion])))
316 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
317 [complete-env-variable] '("Complete Env. Variable Name" .
318 shell-dynamic-complete-environment-variable)
319 'complete-file)
320 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
321 [expand-directory] '("Expand Directory Reference" .
322 shell-replace-by-expanded-directory)
323 'complete-expand)))
325 (defcustom shell-mode-hook '()
326 "*Hook for customising Shell mode."
327 :type 'hook
328 :group 'shell)
330 (defvar shell-font-lock-keywords
331 '(("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
332 ("^[^ \t\n]+:.*" . font-lock-string-face)
333 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
334 "Additional expressions to highlight in Shell mode.")
336 ;;; Basic Procedures
338 (put 'shell-mode 'mode-class 'special)
340 (defun shell-mode ()
341 "Major mode for interacting with an inferior shell.
342 \\[comint-send-input] after the end of the process' output sends the text from
343 the end of process to the end of the current line.
344 \\[comint-send-input] before end of process output copies the current line minus the prompt to
345 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
346 \\[send-invisible] reads a line of text without echoing it, and sends it to
347 the shell. This is useful for entering passwords. Or, add the function
348 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
350 If you want to make multiple shell buffers, rename the `*shell*' buffer
351 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
353 If you want to make shell buffers limited in length, add the function
354 `comint-truncate-buffer' to `comint-output-filter-functions'.
356 If you accidentally suspend your process, use \\[comint-continue-subjob]
357 to continue it.
359 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
360 keep this buffer's default directory the same as the shell's working directory.
361 While directory tracking is enabled, the shell's working directory is displayed
362 by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
363 \\[dirs] queries the shell and resyncs Emacs' idea of what the current
364 directory stack is.
365 \\[dirtrack-mode] turns directory tracking on and off.
367 \\{shell-mode-map}
368 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
369 `shell-mode-hook' (in that order). Before each input, the hooks on
370 `comint-input-filter-functions' are run. After each shell output, the hooks
371 on `comint-output-filter-functions' are run.
373 Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
374 and `shell-popd-regexp' are used to match their respective commands,
375 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
376 control the behavior of the relevant command.
378 Variables `comint-completion-autolist', `comint-completion-addsuffix',
379 `comint-completion-recexact' and `comint-completion-fignore' control the
380 behavior of file name, command name and variable name completion. Variable
381 `shell-completion-execonly' controls the behavior of command name completion.
382 Variable `shell-completion-fignore' is used to initialise the value of
383 `comint-completion-fignore'.
385 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
386 the initialisation of the input ring history, and history expansion.
388 Variables `comint-output-filter-functions', a hook, and
389 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
390 control whether input and output cause the window to scroll to the end of the
391 buffer."
392 (interactive)
393 (comint-mode)
394 (setq major-mode 'shell-mode)
395 (setq mode-name "Shell")
396 (use-local-map shell-mode-map)
397 (setq comint-prompt-regexp shell-prompt-pattern)
398 (setq comint-completion-fignore shell-completion-fignore)
399 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
400 (setq comint-file-name-chars shell-file-name-chars)
401 (setq comint-file-name-quote-list shell-file-name-quote-list)
402 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
403 (make-local-variable 'paragraph-start)
404 (setq paragraph-start comint-prompt-regexp)
405 (make-local-variable 'font-lock-defaults)
406 (setq font-lock-defaults '(shell-font-lock-keywords t))
407 (make-local-variable 'shell-dirstack)
408 (setq shell-dirstack nil)
409 (make-local-variable 'shell-last-dir)
410 (setq shell-last-dir nil)
411 (make-local-variable 'shell-dirtrackp)
412 (setq shell-dirtrackp t)
413 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
414 (setq comint-input-autoexpand shell-input-autoexpand)
415 ;; This is not really correct, since the shell buffer does not really
416 ;; edit this directory. But it is useful in the buffer list and menus.
417 (make-local-variable 'list-buffers-directory)
418 (setq list-buffers-directory (expand-file-name default-directory))
419 ;; shell-dependent assignments.
420 (let ((shell (file-name-nondirectory (car
421 (process-command (get-buffer-process (current-buffer)))))))
422 (setq comint-input-ring-file-name
423 (or (getenv "HISTFILE")
424 (cond ((string-equal shell "bash") "~/.bash_history")
425 ((string-equal shell "ksh") "~/.sh_history")
426 (t "~/.history"))))
427 (if (or (equal comint-input-ring-file-name "")
428 (equal (file-truename comint-input-ring-file-name)
429 (file-truename "/dev/null")))
430 (setq comint-input-ring-file-name nil))
431 ;; Arrange to write out the input ring on exit, if the shell doesn't
432 ;; do this itself.
433 (if (and comint-input-ring-file-name
434 (string-match shell-dumb-shell-regexp shell))
435 (set-process-sentinel (get-buffer-process (current-buffer))
436 #'shell-write-history-on-exit))
437 (setq shell-dirstack-query
438 (cond ((string-equal shell "sh") "pwd")
439 ((string-equal shell "ksh") "echo $PWD ~-")
440 (t "dirs"))))
441 (run-hooks 'shell-mode-hook)
442 (comint-read-input-ring t))
444 (defun shell-write-history-on-exit (process event)
445 "Called when the shell process is stopped.
447 Writes the input history to a history file
448 `comint-comint-input-ring-file-name' using `comint-write-input-ring'
449 and inserts a short message in the shell buffer.
451 This function is a sentinel watching the shell interpreter process.
452 Sentinels will always get the two parameters PROCESS and EVENT."
453 ;; Write history.
454 (comint-write-input-ring)
455 (if (buffer-live-p (process-buffer process))
456 (insert (format "\nProcess %s %s\n" process event))))
458 ;;;###autoload
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.)"
487 (interactive
488 (list
489 (and current-prefix-arg
490 (read-buffer "Shell buffer: " "*shell*"))))
491 (when (null buffer)
492 (setq buffer "*shell*"))
493 (if (not (comint-check-proc buffer))
494 (let* ((prog (or explicit-shell-file-name
495 (getenv "ESHELL")
496 (getenv "SHELL")
497 "/bin/sh"))
498 (name (file-name-nondirectory prog))
499 (startfile (concat "~/.emacs_" name))
500 (xargs-name (intern-soft (concat "explicit-" name "-args")))
501 shell-buffer)
502 (save-excursion
503 (set-buffer (apply 'make-comint-in-buffer "shell" buffer prog
504 (if (file-exists-p startfile) startfile)
505 (if (and xargs-name (boundp xargs-name))
506 (symbol-value xargs-name)
507 '("-i"))))
508 (setq shell-buffer (current-buffer))
509 (shell-mode))
510 (pop-to-buffer shell-buffer))
511 (pop-to-buffer buffer)))
513 ;;; Don't do this when shell.el is loaded, only while dumping.
514 ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
516 ;;; Directory tracking
518 ;;; This code provides the shell mode input sentinel
519 ;;; SHELL-DIRECTORY-TRACKER
520 ;;; that tracks cd, pushd, and popd commands issued to the shell, and
521 ;;; changes the current directory of the shell buffer accordingly.
523 ;;; This is basically a fragile hack, although it's more accurate than
524 ;;; the version in Emacs 18's shell.el. It has the following failings:
525 ;;; 1. It doesn't know about the cdpath shell variable.
526 ;;; 2. It cannot infallibly deal with command sequences, though it does well
527 ;;; with these and with ignoring commands forked in another shell with ()s.
528 ;;; 3. More generally, any complex command is going to throw it. Otherwise,
529 ;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
530 ;;; that, there's no way to catch shell commands where cd's are buried
531 ;;; inside conditional expressions, aliases, and so forth.
533 ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
534 ;;; messes it up. You run other processes under the shell; these each have
535 ;;; separate working directories, and some have commands for manipulating
536 ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
537 ;;; commands that do *not* affect the current w.d. at all, but look like they
538 ;;; do (e.g., the cd command in ftp). In shells that allow you job
539 ;;; control, you can switch between jobs, all having different w.d.'s. So
540 ;;; simply saying %3 can shift your w.d..
542 ;;; The solution is to relax, not stress out about it, and settle for
543 ;;; a hack that works pretty well in typical circumstances. Remember
544 ;;; that a half-assed solution is more in keeping with the spirit of Unix,
545 ;;; anyway. Blech.
547 ;;; One good hack not implemented here for users of programmable shells
548 ;;; is to program up the shell w.d. manipulation commands to output
549 ;;; a coded command sequence to the tty. Something like
550 ;;; ESC | <cwd> |
551 ;;; where <cwd> is the new current working directory. Then trash the
552 ;;; directory tracking machinery currently used in this package, and
553 ;;; replace it with a process filter that watches for and strips out
554 ;;; these messages.
556 (defun shell-directory-tracker (str)
557 "Tracks cd, pushd and popd commands issued to the shell.
558 This function is called on each input passed to the shell.
559 It watches for cd, pushd and popd commands and sets the buffer's
560 default directory to track these commands.
562 You may toggle this tracking on and off with M-x dirtrack-mode.
563 If emacs gets confused, you can resync with the shell with M-x dirs.
565 See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
566 and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
567 and `shell-pushd-dunique' control the behavior of the relevant command.
569 Environment variables are expanded, see function `substitute-in-file-name'."
570 (if shell-dirtrackp
571 ;; We fail gracefully if we think the command will fail in the shell.
572 (condition-case chdir-failure
573 (let ((start (progn (string-match "^[; \t]*" str) ; skip whitespace
574 (match-end 0)))
575 end cmd arg1)
576 (while (string-match shell-command-regexp str start)
577 (setq end (match-end 0)
578 cmd (comint-arguments (substring str start end) 0 0)
579 arg1 (comint-arguments (substring str start end) 1 1))
580 (if arg1
581 (setq arg1 (shell-unquote-argument arg1)))
582 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
583 "\\)\\($\\|[ \t]\\)")
584 cmd)
585 (shell-process-popd (comint-substitute-in-file-name arg1)))
586 ((string-match (concat "\\`\\(" shell-pushd-regexp
587 "\\)\\($\\|[ \t]\\)")
588 cmd)
589 (shell-process-pushd (comint-substitute-in-file-name arg1)))
590 ((string-match (concat "\\`\\(" shell-cd-regexp
591 "\\)\\($\\|[ \t]\\)")
592 cmd)
593 (shell-process-cd (comint-substitute-in-file-name arg1)))
594 ((and shell-chdrive-regexp
595 (string-match (concat "\\`\\(" shell-chdrive-regexp
596 "\\)\\($\\|[ \t]\\)")
597 cmd))
598 (shell-process-cd (comint-substitute-in-file-name cmd))))
599 (setq start (progn (string-match "[; \t]*" str end) ; skip again
600 (match-end 0)))))
601 (error "Couldn't cd"))))
603 (defun shell-unquote-argument (string)
604 "Remove all kinds of shell quoting from STRING."
605 (save-match-data
606 (let ((idx 0) next inside)
607 (while (and (< idx (length string))
608 (setq next (string-match "[\\'`\"]" string next)))
609 (cond ((= (aref string next) ?\\)
610 (setq string (replace-match "" nil nil string))
611 (setq next (1+ next)))
612 ((and inside (= (aref string next) inside))
613 (setq string (replace-match "" nil nil string))
614 (setq inside nil))
615 (inside
616 (setq next (1+ next)))
618 (setq inside (aref string next))
619 (setq string (replace-match "" nil nil string)))))
620 string)))
622 ;;; popd [+n]
623 (defun shell-process-popd (arg)
624 (let ((num (or (shell-extract-num arg) 0)))
625 (cond ((and num (= num 0) shell-dirstack)
626 (shell-cd (car shell-dirstack))
627 (setq shell-dirstack (cdr shell-dirstack))
628 (shell-dirstack-message))
629 ((and num (> num 0) (<= num (length shell-dirstack)))
630 (let* ((ds (cons nil shell-dirstack))
631 (cell (nthcdr (1- num) ds)))
632 (rplacd cell (cdr (cdr cell)))
633 (setq shell-dirstack (cdr ds))
634 (shell-dirstack-message)))
636 (error "Couldn't popd")))))
638 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
639 (defun shell-prefixed-directory-name (dir)
640 (if (= (length comint-file-name-prefix) 0)
642 (if (file-name-absolute-p dir)
643 ;; The name is absolute, so prepend the prefix.
644 (concat comint-file-name-prefix dir)
645 ;; For relative name we assume default-directory already has the prefix.
646 (expand-file-name dir))))
648 ;;; cd [dir]
649 (defun shell-process-cd (arg)
650 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
651 "~"))
652 ((string-equal "-" arg) shell-last-dir)
653 (t (shell-prefixed-directory-name arg)))))
654 (setq shell-last-dir default-directory)
655 (shell-cd new-dir)
656 (shell-dirstack-message)))
658 ;;; pushd [+n | dir]
659 (defun shell-process-pushd (arg)
660 (let ((num (shell-extract-num arg)))
661 (cond ((zerop (length arg))
662 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
663 (cond (shell-pushd-tohome
664 (shell-process-pushd (concat comint-file-name-prefix "~")))
665 (shell-dirstack
666 (let ((old default-directory))
667 (shell-cd (car shell-dirstack))
668 (setq shell-dirstack (cons old (cdr shell-dirstack)))
669 (shell-dirstack-message)))
671 (message "Directory stack empty."))))
672 ((numberp num)
673 ;; pushd +n
674 (cond ((> num (length shell-dirstack))
675 (message "Directory stack not that deep."))
676 ((= num 0)
677 (error (message "Couldn't cd.")))
678 (shell-pushd-dextract
679 (let ((dir (nth (1- num) shell-dirstack)))
680 (shell-process-popd arg)
681 (shell-process-pushd default-directory)
682 (shell-cd dir)
683 (shell-dirstack-message)))
685 (let* ((ds (cons default-directory shell-dirstack))
686 (dslen (length ds))
687 (front (nthcdr num ds))
688 (back (reverse (nthcdr (- dslen num) (reverse ds))))
689 (new-ds (append front back)))
690 (shell-cd (car new-ds))
691 (setq shell-dirstack (cdr new-ds))
692 (shell-dirstack-message)))))
694 ;; pushd <dir>
695 (let ((old-wd default-directory))
696 (shell-cd (shell-prefixed-directory-name arg))
697 (if (or (null shell-pushd-dunique)
698 (not (member old-wd shell-dirstack)))
699 (setq shell-dirstack (cons old-wd shell-dirstack)))
700 (shell-dirstack-message))))))
702 ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
703 (defun shell-extract-num (str)
704 (and (string-match "^\\+[1-9][0-9]*$" str)
705 (string-to-int str)))
708 (defun shell-dirtrack-mode ()
709 "Turn directory tracking on and off in a shell buffer."
710 (interactive)
711 (if (setq shell-dirtrackp (not shell-dirtrackp))
712 (setq list-buffers-directory default-directory)
713 (setq list-buffers-directory nil))
714 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
716 ;;; For your typing convenience:
717 (defalias 'shell-dirtrack-toggle 'shell-dirtrack-mode)
718 (defalias 'dirtrack-toggle 'shell-dirtrack-mode)
719 (defalias 'dirtrack-mode 'shell-dirtrack-mode)
721 (defun shell-cd (dir)
722 "Do normal `cd' to DIR, and set `list-buffers-directory'."
723 (if shell-dirtrackp
724 (setq list-buffers-directory (file-name-as-directory
725 (expand-file-name dir))))
726 (cd dir))
728 (defun shell-resync-dirs ()
729 "Resync the buffer's idea of the current directory stack.
730 This command queries the shell with the command bound to
731 `shell-dirstack-query' (default \"dirs\"), reads the next
732 line output and parses it to form the new directory stack.
733 DON'T issue this command unless the buffer is at a shell prompt.
734 Also, note that if some other subprocess decides to do output
735 immediately after the query, its output will be taken as the
736 new directory stack -- you lose. If this happens, just do the
737 command again."
738 (interactive)
739 (let* ((proc (get-buffer-process (current-buffer)))
740 (pmark (process-mark proc)))
741 (goto-char pmark)
742 (insert shell-dirstack-query) (insert "\n")
743 (sit-for 0) ; force redisplay
744 (comint-send-string proc shell-dirstack-query)
745 (comint-send-string proc "\n")
746 (set-marker pmark (point))
747 (let ((pt (point))) ; wait for 1 line
748 ;; This extra newline prevents the user's pending input from spoofing us.
749 (insert "\n") (backward-char 1)
750 (while (not (looking-at ".+\n"))
751 (accept-process-output proc)
752 (goto-char pt)))
753 (goto-char pmark) (delete-char 1) ; remove the extra newline
754 ;; That's the dirlist. grab it & parse it.
755 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
756 (dl-len (length dl))
757 (ds '()) ; new dir stack
758 (i 0))
759 (while (< i dl-len)
760 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
761 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
762 (setq ds (cons (concat comint-file-name-prefix
763 (substring dl (match-beginning 1)
764 (match-end 1)))
765 ds))
766 (setq i (match-end 0)))
767 (let ((ds (nreverse ds)))
768 (condition-case nil
769 (progn (shell-cd (car ds))
770 (setq shell-dirstack (cdr ds)
771 shell-last-dir (car shell-dirstack))
772 (shell-dirstack-message))
773 (error (message "Couldn't cd.")))))))
775 ;;; For your typing convenience:
776 (defalias 'dirs 'shell-resync-dirs)
779 ;;; Show the current dirstack on the message line.
780 ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
781 ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
782 ;;; All the commands that mung the buffer's dirstack finish by calling
783 ;;; this guy.
784 (defun shell-dirstack-message ()
785 (when shell-dirtrack-verbose
786 (let* ((msg "")
787 (ds (cons default-directory shell-dirstack))
788 (home (expand-file-name (concat comint-file-name-prefix "~/")))
789 (homelen (length home)))
790 (while ds
791 (let ((dir (car ds)))
792 (and (>= (length dir) homelen)
793 (string= home (substring dir 0 homelen))
794 (setq dir (concat "~/" (substring dir homelen))))
795 ;; Strip off comint-file-name-prefix if present.
796 (and comint-file-name-prefix
797 (>= (length dir) (length comint-file-name-prefix))
798 (string= comint-file-name-prefix
799 (substring dir 0 (length comint-file-name-prefix)))
800 (setq dir (substring dir (length comint-file-name-prefix)))
801 (setcar ds dir))
802 (setq msg (concat msg (directory-file-name dir) " "))
803 (setq ds (cdr ds))))
804 (message "%s" msg))))
806 ;; This was mostly copied from shell-resync-dirs.
807 (defun shell-snarf-envar (var)
808 "Return as a string the shell's value of environment variable VAR."
809 (let* ((cmd (format "printenv '%s'\n" var))
810 (proc (get-buffer-process (current-buffer)))
811 (pmark (process-mark proc)))
812 (goto-char pmark)
813 (insert cmd)
814 (sit-for 0) ; force redisplay
815 (comint-send-string proc cmd)
816 (set-marker pmark (point))
817 (let ((pt (point))) ; wait for 1 line
818 ;; This extra newline prevents the user's pending input from spoofing us.
819 (insert "\n") (backward-char 1)
820 (while (not (looking-at ".+\n"))
821 (accept-process-output proc)
822 (goto-char pt)))
823 (goto-char pmark) (delete-char 1) ; remove the extra newline
824 (buffer-substring (match-beginning 0) (1- (match-end 0)))))
826 (defun shell-copy-environment-variable (variable)
827 "Copy the environment variable VARIABLE from the subshell to Emacs.
828 This command reads the value of the specified environment variable
829 in the shell, and sets the same environment variable in Emacs
830 \(what `getenv' in Emacs would return) to that value.
831 That value will affect any new subprocesses that you subsequently start
832 from Emacs."
833 (interactive (list (read-envvar-name "\
834 Copy Shell environment variable to Emacs: ")))
835 (setenv variable (shell-snarf-envar variable)))
837 (defun shell-forward-command (&optional arg)
838 "Move forward across ARG shell command(s). Does not cross lines.
839 See `shell-command-regexp'."
840 (interactive "p")
841 (let ((limit (save-excursion (end-of-line nil) (point))))
842 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
843 limit 'move arg)
844 (skip-syntax-backward " "))))
847 (defun shell-backward-command (&optional arg)
848 "Move backward across ARG shell command(s). Does not cross lines.
849 See `shell-command-regexp'."
850 (interactive "p")
851 (let ((limit (save-excursion (comint-bol nil) (point))))
852 (when (> limit (point))
853 (setq limit (line-beginning-position)))
854 (skip-syntax-backward " " limit)
855 (if (re-search-backward
856 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
857 (progn (goto-char (match-beginning 1))
858 (skip-chars-forward ";&|")))))
861 (defun shell-dynamic-complete-command ()
862 "Dynamically complete the command at point.
863 This function is similar to `comint-dynamic-complete-filename', except that it
864 searches `exec-path' (minus the trailing emacs library path) for completion
865 candidates. Note that this may not be the same as the shell's idea of the
866 path.
868 Completion is dependent on the value of `shell-completion-execonly', plus
869 those that effect file completion. See `shell-dynamic-complete-as-command'.
871 Returns t if successful."
872 (interactive)
873 (let ((filename (comint-match-partial-filename)))
874 (if (and filename
875 (save-match-data (not (string-match "[~/]" filename)))
876 (eq (match-beginning 0)
877 (save-excursion (shell-backward-command 1) (point))))
878 (prog2 (message "Completing command name...")
879 (shell-dynamic-complete-as-command)))))
882 (defun shell-dynamic-complete-as-command ()
883 "Dynamically complete at point as a command.
884 See `shell-dynamic-complete-filename'. Returns t if successful."
885 (let* ((filename (or (comint-match-partial-filename) ""))
886 (pathnondir (file-name-nondirectory filename))
887 (paths (cdr (reverse exec-path)))
888 (cwd (file-name-as-directory (expand-file-name default-directory)))
889 (ignored-extensions
890 (and comint-completion-fignore
891 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
892 comint-completion-fignore "\\|")))
893 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
894 ;; Go thru each path in the search path, finding completions.
895 (while paths
896 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
897 comps-in-path (and (file-accessible-directory-p path)
898 (file-name-all-completions pathnondir path)))
899 ;; Go thru each completion found, to see whether it should be used.
900 (while comps-in-path
901 (setq file (car comps-in-path)
902 filepath (concat path file))
903 (if (and (not (member file completions))
904 (not (and ignored-extensions
905 (string-match ignored-extensions file)))
906 (or (string-equal path cwd)
907 (not (file-directory-p filepath)))
908 (or (null shell-completion-execonly)
909 (file-executable-p filepath)))
910 (setq completions (cons file completions)))
911 (setq comps-in-path (cdr comps-in-path)))
912 (setq paths (cdr paths)))
913 ;; OK, we've got a list of completions.
914 (let ((success (let ((comint-completion-addsuffix nil))
915 (comint-dynamic-simple-complete pathnondir completions))))
916 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
917 (not (file-directory-p (comint-match-partial-filename))))
918 (insert " "))
919 success)))
922 (defun shell-match-partial-variable ()
923 "Return the shell variable at point, or nil if none is found."
924 (save-excursion
925 (let ((limit (point)))
926 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
927 (or (looking-at "\\$") (forward-char 1)))
928 ;; Anchor the search forwards.
929 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
931 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
932 (buffer-substring (match-beginning 0) (match-end 0))))))
935 (defun shell-dynamic-complete-environment-variable ()
936 "Dynamically complete the environment variable at point.
937 Completes if after a variable, i.e., if it starts with a \"$\".
938 See `shell-dynamic-complete-as-environment-variable'.
940 This function is similar to `comint-dynamic-complete-filename', except that it
941 searches `process-environment' for completion candidates. Note that this may
942 not be the same as the interpreter's idea of variable names. The main problem
943 with this type of completion is that `process-environment' is the environment
944 which Emacs started with. Emacs does not track changes to the environment made
945 by the interpreter. Perhaps it would be more accurate if this function was
946 called `shell-dynamic-complete-process-environment-variable'.
948 Returns non-nil if successful."
949 (interactive)
950 (let ((variable (shell-match-partial-variable)))
951 (if (and variable (string-match "^\\$" variable))
952 (prog2 (message "Completing variable name...")
953 (shell-dynamic-complete-as-environment-variable)))))
956 (defun shell-dynamic-complete-as-environment-variable ()
957 "Dynamically complete at point as an environment variable.
958 Used by `shell-dynamic-complete-environment-variable'.
959 Uses `comint-dynamic-simple-complete'."
960 (let* ((var (or (shell-match-partial-variable) ""))
961 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
962 (variables (mapcar (function (lambda (x)
963 (substring x 0 (string-match "=" x))))
964 process-environment))
965 (addsuffix comint-completion-addsuffix)
966 (comint-completion-addsuffix nil)
967 (success (comint-dynamic-simple-complete variable variables)))
968 (if (memq success '(sole shortest))
969 (let* ((var (shell-match-partial-variable))
970 (variable (substring var (string-match "[^$({]" var)))
971 (protection (cond ((string-match "{" var) "}")
972 ((string-match "(" var) ")")
973 (t "")))
974 (suffix (cond ((null addsuffix) "")
975 ((file-directory-p
976 (comint-directory (getenv variable))) "/")
977 (t " "))))
978 (insert protection suffix)))
979 success))
982 (defun shell-replace-by-expanded-directory ()
983 "Expand directory stack reference before point.
984 Directory stack references are of the form \"=digit\" or \"=-\".
985 See `default-directory' and `shell-dirstack'.
987 Returns t if successful."
988 (interactive)
989 (if (comint-match-partial-filename)
990 (save-excursion
991 (goto-char (match-beginning 0))
992 (let ((stack (cons default-directory shell-dirstack))
993 (index (cond ((looking-at "=-/?")
994 (length shell-dirstack))
995 ((looking-at "=\\([0-9]+\\)")
996 (string-to-number
997 (buffer-substring
998 (match-beginning 1) (match-end 1)))))))
999 (cond ((null index)
1000 nil)
1001 ((>= index (length stack))
1002 (error "Directory stack not that deep."))
1004 (replace-match (file-name-as-directory (nth index stack)) t t)
1005 (message "Directory item: %d" index)
1006 t))))))
1008 (provide 'shell)
1010 ;;; shell.el ends here