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