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