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