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