*** empty log message ***
[bpt/emacs.git] / lisp / comint.el
CommitLineData
c0274f38
ER
1;;; comint.el --- general command interpreter in a window stuff
2
49116ac0 3;;; Copyright Olin Shivers (1988).
be9b65ac
DL
4
5;;; This file is part of GNU Emacs.
6
7;;; GNU Emacs is free software; you can redistribute it and/or modify
8;;; it under the terms of the GNU General Public License as published by
9;;; the Free Software Foundation; either version 1, or (at your option)
10;;; any later version.
11
12;;; GNU Emacs is distributed in the hope that it will be useful,
13;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15;;; GNU General Public License for more details.
16
17;;; You should have received a copy of the GNU General Public License
18;;; along with GNU Emacs; see the file COPYING. If not, write to
19;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
20
49116ac0
JB
21;;; The changelog is at the end of this file.
22
23;;; Please send me bug reports, bug fixes, and extensions, so that I can
24;;; merge them into the master source.
25;;; - Olin Shivers (shivers@cs.cmu.edu)
26
be9b65ac
DL
27;;; This file defines a general command-interpreter-in-a-buffer package
28;;; (comint mode). The idea is that you can build specific process-in-a-buffer
29;;; modes on top of comint mode -- e.g., lisp, shell, scheme, T, soar, ....
30;;; This way, all these specific packages share a common base functionality,
31;;; and a common set of bindings, which makes them easier to use (and
32;;; saves code, implementation time, etc., etc.).
33
49116ac0
JB
34;;; Several packages are already defined using comint mode:
35;;; - cmushell.el defines a shell-in-a-buffer mode.
36;;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
37;;; Cmushell and cmulisp mode are similar to, and intended to replace,
38;;; their counterparts in the standard gnu emacs release (in shell.el).
39;;; These replacements are more featureful, robust, and uniform than the
40;;; released versions. The key bindings in lisp mode are also more compatible
41;;; with the bindings of Hemlock and Zwei (the Lisp Machine emacs).
42;;;
43;;; - The file cmuscheme.el defines a scheme-in-a-buffer mode.
44;;; - The file tea.el tunes scheme and inferior-scheme modes for T.
45;;; - The file soar.el tunes lisp and inferior-lisp modes for Soar.
46;;; - cmutex.el defines tex and latex modes that invoke tex, latex, bibtex,
47;;; previewers, and printers from within emacs.
48;;; - background.el allows csh-like job control inside emacs.
49;;; It is pretty easy to make new derived modes for other processes.
50
be9b65ac
DL
51;;; For documentation on the functionality provided by comint mode, and
52;;; the hooks available for customising it, see the comments below.
53;;; For further information on the standard derived modes (shell,
54;;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
55
49116ac0
JB
56;;; For hints on converting existing process modes (e.g., tex-mode,
57;;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
be9b65ac
DL
58;;; instead of shell-mode, see the notes at the end of this file.
59
87ef29fd 60(defconst comint-version "2.03")
be9b65ac
DL
61
62\f
49116ac0
JB
63;;; Brief Command Documentation:
64;;;============================================================================
65;;; Comint Mode Commands: (common to all derived modes, like cmushell & cmulisp
66;;; mode)
67;;;
68;;; m-p comint-previous-input Cycle backwards in input history
69;;; m-n comint-next-input Cycle forwards
70;;; m-s comint-previous-similar-input Previous similar input
87ef29fd 71;;; c-m-r comint-previous-input-matching Search backwards in input history
49116ac0
JB
72;;; return comint-send-input
73;;; c-a comint-bol Beginning of line; skip prompt.
74;;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff.
75;;; c-c c-u comint-kill-input ^u
76;;; c-c c-w backward-kill-word ^w
77;;; c-c c-c comint-interrupt-subjob ^c
78;;; c-c c-z comint-stop-subjob ^z
79;;; c-c c-\ comint-quit-subjob ^\
80;;; c-c c-o comint-kill-output Delete last batch of process output
81;;; c-c c-r comint-show-output Show last batch of process output
82;;;
be9b65ac
DL
83;;; Not bound by default in comint-mode
84;;; send-invisible Read a line w/o echo, and send to proc
85;;; (These are bound in shell-mode)
86;;; comint-dynamic-complete Complete filename at point.
87;;; comint-dynamic-list-completions List completions in help buffer.
88;;; comint-replace-by-expanded-filename Expand and complete filename at point;
89;;; replace with expanded/completed name.
49116ac0
JB
90;;; comint-kill-subjob No mercy.
91;;; comint-continue-subjob Send CONT signal to buffer's process
92;;; group. Useful if you accidentally
93;;; suspend your process (with C-c C-z).
94;;;
95;;; These used to be bound for RMS -- I prefer the input history stuff,
96;;; but you might like 'em.
97;;; m-P comint-msearch-input Search backwards for prompt
98;;; m-N comint-psearch-input Search forwards for prompt
99;;; C-cR comint-msearch-input-matching Search backwards for prompt & string
100
101;;; comint-mode-hook is the comint mode hook. Basically for your keybindings.
102;;; comint-load-hook is run after loading in this package.
be9b65ac 103
be9b65ac
DL
104\f
105;;; Buffer Local Variables:
106;;;============================================================================
107;;; Comint mode buffer local variables:
108;;; comint-prompt-regexp - string comint-bol uses to match prompt.
87ef29fd 109;;; comint-last-input-start - marker Handy if inferior always echos
49116ac0 110;;; comint-last-input-end - marker For comint-kill-output command
be9b65ac
DL
111;;; input-ring-size - integer For the input history
112;;; input-ring - ring mechanism
113;;; input-ring-index - marker ...
114;;; comint-last-input-match - string ...
115;;; comint-get-old-input - function Hooks for specific
116;;; comint-input-sentinel - function process-in-a-buffer
117;;; comint-input-filter - function modes.
118;;; comint-input-send - function
119;;; comint-eol-on-send - boolean
120
49116ac0
JB
121(defvar comint-prompt-regexp "^"
122 "Regexp to recognise prompts in the inferior process.
123Defaults to \"^\", the null string at BOL.
be9b65ac
DL
124
125Good choices:
49116ac0 126 Canonical Lisp: \"^[^> ]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
be9b65ac 127 Lucid Common Lisp: \"^\\(>\\|\\(->\\)+\\) *\"
49116ac0
JB
128 franz: \"^\\(->\\|<[0-9]*>:\\) *\"
129 kcl: \"^>+ *\"
130 shell: \"^[^#$%>]*[#$%>] *\"
131 T: \"^>+ *\"
be9b65ac 132
49116ac0 133This is a good thing to set in mode hooks.")
be9b65ac 134
49116ac0
JB
135(defvar input-ring-size 30
136 "Size of input history ring.")
be9b65ac
DL
137
138;;; Here are the per-interpreter hooks.
49116ac0
JB
139(defvar comint-get-old-input (function comint-get-old-input-default)
140 "Function that submits old text in comint mode.
be9b65ac
DL
141This function is called when return is typed while the point is in old text.
142It returns the text to be submitted as process input. The default is
143comint-get-old-input-default, which grabs the current line, and strips off
49116ac0 144leading text matching comint-prompt-regexp")
be9b65ac 145
49116ac0
JB
146(defvar comint-input-sentinel (function ignore)
147 "Called on each input submitted to comint mode process by comint-send-input.
148Thus it can, for instance, track cd/pushd/popd commands issued to the csh.")
be9b65ac 149
49116ac0
JB
150(defvar comint-input-filter
151 (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
152 "Predicate for filtering additions to input history.
be9b65ac 153Only inputs answering true to this function are saved on the input
49116ac0
JB
154history list. Default is to save anything that isn't all whitespace")
155
156(defvar comint-input-sender (function comint-simple-send)
157 "Function to actually send to PROCESS the STRING submitted by user.
158Usually this is just 'comint-simple-send, but if your mode needs to
159massage the input string, this is your hook. This is called from
160the user command comint-send-input. comint-simple-send just sends
161the string plus a newline.")
162
163(defvar comint-eol-on-send 'T
164 "If non-nil, then jump to the end of the line before sending input to process.
165See comint-send-input")
be9b65ac
DL
166
167(defvar comint-mode-hook '()
49116ac0
JB
168 "Called upon entry into comint-mode
169This is run before the process is cranked up.")
170
171(defvar comint-exec-hook '()
172 "Called each time a process is exec'd by comint-exec.
173This is called after the process is cranked up. It is useful for things that
174must be done each time a process is executed in a comint-mode buffer (e.g.,
175(process-kill-without-query)). In contrast, the comint-mode-hook is only
176executed once when the buffer is created.")
177
178(defvar comint-mode-map nil)
be9b65ac
DL
179
180(defun comint-mode ()
181 "Major mode for interacting with an inferior interpreter.
182Interpreter name is same as buffer name, sans the asterisks.
183Return at end of buffer sends line as input.
184Return not at end copies rest of line to end and sends it.
49116ac0
JB
185Setting mode variable comint-eol-on-send means jump to the end of the line
186before submitting new input.
be9b65ac
DL
187
188This mode is typically customised to create inferior-lisp-mode,
49116ac0
JB
189shell-mode, etc.. This can be done by setting the hooks
190comint-input-sentinel, comint-input-filter, comint-input-sender and
191comint-get-old-input to appropriate functions, and the variable
192comint-prompt-regexp to the appropriate regular expression.
be9b65ac
DL
193
194An input history is maintained of size input-ring-size, and
195can be accessed with the commands comint-next-input [\\[comint-next-input]] and
196comint-previous-input [\\[comint-previous-input]]. Commands not keybound by
197default are send-invisible, comint-dynamic-complete, and
198comint-list-dynamic-completions.
199
200If you accidentally suspend your process, use \\[comint-continue-subjob]
201to continue it.
202
203\\{comint-mode-map}
204
49116ac0 205Entry to this mode runs the hooks on comint-mode-hook"
be9b65ac 206 (interactive)
49116ac0
JB
207 (let ((old-ring (and (assq 'input-ring (buffer-local-variables))
208 (boundp 'input-ring)
209 input-ring))
210 (old-ptyp comint-ptyp)) ; preserve across local var kill. gross.
211; (kill-all-local-variables) ; Removed 1/15/90 Olin
212 (setq major-mode 'comint-mode)
213 (setq mode-name "Comint")
214 (setq mode-line-process '(": %s"))
215 (use-local-map comint-mode-map)
87ef29fd
JB
216 (make-local-variable 'comint-last-input-start)
217 (setq comint-last-input-start (make-marker))
49116ac0
JB
218 (make-local-variable 'comint-last-input-end)
219 (setq comint-last-input-end (make-marker))
220 (make-local-variable 'comint-last-input-match)
221 (setq comint-last-input-match "")
222 (make-local-variable 'comint-prompt-regexp) ; Don't set; default
223 (make-local-variable 'input-ring-size) ; ...to global val.
224 (make-local-variable 'input-ring)
225 (make-local-variable 'input-ring-index)
226 (setq input-ring-index 0)
227 (make-local-variable 'comint-get-old-input)
228 (make-local-variable 'comint-input-sentinel)
229 (make-local-variable 'comint-input-filter)
230 (make-local-variable 'comint-input-sender)
231 (make-local-variable 'comint-eol-on-send)
232 (make-local-variable 'comint-ptyp)
233 (setq comint-ptyp old-ptyp)
87ef29fd 234 (make-local-variable 'comint-exec-hook)
49116ac0
JB
235 (run-hooks 'comint-mode-hook)
236 ;Do this after the hook so the user can mung INPUT-RING-SIZE w/his hook.
237 ;The test is so we don't lose history if we run comint-mode twice in
238 ;a buffer.
239 (setq input-ring (if (ring-p old-ring) old-ring
240 (make-ring input-ring-size)))))
241
242;;; The old-ptyp stuff above is because we have to preserve the value of
243;;; comint-ptyp across calls to comint-mode, in spite of the
244;;; kill-all-local-variables that it does. Blech. Hopefully, this will all
245;;; go away when a later release fixes the signalling bug.
246;;; (Later: I removed the kill-all-local-variables, but have left this
247;;; other code in place just in case I reverse myself.)
be9b65ac 248
49116ac0
JB
249(if comint-mode-map
250 nil
251 (setq comint-mode-map (make-sparse-keymap))
252 (define-key comint-mode-map "\ep" 'comint-previous-input)
253 (define-key comint-mode-map "\en" 'comint-next-input)
254 (define-key comint-mode-map "\es" 'comint-previous-similar-input)
255 (define-key comint-mode-map "\C-m" 'comint-send-input)
256 (define-key comint-mode-map "\C-d" 'comint-delchar-or-maybe-eof)
257 (define-key comint-mode-map "\C-a" 'comint-bol)
258 (define-key comint-mode-map "\C-c\C-u" 'comint-kill-input)
259 (define-key comint-mode-map "\C-c\C-w" 'backward-kill-word)
260 (define-key comint-mode-map "\C-c\C-c" 'comint-interrupt-subjob)
261 (define-key comint-mode-map "\C-c\C-z" 'comint-stop-subjob)
262 (define-key comint-mode-map "\C-c\C-\\" 'comint-quit-subjob)
263 (define-key comint-mode-map "\C-c\C-o" 'comint-kill-output)
264 (define-key comint-mode-map "\C-\M-r" 'comint-previous-input-matching)
265 (define-key comint-mode-map "\C-c\C-r" 'comint-show-output)
266 ;;; prompt-search commands commented out 3/90 -Olin
267; (define-key comint-mode-map "\eP" 'comint-msearch-input)
268; (define-key comint-mode-map "\eN" 'comint-psearch-input)
269; (define-key comint-mode-map "\C-cR" 'comint-msearch-input-matching)
270 )
271
272
273;;; This function is used to make a full copy of the comint mode map,
274;;; so that client modes won't interfere with each other. This function
275;;; isn't necessary in emacs 18.5x, but we keep it around for 18.4x versions.
276(defun full-copy-sparse-keymap (km)
277 "Recursively copy the sparse keymap KM"
278 (cond ((consp km)
279 (cons (full-copy-sparse-keymap (car km))
280 (full-copy-sparse-keymap (cdr km))))
281 (t km)))
282
283(defun comint-check-proc (buffer)
284 "True if there is a process associated w/buffer BUFFER, and
285it is alive (status RUN or STOP). BUFFER can be either a buffer or the
286name of one"
287 (let ((proc (get-buffer-process buffer)))
288 (and proc (memq (process-status proc) '(run stop)))))
be9b65ac
DL
289
290;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
291;;; for the second argument (program).
292(defun make-comint (name program &optional startfile &rest switches)
49116ac0 293 (let ((buffer (get-buffer-create (concat "*" name "*"))))
be9b65ac
DL
294 ;; If no process, or nuked process, crank up a new one and put buffer in
295 ;; comint mode. Otherwise, leave buffer and existing process alone.
1ff6cf10 296 (cond ((not (comint-check-proc buffer))
49116ac0 297 (save-excursion
be9b65ac
DL
298 (set-buffer buffer)
299 (comint-mode)) ; Install local vars, mode, keymap, ...
300 (comint-exec buffer name program startfile switches)))
301 buffer))
302
49116ac0
JB
303(defvar comint-ptyp t
304 "True if communications via pty; false if by pipe. Buffer local.
305This is to work around a bug in emacs process signalling.")
306
be9b65ac
DL
307(defun comint-exec (buffer name command startfile switches)
308 "Fires up a process in buffer for comint modes.
49116ac0
JB
309Blasts any old process running in the buffer. Doesn't set the buffer mode.
310You can use this to cheaply run a series of processes in the same comint
311buffer. The hook comint-exec-hook is run after each exec."
be9b65ac
DL
312 (save-excursion
313 (set-buffer buffer)
314 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
315 (if proc (delete-process proc)))
316 ;; Crank up a new process
317 (let ((proc (comint-exec-1 name buffer command switches)))
49116ac0
JB
318 (make-local-variable 'comint-ptyp)
319 (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
be9b65ac 320 ;; Jump to the end, and set the process mark.
49116ac0 321 (goto-char (point-max))
87ef29fd 322 (set-marker (process-mark proc) (point))
be9b65ac
DL
323 ;; Feed it the startfile.
324 (cond (startfile
325 ;;This is guaranteed to wait long enough
326 ;;but has bad results if the comint does not prompt at all
327 ;; (while (= size (buffer-size))
328 ;; (sleep-for 1))
329 ;;I hope 1 second is enough!
330 (sleep-for 1)
331 (goto-char (point-max))
332 (insert-file-contents startfile)
333 (setq startfile (buffer-substring (point) (point-max)))
334 (delete-region (point) (point-max))
49116ac0
JB
335 (comint-send-string proc startfile)))
336 (run-hooks 'comint-exec-hook)
87ef29fd 337 buffer)))
be9b65ac
DL
338
339;;; This auxiliary function cranks up the process for comint-exec in
e065a56e 340;;; the appropriate environment.
be9b65ac
DL
341
342(defun comint-exec-1 (name buffer command switches)
e065a56e
JB
343 (let ((process-environment
344 (comint-update-env process-environment
345 (list (format "TERMCAP=emacs:co#%d:tc=unknown"
f98955ea 346 (frame-width))
e065a56e
JB
347 "TERM=emacs"
348 "EMACS=t"))))
349 (apply 'start-process name buffer command switches)))
49116ac0
JB
350
351
be9b65ac
DL
352
353;; This is just (append new old-env) that compresses out shadowed entries.
fc68affa 354;; It's also pretty ugly, mostly due to lisp's horrible iteration structures.
be9b65ac
DL
355(defun comint-update-env (old-env new)
356 (let ((ans (reverse new))
357 (vars (mapcar (function (lambda (vv)
358 (and (string-match "^[^=]*=" vv)
359 (substring vv 0 (match-end 0)))))
360 new)))
361 (while old-env
362 (let* ((vv (car old-env)) ; vv is var=value
363 (var (and (string-match "^[^=]*=" vv)
364 (substring vv 0 (match-end 0)))))
365 (setq old-env (cdr old-env))
49116ac0 366 (cond ((not (and var (comint-mem var vars)))
be9b65ac
DL
367 (if var (setq var (cons var vars)))
368 (setq ans (cons vv ans))))))
369 (nreverse ans)))
49116ac0
JB
370
371;;; This should be in emacs, but it isn't.
372(defun comint-mem (item list &optional elt=)
373 "Test to see if ITEM is equal to an item in LIST.
374Option comparison function ELT= defaults to equal."
375 (let ((elt= (or elt= (function equal)))
376 (done nil))
377 (while (and list (not done))
378 (if (funcall elt= item (car list))
379 (setq done list)
380 (setq list (cdr list))))
381 done))
382
be9b65ac 383\f
49116ac0
JB
384;;; Ring Code
385;;;============================================================================
386;;; This code defines a ring data structure. A ring is a
387;;; (hd-index tl-index . vector)
388;;; list. You can insert to, remove from, and rotate a ring. When the ring
389;;; fills up, insertions cause the oldest elts to be quietly dropped.
390;;;
391;;; HEAD = index of the newest item on the ring.
392;;; TAIL = index of the oldest item on the ring.
393;;;
394;;; These functions are used by the input history mechanism, but they can
395;;; be used for other purposes as well.
396
397(defun ring-p (x)
398 "T if X is a ring; NIL otherwise."
399 (and (consp x) (integerp (car x))
400 (consp (cdr x)) (integerp (car (cdr x)))
401 (vectorp (cdr (cdr x)))))
402
403(defun make-ring (size)
404 "Make a ring that can contain SIZE elts"
405 (cons 1 (cons 0 (make-vector (+ size 1) nil))))
406
407(defun ring-plus1 (index veclen)
408 "INDEX+1, with wraparound"
409 (let ((new-index (+ index 1)))
410 (if (= new-index veclen) 0 new-index)))
411
412(defun ring-minus1 (index veclen)
413 "INDEX-1, with wraparound"
414 (- (if (= 0 index) veclen index) 1))
415
416(defun ring-length (ring)
417 "Number of elts in the ring."
418 (let ((hd (car ring)) (tl (car (cdr ring))) (siz (length (cdr (cdr ring)))))
419 (let ((len (if (<= hd tl) (+ 1 (- tl hd)) (+ 1 tl (- siz hd)))))
420 (if (= len siz) 0 len))))
421
422(defun ring-empty-p (ring)
423 (= 0 (ring-length ring)))
424
425(defun ring-insert (ring item)
426 "Insert a new item onto the ring. If the ring is full, dump the oldest
427item to make room."
428 (let* ((vec (cdr (cdr ring))) (len (length vec))
429 (new-hd (ring-minus1 (car ring) len)))
430 (setcar ring new-hd)
431 (aset vec new-hd item)
432 (if (ring-empty-p ring) ;overflow -- dump one off the tail.
433 (setcar (cdr ring) (ring-minus1 (car (cdr ring)) len)))))
434
435(defun ring-remove (ring)
436 "Remove the oldest item retained on the ring."
437 (if (ring-empty-p ring) (error "Ring empty")
438 (let ((tl (car (cdr ring))) (vec (cdr (cdr ring))))
439 (set-car (cdr ring) (ring-minus1 tl (length vec)))
440 (aref vec tl))))
441
442;;; This isn't actually used in this package. I just threw it in in case
443;;; someone else wanted it. If you want rotating-ring behavior on your history
444;;; retrieval (analagous to kill ring behavior), this function is what you
445;;; need. I should write the yank-input and yank-pop-input-or-kill to go with
446;;; this, and not bind it to a key by default, so it would be available to
447;;; people who want to bind it to a key. But who would want it? Blech.
448(defun ring-rotate (ring n)
449 (if (not (= n 0))
450 (if (ring-empty-p ring) ;Is this the right error check?
451 (error "ring empty")
452 (let ((hd (car ring)) (tl (car (cdr ring))) (vec (cdr (cdr ring))))
453 (let ((len (length vec)))
454 (while (> n 0)
455 (setq tl (ring-plus1 tl len))
456 (aset ring tl (aref ring hd))
457 (setq hd (ring-plus1 hd len))
458 (setq n (- n 1)))
459 (while (< n 0)
460 (setq hd (ring-minus1 hd len))
461 (aset vec hd (aref vec tl))
462 (setq tl (ring-minus1 tl len))
463 (setq n (- n 1))))
464 (set-car ring hd)
465 (set-car (cdr ring) tl)))))
466
467(defun comint-mod (n m)
468 "Returns N mod M. M is positive. Answer is guaranteed to be non-negative,
469and less than m."
470 (let ((n (% n m)))
471 (if (>= n 0) n
472 (+ n
473 (if (>= m 0) m (- m)))))) ; (abs m)
474
475(defun ring-ref (ring index)
476 (let ((numelts (ring-length ring)))
477 (if (= numelts 0) (error "indexed empty ring")
478 (let* ((hd (car ring)) (tl (car (cdr ring))) (vec (cdr (cdr ring)))
479 (index (comint-mod index numelts))
480 (vec-index (comint-mod (+ index hd)
481 (length vec))))
482 (aref vec vec-index)))))
483
484
be9b65ac
DL
485;;; Input history retrieval commands
486;;; M-p -- previous input M-n -- next input
49116ac0 487;;; M-C-r -- previous input matching
be9b65ac
DL
488;;; ===========================================================================
489
490(defun comint-previous-input (arg)
491 "Cycle backwards through input history."
492 (interactive "*p")
493 (let ((len (ring-length input-ring)))
49116ac0
JB
494 (cond ((<= len 0)
495 (message "Empty input ring")
496 (ding))
497 ((not (comint-after-pmark-p))
498 (message "Not after process mark")
499 (ding))
500 (t
501 (cond ((eq last-command 'comint-previous-input)
502 (delete-region (mark) (point)))
503 ((eq last-command 'comint-previous-similar-input)
504 (delete-region
505 (process-mark (get-buffer-process (current-buffer)))
506 (point)))
507 (t
508 (setq input-ring-index
509 (if (> arg 0) -1
510 (if (< arg 0) 1 0)))
511 (push-mark (point))))
512 (setq input-ring-index (comint-mod (+ input-ring-index arg) len))
513 (message "%d" (1+ input-ring-index))
514 (insert (ring-ref input-ring input-ring-index))
515 (setq this-command 'comint-previous-input)))))
516
be9b65ac
DL
517(defun comint-next-input (arg)
518 "Cycle forwards through input history."
519 (interactive "*p")
520 (comint-previous-input (- arg)))
521
49116ac0
JB
522(defvar comint-last-input-match ""
523 "Last string searched for by comint input history search, for defaulting.
524Buffer local variable.")
525
be9b65ac
DL
526(defun comint-previous-input-matching (str)
527 "Searches backwards through input history for substring match."
528 (interactive (let* ((last-command last-command) ; preserve around r-f-m
529 (s (read-from-minibuffer
530 (format "Command substring (default %s): "
531 comint-last-input-match))))
532 (list (if (string= s "") comint-last-input-match s))))
533; (interactive "sCommand substring: ")
534 (setq comint-last-input-match str) ; update default
535 (if (not (eq last-command 'comint-previous-input))
536 (setq input-ring-index -1))
537 (let ((str (regexp-quote str))
538 (len (ring-length input-ring))
539 (n (+ input-ring-index 1)))
540 (while (and (< n len) (not (string-match str (ring-ref input-ring n))))
541 (setq n (+ n 1)))
542 (cond ((< n len)
543 (comint-previous-input (- n input-ring-index)))
544 (t (if (eq last-command 'comint-previous-input)
545 (setq this-command 'comint-previous-input))
49116ac0
JB
546 (message "Not found.")
547 (ding)))))
548
549
550;;; These next three commands are alternatives to the input history commands
551;;; -- comint-next-input, comint-previous-input and
552;;; comint-previous-input-matching. They search through the process buffer
553;;; text looking for occurrences of the prompt. Bound to M-P, M-N, and C-c R
554;;; (uppercase P, N, and R) for now. Try'em out. Go with what you like...
555
556;;; comint-msearch-input-matching prompts for a string, not a regexp.
557;;; This could be considered to be the wrong thing. I decided to keep it
558;;; simple, and not make the user worry about regexps. This, of course,
559;;; limits functionality.
560
561;;; These commands were deemed non-winning and have been commented out.
562;;; Feel free to re-enable them if you like. -Olin 3/91
563
564;(defun comint-psearch-input ()
565; "Search forwards for next occurrence of prompt and skip to end of line.
566;\(prompt is anything matching regexp comint-prompt-regexp)"
567; (interactive)
568; (if (re-search-forward comint-prompt-regexp (point-max) t)
569; (end-of-line)
570; (error "No occurrence of prompt found")))
571;
572;(defun comint-msearch-input ()
573; "Search backwards for previous occurrence of prompt and skip to end of line.
574;Search starts from beginning of current line."
575; (interactive)
576; (let ((p (save-excursion
577; (beginning-of-line)
578; (cond ((re-search-backward comint-prompt-regexp (point-min) t)
579; (end-of-line)
580; (point))
581; (t nil)))))
582; (if p (goto-char p)
583; (error "No occurrence of prompt found"))))
584;
585;(defun comint-msearch-input-matching (str)
586; "Search backwards for occurrence of prompt followed by STRING.
587;STRING is prompted for, and is NOT a regular expression."
588; (interactive (let ((s (read-from-minibuffer
589; (format "Command (default %s): "
590; comint-last-input-match))))
591; (list (if (string= s "") comint-last-input-match s))))
592;; (interactive "sCommand: ")
593; (setq comint-last-input-match str) ; update default
594; (let* ((r (concat comint-prompt-regexp (regexp-quote str)))
595; (p (save-excursion
596; (beginning-of-line)
597; (cond ((re-search-backward r (point-min) t)
598; (end-of-line)
599; (point))
600; (t nil)))))
601; (if p (goto-char p)
602; (error "No match"))))
be9b65ac
DL
603
604;;;
605;;; Similar input -- contributed by ccm and highly winning.
606;;;
607;;; Reenter input, removing back to the last insert point if it exists.
608;;;
49116ac0
JB
609(defvar comint-last-similar-string ""
610 "The string last used in a similar string search.")
be9b65ac
DL
611(defun comint-previous-similar-input (arg)
612 "Reenters the last input that matches the string typed so far. If repeated
613successively older inputs are reentered. If arg is 1, it will go back
614in the history, if -1 it will go forward."
615 (interactive "p")
49116ac0 616 (if (not (comint-after-pmark-p))
be9b65ac
DL
617 (error "Not after process mark"))
618 (if (not (eq last-command 'comint-previous-similar-input))
619 (setq input-ring-index -1
49116ac0
JB
620 comint-last-similar-string
621 (buffer-substring
622 (process-mark (get-buffer-process (current-buffer)))
623 (point))))
be9b65ac
DL
624 (let* ((size (length comint-last-similar-string))
625 (len (ring-length input-ring))
626 (n (+ input-ring-index arg))
627 entry)
628 (while (and (< n len)
629 (or (< (length (setq entry (ring-ref input-ring n))) size)
630 (not (equal comint-last-similar-string
631 (substring entry 0 size)))))
632 (setq n (+ n arg)))
633 (cond ((< n len)
634 (setq input-ring-index n)
635 (if (eq last-command 'comint-previous-similar-input)
49116ac0
JB
636 (delete-region (mark) (point)) ; repeat
637 (push-mark (point))) ; 1st time
be9b65ac 638 (insert (substring entry size)))
49116ac0
JB
639 (t (message "Not found.") (ding) (sit-for 1)))
640 (message "%d" (1+ input-ring-index))))
641
be9b65ac 642\f
49116ac0
JB
643(defun comint-send-input ()
644 "Send input to process. After the process output mark, sends all text
645from the process mark to point as input to the process. Before the process
646output mark, calls value of variable comint-get-old-input to retrieve old
647input, copies it to the process mark, and sends it. A terminal newline is
648also inserted into the buffer and sent to the process. In either case, value
649of variable comint-input-sentinel is called on the input before sending it.
650The input is entered into the input history ring, if the value of variable
651comint-input-filter returns non-nil when called on the input.
652
653If variable comint-eol-on-send is non-nil, then point is moved to the end of
654line before sending the input.
be9b65ac
DL
655
656comint-get-old-input, comint-input-sentinel, and comint-input-filter are chosen
49116ac0 657according to the command interpreter running in the buffer. E.g.,
be9b65ac 658If the interpreter is the csh,
49116ac0
JB
659 comint-get-old-input is the default: take the current line, discard any
660 initial string matching regexp comint-prompt-regexp.
661 comint-input-sentinel monitors input for \"cd\", \"pushd\", and \"popd\"
662 commands. When it sees one, it cd's the buffer.
663 comint-input-filter is the default: returns T if the input isn't all white
664 space.
be9b65ac
DL
665
666If the comint is Lucid Common Lisp,
49116ac0
JB
667 comint-get-old-input snarfs the sexp ending at point.
668 comint-input-sentinel does nothing.
669 comint-input-filter returns NIL if the input matches input-filter-regexp,
be9b65ac
DL
670 which matches (1) all whitespace (2) :a, :c, etc.
671
49116ac0 672Similarly for Soar, Scheme, etc.."
be9b65ac
DL
673 (interactive)
674 ;; Note that the input string does not include its terminal newline.
49116ac0
JB
675 (let ((proc (get-buffer-process (current-buffer))))
676 (if (not proc) (error "Current buffer has no process")
677 (let* ((pmark (process-mark proc))
678 (pmark-val (marker-position pmark))
679 (input (if (>= (point) pmark-val)
680 (progn (if comint-eol-on-send (end-of-line))
681 (buffer-substring pmark (point)))
87ef29fd
JB
682 (let ((copy (funcall comint-get-old-input)))
683 (goto-char pmark)
684 (insert copy)
685 copy))))
49116ac0
JB
686 (insert ?\n)
687 (if (funcall comint-input-filter input) (ring-insert input-ring input))
688 (funcall comint-input-sentinel input)
689 (funcall comint-input-sender proc input)
87ef29fd
JB
690 (set-marker comint-last-input-start pmark)
691 (set-marker comint-last-input-end (point))
692 (set-marker (process-mark proc) (point))))))
be9b65ac
DL
693
694(defun comint-get-old-input-default ()
49116ac0
JB
695 "Default for comint-get-old-input: take the current line, and discard
696any initial text matching comint-prompt-regexp."
be9b65ac 697 (save-excursion
49116ac0
JB
698 (beginning-of-line)
699 (comint-skip-prompt)
700 (let ((beg (point)))
701 (end-of-line)
702 (buffer-substring beg (point)))))
703
704(defun comint-skip-prompt ()
705 "Skip past the text matching regexp comint-prompt-regexp.
706If this takes us past the end of the current line, don't skip at all."
707 (let ((eol (save-excursion (end-of-line) (point))))
708 (if (and (looking-at comint-prompt-regexp)
709 (<= (match-end 0) eol))
710 (goto-char (match-end 0)))))
711
712
713(defun comint-after-pmark-p ()
714 "Is point after the process output marker?"
715 ;; Since output could come into the buffer after we looked at the point
716 ;; but before we looked at the process marker's value, we explicitly
717 ;; serialise. This is just because I don't know whether or not emacs
718 ;; services input during execution of lisp commands.
719 (let ((proc-pos (marker-position
720 (process-mark (get-buffer-process (current-buffer))))))
721 (<= proc-pos (point))))
722
723(defun comint-simple-send (proc string)
724 "Default function for sending to PROC input STRING.
725This just sends STRING plus a newline. To override this,
726set the hook COMINT-INPUT-SENDER."
727 (comint-send-string proc string)
728 (comint-send-string proc "\n"))
be9b65ac
DL
729
730(defun comint-bol (arg)
731 "Goes to the beginning of line, then skips past the prompt, if any.
49116ac0
JB
732If a prefix argument is given (\\[universal-argument]), then no prompt skip
733-- go straight to column 0.
be9b65ac 734
49116ac0
JB
735The prompt skip is done by skipping text matching the regular expression
736comint-prompt-regexp, a buffer local variable.
737
738If you don't like this command, reset c-a to beginning-of-line
739in your hook, comint-mode-hook."
be9b65ac
DL
740 (interactive "P")
741 (beginning-of-line)
49116ac0 742 (if (null arg) (comint-skip-prompt)))
be9b65ac
DL
743
744;;; These two functions are for entering text you don't want echoed or
745;;; saved -- typically passwords to ftp, telnet, or somesuch.
49116ac0
JB
746;;; Just enter m-x send-invisible and type in your line.
747
87ef29fd 748(defun comint-read-noecho (prompt &optional stars)
49116ac0
JB
749 "Prompt the user with argument PROMPT. Read a single line of text
750without echoing, and return it. Note that the keystrokes comprising
751the text can still be recovered (temporarily) with \\[view-lossage]. This
87ef29fd
JB
752may be a security bug for some applications. Optional argument STARS
753causes input to be echoed with '*' characters on the prompt line."
be9b65ac 754 (let ((echo-keystrokes 0)
87ef29fd 755 (cursor-in-echo-area t)
be9b65ac
DL
756 (answ "")
757 tem)
87ef29fd
JB
758 (if (not (stringp prompt)) (setq prompt ""))
759 (message prompt)
49116ac0 760 (while (not(or (= (setq tem (read-char)) ?\^m)
be9b65ac 761 (= tem ?\n)))
87ef29fd
JB
762 (setq answ (concat answ (char-to-string tem)))
763 (if stars (setq prompt (concat prompt "*")))
764 (message prompt))
be9b65ac
DL
765 (message "")
766 answ))
767
87ef29fd 768
be9b65ac 769(defun send-invisible (str)
49116ac0
JB
770 "Read a string without echoing, and send it to the process running
771in the current buffer. A new-line is additionally sent. String is not
772saved on comint input history list.
773Security bug: your string can still be temporarily recovered with
774\\[view-lossage]."
be9b65ac
DL
775; (interactive (list (comint-read-noecho "Enter non-echoed text")))
776 (interactive "P") ; Defeat snooping via C-x esc
777 (let ((proc (get-buffer-process (current-buffer))))
778 (if (not proc) (error "Current buffer has no process")
779 (comint-send-string proc
780 (if (stringp str) str
87ef29fd 781 (comint-read-noecho "Non-echoed text: " t)))
be9b65ac
DL
782 (comint-send-string proc "\n"))))
783
784\f
785;;; Low-level process communication
786
787(defvar comint-input-chunk-size 512
788 "*Long inputs send to comint processes are broken up into chunks of this size.
789If your process is choking on big inputs, try lowering the value.")
790
791(defun comint-send-string (proc str)
792 "Send PROCESS the contents of STRING as input.
793This is equivalent to process-send-string, except that long input strings
794are broken up into chunks of size comint-input-chunk-size. Processes
795are given a chance to output between chunks. This can help prevent processes
796from hanging when you send them long inputs on some OS's."
797 (let* ((len (length str))
798 (i (min len comint-input-chunk-size)))
799 (process-send-string proc (substring str 0 i))
800 (while (< i len)
801 (let ((next-i (+ i comint-input-chunk-size)))
802 (accept-process-output)
803 (process-send-string proc (substring str i (min len next-i)))
804 (setq i next-i)))))
805
806(defun comint-send-region (proc start end)
807 "Sends to PROC the region delimited by START and END.
808This is a replacement for process-send-region that tries to keep
809your process from hanging on long inputs. See comint-send-string."
810 (comint-send-string proc (buffer-substring start end)))
811
812\f
813;;; Random input hackage
814
49116ac0 815(defun comint-kill-output ()
be9b65ac
DL
816 "Kill all output from interpreter since last input."
817 (interactive)
49116ac0
JB
818 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
819 (kill-region comint-last-input-end pmark)
820 (goto-char pmark)
821 (insert "*** output flushed ***\n")
822 (set-marker pmark (point))))
be9b65ac
DL
823
824(defun comint-show-output ()
49116ac0
JB
825 "Display start of this batch of interpreter output at top of window.
826Also put cursor there."
be9b65ac
DL
827 (interactive)
828 (goto-char comint-last-input-end)
49116ac0 829 (backward-char)
be9b65ac
DL
830 (beginning-of-line)
831 (set-window-start (selected-window) (point))
49116ac0 832 (end-of-line))
be9b65ac
DL
833
834(defun comint-interrupt-subjob ()
49116ac0 835 "Interrupt the current subjob."
be9b65ac 836 (interactive)
49116ac0 837 (interrupt-process nil comint-ptyp))
be9b65ac
DL
838
839(defun comint-kill-subjob ()
49116ac0 840 "Send kill signal to the current subjob."
be9b65ac 841 (interactive)
49116ac0 842 (kill-process nil comint-ptyp))
be9b65ac
DL
843
844(defun comint-quit-subjob ()
49116ac0 845 "Send quit signal to the current subjob."
be9b65ac 846 (interactive)
49116ac0 847 (quit-process nil comint-ptyp))
be9b65ac
DL
848
849(defun comint-stop-subjob ()
49116ac0 850 "Stop the current subjob.
be9b65ac 851WARNING: if there is no current subjob, you can end up suspending
49116ac0
JB
852the top-level process running in the buffer. If you accidentally do
853this, use \\[comint-continue-subjob] to resume the process. (This
854is not a problem with most shells, since they ignore this signal.)"
be9b65ac 855 (interactive)
49116ac0 856 (stop-process nil comint-ptyp))
be9b65ac
DL
857
858(defun comint-continue-subjob ()
49116ac0 859 "Send CONT signal to process buffer's process group.
be9b65ac
DL
860Useful if you accidentally suspend the top-level process."
861 (interactive)
49116ac0 862 (continue-process nil comint-ptyp))
be9b65ac
DL
863
864(defun comint-kill-input ()
49116ac0 865 "Kill all text from last stuff output by interpreter to point."
be9b65ac 866 (interactive)
49116ac0
JB
867 (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
868 (p-pos (marker-position pmark)))
869 (if (> (point) p-pos)
870 (kill-region pmark (point)))))
be9b65ac
DL
871
872(defun comint-delchar-or-maybe-eof (arg)
873 "Delete ARG characters forward, or send an EOF to process if at end of buffer."
874 (interactive "p")
875 (if (eobp)
876 (process-send-eof)
49116ac0
JB
877 (delete-char arg)))
878
879
880
be9b65ac
DL
881\f
882;;; Support for source-file processing commands.
883;;;============================================================================
884;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
885;;; commands that process files of source text (e.g. loading or compiling
886;;; files). So the corresponding process-in-a-buffer modes have commands
887;;; for doing this (e.g., lisp-load-file). The functions below are useful
888;;; for defining these commands.
889;;;
890;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
891;;; and Soar, in that they don't know anything about file extensions.
892;;; So the compile/load interface gets the wrong default occasionally.
893;;; The load-file/compile-file default mechanism could be smarter -- it
894;;; doesn't know about the relationship between filename extensions and
895;;; whether the file is source or executable. If you compile foo.lisp
896;;; with compile-file, then the next load-file should use foo.bin for
897;;; the default, not foo.lisp. This is tricky to do right, particularly
898;;; because the extension for executable files varies so much (.o, .bin,
899;;; .lbin, .mo, .vo, .ao, ...).
900
901
902;;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
903;;; commands.
904;;;
905;;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
906;;; want to save the buffer before issuing any process requests to the command
907;;; interpreter.
908;;;
909;;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
910;;; for the file to process.
911
912;;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
913;;;============================================================================
914;;; This function computes the defaults for the load-file and compile-file
49116ac0 915;;; commands for tea, soar, cmulisp, and cmuscheme modes.
be9b65ac
DL
916;;;
917;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
918;;; source-file processing command. NIL if there hasn't been one yet.
919;;; - SOURCE-MODES is a list used to determine what buffers contain source
920;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
921;;; Typically, (lisp-mode) or (scheme-mode).
922;;;
923;;; If the command is given while the cursor is inside a string, *and*
924;;; the string is an existing filename, *and* the filename is not a directory,
925;;; then the string is taken as default. This allows you to just position
926;;; your cursor over a string that's a filename and have it taken as default.
927;;;
928;;; If the command is given in a file buffer whose major mode is in
929;;; SOURCE-MODES, then the the filename is the default file, and the
930;;; file's directory is the default directory.
931;;;
932;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
933;;; then the default directory & file are what was used in the last source-file
934;;; processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
935;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
936;;; is the cwd, with no default file. (\"no default file\" = nil)
937;;;
938;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
939;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
940;;; for Soar programs, etc.
941;;;
942;;; The function returns a pair: (default-directory . default-file).
943
944(defun comint-source-default (previous-dir/file source-modes)
945 (cond ((and buffer-file-name (memq major-mode source-modes))
946 (cons (file-name-directory buffer-file-name)
947 (file-name-nondirectory buffer-file-name)))
948 (previous-dir/file)
949 (t
950 (cons default-directory nil))))
951
49116ac0 952
be9b65ac
DL
953;;; (COMINT-CHECK-SOURCE fname)
954;;;============================================================================
49116ac0 955;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
be9b65ac
DL
956;;; process-in-a-buffer modes), this function can be called on the filename.
957;;; If the file is loaded into a buffer, and the buffer is modified, the user
958;;; is queried to see if he wants to save the buffer before proceeding with
959;;; the load or compile.
960
961(defun comint-check-source (fname)
962 (let ((buff (get-file-buffer fname)))
963 (if (and buff
964 (buffer-modified-p buff)
965 (y-or-n-p (format "Save buffer %s first? "
966 (buffer-name buff))))
967 ;; save BUFF.
968 (let ((old-buffer (current-buffer)))
969 (set-buffer buff)
970 (save-buffer)
971 (set-buffer old-buffer)))))
972
49116ac0 973
be9b65ac
DL
974;;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
975;;;============================================================================
976;;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
977;;; commands that process source files (like loading or compiling a file).
978;;; It prompts for the filename, provides a default, if there is one,
979;;; and returns the result filename.
980;;;
981;;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
982;;;
983;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
984;;; from the last source processing command. SOURCE-MODES is a list of major
985;;; modes used to determine what file buffers contain source files. (These
986;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
987;;; then the filename reader will only accept a file that exists.
988;;;
989;;; A typical use:
990;;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
991;;; '(lisp-mode) t))
992
993;;; This is pretty stupid about strings. It decides we're in a string
994;;; if there's a quote on both sides of point on the current line.
995(defun comint-extract-string ()
996 "Returns string around point that starts the current line or nil."
997 (save-excursion
998 (let* ((point (point))
999 (bol (progn (beginning-of-line) (point)))
1000 (eol (progn (end-of-line) (point)))
1001 (start (progn (goto-char point)
1002 (and (search-backward "\"" bol t)
1003 (1+ (point)))))
1004 (end (progn (goto-char point)
1005 (and (search-forward "\"" eol t)
1006 (1- (point))))))
1007 (and start end
1008 (buffer-substring start end)))))
1009
1010(defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
1011 (let* ((def (comint-source-default prev-dir/file source-modes))
1012 (stringfile (comint-extract-string))
1013 (sfile-p (and stringfile
49116ac0
JB
1014 (condition-case ()
1015 (file-exists-p stringfile)
1016 (error nil))
be9b65ac
DL
1017 (not (file-directory-p stringfile))))
1018 (defdir (if sfile-p (file-name-directory stringfile)
1019 (car def)))
1020 (deffile (if sfile-p (file-name-nondirectory stringfile)
1021 (cdr def)))
1022 (ans (read-file-name (if deffile (format "%s(default %s) "
1023 prompt deffile)
1024 prompt)
1025 defdir
1026 (concat defdir deffile)
1027 mustmatch-p)))
1028 (list (expand-file-name (substitute-in-file-name ans)))))
1029
49116ac0
JB
1030;;; I am somewhat divided on this string-default feature. It seems
1031;;; to violate the principle-of-least-astonishment, in that it makes
1032;;; the default harder to predict, so you actually have to look and see
1033;;; what the default really is before choosing it. This can trip you up.
1034;;; On the other hand, it can be useful, I guess. I would appreciate feedback
1035;;; on this.
1036;;; -Olin
1037
be9b65ac
DL
1038\f
1039;;; Simple process query facility.
1040;;; ===========================================================================
1041;;; This function is for commands that want to send a query to the process
1042;;; and show the response to the user. For example, a command to get the
1043;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
1044;;; to an inferior Common Lisp process.
1045;;;
1046;;; This simple facility just sends strings to the inferior process and pops
1047;;; up a window for the process buffer so you can see what the process
1048;;; responds with. We don't do anything fancy like try to intercept what the
1049;;; process responds with and put it in a pop-up window or on the message
1050;;; line. We just display the buffer. Low tech. Simple. Works good.
1051
1052;;; Send to the inferior process PROC the string STR. Pop-up but do not select
1053;;; a window for the inferior process so that its response can be seen.
1054(defun comint-proc-query (proc str)
1055 (let* ((proc-buf (process-buffer proc))
1056 (proc-mark (process-mark proc)))
1057 (display-buffer proc-buf)
1058 (set-buffer proc-buf) ; but it's not the selected *window*
1059 (let ((proc-win (get-buffer-window proc-buf))
1060 (proc-pt (marker-position proc-mark)))
1061 (comint-send-string proc str) ; send the query
1062 (accept-process-output proc) ; wait for some output
1063 ;; Try to position the proc window so you can see the answer.
1064 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
1065 ;; I don't know why. Wizards invited to improve it.
1066 (if (not (pos-visible-in-window-p proc-pt proc-win))
1067 (let ((opoint (window-point proc-win)))
1068 (set-window-point proc-win proc-mark) (sit-for 0)
1069 (if (not (pos-visible-in-window-p opoint proc-win))
1070 (push-mark opoint)
1071 (set-window-point proc-win opoint)))))))
1072
1073\f
1074;;; Filename completion in a buffer
1075;;; ===========================================================================
1076;;; Useful completion functions, courtesy of the Ergo group.
1077;;; M-<Tab> will complete the filename at the cursor as much as possible
1078;;; M-? will display a list of completions in the help buffer.
1079
1080;;; Three commands:
1081;;; comint-dynamic-complete Complete filename at point.
1082;;; comint-dynamic-list-completions List completions in help buffer.
1083;;; comint-replace-by-expanded-filename Expand and complete filename at point;
1084;;; replace with expanded/completed name.
1085
1086;;; These are not installed in the comint-mode keymap. But they are
49116ac0
JB
1087;;; available for people who want them. Shell-mode installs them:
1088;;; (define-key cmushell-mode-map "\M-\t" 'comint-dynamic-complete)
1089;;; (define-key cmushell-mode-map "\M-?" 'comint-dynamic-list-completions)))
1090;;;
1091;;; Commands like this are fine things to put in load hooks if you
1092;;; want them present in specific modes. Example:
1093;;; (setq cmushell-load-hook
1094;;; '((lambda () (define-key lisp-mode-map "\M-\t"
1095;;; 'comint-replace-by-expanded-filename))))
1096;;;
1097
be9b65ac
DL
1098
1099(defun comint-match-partial-pathname ()
49116ac0
JB
1100 "Returns the filename at point or causes an error."
1101 (save-excursion
1102 (if (re-search-backward "[^~/A-Za-z0-9---_.$#,=]" nil 'move)
1103 (forward-char 1))
1104 ;; Anchor the search forwards.
1105 (if (not (looking-at "[~/A-Za-z0-9---_.$#,=]")) (error ""))
1106 (re-search-forward "[~/A-Za-z0-9---_.$#,=]+")
1107 (substitute-in-file-name
1108 (buffer-substring (match-beginning 0) (match-end 0)))))
1109
be9b65ac
DL
1110
1111(defun comint-replace-by-expanded-filename ()
49116ac0
JB
1112"Replace the filename at point with an expanded, canonicalised, and
1113completed replacement.
be9b65ac
DL
1114\"Expanded\" means environment variables (e.g., $HOME) and ~'s are
1115replaced with the corresponding directories. \"Canonicalised\" means ..
49116ac0
JB
1116and \. are removed, and the filename is made absolute instead of relative.
1117See functions expand-file-name and substitute-in-file-name. See also
be9b65ac
DL
1118comint-dynamic-complete."
1119 (interactive)
1120 (let* ((pathname (comint-match-partial-pathname))
1121 (pathdir (file-name-directory pathname))
1122 (pathnondir (file-name-nondirectory pathname))
1123 (completion (file-name-completion pathnondir
1124 (or pathdir default-directory))))
1125 (cond ((null completion)
49116ac0
JB
1126 (message "No completions of %s." pathname)
1127 (ding))
be9b65ac 1128 ((eql completion t)
49116ac0 1129 (message "Unique completion."))
be9b65ac
DL
1130 (t ; this means a string was returned.
1131 (delete-region (match-beginning 0) (match-end 0))
1132 (insert (expand-file-name (concat pathdir completion)))))))
1133
49116ac0 1134
be9b65ac 1135(defun comint-dynamic-complete ()
49116ac0 1136 "Dynamically complete the filename at point.
be9b65ac
DL
1137This function is similar to comint-replace-by-expanded-filename, except
1138that it won't change parts of the filename already entered in the buffer;
1139it just adds completion characters to the end of the filename."
1140 (interactive)
1141 (let* ((pathname (comint-match-partial-pathname))
1142 (pathdir (file-name-directory pathname))
1143 (pathnondir (file-name-nondirectory pathname))
49116ac0 1144 (completion (file-name-completion pathnondir
be9b65ac
DL
1145 (or pathdir default-directory))))
1146 (cond ((null completion)
49116ac0
JB
1147 (message "No completions of %s." pathname)
1148 (ding))
be9b65ac 1149 ((eql completion t)
49116ac0 1150 (message "Unique completion."))
be9b65ac
DL
1151 (t ; this means a string was returned.
1152 (goto-char (match-end 0))
1153 (insert (substring completion (length pathnondir)))))))
1154
1155(defun comint-dynamic-list-completions ()
49116ac0 1156 "List in help buffer all possible completions of the filename at point."
be9b65ac
DL
1157 (interactive)
1158 (let* ((pathname (comint-match-partial-pathname))
1159 (pathdir (file-name-directory pathname))
1160 (pathnondir (file-name-nondirectory pathname))
1161 (completions
1162 (file-name-all-completions pathnondir
1163 (or pathdir default-directory))))
1164 (cond ((null completions)
49116ac0
JB
1165 (message "No completions of %s." pathname)
1166 (ding))
be9b65ac
DL
1167 (t
1168 (let ((conf (current-window-configuration)))
49116ac0 1169 (with-output-to-temp-buffer "*Help*"
be9b65ac
DL
1170 (display-completion-list completions))
1171 (sit-for 0)
1172 (message "Hit space to flush.")
1173 (let ((ch (read-char)))
1174 (if (= ch ?\ )
1175 (set-window-configuration conf)
1176 (setq unread-command-char ch))))))))
1177
49116ac0
JB
1178; Ergo bindings
1179; (global-set-key "\M-\t" 'comint-replace-by-expanded-filename)
1180; (global-set-key "\M-?" 'comint-dynamic-list-completions)
1181; (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
be9b65ac
DL
1182\f
1183;;; Converting process modes to use comint mode
1184;;; ===========================================================================
be14d312
ER
1185;;; The code in the Emacs 19 distribution has all been modified to use comint
1186;;; where needed. However, there are `third-party' packages out there that
1187;;; still use the old shell mode. Here's a guide to conversion.
49116ac0 1188;;;
be9b65ac 1189;;; Renaming variables
49116ac0
JB
1190;;; Most of the work is renaming variables and functions. These are the common
1191;;; ones:
1192;;; Local variables:
87ef29fd 1193;;; last-input-start comint-last-input-start
49116ac0 1194;;; last-input-end comint-last-input-end
49116ac0
JB
1195;;; shell-prompt-pattern comint-prompt-regexp
1196;;; shell-set-directory-error-hook <no equivalent>
1197;;; Miscellaneous:
be9b65ac
DL
1198;;; shell-set-directory <unnecessary>
1199;;; shell-mode-map comint-mode-map
49116ac0 1200;;; Commands:
be9b65ac
DL
1201;;; shell-send-input comint-send-input
1202;;; shell-send-eof comint-delchar-or-maybe-eof
1203;;; kill-shell-input comint-kill-input
1204;;; interrupt-shell-subjob comint-interrupt-subjob
1205;;; stop-shell-subjob comint-stop-subjob
1206;;; quit-shell-subjob comint-quit-subjob
1207;;; kill-shell-subjob comint-kill-subjob
1208;;; kill-output-from-shell comint-kill-output
1209;;; show-output-from-shell comint-show-output
1210;;; copy-last-shell-input Use comint-previous-input/comint-next-input
1211;;;
87ef29fd
JB
1212;;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
1213;;; SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-sentinel.
1214;;; Comint mode does not provide functionality equivalent to
be9b65ac 1215;;; shell-set-directory-error-hook; it is gone.
87ef29fd
JB
1216;;;
1217;;; comint-last-input-start is provided for modes which want to munge
1218;;; the buffer after input is sent, perhaps because the inferior
1219;;; insists on echoing the input. The LAST-INPUT-START variable in
1220;;; the old shell package was used to implement a history mechanism,
1221;;; but you should think twice before using comint-last-input-start
1222;;; for this; the input history ring often does the job better.
be9b65ac
DL
1223;;;
1224;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
1225;;; *not* create the comint-mode local variables in your foo-mode function.
1226;;; This is not modular. Instead, call comint-mode, and let *it* create the
1227;;; necessary comint-specific local variables. Then create the
1228;;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
1229;;; be foo-mode-map, and its mode to be foo-mode. Set the comint-mode hooks
1230;;; (comint-prompt-regexp, comint-input-filter, comint-input-sentinel,
1231;;; comint-get-old-input) that need to be different from the defaults. Call
1232;;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
49116ac0
JB
1233;;; comint-mode will take care of it. The following example, from cmushell.el,
1234;;; is typical:
1235;;;
1236;;; (defun shell-mode ()
1237;;; (interactive)
1238;;; (comint-mode)
1239;;; (setq comint-prompt-regexp shell-prompt-pattern)
1240;;; (setq major-mode 'shell-mode)
1241;;; (setq mode-name "Shell")
1242;;; (cond ((not shell-mode-map)
1243;;; (setq shell-mode-map (full-copy-sparse-keymap comint-mode-map))
1244;;; (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
1245;;; (define-key shell-mode-map "\M-?"
1246;;; 'comint-dynamic-list-completions)))
1247;;; (use-local-map shell-mode-map)
1248;;; (make-local-variable 'shell-directory-stack)
1249;;; (setq shell-directory-stack nil)
1250;;; (setq comint-input-sentinel 'shell-directory-tracker)
1251;;; (run-hooks 'shell-mode-hook))
1252;;;
be9b65ac
DL
1253;;;
1254;;; Note that make-comint is different from make-shell in that it
1255;;; doesn't have a default program argument. If you give make-shell
1256;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
1257;;; $ESHELL, $SHELL, or /bin/sh. If you give make-comint a program argument
1258;;; of NIL, it barfs. Adjust your code accordingly...
49116ac0
JB
1259;;;
1260\f
1261;;; Do the user's customisation...
1262
1263(defvar comint-load-hook nil
1264 "This hook is run when comint is loaded in.
1265This is a good place to put keybindings.")
1266
1267(run-hooks 'comint-load-hook)
1268
1269;;; Change log:
1270;;; 9/12/89
1271;;; - Souped up the filename expansion procedures.
1272;;; Doc strings are much clearer and more detailed.
1273;;; Fixed a bug where doing a filename completion when the point
1274;;; was in the middle of the filename instead of at the end would lose.
1275;;;
1276;;; 2/17/90
1277;;; - Souped up the command history stuff so that text inserted
1278;;; by comint-previous-input-matching is removed by following
1279;;; command history recalls. comint-next/previous-input-matching
1280;;; is now much more smoothly integrated w/the command history stuff.
1281;;; - Added comint-eol-on-send flag and comint-input-sender hook.
1282;;; Comint-input-sender based on code contributed by Jeff Peck
1283;;; (peck@sun.com).
1284;;;
1285;;; 3/13/90 ccm@cmu.cs.edu
1286;;; - Added comint-previous-similar-input for looking up similar inputs.
1287;;; - Added comint-send-and-get-output to allow snarfing input from
1288;;; buffer.
1289;;; - Added the ability to pick up a source file by positioning over
1290;;; a string in comint-get-source.
1291;;; - Added add-hook to make it a little easier for the user to use
1292;;; multiple hooks.
1293;;;
1294;;; 5/22/90 shivers
1295;;; - Moved Chris' multiplexed ipc stuff to comint-ipc.el.
1296;;; - Altered Chris' comint-get-source string feature. The string
1297;;; is only offered as a default if it names an existing file.
1298;;; - Changed comint-exec to directly crank up the process, instead
1299;;; of calling the env program. This made background.el happy.
1300;;; - Added new buffer-local var comint-ptyp. The problem is that
1301;;; the signalling functions don't work as advertised. If you are
1302;;; communicating via pipes, the CURRENT-GROUP arg is supposed to
1303;;; be ignored, but, unfortunately it seems to be the case that you
1304;;; must pass a NIL for this arg in the pipe case. COMINT-PTYP
1305;;; is a flag that tells whether the process is communicating
1306;;; via pipes or a pty. The comint signalling functions use it
1307;;; to determine the necessary CURRENT-GROUP arg value. The bug
1308;;; has been reported to the Gnu folks.
1309;;; - comint-dynamic-complete flushes the help window if you hit space
1310;;; after you execute it.
1311;;; - Added functions comint-send-string, comint-send-region and var
1312;;; comint-input-chunk-size. comint-send-string tries to prevent processes
1313;;; from hanging when you send them long strings by breaking them into
1314;;; chunks and allowing process output between chunks. I got the idea from
1315;;; Eero Simoncelli's Common Lisp package. Note that using
1316;;; comint-send-string means that the process buffer's contents can change
1317;;; during a call! If you depend on process output only happening between
1318;;; toplevel commands, this could be a problem. In such a case, use
1319;;; process-send-string instead. If this is a problem for people, I'd like
1320;;; to hear about it.
1321;;; - Added comint-proc-query as a simple mechanism for commands that
1322;;; want to query an inferior process and display its response. For a
1323;;; typical use, see lisp-show-arglist in cmulisp.el.
1324;;; - Added constant comint-version, which is now "2.01".
1325;;;
1326;;; 6/14/90 shivers
1327;;; - Had comint-update-env defined twice. Removed extra copy. Also
1328;;; renamed mem to be comint-mem, for modularity. The duplication
1329;;; was reported by Michael Meissner.
1330;;; 6/16/90 shivers
1331;;; - Emacs has two different mechanisms for maintaining the process
1332;;; environment, determined at compile time by the MAINTAIN-ENVIRONMENT
1333;;; #define. One uses the process-environment global variable, and
1334;;; one uses a getenv/setenv interface. comint-exec assumed the
1335;;; process-environment interface; it has been generalised (with
1336;;; comint-exec-1) to handle both cases. Pretty bogus. We could,
1337;;; of course, skip all this and just use the etc/env program to
1338;;; handle the environment tweaking, but that obscures process
1339;;; queries that other modules (like background.el) depend on. etc/env
1340;;; is also fairly bogus. This bug, and some of the fix code was
1341;;; reported by Dan Pierson.
1342;;;
1343;;; 9/5/90 shivers
1344;;; - Changed make-variable-buffer-local's to make-local-variable's.
1345;;; This leaves non-comint-mode buffers alone. Stephane Payrard
1346;;; reported the sloppy useage.
1347;;; - You can now go from comint-previous-similar-input to
1348;;; comint-previous-input with no problem.
1349;;;
1350;;; 12/21/90 shivers
1351;;; - Added a condition-case to comint-get-source. Bogus strings
1352;;; beginning with ~ were making the file-exists-p barf.
1353;;; - Added "=" to the set of chars recognised by file completion
1354;;; as constituting a filename.
1355;;;
1356;;; 1/90 shivers
1357;;; These changes comprise release 2.02:
1358;;; - Removed the kill-all-local-variables in comint-mode. This
1359;;; made it impossible for client modes to set things before calling
1360;;; comint-mode. (In particular, it messed up ilisp.el) In general,
1361;;; the client mode should be responsible for a k-a-l-v's.
1362;;; - Fixed comint-match-partial-pathname so that it works in
1363;;; more cases: if the filename begins at the start-of-buffer;
1364;;; if point is on the first char of the filename. Just a question
1365;;; of getting the tricky bits right.
1366;;; - Added a hook, comint-exec-hook that is run each time a process
1367;;; is cranked up. Useful for things like process-kill-without-query.
1368;;;
87ef29fd 1369;;; These two were pointed out by tale:
49116ac0
JB
1370;;; - Improved the doc string in comint-send-input a little bit.
1371;;; - Tweaked make-comint to check process status with comint-check-proc
1372;;; instead of equivalent inline code.
87ef29fd 1373;;;
49116ac0
JB
1374;;; - Prompt-search history commands have been commented out. I never
1375;;; liked them; I don't think anyone used them.
87ef29fd
JB
1376;;; - Made comint-exec-hook a local var, as it should have been.
1377;;; (This way, for instance, you can have cmushell procs kill-w/o-query,
1378;;; but let Scheme procs be default.)
1379;;;
1380;;; 7/91 Shivers
1381;;; - Souped up comint-read-noecho with an optional argument, STARS.
1382;;; Suggested by mjlx@EAGLE.CNSF.CORNELL.EDU.
1383;;; - Moved comint-previous-input-matching from C-c r to C-M-r.
1384;;; C-c <letter> bindings are reserved for the user.
1385;;; These bindings were done by Jim Blandy.
1386;;; These changes comprise version 2.03.
49116ac0
JB
1387
1388(provide 'comint)
c0274f38
ER
1389
1390;;; comint.el ends here