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