(Fmake_temp_name): Doc fix.
[bpt/emacs.git] / lisp / shell.el
CommitLineData
5336e829 1;;; shell.el --- specialized comint.el for running the shell.
5109bfb0 2
ed366e87 3;; Copyright (C) 1988, 93, 94, 95, 96, 1997 Free Software Foundation, Inc.
6d74b528 4
f8604035
SM
5;; Author: Olin Shivers <shivers@cs.cmu.edu> then
6;; Simon Marshall <simon@gnu.ai.mit.edu>
7;; Maintainer: FSF
d7b4d18f 8;; Keywords: processes
630cc463 9
5109bfb0 10;; This file is part of GNU Emacs.
c88ab9ce 11
5109bfb0
KH
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.
c88ab9ce 16
5109bfb0
KH
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.
c88ab9ce 21
5109bfb0 22;; You should have received a copy of the GNU General Public License
b578f267
EN
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.
be9b65ac 26
630cc463
ER
27;;; Commentary:
28
b578f267
EN
29;; Please send me bug reports, bug fixes, and extensions, so that I can
30;; merge them into the master source.
31;; - Olin Shivers (shivers@cs.cmu.edu)
32;; - Simon Marshall (simon@gnu.ai.mit.edu)
be9b65ac 33
b578f267
EN
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.
be9b65ac 38
b578f267
EN
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.
be9b65ac 43
b578f267
EN
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.
be9b65ac 47
b578f267
EN
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?
be9b65ac 53
a9ec2adb
JB
54;; YOUR .EMACS FILE
55;;=============================================================================
56;; Some suggestions for your .emacs file.
57;;
0b3c9cf1
SM
58;; ;; Define M-# to run some strange command:
59;; (eval-after-load "shell"
60;; '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
a9ec2adb 61\f
b578f267
EN
62;; Brief Command Documentation:
63;;============================================================================
64;; Comint Mode Commands: (common to shell and all comint-derived modes)
65;;
66;; m-p comint-previous-input Cycle backwards in input history
67;; m-n comint-next-input Cycle forwards
68;; m-r comint-previous-matching-input Previous input matching a regexp
69;; m-s comint-next-matching-input Next input that matches
70;; m-c-l comint-show-output Show last batch of process output
71;; return comint-send-input
72;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
73;; c-c c-a comint-bol Beginning of line; skip prompt
74;; c-c c-u comint-kill-input ^u
75;; c-c c-w backward-kill-word ^w
76;; c-c c-c comint-interrupt-subjob ^c
77;; c-c c-z comint-stop-subjob ^z
78;; c-c c-\ comint-quit-subjob ^\
79;; c-c c-o comint-kill-output Delete last batch of process output
80;; c-c c-r comint-show-output Show last batch of process output
81;; c-c c-h comint-dynamic-list-input-ring List input history
82;; send-invisible Read line w/o echo & send to proc
83;; comint-continue-subjob Useful if you accidentally suspend
84;; top-level job
85;; comint-mode-hook is the comint mode hook.
86
87;; Shell Mode Commands:
88;; shell Fires up the shell process
89;; tab comint-dynamic-complete Complete filename/command/history
90;; m-? comint-dynamic-list-filename-completions
91;; List completions in help buffer
92;; m-c-f shell-forward-command Forward a shell command
93;; m-c-b shell-backward-command Backward a shell command
94;; dirs Resync the buffer's dir stack
95;; dirtrack-toggle Turn dir tracking on/off
96;; comint-strip-ctrl-m Remove trailing ^Ms from output
97;;
98;; The shell mode hook is shell-mode-hook
99;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
100;; compatibility.
a9ec2adb 101
b578f267 102;; Read the rest of this file for more information.
a9ec2adb 103\f
630cc463
ER
104;;; Code:
105
106(require 'comint)
107
b578f267
EN
108;;; Customization and Buffer Variables
109
ed366e87
RS
110(defgroup shell nil
111 "Running shell from within Emacs buffers"
112 :group 'processes
113 :group 'unix)
114
115(defgroup shell-directories nil
116 "Directory support in shell mode"
117 :group 'shell)
118
119(defgroup shell-faces nil
120 "Faces in shell buffers"
121 :group 'shell)
122
c88ab9ce 123;;;###autoload
ac75ef20 124(defvar shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
a9ec2adb 125 "Regexp to match prompts in the inferior shell.
ac75ef20 126Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
24fdffaa 127This variable is used to initialise `comint-prompt-regexp' in the
a9ec2adb
JB
128shell buffer.
129
ac75ef20 130The pattern should probably not match more than one line. If it does,
221ca406 131Shell mode may become confused trying to distinguish prompt from input
ac75ef20
JB
132on lines which don't start with a prompt.
133
24fdffaa 134This is a fine thing to set in your `.emacs' file.")
a9ec2adb 135
ed366e87 136(defcustom shell-completion-fignore nil
e11284d5
RS
137 "*List of suffixes to be disregarded during file/command completion.
138This variable is used to initialize `comint-completion-fignore' in the shell
139buffer. The default is nil, for compatibility with most shells.
140Some people like (\"~\" \"#\" \"%\").
141
ed366e87
RS
142This is a fine thing to set in your `.emacs' file."
143 :type '(repeat (string :tag "Suffix"))
144 :group 'shell)
e11284d5 145
56eb1060 146(defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
d76b71af 147 "List of characters to recognise as separate arguments.
56eb1060 148This variable is used to initialize `comint-delimiter-argument-list' in the
39d1a2ce
SM
149shell buffer. The value may depend on the operating system or shell.
150
151This is a fine thing to set in your `.emacs' file.")
152
76f63ea0 153(defvar shell-file-name-chars
39d1a2ce
SM
154 (if (memq system-type '(ms-dos windows-nt))
155 "~/A-Za-z0-9_^$!#%&{}@`'.()-"
156 "~/A-Za-z0-9+@:_.$#%,={}-")
76f63ea0
RS
157 "String of characters valid in a file name.
158This variable is used to initialize `comint-file-name-chars' in the
39d1a2ce 159shell buffer. The value may depend on the operating system or shell.
d76b71af
RS
160
161This is a fine thing to set in your `.emacs' file.")
162
7b4c6503 163(defvar shell-file-name-quote-list
39d1a2ce
SM
164 (if (memq system-type '(ms-dos windows-nt))
165 nil
166 (append shell-delimiter-argument-list '(?\ ?\* ?\! ?\" ?\' ?\`)))
7b4c6503
SM
167 "List of characters to quote when in a file name.
168This variable is used to initialize `comint-file-name-quote-list' in the
39d1a2ce 169shell buffer. The value may depend on the operating system or shell.
7b4c6503
SM
170
171This is a fine thing to set in your `.emacs' file.")
172
988a4d60
RS
173(defvar shell-dynamic-complete-functions
174 '(comint-replace-by-expanded-history
175 shell-dynamic-complete-environment-variable
176 shell-dynamic-complete-command
177 shell-replace-by-expanded-directory
178 comint-dynamic-complete-filename)
179 "List of functions called to perform completion.
180This variable is used to initialise `comint-dynamic-complete-functions' in the
181shell buffer.
182
183This is a fine thing to set in your `.emacs' file.")
184
ed366e87 185(defcustom shell-command-regexp "[^;&|\n]+"
a8e0effb 186 "*Regexp to match a single command within a pipeline.
ed366e87
RS
187This is used for directory tracking and does not do a perfect job."
188 :type 'regexp
189 :group 'shell)
d76b71af 190
ed366e87 191(defcustom shell-completion-execonly t
d76b71af 192 "*If non-nil, use executable files only for completion candidates.
5394cb44 193This mirrors the optional behavior of tcsh.
d76b71af 194
ed366e87
RS
195Detecting executability of files may slow command completion considerably."
196 :type 'boolean
197 :group 'shell)
d76b71af 198
ed366e87
RS
199(defcustom shell-popd-regexp "popd"
200 "*Regexp to match subshell commands equivalent to popd."
201 :type 'regexp
202 :group 'shell-directories)
be9b65ac 203
ed366e87
RS
204(defcustom shell-pushd-regexp "pushd"
205 "*Regexp to match subshell commands equivalent to pushd."
206 :type 'regexp
207 :group 'shell-directories)
be9b65ac 208
ed366e87 209(defcustom shell-pushd-tohome nil
d76b71af 210 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
ed366e87
RS
211This mirrors the optional behavior of tcsh."
212 :type 'boolean
213 :group 'shell-directories)
d76b71af 214
ed366e87 215(defcustom shell-pushd-dextract nil
d76b71af 216 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
ed366e87
RS
217This mirrors the optional behavior of tcsh."
218 :type 'boolean
219 :group 'shell-directories)
d76b71af 220
ed366e87 221(defcustom shell-pushd-dunique nil
d76b71af 222 "*If non-nil, make pushd only add unique directories to the stack.
ed366e87
RS
223This mirrors the optional behavior of tcsh."
224 :type 'boolean
225 :group 'shell-directories)
d76b71af 226
ed366e87
RS
227(defcustom shell-cd-regexp "cd"
228 "*Regexp to match subshell commands equivalent to cd."
229 :type 'regexp
230 :group 'shell-directories)
be9b65ac 231
ed366e87 232(defcustom shell-chdrive-regexp
32d01212
RS
233 (if (memq system-type '(ms-dos windows-nt))
234 ; NetWare allows the five chars between upper and lower alphabetics.
235 "[]a-zA-Z^_`\\[\\\\]:"
236 nil)
ed366e87
RS
237 "*If non-nil, is regexp used to track drive changes."
238 :type 'regexp
239 :group 'shell-directories)
32d01212 240
ed366e87
RS
241(defcustom explicit-shell-file-name nil
242 "*If non-nil, is file name to use for explicitly requested inferior shell."
243 :type '(choice (const :tag "None" nil) file)
244 :group 'shell)
be9b65ac 245
ed366e87 246(defcustom explicit-csh-args
be9b65ac
DL
247 (if (eq system-type 'hpux)
248 ;; -T persuades HP's csh not to think it is smarter
249 ;; than us about what terminal modes to use.
250 '("-i" "-T")
251 '("-i"))
252 "*Args passed to inferior shell by M-x shell, if the shell is csh.
ed366e87
RS
253Value is a list of strings, which may be nil."
254 :type '(repeat (string :tag "Argument"))
255 :group 'shell)
be9b65ac 256
ed366e87 257(defcustom shell-input-autoexpand 'history
4f99443b
RS
258 "*If non-nil, expand input command history references on completion.
259This mirrors the optional behavior of tcsh (its autoexpand and histlit).
260
261If the value is `input', then the expansion is seen on input.
262If the value is `history', then the expansion is only when inserting
263into the buffer's input ring. See also `comint-magic-space' and
264`comint-dynamic-complete'.
265
266This variable supplies a default for `comint-input-autoexpand',
ed366e87
RS
267for Shell mode only."
268 :type '(choice (const nil) (const input) (const history))
269 :type 'shell)
4f99443b 270
be9b65ac 271(defvar shell-dirstack nil
c88ab9ce
ER
272 "List of directories saved by pushd in this buffer's shell.
273Thus, this does not include the shell's current directory.")
be9b65ac 274
b493a9b2
RS
275(defvar shell-dirtrackp t
276 "Non-nil in a shell buffer means directory tracking is enabled.")
277
fa8f1b25
ER
278(defvar shell-last-dir nil
279 "Keep track of last directory for ksh `cd -' command.")
280
c63e83a4 281(defvar shell-dirstack-query nil
24fdffaa 282 "Command used by `shell-resync-dir' to query the shell.")
be9b65ac 283
9376442d 284(defvar shell-mode-map nil)
be9b65ac 285(cond ((not shell-mode-map)
1ed30e75 286 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
d76b71af
RS
287 (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
288 (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
be9b65ac 289 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
d76b71af 290 (define-key shell-mode-map "\M-?"
988a4d60 291 'comint-dynamic-list-filename-completions)
1ed30e75
RS
292 (define-key shell-mode-map [menu-bar completion]
293 (copy-keymap (lookup-key comint-mode-map [menu-bar completion])))
5109bfb0
KH
294 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
295 [complete-env-variable] '("Complete Env. Variable Name" .
296 shell-dynamic-complete-environment-variable)
297 'complete-file)
298 (define-key-after (lookup-key shell-mode-map [menu-bar completion])
299 [expand-directory] '("Expand Directory Reference" .
300 shell-replace-by-expanded-directory)
301 'complete-expand)))
be9b65ac 302
ed366e87
RS
303(defcustom shell-mode-hook '()
304 "*Hook for customising Shell mode."
305 :type 'hook
306 :group 'shell)
be9b65ac 307
5945a1f7 308(defvar shell-font-lock-keywords
473fbd89
SM
309 '((eval . (cons shell-prompt-pattern 'font-lock-warning-face))
310 ("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
311 ("^[^ \t\n]+:.*" . font-lock-string-face)
312 ("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
5945a1f7 313 "Additional expressions to highlight in Shell mode.")
be9b65ac
DL
314\f
315;;; Basic Procedures
be9b65ac 316
e9904b59
RS
317(put 'shell-mode 'mode-class 'special)
318
be9b65ac
DL
319(defun shell-mode ()
320 "Major mode for interacting with an inferior shell.
8079b590
SM
321\\[comint-send-input] after the end of the process' output sends the text from
322 the end of process to the end of the current line.
323\\[comint-send-input] before end of process output copies the current line minus the prompt to
324 the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
e9933cb1 325\\[send-invisible] reads a line of text without echoing it, and sends it to
56783585
RS
326 the shell. This is useful for entering passwords. Or, add the function
327 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
be9b65ac 328
e9933cb1
SM
329If you want to make multiple shell buffers, rename the `*shell*' buffer
330using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
331
8079b590 332If you want to make shell buffers limited in length, add the function
4841acc4 333`comint-truncate-buffer' to `comint-output-filter-functions'.
8079b590 334
be9b65ac
DL
335If you accidentally suspend your process, use \\[comint-continue-subjob]
336to continue it.
337
e9933cb1
SM
338`cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
339keep this buffer's default directory the same as the shell's working directory.
0b3c9cf1
SM
340While directory tracking is enabled, the shell's working directory is displayed
341by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
e9933cb1 342\\[dirs] queries the shell and resyncs Emacs' idea of what the current
be9b65ac 343 directory stack is.
e9933cb1 344\\[dirtrack-toggle] turns directory tracking on and off.
be9b65ac
DL
345
346\\{shell-mode-map}
24fdffaa 347Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
988a4d60 348`shell-mode-hook' (in that order). Before each input, the hooks on
ba02c167
RS
349`comint-input-filter-functions' are run. After each shell output, the hooks
350on `comint-output-filter-functions' are run.
be9b65ac 351
32d01212
RS
352Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp'
353and `shell-popd-regexp' are used to match their respective commands,
354while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
355control the behavior of the relevant command.
d76b71af 356
e11284d5
RS
357Variables `comint-completion-autolist', `comint-completion-addsuffix',
358`comint-completion-recexact' and `comint-completion-fignore' control the
359behavior of file name, command name and variable name completion. Variable
360`shell-completion-execonly' controls the behavior of command name completion.
361Variable `shell-completion-fignore' is used to initialise the value of
362`comint-completion-fignore'.
d76b71af
RS
363
364Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
365the initialisation of the input ring history, and history expansion.
366
ba02c167 367Variables `comint-output-filter-functions', a hook, and
e11284d5 368`comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
988a4d60
RS
369control whether input and output cause the window to scroll to the end of the
370buffer."
be9b65ac
DL
371 (interactive)
372 (comint-mode)
a9ec2adb 373 (setq major-mode 'shell-mode)
bd5201e3 374 (setq mode-name "Shell")
be9b65ac 375 (use-local-map shell-mode-map)
d76b71af 376 (setq comint-prompt-regexp shell-prompt-pattern)
e11284d5 377 (setq comint-completion-fignore shell-completion-fignore)
d76b71af 378 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
76f63ea0 379 (setq comint-file-name-chars shell-file-name-chars)
7b4c6503 380 (setq comint-file-name-quote-list shell-file-name-quote-list)
988a4d60 381 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
d76b71af
RS
382 (make-local-variable 'paragraph-start)
383 (setq paragraph-start comint-prompt-regexp)
c156572f
SM
384 (make-local-variable 'font-lock-defaults)
385 (setq font-lock-defaults '(shell-font-lock-keywords t))
be9b65ac 386 (make-local-variable 'shell-dirstack)
a9ec2adb 387 (setq shell-dirstack nil)
fa8f1b25 388 (setq shell-last-dir nil)
a9ec2adb
JB
389 (make-local-variable 'shell-dirtrackp)
390 (setq shell-dirtrackp t)
1458efa0 391 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
4f99443b 392 (setq comint-input-autoexpand shell-input-autoexpand)
5d9719e6
RS
393 ;; This is not really correct, since the shell buffer does not really
394 ;; edit this directory. But it is useful in the buffer list and menus.
395 (make-local-variable 'list-buffers-directory)
396 (setq list-buffers-directory (expand-file-name default-directory))
d76b71af 397 ;; shell-dependent assignments.
c63e83a4
RS
398 (let ((shell (file-name-nondirectory (car
399 (process-command (get-buffer-process (current-buffer)))))))
d76b71af
RS
400 (setq comint-input-ring-file-name
401 (or (getenv "HISTFILE")
c63e83a4
RS
402 (cond ((string-equal shell "bash") "~/.bash_history")
403 ((string-equal shell "ksh") "~/.sh_history")
404 (t "~/.history"))))
525c5be7 405 (if (or (equal comint-input-ring-file-name "")
fbcb3055
RS
406 (equal (file-truename comint-input-ring-file-name)
407 (file-truename "/dev/null")))
3c24374d 408 (setq comint-input-ring-file-name nil))
c63e83a4 409 (setq shell-dirstack-query
221ca406
SM
410 (cond ((string-equal shell "sh") "pwd")
411 ((string-equal shell "ksh") "echo $PWD ~-")
412 (t "dirs"))))
d76b71af 413 (run-hooks 'shell-mode-hook)
4f99443b 414 (comint-read-input-ring t))
be9b65ac 415\f
c88ab9ce 416;;;###autoload
be9b65ac
DL
417(defun shell ()
418 "Run an inferior shell, with I/O through buffer *shell*.
419If buffer exists but shell process is not running, make new shell.
d76b71af 420If buffer exists and shell process is running, just switch to buffer `*shell*'.
24fdffaa 421Program used comes from variable `explicit-shell-file-name',
a9ec2adb
JB
422 or (if that is nil) from the ESHELL environment variable,
423 or else from SHELL if there is no ESHELL.
fbc270e7 424If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
a9ec2adb
JB
425 (Note that this may lose due to a timing error if the shell
426 discards input when it starts up.)
fbc270e7
RS
427The buffer is put in Shell mode, giving commands for sending input
428and controlling the subjobs of the shell. See `shell-mode'.
429See also the variable `shell-prompt-pattern'.
be9b65ac 430
ebe4d555
RS
431To specify a coding system for converting non-ASCII characters
432in the input and output to the shell, use \\[universal-coding-system-argument]
433before \\[shell]. You can also specify this with \\[set-buffer-process-coding-system]
434in the shell buffer, after you start the shell.
435The default comes from `process-coding-system-alist' and
436`default-process-coding-system'.
437
a9ec2adb 438The shell file name (sans directories) is used to make a symbol name
62c9fad7 439such as `explicit-csh-args'. If that symbol is a variable,
be9b65ac
DL
440its value is used as a list of arguments when invoking the shell.
441Otherwise, one argument `-i' is passed to the shell.
442
443\(Type \\[describe-mode] in the shell buffer for a list of commands.)"
444 (interactive)
d76b71af
RS
445 (if (not (comint-check-proc "*shell*"))
446 (let* ((prog (or explicit-shell-file-name
447 (getenv "ESHELL")
448 (getenv "SHELL")
449 "/bin/sh"))
450 (name (file-name-nondirectory prog))
451 (startfile (concat "~/.emacs_" name))
519bfec4
RS
452 (xargs-name (intern-soft (concat "explicit-" name "-args")))
453 shell-buffer)
454 (save-excursion
455 (set-buffer (apply 'make-comint "shell" prog
456 (if (file-exists-p startfile) startfile)
457 (if (and xargs-name (boundp xargs-name))
458 (symbol-value xargs-name)
459 '("-i"))))
460 (setq shell-buffer (current-buffer))
461 (shell-mode))
462 (pop-to-buffer shell-buffer))
463 (pop-to-buffer "*shell*")))
464
465;;; Don't do this when shell.el is loaded, only while dumping.
466;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
be9b65ac
DL
467\f
468;;; Directory tracking
b578f267 469;;;
be9b65ac
DL
470;;; This code provides the shell mode input sentinel
471;;; SHELL-DIRECTORY-TRACKER
472;;; that tracks cd, pushd, and popd commands issued to the shell, and
473;;; changes the current directory of the shell buffer accordingly.
474;;;
475;;; This is basically a fragile hack, although it's more accurate than
b7fc702e 476;;; the version in Emacs 18's shell.el. It has the following failings:
be9b65ac 477;;; 1. It doesn't know about the cdpath shell variable.
d76b71af
RS
478;;; 2. It cannot infallibly deal with command sequences, though it does well
479;;; with these and with ignoring commands forked in another shell with ()s.
480;;; 3. More generally, any complex command is going to throw it. Otherwise,
481;;; you'd have to build an entire shell interpreter in emacs lisp. Failing
482;;; that, there's no way to catch shell commands where cd's are buried
483;;; inside conditional expressions, aliases, and so forth.
be9b65ac
DL
484;;;
485;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
486;;; messes it up. You run other processes under the shell; these each have
487;;; separate working directories, and some have commands for manipulating
488;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
a9ec2adb 489;;; commands that do *not* affect the current w.d. at all, but look like they
be9b65ac
DL
490;;; do (e.g., the cd command in ftp). In shells that allow you job
491;;; control, you can switch between jobs, all having different w.d.'s. So
492;;; simply saying %3 can shift your w.d..
493;;;
494;;; The solution is to relax, not stress out about it, and settle for
495;;; a hack that works pretty well in typical circumstances. Remember
496;;; that a half-assed solution is more in keeping with the spirit of Unix,
497;;; anyway. Blech.
498;;;
499;;; One good hack not implemented here for users of programmable shells
500;;; is to program up the shell w.d. manipulation commands to output
501;;; a coded command sequence to the tty. Something like
502;;; ESC | <cwd> |
503;;; where <cwd> is the new current working directory. Then trash the
504;;; directory tracking machinery currently used in this package, and
505;;; replace it with a process filter that watches for and strips out
506;;; these messages.
507
be9b65ac
DL
508(defun shell-directory-tracker (str)
509 "Tracks cd, pushd and popd commands issued to the shell.
510This function is called on each input passed to the shell.
511It watches for cd, pushd and popd commands and sets the buffer's
512default directory to track these commands.
513
514You may toggle this tracking on and off with M-x dirtrack-toggle.
515If emacs gets confused, you can resync with the shell with M-x dirs.
516
32d01212
RS
517See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
518and `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract',
519and `shell-pushd-dunique' control the behavior of the relevant command.
d76b71af 520
24fdffaa 521Environment variables are expanded, see function `substitute-in-file-name'."
d76b71af
RS
522 (if shell-dirtrackp
523 ;; We fail gracefully if we think the command will fail in the shell.
524 (condition-case chdir-failure
54021695 525 (let ((start (progn (string-match "^[; \t]*" str) ; skip whitespace
d76b71af
RS
526 (match-end 0)))
527 end cmd arg1)
528 (while (string-match shell-command-regexp str start)
529 (setq end (match-end 0)
530 cmd (comint-arguments (substring str start end) 0 0)
531 arg1 (comint-arguments (substring str start end) 1 1))
54021695
KH
532 (cond ((string-match (concat "\\`\\(" shell-popd-regexp
533 "\\)\\($\\|[ \t]\\)")
534 cmd)
32d01212 535 (shell-process-popd (comint-substitute-in-file-name arg1)))
54021695
KH
536 ((string-match (concat "\\`\\(" shell-pushd-regexp
537 "\\)\\($\\|[ \t]\\)")
538 cmd)
32d01212 539 (shell-process-pushd (comint-substitute-in-file-name arg1)))
54021695
KH
540 ((string-match (concat "\\`\\(" shell-cd-regexp
541 "\\)\\($\\|[ \t]\\)")
542 cmd)
32d01212
RS
543 (shell-process-cd (comint-substitute-in-file-name arg1)))
544 ((and shell-chdrive-regexp
545 (string-match (concat "\\`\\(" shell-chdrive-regexp
546 "\\)\\($\\|[ \t]\\)")
547 cmd))
548 (shell-process-cd (comint-substitute-in-file-name cmd))))
54021695 549 (setq start (progn (string-match "[; \t]*" str end) ; skip again
d76b71af 550 (match-end 0)))))
ba02c167 551 (error "Couldn't cd"))))
d76b71af 552
be9b65ac
DL
553;;; popd [+n]
554(defun shell-process-popd (arg)
d76b71af
RS
555 (let ((num (or (shell-extract-num arg) 0)))
556 (cond ((and num (= num 0) shell-dirstack)
0b3c9cf1 557 (shell-cd (car shell-dirstack))
d76b71af
RS
558 (setq shell-dirstack (cdr shell-dirstack))
559 (shell-dirstack-message))
560 ((and num (> num 0) (<= num (length shell-dirstack)))
561 (let* ((ds (cons nil shell-dirstack))
562 (cell (nthcdr (1- num) ds)))
563 (rplacd cell (cdr (cdr cell)))
564 (setq shell-dirstack (cdr ds))
565 (shell-dirstack-message)))
566 (t
ba02c167 567 (error "Couldn't popd")))))
be9b65ac 568
3db9a4eb 569;; Return DIR prefixed with comint-file-name-prefix as appropriate.
4a02b552
RS
570(defun shell-prefixed-directory-name (dir)
571 (if (= (length comint-file-name-prefix) 0)
572 dir
573 (if (file-name-absolute-p dir)
574 ;; The name is absolute, so prepend the prefix.
575 (concat comint-file-name-prefix dir)
0b3c9cf1 576 ;; For relative name we assume default-directory already has the prefix.
4a02b552 577 (expand-file-name dir))))
3db9a4eb 578
be9b65ac
DL
579;;; cd [dir]
580(defun shell-process-cd (arg)
3db9a4eb
RM
581 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
582 "~"))
d76b71af 583 ((string-equal "-" arg) shell-last-dir)
3db9a4eb 584 (t (shell-prefixed-directory-name arg)))))
d76b71af 585 (setq shell-last-dir default-directory)
0b3c9cf1 586 (shell-cd new-dir)
d76b71af 587 (shell-dirstack-message)))
be9b65ac
DL
588
589;;; pushd [+n | dir]
590(defun shell-process-pushd (arg)
d76b71af
RS
591 (let ((num (shell-extract-num arg)))
592 (cond ((zerop (length arg))
593 ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
594 (cond (shell-pushd-tohome
3db9a4eb 595 (shell-process-pushd (concat comint-file-name-prefix "~")))
d76b71af
RS
596 (shell-dirstack
597 (let ((old default-directory))
0b3c9cf1 598 (shell-cd (car shell-dirstack))
221ca406 599 (setq shell-dirstack (cons old (cdr shell-dirstack)))
d76b71af
RS
600 (shell-dirstack-message)))
601 (t
602 (message "Directory stack empty."))))
603 ((numberp num)
604 ;; pushd +n
605 (cond ((> num (length shell-dirstack))
606 (message "Directory stack not that deep."))
607 ((= num 0)
608 (error (message "Couldn't cd.")))
609 (shell-pushd-dextract
610 (let ((dir (nth (1- num) shell-dirstack)))
611 (shell-process-popd arg)
612 (shell-process-pushd default-directory)
0b3c9cf1 613 (shell-cd dir)
d76b71af
RS
614 (shell-dirstack-message)))
615 (t
616 (let* ((ds (cons default-directory shell-dirstack))
617 (dslen (length ds))
618 (front (nthcdr num ds))
619 (back (reverse (nthcdr (- dslen num) (reverse ds))))
620 (new-ds (append front back)))
0b3c9cf1 621 (shell-cd (car new-ds))
d76b71af
RS
622 (setq shell-dirstack (cdr new-ds))
623 (shell-dirstack-message)))))
624 (t
625 ;; pushd <dir>
626 (let ((old-wd default-directory))
0b3c9cf1 627 (shell-cd (shell-prefixed-directory-name arg))
d76b71af
RS
628 (if (or (null shell-pushd-dunique)
629 (not (member old-wd shell-dirstack)))
630 (setq shell-dirstack (cons old-wd shell-dirstack)))
631 (shell-dirstack-message))))))
be9b65ac
DL
632
633;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
634(defun shell-extract-num (str)
635 (and (string-match "^\\+[1-9][0-9]*$" str)
636 (string-to-int str)))
637
638
639(defun shell-dirtrack-toggle ()
640 "Turn directory tracking on and off in a shell buffer."
641 (interactive)
0b3c9cf1
SM
642 (if (setq shell-dirtrackp (not shell-dirtrackp))
643 (setq list-buffers-directory default-directory)
644 (setq list-buffers-directory nil))
d76b71af 645 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
be9b65ac
DL
646
647;;; For your typing convenience:
31e1d920 648(defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
be9b65ac 649
0b3c9cf1
SM
650(defun shell-cd (dir)
651 "Do normal `cd' to DIR, and set `list-buffers-directory'."
b7e97ed5
SM
652 (if shell-dirtrackp
653 (setq list-buffers-directory (file-name-as-directory
654 (expand-file-name dir))))
0b3c9cf1 655 (cd dir))
be9b65ac
DL
656
657(defun shell-resync-dirs ()
658 "Resync the buffer's idea of the current directory stack.
659This command queries the shell with the command bound to
24fdffaa 660`shell-dirstack-query' (default \"dirs\"), reads the next
be9b65ac
DL
661line output and parses it to form the new directory stack.
662DON'T issue this command unless the buffer is at a shell prompt.
663Also, note that if some other subprocess decides to do output
664immediately after the query, its output will be taken as the
665new directory stack -- you lose. If this happens, just do the
666command again."
667 (interactive)
668 (let* ((proc (get-buffer-process (current-buffer)))
669 (pmark (process-mark proc)))
670 (goto-char pmark)
671 (insert shell-dirstack-query) (insert "\n")
672 (sit-for 0) ; force redisplay
673 (comint-send-string proc shell-dirstack-query)
674 (comint-send-string proc "\n")
675 (set-marker pmark (point))
676 (let ((pt (point))) ; wait for 1 line
677 ;; This extra newline prevents the user's pending input from spoofing us.
678 (insert "\n") (backward-char 1)
679 (while (not (looking-at ".+\n"))
680 (accept-process-output proc)
681 (goto-char pt)))
682 (goto-char pmark) (delete-char 1) ; remove the extra newline
683 ;; That's the dirlist. grab it & parse it.
d76b71af 684 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
be9b65ac
DL
685 (dl-len (length dl))
686 (ds '()) ; new dir stack
687 (i 0))
688 (while (< i dl-len)
689 ;; regexp = optional whitespace, (non-whitespace), optional whitespace
690 (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
3db9a4eb
RM
691 (setq ds (cons (concat comint-file-name-prefix
692 (substring dl (match-beginning 1)
693 (match-end 1)))
be9b65ac
DL
694 ds))
695 (setq i (match-end 0)))
3db9a4eb 696 (let ((ds (nreverse ds)))
be9b65ac 697 (condition-case nil
0b3c9cf1 698 (progn (shell-cd (car ds))
221ca406
SM
699 (setq shell-dirstack (cdr ds)
700 shell-last-dir (car shell-dirstack))
be9b65ac
DL
701 (shell-dirstack-message))
702 (error (message "Couldn't cd.")))))))
703
704;;; For your typing convenience:
31e1d920 705(defalias 'dirs 'shell-resync-dirs)
be9b65ac
DL
706
707
708;;; Show the current dirstack on the message line.
709;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
710;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
711;;; All the commands that mung the buffer's dirstack finish by calling
712;;; this guy.
713(defun shell-dirstack-message ()
94f9dcbe
RM
714 (let* ((msg "")
715 (ds (cons default-directory shell-dirstack))
d76b71af 716 (home (expand-file-name (concat comint-file-name-prefix "~/")))
94f9dcbe 717 (homelen (length home)))
be9b65ac
DL
718 (while ds
719 (let ((dir (car ds)))
94f9dcbe
RM
720 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
721 (setq dir (concat "~/" (substring dir homelen))))
d76b71af
RS
722 ;; Strip off comint-file-name-prefix if present.
723 (and comint-file-name-prefix
724 (>= (length dir) (length comint-file-name-prefix))
725 (string= comint-file-name-prefix
726 (substring dir 0 (length comint-file-name-prefix)))
727 (setq dir (substring dir (length comint-file-name-prefix)))
94f9dcbe 728 (setcar ds dir))
d76b71af 729 (setq msg (concat msg (directory-file-name dir) " "))
be9b65ac 730 (setq ds (cdr ds))))
6048fac7 731 (message "%s" msg)))
a9ec2adb 732\f
d76b71af
RS
733(defun shell-forward-command (&optional arg)
734 "Move forward across ARG shell command(s). Does not cross lines.
735See `shell-command-regexp'."
736 (interactive "p")
737 (let ((limit (save-excursion (end-of-line nil) (point))))
19134c18 738 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
d76b71af 739 limit 'move arg)
b0f86743 740 (skip-syntax-backward " "))))
d76b71af
RS
741
742
743(defun shell-backward-command (&optional arg)
744 "Move backward across ARG shell command(s). Does not cross lines.
745See `shell-command-regexp'."
746 (interactive "p")
747 (let ((limit (save-excursion (comint-bol nil) (point))))
b0f86743
RS
748 (if (> limit (point))
749 (save-excursion (beginning-of-line) (setq limit (point))))
750 (skip-syntax-backward " " limit)
d76b71af 751 (if (re-search-backward
19134c18 752 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
d76b71af 753 (progn (goto-char (match-beginning 1))
b0f86743 754 (skip-chars-forward ";&|")))))
d76b71af
RS
755
756
d76b71af
RS
757(defun shell-dynamic-complete-command ()
758 "Dynamically complete the command at point.
759This function is similar to `comint-dynamic-complete-filename', except that it
760searches `exec-path' (minus the trailing emacs library path) for completion
761candidates. Note that this may not be the same as the shell's idea of the
762path.
763
764Completion is dependent on the value of `shell-completion-execonly', plus
988a4d60
RS
765those that effect file completion. See `shell-dynamic-complete-as-command'.
766
767Returns t if successful."
d76b71af 768 (interactive)
988a4d60
RS
769 (let ((filename (comint-match-partial-filename)))
770 (if (and filename
771 (save-match-data (not (string-match "[~/]" filename)))
772 (eq (match-beginning 0)
773 (save-excursion (shell-backward-command 1) (point))))
774 (prog2 (message "Completing command name...")
775 (shell-dynamic-complete-as-command)))))
776
777
778(defun shell-dynamic-complete-as-command ()
779 "Dynamically complete at point as a command.
780See `shell-dynamic-complete-filename'. Returns t if successful."
56783585 781 (let* ((filename (or (comint-match-partial-filename) ""))
d76b71af
RS
782 (pathnondir (file-name-nondirectory filename))
783 (paths (cdr (reverse exec-path)))
784 (cwd (file-name-as-directory (expand-file-name default-directory)))
785 (ignored-extensions
a867a90a
RS
786 (and comint-completion-fignore
787 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
788 comint-completion-fignore "\\|")))
d76b71af
RS
789 (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
790 ;; Go thru each path in the search path, finding completions.
791 (while paths
792 (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
793 comps-in-path (and (file-accessible-directory-p path)
794 (file-name-all-completions pathnondir path)))
795 ;; Go thru each completion found, to see whether it should be used.
796 (while comps-in-path
797 (setq file (car comps-in-path)
798 filepath (concat path file))
799 (if (and (not (member file completions))
7b2db0a0
KH
800 (not (and ignored-extensions
801 (string-match ignored-extensions file)))
d76b71af
RS
802 (or (string-equal path cwd)
803 (not (file-directory-p filepath)))
804 (or (null shell-completion-execonly)
805 (file-executable-p filepath)))
806 (setq completions (cons file completions)))
807 (setq comps-in-path (cdr comps-in-path)))
808 (setq paths (cdr paths)))
809 ;; OK, we've got a list of completions.
56783585
RS
810 (let ((success (let ((comint-completion-addsuffix nil))
811 (comint-dynamic-simple-complete pathnondir completions))))
812 (if (and (memq success '(sole shortest)) comint-completion-addsuffix
813 (not (file-directory-p (comint-match-partial-filename))))
814 (insert " "))
815 success)))
988a4d60
RS
816
817
818(defun shell-match-partial-variable ()
da6a48c9 819 "Return the shell variable at point, or nil if none is found."
988a4d60
RS
820 (save-excursion
821 (let ((limit (point)))
822 (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
823 (or (looking-at "\\$") (forward-char 1)))
824 ;; Anchor the search forwards.
825 (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
826 nil
827 (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
828 (buffer-substring (match-beginning 0) (match-end 0))))))
a9ec2adb 829
988a4d60
RS
830
831(defun shell-dynamic-complete-environment-variable ()
832 "Dynamically complete the environment variable at point.
833Completes if after a variable, i.e., if it starts with a \"$\".
834See `shell-dynamic-complete-as-environment-variable'.
835
836This function is similar to `comint-dynamic-complete-filename', except that it
837searches `process-environment' for completion candidates. Note that this may
838not be the same as the interpreter's idea of variable names. The main problem
839with this type of completion is that `process-environment' is the environment
840which Emacs started with. Emacs does not track changes to the environment made
841by the interpreter. Perhaps it would be more accurate if this function was
842called `shell-dynamic-complete-process-environment-variable'.
843
844Returns non-nil if successful."
845 (interactive)
846 (let ((variable (shell-match-partial-variable)))
847 (if (and variable (string-match "^\\$" variable))
848 (prog2 (message "Completing variable name...")
849 (shell-dynamic-complete-as-environment-variable)))))
850
851
852(defun shell-dynamic-complete-as-environment-variable ()
853 "Dynamically complete at point as an environment variable.
854Used by `shell-dynamic-complete-environment-variable'.
855Uses `comint-dynamic-simple-complete'."
856 (let* ((var (or (shell-match-partial-variable) ""))
857 (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
858 (variables (mapcar (function (lambda (x)
859 (substring x 0 (string-match "=" x))))
860 process-environment))
861 (addsuffix comint-completion-addsuffix)
862 (comint-completion-addsuffix nil)
863 (success (comint-dynamic-simple-complete variable variables)))
864 (if (memq success '(sole shortest))
865 (let* ((var (shell-match-partial-variable))
866 (variable (substring var (string-match "[^$({]" var)))
867 (protection (cond ((string-match "{" var) "}")
868 ((string-match "(" var) ")")
869 (t "")))
870 (suffix (cond ((null addsuffix) "")
871 ((file-directory-p
872 (comint-directory (getenv variable))) "/")
873 (t " "))))
874 (insert protection suffix)))
875 success))
876
877
878(defun shell-replace-by-expanded-directory ()
879 "Expand directory stack reference before point.
880Directory stack references are of the form \"=digit\" or \"=-\".
881See `default-directory' and `shell-dirstack'.
882
883Returns t if successful."
884 (interactive)
885 (if (comint-match-partial-filename)
886 (save-excursion
988a4d60
RS
887 (goto-char (match-beginning 0))
888 (let ((stack (cons default-directory shell-dirstack))
889 (index (cond ((looking-at "=-/?")
890 (length shell-dirstack))
891 ((looking-at "=\\([0-9]+\\)")
892 (string-to-number
893 (buffer-substring
894 (match-beginning 1) (match-end 1)))))))
895 (cond ((null index)
896 nil)
897 ((>= index (length stack))
898 (error "Directory stack not that deep."))
899 (t
900 (replace-match (file-name-as-directory (nth index stack)) t t)
901 (message "Directory item: %d" index)
902 t))))))
903\f
c88ab9ce
ER
904(provide 'shell)
905
906;;; shell.el ends here