]> code.delx.au - gnu-emacs/blob - lisp/shell.el
Add % to comint-match-partial-filename.
[gnu-emacs] / lisp / shell.el
1 ;;; shell.el --- specialized comint.el for running the shell.
2
3 ;; Copyright (C) 1988, 1993, 1994 Free Software Foundation, Inc.
4
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
6 ;; Maintainer: Simon Marshall <simon@gnu.ai.mit.edu>
7 ;; Keywords: processes
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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.
24
25 ;;; Commentary:
26
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)
30 ;;; - Simon Marshall (simon@gnu.ai.mit.edu)
31
32 ;;; This file defines a a shell-in-a-buffer package (shell mode) built
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.
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.
40 ;;; This makes these modes easier to use.
41
42 ;;; For documentation on the functionality provided by comint mode, and
43 ;;; the hooks available for customising it, see the file comint.el.
44 ;;; For further information on shell mode, see the comments below.
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
52 ;; YOUR .EMACS FILE
53 ;;=============================================================================
54 ;; Some suggestions for your .emacs file.
55 ;;
56 ;; ;; Define C-c t to run my favorite command in shell mode:
57 ;; (setq shell-mode-hook
58 ;; '((lambda ()
59 ;; (define-key shell-mode-map "\C-ct" 'favorite-cmd))))
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
68 ;;; m-r comint-previous-matching-input Previous input matching a regexp
69 ;;; m-s comint-next-matching-input Next input that matches
70 ;;; m-c-l comint-show-output Show last batch of process output
71 ;;; return comint-send-input
72 ;;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
73 ;;; c-c c-a comint-bol Beginning of line; skip prompt
74 ;;; c-c c-u comint-kill-input ^u
75 ;;; c-c c-w backward-kill-word ^w
76 ;;; c-c c-c comint-interrupt-subjob ^c
77 ;;; c-c c-z comint-stop-subjob ^z
78 ;;; c-c c-\ comint-quit-subjob ^\
79 ;;; c-c c-o comint-kill-output Delete last batch of process output
80 ;;; c-c c-r comint-show-output Show last batch of process output
81 ;;; c-c c-h comint-dynamic-list-input-ring List input history
82 ;;; send-invisible Read line w/o echo & send to proc
83 ;;; comint-continue-subjob Useful if you accidentally suspend
84 ;;; top-level job
85 ;;; comint-mode-hook is the comint mode hook.
86
87 ;;; Shell Mode Commands:
88 ;;; shell Fires up the shell process
89 ;;; tab comint-dynamic-complete Complete filename/command/history
90 ;;; m-? comint-dynamic-list-filename-completions 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
95 ;;; shell-strip-ctrl-m Remove trailing ^Ms from output
96 ;;;
97 ;;; The shell mode hook is shell-mode-hook
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
103 ;;; Customization and Buffer Variables
104 ;;; ===========================================================================
105 ;;;
106
107 ;;; Code:
108
109 (require 'comint)
110
111 ;;;###autoload
112 (defvar shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
113 "Regexp to match prompts in the inferior shell.
114 Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
115 This variable is used to initialise `comint-prompt-regexp' in the
116 shell buffer.
117
118 The pattern should probably not match more than one line. If it does,
119 shell-mode may become confused trying to distinguish prompt from input
120 on lines which don't start with a prompt.
121
122 This is a fine thing to set in your `.emacs' file.")
123
124 (defvar shell-completion-fignore nil
125 "*List of suffixes to be disregarded during file/command completion.
126 This variable is used to initialize `comint-completion-fignore' in the shell
127 buffer. The default is nil, for compatibility with most shells.
128 Some people like (\"~\" \"#\" \"%\").
129
130 This is a fine thing to set in your `.emacs' file.")
131
132 (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
133 "List of characters to recognise as separate arguments.
134 This variable is used to initialize `comint-delimiter-argument-list' in the
135 shell buffer. The default is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
136
137 This is a fine thing to set in your `.emacs' file.")
138
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.
146 This variable is used to initialise `comint-dynamic-complete-functions' in the
147 shell buffer.
148
149 This is a fine thing to set in your `.emacs' file.")
150
151 (defvar shell-command-regexp "[^;&|\n]+"
152 "*Regexp to match a single command within a pipeline.
153 This is used for directory tracking and does not do a perfect job.")
154
155 (defvar shell-completion-execonly t
156 "*If non-nil, use executable files only for completion candidates.
157 This mirrors the optional behavior of tcsh.
158
159 Detecting executability of files may slow command completion considerably.")
160
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
167 (defvar shell-pushd-tohome nil
168 "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
169 This mirrors the optional behavior of tcsh.")
170
171 (defvar shell-pushd-dextract nil
172 "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
173 This mirrors the optional behavior of tcsh.")
174
175 (defvar shell-pushd-dunique nil
176 "*If non-nil, make pushd only add unique directories to the stack.
177 This mirrors the optional behavior of tcsh.")
178
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.
192 Value is a list of strings, which may be nil.")
193
194 (defvar shell-input-autoexpand 'history
195 "*If non-nil, expand input command history references on completion.
196 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
197
198 If the value is `input', then the expansion is seen on input.
199 If the value is `history', then the expansion is only when inserting
200 into the buffer's input ring. See also `comint-magic-space' and
201 `comint-dynamic-complete'.
202
203 This variable supplies a default for `comint-input-autoexpand',
204 for Shell mode only.")
205
206 (defvar shell-dirstack nil
207 "List of directories saved by pushd in this buffer's shell.
208 Thus, this does not include the shell's current directory.")
209
210 (defvar shell-dirtrackp t
211 "Non-nil in a shell buffer means directory tracking is enabled.")
212
213 (defvar shell-last-dir nil
214 "Keep track of last directory for ksh `cd -' command.")
215
216 (defvar shell-dirstack-query nil
217 "Command used by `shell-resync-dir' to query the shell.")
218
219 (defvar shell-mode-map nil)
220 (cond ((not shell-mode-map)
221 (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
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)
224 (define-key shell-mode-map "\t" 'comint-dynamic-complete)
225 (define-key shell-mode-map "\M-?"
226 'comint-dynamic-list-filename-completions)
227 (define-key shell-mode-map [menu-bar completion]
228 (copy-keymap (lookup-key comint-mode-map [menu-bar completion])))
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)))
237
238 (defvar shell-mode-hook '()
239 "*Hook for customising Shell mode.")
240
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)
244 '("^[^ \t\n]+:.*$" . font-lock-string-face)
245 '("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
246 "Additional expressions to highlight in Shell mode.")
247 \f
248 ;;; Basic Procedures
249 ;;; ===========================================================================
250 ;;;
251
252 (defun shell-mode ()
253 "Major mode for interacting with an inferior shell.
254 Return after the end of the process' output sends the text from the
255 end of process to the end of the current line.
256 Return before end of process output copies the current line (except
257 for the prompt) to the end of the buffer and sends it.
258 \\[send-invisible] reads a line of text without echoing it, and sends it to
259 the shell. This is useful for entering passwords. Or, add the function
260 `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
261
262 If you want to make multiple shell buffers, rename the `*shell*' buffer
263 using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
264
265 If you accidentally suspend your process, use \\[comint-continue-subjob]
266 to continue it.
267
268 `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
269 keep 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
271 directory stack is.
272 \\[dirtrack-toggle] turns directory tracking on and off.
273
274 \\{shell-mode-map}
275 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
276 `shell-mode-hook' (in that order). Before each input, the hooks on
277 `comint-input-filter-functions' are run. After each shell output, the hooks
278 on `comint-output-filter-functions' are run.
279
280 Variables `shell-cd-regexp', `shell-pushd-regexp' and `shell-popd-regexp'
281 are used to match their respective commands, while `shell-pushd-tohome',
282 `shell-pushd-dextract' and `shell-pushd-dunique' control the behavior of the
283 relevant command.
284
285 Variables `comint-completion-autolist', `comint-completion-addsuffix',
286 `comint-completion-recexact' and `comint-completion-fignore' control the
287 behavior of file name, command name and variable name completion. Variable
288 `shell-completion-execonly' controls the behavior of command name completion.
289 Variable `shell-completion-fignore' is used to initialise the value of
290 `comint-completion-fignore'.
291
292 Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
293 the initialisation of the input ring history, and history expansion.
294
295 Variables `comint-output-filter-functions', a hook, and
296 `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
297 control whether input and output cause the window to scroll to the end of the
298 buffer."
299 (interactive)
300 (comint-mode)
301 (setq major-mode 'shell-mode)
302 (setq mode-name "Shell")
303 (use-local-map shell-mode-map)
304 (setq comint-prompt-regexp shell-prompt-pattern)
305 (setq comint-completion-fignore shell-completion-fignore)
306 (setq comint-delimiter-argument-list shell-delimiter-argument-list)
307 (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
308 (make-local-variable 'paragraph-start)
309 (setq paragraph-start comint-prompt-regexp)
310 (make-local-variable 'font-lock-defaults)
311 (setq font-lock-defaults '(shell-font-lock-keywords t))
312 (make-local-variable 'shell-dirstack)
313 (setq shell-dirstack nil)
314 (setq shell-last-dir nil)
315 (make-local-variable 'shell-dirtrackp)
316 (setq shell-dirtrackp t)
317 (add-hook 'comint-input-filter-functions 'shell-directory-tracker)
318 (setq comint-input-autoexpand shell-input-autoexpand)
319 ;; shell-dependent assignments.
320 (let ((shell (file-name-nondirectory (car
321 (process-command (get-buffer-process (current-buffer)))))))
322 (setq comint-input-ring-file-name
323 (or (getenv "HISTFILE")
324 (cond ((string-equal shell "bash") "~/.bash_history")
325 ((string-equal shell "ksh") "~/.sh_history")
326 (t "~/.history"))))
327 (if (equal (file-truename comint-input-ring-file-name) "/dev/null")
328 (setq comint-input-ring-file-name nil))
329 (setq shell-dirstack-query
330 (if (string-match "^k?sh$" shell) "pwd" "dirs")))
331 (run-hooks 'shell-mode-hook)
332 (comint-read-input-ring t))
333 \f
334 ;;;###autoload
335 (defun shell ()
336 "Run an inferior shell, with I/O through buffer *shell*.
337 If buffer exists but shell process is not running, make new shell.
338 If buffer exists and shell process is running, just switch to buffer `*shell*'.
339 Program used comes from variable `explicit-shell-file-name',
340 or (if that is nil) from the ESHELL environment variable,
341 or else from SHELL if there is no ESHELL.
342 If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
343 (Note that this may lose due to a timing error if the shell
344 discards input when it starts up.)
345 The buffer is put in Shell mode, giving commands for sending input
346 and controlling the subjobs of the shell. See `shell-mode'.
347 See also the variable `shell-prompt-pattern'.
348
349 The shell file name (sans directories) is used to make a symbol name
350 such as `explicit-csh-args'. If that symbol is a variable,
351 its value is used as a list of arguments when invoking the shell.
352 Otherwise, one argument `-i' is passed to the shell.
353
354 \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
355 (interactive)
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"))))
369 (shell-mode)
370 (switch-to-buffer (current-buffer)))
371 (switch-to-buffer "*shell*")))
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
381 ;;; the version in Emacs 18's shell.el. It has the following failings:
382 ;;; 1. It doesn't know about the cdpath shell variable.
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.
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
394 ;;; commands that do *not* affect the current w.d. at all, but look like they
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
413 (defun shell-directory-tracker (str)
414 "Tracks cd, pushd and popd commands issued to the shell.
415 This function is called on each input passed to the shell.
416 It watches for cd, pushd and popd commands and sets the buffer's
417 default directory to track these commands.
418
419 You may toggle this tracking on and off with M-x dirtrack-toggle.
420 If emacs gets confused, you can resync with the shell with M-x dirs.
421
422 See variables `shell-cd-regexp', `shell-pushd-regexp', and `shell-popd-regexp',
423 while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique'
424 control the behavior of the relevant command.
425
426 Environment variables are expanded, see function `substitute-in-file-name'."
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)))))
445 (error "Couldn't cd"))))
446
447 ;;; popd [+n]
448 (defun shell-process-popd (arg)
449 (let ((num (or (shell-extract-num arg) 0)))
450 (cond ((and num (= num 0) shell-dirstack)
451 (cd (car shell-dirstack))
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
461 (error "Couldn't popd")))))
462
463 ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
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))))
472
473 ;;; cd [dir]
474 (defun shell-process-cd (arg)
475 (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
476 "~"))
477 ((string-equal "-" arg) shell-last-dir)
478 (t (shell-prefixed-directory-name arg)))))
479 (setq shell-last-dir default-directory)
480 (cd new-dir)
481 (shell-dirstack-message)))
482
483 ;;; pushd [+n | dir]
484 (defun shell-process-pushd (arg)
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
489 (shell-process-pushd (concat comint-file-name-prefix "~")))
490 (shell-dirstack
491 (let ((old default-directory))
492 (cd (car shell-dirstack))
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)
508 (cd dir)
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)))
516 (cd (car new-ds))
517 (setq shell-dirstack (cdr new-ds))
518 (shell-dirstack-message)))))
519 (t
520 ;; pushd <dir>
521 (let ((old-wd default-directory))
522 (cd (shell-prefixed-directory-name arg))
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))))))
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))
538 (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
539
540 ;;; For your typing convenience:
541 (defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
542
543
544 (defun shell-resync-dirs ()
545 "Resync the buffer's idea of the current directory stack.
546 This command queries the shell with the command bound to
547 `shell-dirstack-query' (default \"dirs\"), reads the next
548 line output and parses it to form the new directory stack.
549 DON'T issue this command unless the buffer is at a shell prompt.
550 Also, note that if some other subprocess decides to do output
551 immediately after the query, its output will be taken as the
552 new directory stack -- you lose. If this happens, just do the
553 command 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.
571 (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
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
578 (setq ds (cons (concat comint-file-name-prefix
579 (substring dl (match-beginning 1)
580 (match-end 1)))
581 ds))
582 (setq i (match-end 0)))
583 (let ((ds (nreverse ds)))
584 (condition-case nil
585 (progn (cd (car ds))
586 (setq shell-dirstack (cdr ds))
587 (shell-dirstack-message))
588 (error (message "Couldn't cd.")))))))
589
590 ;;; For your typing convenience:
591 (defalias 'dirs 'shell-resync-dirs)
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 ()
600 (let* ((msg "")
601 (ds (cons default-directory shell-dirstack))
602 (home (expand-file-name (concat comint-file-name-prefix "~/")))
603 (homelen (length home)))
604 (while ds
605 (let ((dir (car ds)))
606 (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
607 (setq dir (concat "~/" (substring dir homelen))))
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)))
614 (setcar ds dir))
615 (setq msg (concat msg (directory-file-name dir) " "))
616 (setq ds (cdr ds))))
617 (message msg)))
618 \f
619 (defun shell-forward-command (&optional arg)
620 "Move forward across ARG shell command(s). Does not cross lines.
621 See `shell-command-regexp'."
622 (interactive "p")
623 (let ((limit (save-excursion (end-of-line nil) (point))))
624 (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
625 limit 'move arg)
626 (skip-syntax-backward " "))))
627
628
629 (defun shell-backward-command (&optional arg)
630 "Move backward across ARG shell command(s). Does not cross lines.
631 See `shell-command-regexp'."
632 (interactive "p")
633 (let ((limit (save-excursion (comint-bol nil) (point))))
634 (if (> limit (point))
635 (save-excursion (beginning-of-line) (setq limit (point))))
636 (skip-syntax-backward " " limit)
637 (if (re-search-backward
638 (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
639 (progn (goto-char (match-beginning 1))
640 (skip-chars-forward ";&|")))))
641
642
643 (defun shell-dynamic-complete-command ()
644 "Dynamically complete the command at point.
645 This function is similar to `comint-dynamic-complete-filename', except that it
646 searches `exec-path' (minus the trailing emacs library path) for completion
647 candidates. Note that this may not be the same as the shell's idea of the
648 path.
649
650 Completion is dependent on the value of `shell-completion-execonly', plus
651 those that effect file completion. See `shell-dynamic-complete-as-command'.
652
653 Returns t if successful."
654 (interactive)
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.
666 See `shell-dynamic-complete-filename'. Returns t if successful."
667 (let* ((filename (or (comint-match-partial-filename) ""))
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
672 (and comint-completion-fignore
673 (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
674 comint-completion-fignore "\\|")))
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))
686 (not (and ignored-extensions
687 (string-match ignored-extensions file)))
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.
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)))
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))))))
715
716
717 (defun shell-dynamic-complete-environment-variable ()
718 "Dynamically complete the environment variable at point.
719 Completes if after a variable, i.e., if it starts with a \"$\".
720 See `shell-dynamic-complete-as-environment-variable'.
721
722 This function is similar to `comint-dynamic-complete-filename', except that it
723 searches `process-environment' for completion candidates. Note that this may
724 not be the same as the interpreter's idea of variable names. The main problem
725 with this type of completion is that `process-environment' is the environment
726 which Emacs started with. Emacs does not track changes to the environment made
727 by the interpreter. Perhaps it would be more accurate if this function was
728 called `shell-dynamic-complete-process-environment-variable'.
729
730 Returns 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.
740 Used by `shell-dynamic-complete-environment-variable'.
741 Uses `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.
766 Directory stack references are of the form \"=digit\" or \"=-\".
767 See `default-directory' and `shell-dirstack'.
768
769 Returns t if successful."
770 (interactive)
771 (if (comint-match-partial-filename)
772 (save-excursion
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
790 (provide 'shell)
791
792 ;;; shell.el ends here