(rmail-summary-wipe): If rmail buffer is not visible,
[bpt/emacs.git] / lisp / comint.el
... / ...
CommitLineData
1;;; comint.el --- general command interpreter in a window stuff
2
3;; Copyright (C) 1988, 1990, 1992, 1993 Free Software Foundation, Inc.
4
5;; Author: Olin Shivers <shivers@cs.cmu.edu>
6;; Adapted-by: Simon Marshall <s.marshall@dcs.hull.ac.uk>
7;; Keywords: processes
8
9;; This file is part of GNU Emacs.
10
11;; GNU Emacs is free software; you can redistribute it and/or modify
12;; it under the terms of the GNU General Public License as published by
13;; the Free Software Foundation; either version 2, or (at your option)
14;; any later version.
15
16;; GNU Emacs is distributed in the hope that it will be useful,
17;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19;; GNU General Public License for more details.
20
21;; You should have received a copy of the GNU General Public License
22;; along with GNU Emacs; see the file COPYING. If not, write to
23;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
24
25;;; Commentary:
26
27;;; Please send me bug reports, bug fixes, and extensions, so that I can
28;;; merge them into the master source.
29;;; - Olin Shivers (shivers@cs.cmu.edu)
30;;; - Simon Marshall (s.marshall@dcs.hull.ac.uk)
31
32;;; This file defines a general command-interpreter-in-a-buffer package
33;;; (comint mode). The idea is that you can build specific process-in-a-buffer
34;;; modes on top of comint mode -- e.g., lisp, shell, scheme, T, soar, ....
35;;; This way, all these specific packages share a common base functionality,
36;;; and a common set of bindings, which makes them easier to use (and
37;;; saves code, implementation time, etc., etc.).
38
39;;; Several packages are already defined using comint mode:
40;;; - shell.el defines a shell-in-a-buffer mode.
41;;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
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
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
56;;; For hints on converting existing process modes (e.g., tex-mode,
57;;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
58;;; instead of shell-mode, see the notes at the end of this file.
59
60\f
61;;; Brief Command Documentation:
62;;;============================================================================
63;;; Comint Mode Commands: (common to all derived modes, like shell & cmulisp
64;;; mode)
65;;;
66;;; m-p comint-previous-input Cycle backwards in input history
67;;; m-n comint-next-input Cycle forwards
68;;; m-r comint-previous-matching-input Previous input matching a regexp
69;;; m-s comint-next-matching-input Next input that matches
70;;; m-c-r comint-previous-input-matching Search backwards in input history
71;;; return comint-send-input
72;;; c-a comint-bol Beginning of line; skip prompt
73;;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff
74;;; c-c c-u comint-kill-input ^u
75;;; c-c c-w backward-kill-word ^w
76;;; c-c c-c comint-interrupt-subjob ^c
77;;; c-c c-z comint-stop-subjob ^z
78;;; c-c c-\ comint-quit-subjob ^\
79;;; c-c c-o comint-kill-output Delete last batch of process output
80;;; c-c c-r comint-show-output Show last batch of process output
81;;; c-c c-h comint-dynamic-list-input-ring List input history
82;;;
83;;; Not bound by default in comint-mode (some are in shell mode)
84;;; send-invisible Read a line w/o echo, and send to proc
85;;; comint-dynamic-complete-filename Complete filename at point.
86;;; comint-dynamic-complete-variable Complete variable name at point.
87;;; comint-dynamic-list-filename-completions List completions in help buffer.
88;;; comint-replace-by-expanded-filename Expand and complete filename at point;
89;;; replace with expanded/completed name.
90;;; comint-replace-by-expanded-history Expand history at point;
91;;; replace with expanded name.
92;;; comint-magic-space Expand history and add (a) space(s).
93;;; comint-kill-subjob No mercy.
94;;; comint-show-maximum-output Show as much output as possible.
95;;; comint-continue-subjob Send CONT signal to buffer's process
96;;; group. Useful if you accidentally
97;;; suspend your process (with C-c C-z).
98
99;;; comint-mode-hook is the comint mode hook. Basically for your keybindings.
100
101;;; Code:
102
103(require 'ring)
104\f
105;;; Buffer Local Variables:
106;;;============================================================================
107;;; Comint mode buffer local variables:
108;;; comint-prompt-regexp - string comint-bol uses to match prompt
109;;; comint-delimiter-argument-list - list For delimiters and arguments
110;;; comint-last-input-start - marker Handy if inferior always echoes
111;;; comint-last-input-end - marker For comint-kill-output command
112;;; comint-input-ring-size - integer For the input history
113;;; comint-input-ring - ring mechanism
114;;; comint-input-ring-index - number ...
115;;; comint-input-autoexpand - symbol ...
116;;; comint-input-ignoredups - boolean ...
117;;; comint-last-input-match - string ...
118;;; comint-get-old-input - function Hooks for specific
119;;; comint-get-current-command - function process-in-a-buffer
120;;; comint-dynamic-complete-command-command - function modes.
121;;; comint-after-partial-filename-command -
122;;; comint-input-sentinel - function ...
123;;; comint-input-filter - function ...
124;;; comint-input-send - function ...
125;;; comint-eol-on-send - boolean ...
126;;; comint-process-echoes - boolean ...
127;;; comint-scroll-to-bottom-on-input - symbol For scroll behavior
128;;; comint-scroll-to-bottom-on-output - symbol ...
129;;; comint-scroll-show-maximum-output - boolean ...
130;;;
131;;; Comint mode non-buffer local variables:
132;;; comint-completion-addsuffix - boolean For file name completion
133;;; comint-completion-autolist - boolean behavior
134;;; comint-completion-recexact - boolean ...
135
136(defvar comint-prompt-regexp "^"
137 "Regexp to recognise prompts in the inferior process.
138Defaults to \"^\", the null string at BOL.
139
140Good choices:
141 Canonical Lisp: \"^[^> ]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
142 Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
143 franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
144 kcl: \"^>+ *\"
145 shell: \"^[^#$%>]*[#$%>] *\"
146 T: \"^>+ *\"
147
148This is a good thing to set in mode hooks.")
149
150(defvar comint-delimiter-argument-list ()
151 "List of characters to recognise as separate arguments in input.
152Strings comprising a character in this list will separate the arguments
153surrounding them, and also be regarded as arguments in their own right (unlike
154whitespace). See `comint-arguments'.
155Defaults to (), the empty list.
156
157Good choices:
158 shell: \(\"|\" \"&\" \"<\" \">\" \"\(\" \")\" \";\")
159
160This is a good thing to set in mode hooks.")
161
162(defvar comint-input-autoexpand 'history
163 "*If non-nil, expand input command history references on completion.
164This mirrors the optional behavior of tcsh (its autoexpand and histlit).
165
166If the value is `input', then the expansion is seen on input.
167If the value is `history', then the expansion is only when inserting
168into the buffer's input ring. See also `comint-magic-space' and
169`comint-dynamic-complete'.
170
171This variable is buffer-local.")
172
173(defvar comint-input-ignoredups nil
174 "*If non-nil, don't add input matching the last on the input ring.
175This mirrors the optional behavior of bash.
176
177This variable is buffer-local.")
178
179(defvar comint-input-ring-file-name nil
180 "*If non-nil, name of the file to read/write input history.
181See also `comint-read-input-ring' and `comint-write-input-ring'.
182
183This variable is buffer-local, and is a good thing to set in mode hooks.")
184
185(defvar comint-scroll-to-bottom-on-input nil
186 "*Controls whether input to interpreter causes window to scroll.
187If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
188If `this', scroll only the selected window.
189
190The default is nil.
191
192See `comint-preinput-scroll-to-bottom'. This variable is buffer-local.")
193
194(defvar comint-scroll-to-bottom-on-output nil
195 "*Controls whether interpreter output causes window to scroll.
196If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
197If `this', scroll only the selected window.
198If `others', scroll only those that are not the selected window.
199
200The default is nil.
201
202See variable `comint-scroll-show-maximum-output' and function
203`comint-postoutput-scroll-to-bottom'. This variable is buffer-local.")
204
205(defvar comint-scroll-show-maximum-output nil
206 "*Controls how interpreter output causes window to scroll.
207If non-nil, then show the maximum output when the window is scrolled.
208
209See variable `comint-scroll-to-bottom-on-output' and function
210`comint-postoutput-scroll-to-bottom'. This variable is buffer-local.")
211
212(defvar comint-input-ring-size 32
213 "Size of input history ring.")
214
215(defvar comint-process-echoes nil
216 "*If non-nil, assume that the subprocess echoes any input.
217If so, delete one copy of the input so that only one copy eventually
218appears in the buffer.
219
220This variable is buffer-local.")
221
222;;; Here are the per-interpreter hooks.
223(defvar comint-get-old-input (function comint-get-old-input-default)
224 "Function that returns old text in comint mode.
225This function is called when return is typed while the point is in old text.
226It returns the text to be submitted as process input. The default is
227`comint-get-old-input-default', which grabs the current line, and strips off
228leading text matching `comint-prompt-regexp'.")
229
230(defvar comint-after-partial-filename-command 'comint-after-partial-filename
231 "Function that returns non-nil if point is after a file name.
232By default this is `comint-after-partial-filename'.
233
234This is a good thing to set in mode hooks.")
235
236(defvar comint-dynamic-complete-filename-command
237 'comint-dynamic-complete-filename
238 "Function that dynamically completes the file name at point.
239By default this is `comint-dynamic-complete-filename', though an alternative is
240`comint-replace-by-expanded-filename'.
241
242This is a good thing to set in mode hooks.")
243
244(defvar comint-dynamic-complete-command-command
245 'comint-dynamic-complete-filename
246 "Function that dynamically completes the command at point.
247By default this is `comint-dynamic-complete-filename'.
248
249This is a good thing to set in mode hooks.")
250
251(defvar comint-get-current-command 'comint-get-old-input-default
252 "Function that returns the current command including arguments.
253By default this is `comint-get-old-input-default', meaning the whole line.
254
255This is a good thing to set in mode hooks.")
256
257(defvar comint-input-sentinel (function ignore)
258 "Called on each input submitted to comint mode process by `comint-send-input'.
259Thus it can, for instance, track cd/pushd/popd commands issued to a shell.")
260
261(defvar comint-input-filter
262 (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
263 "Predicate for filtering additions to input history.
264Takes one argument, the input. If non-nil, the input may be saved on the input
265history list. Default is to save anything that isn't all whitespace.")
266
267(defvar comint-output-filter-functions '(comint-postoutput-scroll-to-bottom)
268 "Functions to call after output is inserted into the buffer.
269One possible function is `comint-postoutput-scroll-to-bottom'.
270These functions get one argument, a string containing the text just inserted.
271
272This variable is buffer-local.")
273
274(defvar comint-input-sender (function comint-simple-send)
275 "Function to actually send to PROCESS the STRING submitted by user.
276Usually this is just `comint-simple-send', but if your mode needs to
277massage the input string, put a different function here.
278`comint-simple-send' just sends the string plus a newline.
279This is called from the user command `comint-send-input'.")
280
281(defvar comint-eol-on-send t
282 "*Non-nil means go to the end of the line before sending input.
283See `comint-send-input'.")
284
285(defvar comint-mode-hook '()
286 "Called upon entry into comint-mode
287This is run before the process is cranked up.")
288
289(defvar comint-exec-hook '()
290 "Called each time a process is exec'd by `comint-exec'.
291This is called after the process is cranked up. It is useful for things that
292must be done each time a process is executed in a comint mode buffer (e.g.,
293`(process-kill-without-query)'). In contrast, the `comint-mode-hook' is only
294executed once when the buffer is created.")
295
296(defvar comint-mode-map nil)
297
298(defvar comint-ptyp t
299 "Non-nil if communications via pty; false if by pipe. Buffer local.
300This is to work around a bug in Emacs process signalling.")
301
302(defvar comint-input-ring nil)
303(defvar comint-last-input-start)
304(defvar comint-last-input-end)
305(defvar comint-input-ring-index nil
306 "Index of last matched history element.")
307(defvar comint-matching-input-from-input-string ""
308 "Input previously used to match input history.")
309(put 'comint-input-ring 'permanent-local t)
310(put 'comint-input-ring-index 'permanent-local t)
311(put 'comint-input-autoexpand 'permanent-local t)
312(put 'comint-output-filter-functions 'permanent-local t)
313(put 'comint-scroll-to-bottom-on-input 'permanent-local t)
314(put 'comint-scroll-to-bottom-on-output 'permanent-local t)
315(put 'comint-scroll-show-maximum-output 'permanent-local t)
316(put 'comint-ptyp 'permanent-local t)
317
318(defun comint-mode ()
319 "Major mode for interacting with an inferior interpreter.
320Interpreter name is same as buffer name, sans the asterisks.
321Return at end of buffer sends line as input.
322Return not at end copies rest of line to end and sends it.
323Setting variable `comint-eol-on-send' means jump to the end of the line
324before submitting new input.
325
326This mode is customised to create major modes such as Inferior Lisp
327mode, Shell mode, etc. This can be done by setting the hooks
328`comint-input-sentinel', `comint-input-filter', `comint-input-sender'
329and `comint-get-old-input' to appropriate functions, and the variable
330`comint-prompt-regexp' to the appropriate regular expression.
331
332An input history is maintained of size `comint-input-ring-size', and
333can be accessed with the commands \\[comint-next-input], \\[comint-previous-input], and \\[comint-dynamic-list-input-ring].
334Input ring history expansion can be achieved with the commands
335\\[comint-replace-by-expanded-history] or \\[comint-magic-space].
336Input ring expansion is controlled by the variable `comint-input-autoexpand',
337and addition is controlled by the variable `comint-input-ignoredups'.
338
339Commands with no default key bindings include `send-invisible',
340`comint-dynamic-complete', `comint-list-dynamic-completions', and
341`comint-magic-space'.
342
343Input to, and output from, the subprocess can cause the window to scroll to
344the end of the buffer. See variables `comint-output-filter-functions',
345`comint-scroll-to-bottom-on-input', and `comint-scroll-to-bottom-on-output'.
346
347If you accidentally suspend your process, use \\[comint-continue-subjob]
348to continue it.
349
350\\{comint-mode-map}
351
352Entry to this mode runs the hooks on `comint-mode-hook'."
353 (interactive)
354 ;; Do not remove this. All major modes must do this.
355 (kill-all-local-variables)
356 (setq major-mode 'comint-mode)
357 (setq mode-name "Comint")
358 (setq mode-line-process '(": %s"))
359 (use-local-map comint-mode-map)
360 (make-local-variable 'comint-last-input-start)
361 (setq comint-last-input-start (make-marker))
362 (make-local-variable 'comint-last-input-end)
363 (setq comint-last-input-end (make-marker))
364 (make-local-variable 'comint-last-output-start)
365 (setq comint-last-output-start (make-marker))
366 (make-local-variable 'comint-prompt-regexp) ; Don't set; default
367 (make-local-variable 'comint-input-ring-size) ; ...to global val.
368 (make-local-variable 'comint-input-ring)
369 (make-local-variable 'comint-input-ring-file-name)
370 (or (and (boundp 'comint-input-ring) comint-input-ring)
371 (setq comint-input-ring (make-ring comint-input-ring-size)))
372 (make-local-variable 'comint-input-ring-index)
373 (or (and (boundp 'comint-input-ring-index) comint-input-ring-index)
374 (setq comint-input-ring-index nil))
375 (make-local-variable 'comint-matching-input-from-input-string)
376 (make-local-variable 'comint-input-autoexpand)
377 (make-local-variable 'comint-input-ignoredups)
378 (make-local-variable 'comint-delimiter-argument-list)
379 (make-local-variable 'comint-after-partial-filename-command)
380 (make-local-variable 'comint-dynamic-complete-filename-command)
381 (make-local-variable 'comint-dynamic-complete-command-command)
382 (make-local-variable 'comint-get-current-command)
383 (make-local-variable 'comint-get-old-input)
384 (make-local-variable 'comint-input-sentinel)
385 (make-local-variable 'comint-input-filter)
386 (make-local-variable 'comint-input-sender)
387 (make-local-variable 'comint-eol-on-send)
388 (make-local-variable 'comint-scroll-to-bottom-on-input)
389 (make-local-variable 'comint-scroll-to-bottom-on-output)
390 (make-local-variable 'comint-scroll-show-maximum-output)
391 (make-local-variable 'pre-command-hook)
392 (add-hook 'pre-command-hook 'comint-preinput-scroll-to-bottom)
393 (make-local-variable 'comint-output-filter-functions)
394 (make-local-variable 'comint-ptyp)
395 (make-local-variable 'comint-exec-hook)
396 (make-local-variable 'comint-process-echoes)
397 (run-hooks 'comint-mode-hook))
398
399(if comint-mode-map
400 nil
401 ;; Keys:
402 (setq comint-mode-map (make-sparse-keymap))
403 (define-key comint-mode-map "\ep" 'comint-previous-input)
404 (define-key comint-mode-map "\en" 'comint-next-input)
405 (define-key comint-mode-map "\er" 'comint-previous-matching-input)
406 (define-key comint-mode-map "\es" 'comint-next-matching-input)
407 (define-key comint-mode-map [?\A-\M-r] 'comint-previous-matching-input-from-input)
408 (define-key comint-mode-map [?\A-\M-s] 'comint-next-matching-input-from-input)
409 (define-key comint-mode-map "\C-m" 'comint-send-input)
410 (define-key comint-mode-map "\C-d" 'comint-delchar-or-maybe-eof)
411 (define-key comint-mode-map "\C-a" 'comint-bol)
412 (define-key comint-mode-map "\C-c\C-u" 'comint-kill-input)
413 (define-key comint-mode-map "\C-c\C-w" 'backward-kill-word)
414 (define-key comint-mode-map "\C-c\C-c" 'comint-interrupt-subjob)
415 (define-key comint-mode-map "\C-c\C-z" 'comint-stop-subjob)
416 (define-key comint-mode-map "\C-c\C-\\" 'comint-quit-subjob)
417 ;; " ; Stops emacs-19.19's hilit getting confused.
418 (define-key comint-mode-map "\C-c\C-m" 'comint-copy-old-input)
419 (define-key comint-mode-map "\C-c\C-o" 'comint-kill-output)
420 (define-key comint-mode-map "\C-c\C-r" 'comint-show-output)
421 (define-key comint-mode-map "\C-c\C-e" 'comint-show-maximum-output)
422 (define-key comint-mode-map "\C-c\C-h" 'comint-dynamic-list-input-ring)
423 (define-key comint-mode-map "\C-c\C-n" 'comint-next-prompt)
424 (define-key comint-mode-map "\C-c\C-p" 'comint-previous-prompt)
425 (define-key comint-mode-map "\C-c\C-d" 'comint-send-eof)
426 ;; Menu bars:
427 ;; completion:
428 (define-key comint-mode-map [menu-bar completion]
429 (cons "Complete" (make-sparse-keymap "Complete")))
430 (define-key comint-mode-map [menu-bar completion complete-expand]
431 '("Expand File Name" . comint-replace-by-expanded-filename))
432 (define-key comint-mode-map [menu-bar completion complete-listing]
433 '("File Completion Listing" . comint-dynamic-list-filename-completions))
434 (define-key comint-mode-map [menu-bar completion complete-variable]
435 '("Complete Variable Name" . comint-dynamic-complete-variable))
436 (define-key comint-mode-map [menu-bar completion complete-command]
437 '("Complete Command Name" . (lambda () (interactive)
438 (funcall
439 comint-dynamic-complete-command-command))))
440 (define-key comint-mode-map [menu-bar completion complete-file]
441 '("Complete File Name" . comint-dynamic-complete-filename))
442 (define-key comint-mode-map [menu-bar completion complete]
443 '("Complete Before Point" . comint-dynamic-complete))
444 ;; Input history:
445 (define-key comint-mode-map [menu-bar input]
446 (cons "In/Out" (make-sparse-keymap "In/Out")))
447 (define-key comint-mode-map [menu-bar input kill-output]
448 '("Kill Current Output Group" . comint-kill-output))
449 (define-key comint-mode-map [menu-bar input next-prompt]
450 '("Forward Output Group" . comint-next-prompt))
451 (define-key comint-mode-map [menu-bar input previous-prompt]
452 '("Backward Output Group" . comint-previous-prompt))
453 (define-key comint-mode-map [menu-bar input show-maximum-output]
454 '("Show Maximum Output" . comint-show-maximum-output))
455 (define-key comint-mode-map [menu-bar input show-output]
456 '("Show Current Output Group" . comint-show-output))
457 (define-key comint-mode-map [menu-bar input kill-input]
458 '("Kill Current Input" . comint-kill-input))
459 (define-key comint-mode-map [menu-bar input copy-input]
460 '("Copy Old Input" . comint-copy-old-input))
461 (define-key comint-mode-map [menu-bar input forward-matching-history]
462 '("Forward Matching Input..." . comint-forward-matching-input))
463 (define-key comint-mode-map [menu-bar input backward-matching-history]
464 '("Backward Matching Input..." . comint-backward-matching-input))
465 (define-key comint-mode-map [menu-bar input next-matching-history]
466 '("Next Matching Input..." . comint-next-matching-input))
467 (define-key comint-mode-map [menu-bar input previous-matching-history]
468 '("Previous Matching Input..." . comint-previous-matching-input))
469 (define-key comint-mode-map [menu-bar input next-matching-history-from-input]
470 '("Next Matching Current Input" . comint-next-matching-input-from-input))
471 (define-key comint-mode-map [menu-bar input previous-matching-history-from-input]
472 '("Previous Matching Current Input" . comint-previous-matching-input-from-input))
473 (define-key comint-mode-map [menu-bar input next-history]
474 '("Next Input" . comint-next-input))
475 (define-key comint-mode-map [menu-bar input previous-history]
476 '("Previous Input" . comint-previous-input))
477 (define-key comint-mode-map [menu-bar input list-history]
478 '("List Input History" . comint-dynamic-list-input-ring))
479 (define-key comint-mode-map [menu-bar input expand-history]
480 '("Expand History Before Point" . comint-replace-by-expanded-history))
481 ;; Signals
482 (define-key comint-mode-map [menu-bar signals]
483 (cons "Signals" (make-sparse-keymap "Signals")))
484 (define-key comint-mode-map [menu-bar signals eof]
485 '("EOF" . comint-send-eof))
486 (define-key comint-mode-map [menu-bar signals kill]
487 '("KILL" . comint-kill-subjob))
488 (define-key comint-mode-map [menu-bar signals quit]
489 '("QUIT" . comint-quit-subjob))
490 (define-key comint-mode-map [menu-bar signals cont]
491 '("CONT" . comint-continue-subjob))
492 (define-key comint-mode-map [menu-bar signals stop]
493 '("STOP" . comint-stop-subjob))
494 (define-key comint-mode-map [menu-bar signals break]
495 '("BREAK" . comint-interrupt-subjob))
496 ;; Put them in the menu bar:
497 (setq menu-bar-final-items (append '(completion input output signals)
498 menu-bar-final-items))
499 )
500
501
502;;; This function is used to make a full copy of the comint mode map,
503;;; so that client modes won't interfere with each other. This function
504;;; isn't necessary in emacs 18.5x, but we keep it around for 18.4x versions.
505(defun full-copy-sparse-keymap (km)
506 "Recursively copy the sparse keymap KM."
507 (cond ((consp km)
508 (cons (full-copy-sparse-keymap (car km))
509 (full-copy-sparse-keymap (cdr km))))
510 (t km)))
511
512(defun comint-check-proc (buffer)
513 "Return t if there is a living process associated w/buffer BUFFER.
514Living means the status is `run' or `stop'.
515BUFFER can be either a buffer or the name of one."
516 (let ((proc (get-buffer-process buffer)))
517 (and proc (memq (process-status proc) '(run stop)))))
518
519;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
520;;; for the second argument (program).
521;;;###autoload
522(defun make-comint (name program &optional startfile &rest switches)
523 "Make a comint process NAME in a buffer, running PROGRAM.
524The name of the buffer is made by surrounding NAME with `*'s.
525If there is already a running process in that buffer, it is not restarted.
526Optional third arg STARTFILE is the name of a file to send the contents of to
527the process. Any more args are arguments to PROGRAM."
528 (let ((buffer (get-buffer-create (concat "*" name "*"))))
529 ;; If no process, or nuked process, crank up a new one and put buffer in
530 ;; comint mode. Otherwise, leave buffer and existing process alone.
531 (cond ((not (comint-check-proc buffer))
532 (save-excursion
533 (set-buffer buffer)
534 (comint-mode)) ; Install local vars, mode, keymap, ...
535 (comint-exec buffer name program startfile switches)))
536 buffer))
537
538(defun comint-exec (buffer name command startfile switches)
539 "Start up a process in buffer BUFFER for comint modes.
540Blasts any old process running in the buffer. Doesn't set the buffer mode.
541You can use this to cheaply run a series of processes in the same comint
542buffer. The hook `comint-exec-hook' is run after each exec."
543 (save-excursion
544 (set-buffer buffer)
545 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
546 (if proc (delete-process proc)))
547 ;; Crank up a new process
548 (let ((proc (comint-exec-1 name buffer command switches)))
549 (set-process-filter proc 'comint-output-filter)
550 (make-local-variable 'comint-ptyp)
551 (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
552 ;; Jump to the end, and set the process mark.
553 (goto-char (point-max))
554 (set-marker (process-mark proc) (point))
555 ;; Feed it the startfile.
556 (cond (startfile
557 ;;This is guaranteed to wait long enough
558 ;;but has bad results if the comint does not prompt at all
559 ;; (while (= size (buffer-size))
560 ;; (sleep-for 1))
561 ;;I hope 1 second is enough!
562 (sleep-for 1)
563 (goto-char (point-max))
564 (insert-file-contents startfile)
565 (setq startfile (buffer-substring (point) (point-max)))
566 (delete-region (point) (point-max))
567 (comint-send-string proc startfile)))
568 (run-hooks 'comint-exec-hook)
569 buffer)))
570
571;;; This auxiliary function cranks up the process for comint-exec in
572;;; the appropriate environment.
573
574(defun comint-exec-1 (name buffer command switches)
575 (let ((process-environment process-environment))
576 (setenv "TERMCAP" (format "emacs:co#%d:tc=unknown" (frame-width)))
577 (setenv "TERM" "emacs")
578 (setenv "EMACS" "t")
579 (apply 'start-process name buffer command switches)))
580\f
581;;; Input history processing in a buffer
582;;; ===========================================================================
583;;; Useful input history functions, courtesy of the Ergo group.
584
585;;; Eleven commands:
586;;; comint-dynamic-list-input-ring List history in help buffer.
587;;; comint-previous-input Previous input...
588;;; comint-previous-matching-input ...matching a string.
589;;; comint-previous-matching-input-from-input ... matching the current input.
590;;; comint-next-input Next input...
591;;; comint-next-matching-input ...matching a string.
592;;; comint-next-matching-input-from-input ... matching the current input.
593;;; comint-backward-matching-input Backwards input...
594;;; comint-forward-matching-input ...matching a string.
595;;; comint-replace-by-expanded-history Expand history at point;
596;;; replace with expanded history.
597;;; comint-magic-space Expand history and insert space.
598;;;
599;;; Two functions:
600;;; comint-read-input-ring Read into comint-input-ring...
601;;; comint-write-input-ring Write to comint-input-ring-file-name.
602
603(defun comint-read-input-ring ()
604 "Sets the buffer's `comint-input-ring' from a history file.
605The name of the file is given by the variable `comint-input-ring-file-name'.
606The history ring is of size `comint-input-ring-size', regardless of file size.
607If `comint-input-ring-file-name' is nil this function does nothing.
608
609Useful within mode or mode hooks.
610
611The structure of the history file should be one input command per line, and
612most recent command last.
613See also `comint-input-ignoredups' and `comint-write-input-ring'."
614 (cond ((or (null comint-input-ring-file-name)
615 (equal comint-input-ring-file-name ""))
616 nil)
617 ((not (file-readable-p comint-input-ring-file-name))
618 (message "Cannot read history file %s" comint-input-ring-file-name))
619 (t
620 (let ((history-buf (get-file-buffer comint-input-ring-file-name))
621 (ring (make-ring comint-input-ring-size)))
622 (save-excursion
623 (set-buffer (or history-buf
624 (find-file-noselect comint-input-ring-file-name)))
625 ;; Save restriction in case file is already visited...
626 ;; Watch for those date stamps in history files!
627 (save-excursion
628 (save-restriction
629 (widen)
630 (goto-char (point-min))
631 (while (re-search-forward "^\\s *\\([^#].*\\)\\s *$" nil t)
632 (let ((history (buffer-substring (match-beginning 1)
633 (match-end 1))))
634 (if (or (null comint-input-ignoredups)
635 (ring-empty-p ring)
636 (not (string-equal (ring-ref ring 0) history)))
637 (ring-insert ring history)))))
638 ;; Kill buffer unless already visited.
639 (if (null history-buf)
640 (kill-buffer nil))))
641 (setq comint-input-ring ring
642 comint-input-ring-index nil)))))
643
644(defun comint-write-input-ring ()
645 "Writes the buffer's `comint-input-ring' to a history file.
646The name of the file is given by the variable `comint-input-ring-file-name'.
647The original contents of the file are lost if `comint-input-ring' is not empty.
648If `comint-input-ring-file-name' is nil this function does nothing.
649
650Useful within process sentinels.
651
652See also `comint-read-input-ring'."
653 (cond ((or (null comint-input-ring-file-name)
654 (equal comint-input-ring-file-name "")
655 (null comint-input-ring) (ring-empty-p comint-input-ring))
656 nil)
657 ((not (file-writable-p comint-input-ring-file-name))
658 (message "Cannot write history file %s" comint-input-ring-file-name))
659 (t
660 (let* ((history-buf (get-buffer-create " *Temp Input History*"))
661 (ring comint-input-ring)
662 (file comint-input-ring-file-name)
663 (index (ring-length ring)))
664 ;; Write it all out into a buffer first. Much faster, but messier,
665 ;; than writing it one line at a time.
666 (save-excursion
667 (set-buffer history-buf)
668 (erase-buffer)
669 (while (> index 0)
670 (setq index (1- index))
671 (insert (ring-ref ring index) ?\n))
672 (write-region (buffer-string) nil file nil 'no-message)
673 (kill-buffer nil))))))
674
675
676(defun comint-dynamic-list-input-ring ()
677 "List in help buffer the buffer's input history."
678 (interactive)
679 (if (or (not (ring-p comint-input-ring))
680 (ring-empty-p comint-input-ring))
681 (message "No history")
682 (let ((history nil)
683 (history-buffer " *Input History*")
684 (index (1- (ring-length comint-input-ring)))
685 (conf (current-window-configuration)))
686 ;; We have to build up a list ourselves from the ring vector.
687 (while (>= index 0)
688 (setq history (cons (ring-ref comint-input-ring index) history)
689 index (1- index)))
690 ;; Change "completion" to "history reference"
691 ;; to make the display accurate.
692 (with-output-to-temp-buffer history-buffer
693 (display-completion-list history)
694 (set-buffer history-buffer)
695 (forward-line 3)
696 (while (search-backward "completion" nil 'move)
697 (replace-match "history reference")))
698 (sit-for 0)
699 (message "Hit space to flush")
700 (let ((ch (read-event)))
701 (if (eq ch ?\ )
702 (set-window-configuration conf)
703 (setq unread-command-events (list ch)))))))
704
705
706(defun comint-regexp-arg (prompt)
707 ;; Return list of regexp and prefix arg using PROMPT.
708 (let* ((minibuffer-history-sexp-flag nil)
709 ;; Don't clobber this.
710 (last-command last-command)
711 (regexp (read-from-minibuffer prompt nil nil nil
712 'minibuffer-history-search-history)))
713 (list (if (string-equal regexp "")
714 (setcar minibuffer-history-search-history
715 (nth 1 minibuffer-history-search-history))
716 regexp)
717 (prefix-numeric-value current-prefix-arg))))
718
719(defun comint-search-arg (arg)
720 ;; First make sure there is a ring and that we are after the process mark
721 (cond ((not (comint-after-pmark-p))
722 (error "Not at command line"))
723 ((or (null comint-input-ring)
724 (ring-empty-p comint-input-ring))
725 (error "Empty input ring"))
726 ((zerop arg)
727 ;; arg of zero resets search from beginning, and uses arg of 1
728 (setq comint-input-ring-index nil)
729 1)
730 (t
731 arg)))
732
733(defun comint-search-start (arg)
734 ;; Index to start a directional search, starting at comint-input-ring-index
735 (if comint-input-ring-index
736 ;; If a search is running, offset by 1 in direction of arg
737 (mod (+ comint-input-ring-index (if (> arg 0) 1 -1))
738 (ring-length comint-input-ring))
739 ;; For a new search, start from beginning or end, as appropriate
740 (if (>= arg 0)
741 0 ; First elt for forward search
742 (1- (ring-length comint-input-ring))))) ; Last elt for backward search
743
744(defun comint-previous-input-string (arg)
745 "Return the string ARG places along the input ring.
746Moves relative to `comint-input-ring-index'."
747 (ring-ref comint-input-ring (if comint-input-ring-index
748 (mod (+ arg comint-input-ring-index)
749 (ring-length comint-input-ring))
750 arg)))
751
752(defun comint-previous-input (arg)
753 "Cycle backwards through input history."
754 (interactive "*p")
755 (comint-previous-matching-input "." arg))
756
757(defun comint-next-input (arg)
758 "Cycle forwards through input history."
759 (interactive "*p")
760 (comint-previous-input (- arg)))
761
762(defun comint-previous-matching-input-string (regexp arg)
763 "Return the string matching REGEXP ARG places along the input ring.
764Moves relative to `comint-input-ring-index'."
765 (let* ((pos (comint-previous-matching-input-string-position regexp arg)))
766 (if pos (ring-ref comint-input-ring pos))))
767
768(defun comint-previous-matching-input-string-position (regexp arg &optional start)
769 "Return the index matching REGEXP ARG places along the input ring.
770Moves relative to START, or `comint-input-ring-index'."
771 (if (or (not (ring-p comint-input-ring))
772 (ring-empty-p comint-input-ring))
773 (error "No history"))
774 (let* ((len (ring-length comint-input-ring))
775 (motion (if (> arg 0) 1 -1))
776 (n (mod (- (or start (comint-search-start arg)) motion) len))
777 (tried-each-ring-item nil)
778 (prev nil))
779 ;; Do the whole search as many times as the argument says.
780 (while (and (/= arg 0) (not tried-each-ring-item))
781 ;; Step once.
782 (setq prev n
783 n (mod (+ n motion) len))
784 ;; If we haven't reached a match, step some more.
785 (while (and (< n len) (not tried-each-ring-item)
786 (not (string-match regexp (ring-ref comint-input-ring n))))
787 (setq n (mod (+ n motion) len)
788 ;; If we have gone all the way around in this search.
789 tried-each-ring-item (= n prev)))
790 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
791 ;; Now that we know which ring element to use, if we found it, return that.
792 (if (string-match regexp (ring-ref comint-input-ring n))
793 n)))
794
795(defun comint-previous-matching-input (regexp arg)
796 "Search backwards through input history for match for REGEXP.
797\(Previous history elements are earlier commands.)
798With prefix argument N, search for Nth previous match.
799If N is negative, find the next or Nth next match."
800 (interactive (comint-regexp-arg "Previous input matching (regexp): "))
801 (setq arg (comint-search-arg arg))
802 (let ((pos (comint-previous-matching-input-string-position regexp arg)))
803 ;; Has a match been found?
804 (if (null pos)
805 (error "Not found")
806 (setq comint-input-ring-index pos)
807 (message "History item: %d" (1+ pos))
808 (delete-region
809 ;; Can't use kill-region as it sets this-command
810 (process-mark (get-buffer-process (current-buffer))) (point))
811 (insert (ring-ref comint-input-ring pos)))))
812
813(defun comint-next-matching-input (regexp arg)
814 "Search forwards through input history for match for REGEXP.
815\(Later history elements are more recent commands.)
816With prefix argument N, search for Nth following match.
817If N is negative, find the previous or Nth previous match."
818 (interactive (comint-regexp-arg "Next input matching (regexp): "))
819 (comint-previous-matching-input regexp (- arg)))
820
821(defun comint-previous-matching-input-from-input (arg)
822 "Search backwards through input history for match for current input.
823\(Previous history elements are earlier commands.)
824With prefix argument N, search for Nth previous match.
825If N is negative, find the next or Nth next match."
826 (interactive "p")
827 (if (not (memq last-command '(comint-previous-matching-input-from-input
828 comint-next-matching-input-from-input)))
829 ;; Starting a new search
830 (setq comint-matching-input-from-input-string
831 (buffer-substring
832 (process-mark (get-buffer-process (current-buffer)))
833 (point))
834 comint-input-ring-index nil))
835 (comint-previous-matching-input
836 (concat "^" (regexp-quote comint-matching-input-from-input-string))
837 arg))
838
839(defun comint-next-matching-input-from-input (arg)
840 "Search forwards through input history for match for current input.
841\(Previous history elements are earlier commands.)
842With prefix argument N, search for Nth previous match.
843If N is negative, find the next or Nth next match."
844 (interactive "p")
845 (comint-previous-matching-input-from-input (- arg)))
846
847
848(defun comint-replace-by-expanded-history ()
849 "Expand input command history references before point.
850This function depends on the buffer's idea of the input history, which may not
851match the command interpreter's idea, assuming it has one.
852
853Assumes history syntax is like typical Un*x shells'. However, since emacs
854cannot know the interpreter's idea of input line numbers, assuming it has one,
855it cannot expand absolute input line number references.
856
857See also `comint-magic-space'."
858 (interactive)
859 (save-excursion
860 (let ((toend (- (save-excursion (end-of-line nil) (point)) (point)))
861 (start (progn (comint-bol nil) (point))))
862 (while (re-search-forward
863 "[!^]" (save-excursion (end-of-line nil) (- (point) toend)) t)
864 ;; This seems a bit complex. We look for references such as !!, !-num,
865 ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
866 ;; If that wasn't enough, the plings can be suffixed with argument
867 ;; range specifiers.
868 ;; Argument ranges are complex too, so we hive off the input line,
869 ;; referenced with plings, with the range string to `comint-args'.
870 (setq comint-input-ring-index nil)
871 (goto-char (match-beginning 0))
872 (cond ((or (= (preceding-char) ?\\)
873 (comint-within-quotes start (point)))
874 ;; The history is quoted, or we're in quotes.
875 (goto-char (match-end 0)))
876 ((looking-at "![0-9]+\\($\\|[^-]\\)")
877 ;; We cannot know the interpreter's idea of input line numbers.
878 (goto-char (match-end 0))
879 (message "Absolute reference cannot be expanded"))
880 ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
881 ;; Just a number of args from `number' lines backward.
882 (let ((number (1- (string-to-number
883 (buffer-substring (match-beginning 1)
884 (match-end 1))))))
885 (if (<= number (ring-length comint-input-ring))
886 (progn
887 (replace-match
888 (comint-args (comint-previous-input-string number)
889 (match-beginning 2) (match-end 2)) t t)
890 (setq comint-input-ring-index number)
891 (message "History item: %d" (1+ number)))
892 (goto-char (match-end 0))
893 (message "Relative reference exceeds input history size"))))
894 ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
895 ;; Just a number of args from the previous input line.
896 (replace-match
897 (comint-args (comint-previous-input-string 0)
898 (match-beginning 1) (match-end 1)) t t))
899 ((looking-at
900 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
901 ;; Most recent input starting with or containing (possibly
902 ;; protected) string, maybe just a number of args. Phew.
903 (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
904 (mb2 (match-beginning 2)) (me2 (match-end 2))
905 (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
906 (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
907 (pos (save-match-data
908 (comint-previous-matching-input-string-position
909 (concat pref (regexp-quote exp)) 1))))
910 (if (null pos)
911 (progn (message "Not found")
912 (goto-char (match-end 0))
913 (ding))
914 (setq comint-input-ring-index pos)
915 (message "History item: %d" (1+ pos))
916 (replace-match
917 (comint-args (ring-ref comint-input-ring pos)
918 (match-beginning 4) (match-end 4))
919 t t))))
920 ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
921 ;; Quick substitution on the previous input line.
922 (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
923 (new (buffer-substring (match-beginning 2) (match-end 2)))
924 (pos nil))
925 (replace-match (comint-previous-input-string 0) t t)
926 (setq pos (point))
927 (goto-char (match-beginning 0))
928 (if (search-forward old pos t)
929 (replace-match new t t)
930 (message "Not found")
931 (ding))))
932 (t
933 (goto-char (match-end 0))))))))
934
935
936(defun comint-magic-space (arg)
937 "Expand input history references before point and insert ARG spaces.
938A useful command to bind to SPC. See `comint-replace-by-expanded-history'."
939 (interactive "p")
940 (comint-replace-by-expanded-history)
941 (self-insert-command arg))
942\f
943(defun comint-within-quotes (beg end)
944 "Return t if the number of quotes between BEG and END is odd.
945Quotes are single and double."
946 (let ((countsq (comint-how-many-region "\\(^\\|[^\\\\]\\)\'" beg end))
947 (countdq (comint-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
948 (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
949
950(defun comint-how-many-region (regexp beg end)
951 "Return number of matches for REGEXP from BEG to END."
952 (let ((count 0))
953 (save-excursion
954 (save-match-data
955 (goto-char beg)
956 (while (re-search-forward regexp end t)
957 (setq count (1+ count)))))
958 count))
959
960(defun comint-args (string begin end)
961 ;; From STRING, return the args depending on the range specified in the text
962 ;; from BEGIN to END. If BEGIN is nil, assume all args. Ignore leading `:'.
963 ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
964 (save-match-data
965 (if (null begin)
966 (comint-arguments string 0 nil)
967 (let* ((range (buffer-substring
968 (if (eq (char-after begin) ?:) (1+ begin) begin) end))
969 (nth (cond ((string-match "^[*^]" range) 1)
970 ((string-match "^-" range) 0)
971 ((string-equal range "$") nil)
972 (t (string-to-number range))))
973 (mth (cond ((string-match "[-*$]$" range) nil)
974 ((string-match "-" range)
975 (string-to-number (substring range (match-end 0))))
976 (t nth))))
977 (comint-arguments string nth mth)))))
978
979(defun comint-delim-arg (arg)
980 ;; Return a list of arguments from ARG. If there's a quote in there, just
981 ;; a list of the arg, otherwise try and break up using characters in
982 ;; comint-delimiter-argument-list. Returned list is backwards.
983 (if (or (null comint-delimiter-argument-list)
984 (string-match "[\"\'\`]" arg))
985 (list arg)
986 (let ((not-delim (format "[^%s]+" (mapconcat
987 (function (lambda (d) (regexp-quote d)))
988 comint-delimiter-argument-list "")))
989 (delim-str (mapconcat (function (lambda (d)
990 (concat (regexp-quote d) "+")))
991 comint-delimiter-argument-list "\\|"))
992 (args ()) (pos 0))
993 (while (or (eq pos (string-match not-delim arg pos))
994 (eq pos (string-match delim-str arg pos)))
995 (setq pos (match-end 0)
996 args (cons (substring arg (match-beginning 0) pos) args)))
997 args)))
998
999(defun comint-arguments (string nth mth)
1000 "Return from STRING the NTH to MTH arguments.
1001NTH and/or MTH can be nil, which means the last argument.
1002Returned arguments are separated by single spaces. Arguments are assumed to be
1003delimited by whitespace. Strings comprising characters in the variable
1004`comint-delimiter-argument-list' are treated as delimiters and arguments.
1005Argument 0 is the command name."
1006 (let ((arg "\\(\\S \\|\\(\"[^\"]*\"\\|\'[^\']*\'\\|\`[^\`]*\`\\)\\)+")
1007 (args ()) (pos 0) (str nil))
1008 ;; We build a list of all the args. Unnecessary, but more efficient, when
1009 ;; ranges of args are required, than picking out one by one and recursing.
1010 (while (string-match arg string pos)
1011 (setq pos (match-end 0)
1012 str (substring string (match-beginning 0) pos)
1013 args (nconc (comint-delim-arg str) args)))
1014 (let ((n (or nth (1- (length args))))
1015 (m (if mth (1- (- (length args) mth)) 0)))
1016 (mapconcat
1017 (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
1018\f
1019;;;
1020;;; Input processing stuff
1021;;;
1022
1023(defun comint-send-input ()
1024 "Send input to process.
1025After the process output mark, sends all text from the process mark to
1026point as input to the process. Before the process output mark, calls value
1027of variable `comint-get-old-input' to retrieve old input, copies it to the
1028process mark, and sends it. If variable `comint-process-echoes' is nil,
1029a terminal newline is also inserted into the buffer and sent to the process
1030\(if it is non-nil, all text from the process mark to point is deleted,
1031since it is assumed the remote process will re-echo it).
1032
1033Any history reference may be expanded depending on the value of the variable
1034`comint-input-autoexpand'. The value of variable `comint-input-sentinel' is
1035called on the input before sending it. The input is entered into the input
1036history ring, if the value of variable `comint-input-filter' returns non-nil
1037when called on the input.
1038
1039If variable `comint-eol-on-send' is non-nil, then point is moved to the
1040end of line before sending the input.
1041
1042`comint-get-old-input', `comint-input-sentinel', and `comint-input-filter'
1043are chosen according to the command interpreter running in the buffer. E.g.,
1044If the interpreter is the csh,
1045 comint-get-old-input is the default: take the current line, discard any
1046 initial string matching regexp comint-prompt-regexp.
1047 comint-input-sentinel monitors input for \"cd\", \"pushd\", and \"popd\"
1048 commands. When it sees one, it cd's the buffer.
1049 comint-input-filter is the default: returns t if the input isn't all white
1050 space.
1051
1052If the comint is Lucid Common Lisp,
1053 comint-get-old-input snarfs the sexp ending at point.
1054 comint-input-sentinel does nothing.
1055 comint-input-filter returns nil if the input matches input-filter-regexp,
1056 which matches (1) all whitespace (2) :a, :c, etc.
1057
1058Similarly for Soar, Scheme, etc."
1059 (interactive)
1060 ;; Note that the input string does not include its terminal newline.
1061 (let ((proc (get-buffer-process (current-buffer))))
1062 (if (not proc) (error "Current buffer has no process")
1063 (let* ((pmark (process-mark proc))
1064 (intxt (if (>= (point) (marker-position pmark))
1065 (progn (if comint-eol-on-send (end-of-line))
1066 (buffer-substring pmark (point)))
1067 (let ((copy (funcall comint-get-old-input)))
1068 (goto-char pmark)
1069 (insert copy)
1070 copy)))
1071 (input (if (not (eq comint-input-autoexpand 'input))
1072 ;; Just whatever's already there
1073 intxt
1074 ;; Expand and leave it visible in buffer
1075 (comint-replace-by-expanded-history)
1076 (buffer-substring pmark (point))))
1077 (history (if (not (eq comint-input-autoexpand 'history))
1078 (comint-arguments input 0 nil)
1079 ;; This is messy 'cos ultimately the original
1080 ;; functions used do insertion, rather than return
1081 ;; strings. We have to expand, then insert back.
1082 (comint-replace-by-expanded-history)
1083 (let ((copy (buffer-substring pmark (point))))
1084 (delete-region pmark (point))
1085 (insert input)
1086 (comint-arguments copy 0 nil)))))
1087 (if comint-process-echoes
1088 (delete-region pmark (point))
1089 (insert ?\n))
1090 (if (and (funcall comint-input-filter history)
1091 (or (null comint-input-ignoredups)
1092 (not (ring-p comint-input-ring))
1093 (ring-empty-p comint-input-ring)
1094 (not (string-equal (ring-ref comint-input-ring 0)
1095 history))))
1096 (ring-insert comint-input-ring history))
1097 (funcall comint-input-sentinel input)
1098 (funcall comint-input-sender proc input)
1099 (setq comint-input-ring-index nil)
1100 (set-marker comint-last-input-start pmark)
1101 (set-marker comint-last-input-end (point))
1102 (set-marker (process-mark proc) (point))
1103 ;; A kludge to prevent the delay between insert and process output
1104 ;; affecting the display. A case for a comint-send-input-hook?
1105 (if (eq (process-filter proc) 'comint-output-filter)
1106 (let ((functions comint-output-filter-functions))
1107 (while functions
1108 (funcall (car functions) (concat input "\n"))
1109 (setq functions (cdr functions)))))))))
1110
1111;; The purpose of using this filter for comint processes
1112;; is to keep comint-last-input-end from moving forward
1113;; when output is inserted.
1114(defun comint-output-filter (process string)
1115 ;; First check for killed buffer
1116 (let ((oprocbuf (process-buffer process)))
1117 (if (and oprocbuf (buffer-name oprocbuf))
1118 (let ((obuf (current-buffer))
1119 (opoint nil) (obeg nil) (oend nil))
1120 (set-buffer oprocbuf)
1121 (setq opoint (point))
1122 (setq obeg (point-min))
1123 (setq oend (point-max))
1124 (let ((buffer-read-only nil)
1125 (nchars (length string))
1126 (ostart nil))
1127 (widen)
1128 (goto-char (process-mark process))
1129 (setq ostart (point))
1130 (if (<= (point) opoint)
1131 (setq opoint (+ opoint nchars)))
1132 ;; Insert after old_begv, but before old_zv.
1133 (if (< (point) obeg)
1134 (setq obeg (+ obeg nchars)))
1135 (if (<= (point) oend)
1136 (setq oend (+ oend nchars)))
1137 (insert-before-markers string)
1138 ;; Don't insert initial prompt outside the top of the window.
1139 (if (= (window-start (selected-window)) (point))
1140 (set-window-start (selected-window) (- (point) (length string))))
1141 (if (and comint-last-input-end
1142 (marker-buffer comint-last-input-end)
1143 (= (point) comint-last-input-end))
1144 (set-marker comint-last-input-end (- comint-last-input-end nchars)))
1145 (set-marker comint-last-output-start ostart)
1146 (set-marker (process-mark process) (point))
1147 (force-mode-line-update))
1148
1149 (narrow-to-region obeg oend)
1150 (goto-char opoint)
1151 (let ((functions comint-output-filter-functions))
1152 (while functions
1153 (funcall (car functions) string)
1154 (setq functions (cdr functions))))
1155 (set-buffer obuf)))))
1156
1157(defun comint-preinput-scroll-to-bottom ()
1158 "Go to the end of buffer in all windows showing it.
1159Movement occurs if point in the selected window is not after the process mark,
1160and `this-command' is an insertion command. Insertion commands recognised
1161are `self-insert-command', `comint-magic-space', `yank', `mouse-yank-at-click',
1162and `hilit-yank'.
1163Depends on the value of `comint-scroll-to-bottom-on-input'.
1164
1165This function should be a pre-command hook."
1166 (if (and comint-scroll-to-bottom-on-input
1167 (memq this-command '(self-insert-command comint-magic-space yank
1168 mouse-yank-at-click hilit-yank)))
1169 (let* ((selected (selected-window))
1170 (current (current-buffer))
1171 (process (get-buffer-process current))
1172 (scroll comint-scroll-to-bottom-on-input))
1173 (if (and process (< (point) (process-mark process))
1174 scroll (not (window-minibuffer-p selected)))
1175 (walk-windows
1176 (function (lambda (window)
1177 (if (and (eq (window-buffer window) current)
1178 (or (eq scroll t) (eq scroll 'all)
1179 (and (eq scroll 'this) (eq selected window))))
1180 (progn
1181 (select-window window)
1182 (goto-char (point-max))
1183 (select-window selected)))))
1184 'not-minibuf t)))))
1185
1186(defun comint-postoutput-scroll-to-bottom (string)
1187 "Go to the end of buffer in all windows showing it.
1188Does not scroll if the current line is the last line in the buffer.
1189Depends on the value of `comint-scroll-to-bottom-on-output' and
1190`comint-scroll-show-maximum-output'.
1191
1192This function should be in the list `comint-output-filter-functions'."
1193 (let* ((selected (selected-window))
1194 (current (current-buffer))
1195 (process (get-buffer-process current))
1196 (scroll comint-scroll-to-bottom-on-output))
1197 (if process
1198 (walk-windows
1199 (function (lambda (window)
1200 (if (eq (window-buffer window) current)
1201 (progn
1202 (select-window window)
1203 (if (and (< (point) (process-mark process))
1204 (or (eq scroll t) (eq scroll 'all)
1205 ;; Maybe user wants point to jump to the end.
1206 (and (eq scroll 'this) (eq selected window))
1207 (and (eq scroll 'others) (not (eq selected window)))
1208 ;; If point was at the end, keep it at the end.
1209 (>= (point)
1210 (- (process-mark process) (length string)))))
1211 (goto-char (process-mark process)))
1212 ;; Optionally scroll so that the text
1213 ;; ends at the bottom of the window.
1214 (if (and comint-scroll-show-maximum-output
1215 (>= (point) (process-mark process)))
1216 (save-excursion
1217 (goto-char (point-max))
1218 (recenter -1)))
1219 (select-window selected)))))
1220 nil t))))
1221
1222(defun comint-show-maximum-output ()
1223 "Put the end of the buffer at the bottom of the window."
1224 (interactive)
1225 (goto-char (point-max))
1226 (recenter -1))
1227
1228(defun comint-get-old-input-default ()
1229 "Default for `comint-get-old-input'.
1230Take the current line, and discard any initial text matching
1231`comint-prompt-regexp'."
1232 (save-excursion
1233 (beginning-of-line)
1234 (comint-skip-prompt)
1235 (let ((beg (point)))
1236 (end-of-line)
1237 (buffer-substring beg (point)))))
1238
1239(defun comint-copy-old-input ()
1240 "Insert after prompt old input at point as new input to be edited.
1241Calls `comint-get-old-input' to get old input."
1242 (interactive)
1243 (let ((input (funcall comint-get-old-input))
1244 (process (get-buffer-process (current-buffer))))
1245 (if (not process)
1246 (error "Current buffer has no process")
1247 (goto-char (process-mark process))
1248 (insert input))))
1249
1250(defun comint-skip-prompt ()
1251 "Skip past the text matching regexp `comint-prompt-regexp'.
1252If this takes us past the end of the current line, don't skip at all."
1253 (let ((eol (save-excursion (end-of-line) (point))))
1254 (if (and (looking-at comint-prompt-regexp)
1255 (<= (match-end 0) eol))
1256 (goto-char (match-end 0)))))
1257
1258(defun comint-after-pmark-p ()
1259 "Return t if point is after the process output marker."
1260 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1261 (<= (marker-position pmark) (point))))
1262
1263(defun comint-simple-send (proc string)
1264 "Default function for sending to PROC input STRING.
1265This just sends STRING plus a newline. To override this,
1266set the hook `comint-input-sender'."
1267 (comint-send-string proc string)
1268 (comint-send-string proc "\n"))
1269
1270(defun comint-bol (arg)
1271 "Goes to the beginning of line, then skips past the prompt, if any.
1272If prefix argument is given (\\[universal-argument]) the prompt is not skipped.
1273
1274The prompt skip is done by skipping text matching the regular expression
1275`comint-prompt-regexp', a buffer local variable.
1276
1277If you don't like this command, bind C-a to `beginning-of-line'
1278in your hook, `comint-mode-hook'."
1279 (interactive "P")
1280 (beginning-of-line)
1281 (if (null arg) (comint-skip-prompt)))
1282
1283;;; These two functions are for entering text you don't want echoed or
1284;;; saved -- typically passwords to ftp, telnet, or somesuch.
1285;;; Just enter m-x send-invisible and type in your line.
1286
1287(defun comint-read-noecho (prompt &optional stars)
1288 "Read a single line of text from user without echoing, and return it.
1289Prompt with argument PROMPT, a string. Optional argument STARS causes
1290input to be echoed with '*' characters on the prompt line. Input ends with
1291RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line. C-g aborts (if
1292`inhibit-quit' is set because e.g. this function was called from a process
1293filter and C-g is pressed, this function returns nil rather than a string).
1294
1295Note that the keystrokes comprising the text can still be recovered
1296\(temporarily) with \\[view-lossage]. This may be a security bug for some
1297applications."
1298 (let ((ans "")
1299 (c 0)
1300 (echo-keystrokes 0)
1301 (cursor-in-echo-area t)
1302 (done nil))
1303 (while (not done)
1304 (if stars
1305 (message "%s%s" prompt (make-string (length ans) ?*))
1306 (message prompt))
1307 (setq c (read-char))
1308 (cond ((= c ?\C-g)
1309 ;; This function may get called from a process filter, where
1310 ;; inhibit-quit is set. In later versions of emacs read-char
1311 ;; may clear quit-flag itself and return C-g. That would make
1312 ;; it impossible to quit this loop in a simple way, so
1313 ;; re-enable it here (for backward-compatibility the check for
1314 ;; quit-flag below would still be necessary, so this is seems
1315 ;; like the simplest way to do things).
1316 (setq quit-flag t
1317 done t))
1318 ((or (= c ?\r) (= c ?\n) (= c ?\e))
1319 (setq done t))
1320 ((= c ?\C-u)
1321 (setq ans ""))
1322 ((and (/= c ?\b) (/= c ?\177))
1323 (setq ans (concat ans (char-to-string c))))
1324 ((> (length ans) 0)
1325 (setq ans (substring ans 0 -1)))))
1326 (if quit-flag
1327 ;; Emulate a true quit, except that we have to return a value.
1328 (prog1
1329 (setq quit-flag nil)
1330 (message "Quit")
1331 (beep t))
1332 (message "")
1333 ans)))
1334
1335(defun send-invisible (str)
1336 "Read a string without echoing.
1337Then send it to the process running in the current buffer. A new-line
1338is additionally sent. String is not saved on comint input history list.
1339Security bug: your string can still be temporarily recovered with
1340\\[view-lossage]."
1341 (interactive "P") ; Defeat snooping via C-x esc
1342 (let ((proc (get-buffer-process (current-buffer))))
1343 (if (not proc) (error "Current buffer has no process")
1344 (comint-send-string proc
1345 (if (stringp str) str
1346 (comint-read-noecho "Non-echoed text: " t)))
1347 (comint-send-string proc "\n"))))
1348
1349\f
1350;;; Low-level process communication
1351
1352(defvar comint-input-chunk-size 512
1353 "*Long inputs are sent to comint processes in chunks of this size.
1354If your process is choking on big inputs, try lowering the value.")
1355
1356(defun comint-send-string (proc str)
1357 "Send PROCESS the contents of STRING as input.
1358This is equivalent to `process-send-string', except that long input strings
1359are broken up into chunks of size `comint-input-chunk-size'. Processes
1360are given a chance to output between chunks. This can help prevent processes
1361from hanging when you send them long inputs on some OS's."
1362 (let* ((len (length str))
1363 (i (min len comint-input-chunk-size)))
1364 (process-send-string proc (substring str 0 i))
1365 (while (< i len)
1366 (let ((next-i (+ i comint-input-chunk-size)))
1367 (accept-process-output)
1368 (sit-for 0)
1369 (process-send-string proc (substring str i (min len next-i)))
1370 (setq i next-i)))))
1371
1372(defun comint-send-region (proc start end)
1373 "Sends to PROC the region delimited by START and END.
1374This is a replacement for `process-send-region' that tries to keep
1375your process from hanging on long inputs. See `comint-send-string'."
1376 (comint-send-string proc (buffer-substring start end)))
1377\f
1378;;; Random input hackage
1379
1380(defun comint-kill-output ()
1381 "Kill all output from interpreter since last input.
1382Does not delete the prompt."
1383 (interactive)
1384 (let ((pmark (progn (goto-char
1385 (process-mark (get-buffer-process (current-buffer))))
1386 (beginning-of-line nil)
1387 (point-marker))))
1388 (kill-region comint-last-input-end pmark)
1389 (insert "*** output flushed ***\n")
1390 (comint-skip-prompt)
1391 (set-marker pmark (point))))
1392
1393(defun comint-show-output ()
1394 "Display start of this batch of interpreter output at top of window.
1395Also put cursor there if the current position is not visible."
1396 (interactive)
1397 (let ((pos (point)))
1398 (goto-char comint-last-input-end)
1399 (beginning-of-line 0)
1400 (set-window-start (selected-window) (point))
1401 (if (pos-visible-in-window-p pos)
1402 (goto-char pos)
1403 (comint-skip-prompt))))
1404
1405(defun comint-interrupt-subjob ()
1406 "Interrupt the current subjob."
1407 (interactive)
1408 (interrupt-process nil comint-ptyp))
1409
1410(defun comint-kill-subjob ()
1411 "Send kill signal to the current subjob."
1412 (interactive)
1413 (kill-process nil comint-ptyp))
1414
1415(defun comint-quit-subjob ()
1416 "Send quit signal to the current subjob."
1417 (interactive)
1418 (quit-process nil comint-ptyp))
1419
1420(defun comint-stop-subjob ()
1421 "Stop the current subjob.
1422WARNING: if there is no current subjob, you can end up suspending
1423the top-level process running in the buffer. If you accidentally do
1424this, use \\[comint-continue-subjob] to resume the process. (This
1425is not a problem with most shells, since they ignore this signal.)"
1426 (interactive)
1427 (stop-process nil comint-ptyp))
1428
1429(defun comint-continue-subjob ()
1430 "Send CONT signal to process buffer's process group.
1431Useful if you accidentally suspend the top-level process."
1432 (interactive)
1433 (continue-process nil comint-ptyp))
1434
1435(defun comint-kill-input ()
1436 "Kill all text from last stuff output by interpreter to point."
1437 (interactive)
1438 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1439 (if (> (point) (marker-position pmark))
1440 (kill-region pmark (point)))))
1441
1442(defun comint-delchar-or-maybe-eof (arg)
1443 "Delete ARG characters forward, or (if at eob) send an EOF to subprocess."
1444 (interactive "p")
1445 (if (eobp)
1446 (process-send-eof)
1447 (delete-char arg)))
1448
1449(defun comint-send-eof ()
1450 "Send an EOF to the current buffer's process."
1451 (interactive)
1452 (process-send-eof))
1453
1454
1455(defun comint-backward-matching-input (regexp arg)
1456 "Search backward through buffer for match for REGEXP.
1457Matches are searched for on lines that match `comint-prompt-regexp'.
1458With prefix argument N, search for Nth previous match.
1459If N is negative, find the next or Nth next match."
1460 (interactive (comint-regexp-arg "Backward input matching (regexp): "))
1461 (let* ((re (concat comint-prompt-regexp ".*" regexp))
1462 (pos (save-excursion (end-of-line (if (> arg 0) 0 1))
1463 (if (re-search-backward re nil t arg)
1464 (point)))))
1465 (if (null pos)
1466 (progn (message "Not found")
1467 (ding))
1468 (goto-char pos)
1469 (comint-bol nil))))
1470
1471(defun comint-forward-matching-input (regexp arg)
1472 "Search forward through buffer for match for REGEXP.
1473Matches are searched for on lines that match `comint-prompt-regexp'.
1474With prefix argument N, search for Nth following match.
1475If N is negative, find the previous or Nth previous match."
1476 (interactive (comint-regexp-arg "Forward input matching (regexp): "))
1477 (comint-backward-matching-input regexp (- arg)))
1478
1479
1480(defun comint-next-prompt (n)
1481 "Move to end of Nth next prompt in the buffer.
1482See `comint-prompt-regexp'."
1483 (interactive "p")
1484 (let ((paragraph-start comint-prompt-regexp))
1485 (end-of-line (if (> n 0) 1 0))
1486 (forward-paragraph n)
1487 (comint-skip-prompt)))
1488
1489(defun comint-previous-prompt (n)
1490 "Move to end of Nth previous prompt in the buffer.
1491See `comint-prompt-regexp'."
1492 (interactive "p")
1493 (comint-next-prompt (- n)))
1494\f
1495;;; Support for source-file processing commands.
1496;;;============================================================================
1497;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
1498;;; commands that process files of source text (e.g. loading or compiling
1499;;; files). So the corresponding process-in-a-buffer modes have commands
1500;;; for doing this (e.g., lisp-load-file). The functions below are useful
1501;;; for defining these commands.
1502;;;
1503;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
1504;;; and Soar, in that they don't know anything about file extensions.
1505;;; So the compile/load interface gets the wrong default occasionally.
1506;;; The load-file/compile-file default mechanism could be smarter -- it
1507;;; doesn't know about the relationship between filename extensions and
1508;;; whether the file is source or executable. If you compile foo.lisp
1509;;; with compile-file, then the next load-file should use foo.bin for
1510;;; the default, not foo.lisp. This is tricky to do right, particularly
1511;;; because the extension for executable files varies so much (.o, .bin,
1512;;; .lbin, .mo, .vo, .ao, ...).
1513
1514
1515;;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
1516;;; commands.
1517;;;
1518;;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
1519;;; want to save the buffer before issuing any process requests to the command
1520;;; interpreter.
1521;;;
1522;;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
1523;;; for the file to process.
1524
1525;;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
1526;;;============================================================================
1527;;; This function computes the defaults for the load-file and compile-file
1528;;; commands for tea, soar, cmulisp, and cmuscheme modes.
1529;;;
1530;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
1531;;; source-file processing command. NIL if there hasn't been one yet.
1532;;; - SOURCE-MODES is a list used to determine what buffers contain source
1533;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
1534;;; Typically, (lisp-mode) or (scheme-mode).
1535;;;
1536;;; If the command is given while the cursor is inside a string, *and*
1537;;; the string is an existing filename, *and* the filename is not a directory,
1538;;; then the string is taken as default. This allows you to just position
1539;;; your cursor over a string that's a filename and have it taken as default.
1540;;;
1541;;; If the command is given in a file buffer whose major mode is in
1542;;; SOURCE-MODES, then the the filename is the default file, and the
1543;;; file's directory is the default directory.
1544;;;
1545;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
1546;;; then the default directory & file are what was used in the last source-file
1547;;; processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
1548;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
1549;;; is the cwd, with no default file. (\"no default file\" = nil)
1550;;;
1551;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
1552;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
1553;;; for Soar programs, etc.
1554;;;
1555;;; The function returns a pair: (default-directory . default-file).
1556
1557(defun comint-source-default (previous-dir/file source-modes)
1558 (cond ((and buffer-file-name (memq major-mode source-modes))
1559 (cons (file-name-directory buffer-file-name)
1560 (file-name-nondirectory buffer-file-name)))
1561 (previous-dir/file)
1562 (t
1563 (cons default-directory nil))))
1564
1565
1566;;; (COMINT-CHECK-SOURCE fname)
1567;;;============================================================================
1568;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
1569;;; process-in-a-buffer modes), this function can be called on the filename.
1570;;; If the file is loaded into a buffer, and the buffer is modified, the user
1571;;; is queried to see if he wants to save the buffer before proceeding with
1572;;; the load or compile.
1573
1574(defun comint-check-source (fname)
1575 (let ((buff (get-file-buffer fname)))
1576 (if (and buff
1577 (buffer-modified-p buff)
1578 (y-or-n-p (format "Save buffer %s first? " (buffer-name buff))))
1579 ;; save BUFF.
1580 (let ((old-buffer (current-buffer)))
1581 (set-buffer buff)
1582 (save-buffer)
1583 (set-buffer old-buffer)))))
1584
1585
1586;;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
1587;;;============================================================================
1588;;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
1589;;; commands that process source files (like loading or compiling a file).
1590;;; It prompts for the filename, provides a default, if there is one,
1591;;; and returns the result filename.
1592;;;
1593;;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
1594;;;
1595;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
1596;;; from the last source processing command. SOURCE-MODES is a list of major
1597;;; modes used to determine what file buffers contain source files. (These
1598;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
1599;;; then the filename reader will only accept a file that exists.
1600;;;
1601;;; A typical use:
1602;;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
1603;;; '(lisp-mode) t))
1604
1605;;; This is pretty stupid about strings. It decides we're in a string
1606;;; if there's a quote on both sides of point on the current line.
1607(defun comint-extract-string ()
1608 "Return string around POINT that starts the current line, or nil."
1609 (save-excursion
1610 (let* ((point (point))
1611 (bol (progn (beginning-of-line) (point)))
1612 (eol (progn (end-of-line) (point)))
1613 (start (progn (goto-char point)
1614 (and (search-backward "\"" bol t)
1615 (1+ (point)))))
1616 (end (progn (goto-char point)
1617 (and (search-forward "\"" eol t)
1618 (1- (point))))))
1619 (and start end
1620 (buffer-substring start end)))))
1621
1622(defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
1623 (let* ((def (comint-source-default prev-dir/file source-modes))
1624 (stringfile (comint-extract-string))
1625 (sfile-p (and stringfile
1626 (condition-case ()
1627 (file-exists-p stringfile)
1628 (error nil))
1629 (not (file-directory-p stringfile))))
1630 (defdir (if sfile-p (file-name-directory stringfile)
1631 (car def)))
1632 (deffile (if sfile-p (file-name-nondirectory stringfile)
1633 (cdr def)))
1634 (ans (read-file-name (if deffile (format "%s(default %s) "
1635 prompt deffile)
1636 prompt)
1637 defdir
1638 (concat defdir deffile)
1639 mustmatch-p)))
1640 (list (expand-file-name (substitute-in-file-name ans)))))
1641
1642;;; I am somewhat divided on this string-default feature. It seems
1643;;; to violate the principle-of-least-astonishment, in that it makes
1644;;; the default harder to predict, so you actually have to look and see
1645;;; what the default really is before choosing it. This can trip you up.
1646;;; On the other hand, it can be useful, I guess. I would appreciate feedback
1647;;; on this.
1648;;; -Olin
1649
1650\f
1651;;; Simple process query facility.
1652;;; ===========================================================================
1653;;; This function is for commands that want to send a query to the process
1654;;; and show the response to the user. For example, a command to get the
1655;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
1656;;; to an inferior Common Lisp process.
1657;;;
1658;;; This simple facility just sends strings to the inferior process and pops
1659;;; up a window for the process buffer so you can see what the process
1660;;; responds with. We don't do anything fancy like try to intercept what the
1661;;; process responds with and put it in a pop-up window or on the message
1662;;; line. We just display the buffer. Low tech. Simple. Works good.
1663
1664;;; Send to the inferior process PROC the string STR. Pop-up but do not select
1665;;; a window for the inferior process so that its response can be seen.
1666(defun comint-proc-query (proc str)
1667 (let* ((proc-buf (process-buffer proc))
1668 (proc-mark (process-mark proc)))
1669 (display-buffer proc-buf)
1670 (set-buffer proc-buf) ; but it's not the selected *window*
1671 (let ((proc-win (get-buffer-window proc-buf))
1672 (proc-pt (marker-position proc-mark)))
1673 (comint-send-string proc str) ; send the query
1674 (accept-process-output proc) ; wait for some output
1675 ;; Try to position the proc window so you can see the answer.
1676 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
1677 ;; I don't know why. Wizards invited to improve it.
1678 (if (not (pos-visible-in-window-p proc-pt proc-win))
1679 (let ((opoint (window-point proc-win)))
1680 (set-window-point proc-win proc-mark)
1681 (sit-for 0)
1682 (if (not (pos-visible-in-window-p opoint proc-win))
1683 (push-mark opoint)
1684 (set-window-point proc-win opoint)))))))
1685
1686\f
1687;;; Filename/command/history completion in a buffer
1688;;; ===========================================================================
1689;;; Useful completion functions, courtesy of the Ergo group.
1690
1691;;; Six functions:
1692;;; comint-dynamic-complete Complete or expand command, filename,
1693;;; history at point.
1694;;; comint-dynamic-complete-filename Complete filename at point.
1695;;; comint-dynamic-complete-variable Complete variable at point.
1696;;; comint-dynamic-list-filename-completions List completions in help buffer.
1697;;; comint-replace-by-expanded-filename Expand and complete filename at point;
1698;;; replace with expanded/completed name.
1699;;; comint-dynamic-simple-complete Complete stub given candidates.
1700
1701;;; Four hooks (defined above):
1702;;; comint-dynamic-complete-filename-command Complete file name at point.
1703;;; comint-dynamic-complete-command-command Complete command at point.
1704;;; comint-get-current-command Return command at point.
1705;;; comint-after-partial-filename-command Return non-nil if after file.
1706
1707;;; These are not installed in the comint-mode keymap. But they are
1708;;; available for people who want them. Shell-mode installs them:
1709;;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
1710;;; (define-key shell-mode-map "\M-?"
1711;;; 'comint-dynamic-list-filename-completions)))
1712;;;
1713;;; Commands like this are fine things to put in load hooks if you
1714;;; want them present in specific modes.
1715
1716(defvar comint-completion-autolist nil
1717 "*If non-nil, automatically list possiblities on partial completion.
1718This mirrors the optional behavior of tcsh.")
1719
1720(defvar comint-completion-addsuffix t
1721 "*If non-nil, add a `/' to completed directories, ` ' to file names.
1722This mirrors the optional behavior of tcsh.")
1723
1724(defvar comint-completion-recexact nil
1725 "*If non-nil, use shortest completion if characters cannot be added.
1726This mirrors the optional behavior of tcsh.
1727
1728A non-nil value is useful if `comint-completion-autolist' is non-nil too.")
1729
1730(defvar comint-file-name-prefix ""
1731 "Prefix prepended to absolute file names taken from process input.
1732This is used by comint's and shell's completion functions, and by shell's
1733directory tracking functions.")
1734
1735
1736(defun comint-directory (directory)
1737 ;; Return expanded DIRECTORY, with `comint-file-name-prefix' if absolute.
1738 (expand-file-name (if (file-name-absolute-p directory)
1739 (concat comint-file-name-prefix directory)
1740 directory)))
1741
1742
1743(defun comint-match-partial-filename ()
1744 "Return the filename at point, or signal an error.
1745Environment variables are substituted."
1746 (save-excursion
1747 (if (re-search-backward "[^~/A-Za-z0-9+@:_.$#,={}-]" nil 'move)
1748 (forward-char 1))
1749 ;; Anchor the search forwards.
1750 (if (not (looking-at "[~/A-Za-z0-9+@:_.$#,={}-]")) (error ""))
1751 (re-search-forward "[~/A-Za-z0-9+@:_.$#,={}-]+")
1752 (substitute-in-file-name
1753 (buffer-substring (match-beginning 0) (match-end 0)))))
1754
1755
1756(defun comint-match-partial-variable ()
1757 "Return the variable at point, or signal an error."
1758 (save-excursion
1759 (if (re-search-backward "[^A-Za-z0-9_${}]" nil 'move)
1760 (forward-char 1))
1761 ;; Anchor the search forwards.
1762 (if (not (looking-at "\\$")) (error ""))
1763 (re-search-forward "\\${?[A-Za-z0-9_]+}?")
1764 (buffer-substring (match-beginning 0) (match-end 0))))
1765
1766
1767(defun comint-after-partial-filename ()
1768 "Returns t if point is after a file name.
1769File names are assumed to contain `/'s or not be the first item in the input.
1770
1771See also `comint-bol'."
1772 (let ((filename (comint-match-partial-filename)))
1773 (or (save-match-data (string-match "/" filename))
1774 (not (eq (match-beginning 0)
1775 (save-excursion (comint-bol nil) (point)))))))
1776
1777
1778(defun comint-dynamic-complete ()
1779 "Dynamically complete/expand the command/filename/history at point.
1780If the text contains (a non-absolute line reference) `!' or `^' and
1781`comint-input-autoexpand' is non-nil, then an attempt is made to complete the
1782history. The value of the variable `comint-after-partial-filename-command' is
1783used to match file names. Otherwise, an attempt is made to complete the
1784command.
1785
1786See also the variables `comint-after-partial-filename-command',
1787`comint-dynamic-complete-filename-command', and
1788`comint-dynamic-complete-command-command', and functions
1789`comint-replace-by-expanded-history' and `comint-magic-space'."
1790 (interactive)
1791 (let ((previous-modified-tick (buffer-modified-tick)))
1792 (if (and comint-input-autoexpand
1793 (string-match "[!^]" (funcall comint-get-current-command)))
1794 ;; Looks like there might be history references in the command.
1795 (comint-replace-by-expanded-history))
1796 (if (= previous-modified-tick (buffer-modified-tick))
1797 ;; No references were expanded, so maybe they were none after all.
1798 (cond ((funcall comint-after-partial-filename-command)
1799 ;; It's a file name.
1800 (funcall comint-dynamic-complete-filename-command))
1801 (t
1802 ;; Assume it's a command.
1803 (funcall comint-dynamic-complete-command-command))))))
1804
1805
1806(defun comint-dynamic-complete-filename ()
1807 "Dynamically complete the filename at point.
1808This function is similar to `comint-replace-by-expanded-filename', except that
1809it won't change parts of the filename already entered in the buffer; it just
1810adds completion characters to the end of the filename. A completions listing
1811may be shown in a help buffer if completion is ambiguous.
1812
1813Completion is dependent on the value of `comint-completion-addsuffix' and
1814`comint-completion-recexact', and the timing of completions listing is
1815dependent on the value of `comint-completion-autolist'."
1816 (interactive)
1817 (let* ((completion-ignore-case nil)
1818 (filename (comint-match-partial-filename))
1819 (pathdir (file-name-directory filename))
1820 (pathnondir (file-name-nondirectory filename))
1821 (directory (if pathdir (comint-directory pathdir) default-directory))
1822 (completion (file-name-completion pathnondir directory)))
1823 (cond ((null completion)
1824 (message "No completions of %s" filename)
1825 (ding))
1826 ((eq completion t) ; Means already completed "file".
1827 (if comint-completion-addsuffix (insert " "))
1828 (message "Sole completion"))
1829 ((string-equal completion "") ; Means completion on "directory/".
1830 (comint-dynamic-list-filename-completions))
1831 (t ; Completion string returned.
1832 (let ((file (concat (file-name-as-directory directory) completion)))
1833 (goto-char (match-end 0))
1834 (insert (substring (directory-file-name completion)
1835 (length pathnondir)))
1836 (cond ((symbolp (file-name-completion completion directory))
1837 ;; We inserted a unique completion.
1838 (if comint-completion-addsuffix
1839 (insert (if (file-directory-p file) "/" " ")))
1840 (message "Completed"))
1841 ((and comint-completion-recexact comint-completion-addsuffix
1842 (string-equal pathnondir completion)
1843 (file-exists-p file))
1844 ;; It's not unique, but user wants shortest match.
1845 (insert (if (file-directory-p file) "/" " "))
1846 (message "Completed shortest"))
1847 ((or comint-completion-autolist
1848 (string-equal pathnondir completion))
1849 ;; It's not unique, list possible completions.
1850 (comint-dynamic-list-filename-completions))
1851 (t
1852 (message "Partially completed"))))))))
1853
1854
1855(defun comint-replace-by-expanded-filename ()
1856 "Dynamically expand and complete the filename at point.
1857Replace the filename with an expanded, canonicalised and completed replacement.
1858\"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
1859with the corresponding directories. \"Canonicalised\" means `..' and `.' are
1860removed, and the filename is made absolute instead of relative. For expansion
1861see `expand-file-name' and `substitute-in-file-name'. For completion see
1862`comint-dynamic-complete-filename'."
1863 (interactive)
1864 (replace-match (expand-file-name (comint-match-partial-filename)) t t)
1865 (comint-dynamic-complete-filename))
1866
1867
1868(defun comint-dynamic-complete-variable ()
1869 "Dynamically complete the environment variable at point.
1870This function is similar to `comint-dynamic-complete-filename', except that it
1871searches `process-environment' for completion candidates. Note that this may
1872not be the same as the interpreter's idea of variable names. The main
1873problem with this type of completion is that `process-environment' is the
1874environment which Emacs started with. Emacs does not track changes to the
1875environment made by the interpreter. Perhaps it would be more accurate if this
1876function was called `comint-dynamic-complete-process-environment-variable'.
1877
1878See also `comint-dynamic-complete-filename'."
1879 (interactive)
1880 (let* ((completion-ignore-case nil)
1881 (variable (comint-match-partial-variable))
1882 (varname (substring variable (string-match "[^$({]" variable)))
1883 (protection (cond ((string-match "{" variable) "}")
1884 ((string-match "(" variable) ")")
1885 (t "")))
1886 (variables (mapcar (function (lambda (x)
1887 (list (substring x 0 (string-match "=" x)))))
1888 process-environment))
1889 (var-directory-p
1890 (function (lambda (var)
1891 (file-directory-p
1892 (comint-directory (substitute-in-file-name (concat "$" var)))))))
1893 (completions (all-completions varname variables)))
1894 ;; Complete variable as if its value were a filename (which it might be).
1895 (cond ((null completions)
1896 (message "No completions of %s" varname)
1897 (ding))
1898 ((= 1 (length completions)) ; Gotcha!
1899 (let ((completion (car completions)))
1900 (if (string-equal completion varname)
1901 (message "Sole completion")
1902 (insert (substring (directory-file-name completion)
1903 (length varname)))
1904 (message "Completed"))
1905 (insert protection)
1906 (if comint-completion-addsuffix
1907 (insert (if (funcall var-directory-p completion) "/" " ")))))
1908 (t ; There's no unique completion.
1909 (let ((completion (try-completion varname variables)))
1910 ;; Insert the longest substring.
1911 (insert (substring (directory-file-name completion)
1912 (length varname)))
1913 (cond ((and comint-completion-recexact comint-completion-addsuffix
1914 (string-equal varname completion)
1915 (member completion completions))
1916 ;; It's not unique, but user wants shortest match.
1917 (insert protection
1918 (if (funcall var-directory-p completion) "/" " "))
1919 (message "Completed shortest"))
1920 ((or comint-completion-autolist
1921 (string-equal varname completion))
1922 ;; It's not unique, list possible completions.
1923 (comint-dynamic-list-completions completions))
1924 (t
1925 (message "Partially completed"))))))))
1926
1927
1928(defun comint-dynamic-simple-complete (stub candidates)
1929 "Dynamically complete STUB from CANDIDATES list.
1930This function inserts completion characters at point by completing STUB from
1931the strings in CANDIDATES. A completions listing may be shown in a help buffer
1932if completion is ambiguous.
1933
1934See also `comint-dynamic-complete-filename'."
1935 (let* ((completion-ignore-case nil)
1936 (candidates (mapcar (function (lambda (x) (list x))) candidates))
1937 (completions (all-completions stub candidates)))
1938 (cond ((null completions)
1939 (message "No completions of %s" stub)
1940 (ding))
1941 ((= 1 (length completions)) ; Gotcha!
1942 (let ((completion (car completions)))
1943 (if (string-equal completion stub)
1944 (message "Sole completion")
1945 (insert (substring completion (length stub)))
1946 (message "Completed"))
1947 (if comint-completion-addsuffix (insert " "))))
1948 (t ; There's no unique completion.
1949 (let ((completion (try-completion stub candidates)))
1950 ;; Insert the longest substring.
1951 (insert (substring completion (length stub)))
1952 (cond ((and comint-completion-recexact comint-completion-addsuffix
1953 (string-equal stub completion)
1954 (member completion completions))
1955 ;; It's not unique, but user wants shortest match.
1956 (insert " ")
1957 (message "Completed shortest"))
1958 ((or comint-completion-autolist
1959 (string-equal stub completion))
1960 ;; It's not unique, list possible completions.
1961 (comint-dynamic-list-completions completions))
1962 (t
1963 (message "Partially completed"))))))))
1964
1965
1966(defun comint-dynamic-list-filename-completions ()
1967 "List in help buffer possible completions of the filename at point."
1968 (interactive)
1969 (let* ((completion-ignore-case nil)
1970 (filename (comint-match-partial-filename))
1971 (pathdir (file-name-directory filename))
1972 (pathnondir (file-name-nondirectory filename))
1973 (directory (if pathdir (comint-directory pathdir) default-directory))
1974 (completions (file-name-all-completions pathnondir directory)))
1975 (if completions
1976 (comint-dynamic-list-completions completions)
1977 (message "No completions of %s" filename)
1978 (ding))))
1979
1980
1981(defun comint-dynamic-list-completions (completions)
1982 "List in help buffer sorted COMPLETIONS.
1983Typing SPC flushes the help buffer."
1984 (let ((conf (current-window-configuration)))
1985 (with-output-to-temp-buffer " *Completions*"
1986 (display-completion-list (sort completions 'string-lessp)))
1987 (sit-for 0)
1988 (message "Hit space to flush")
1989 (let ((ch (read-event)))
1990 (if (eq ch ?\ )
1991 (set-window-configuration conf)
1992 (setq unread-command-events (list ch))))))
1993\f
1994;;; Converting process modes to use comint mode
1995;;; ===========================================================================
1996;;; The code in the Emacs 19 distribution has all been modified to use comint
1997;;; where needed. However, there are `third-party' packages out there that
1998;;; still use the old shell mode. Here's a guide to conversion.
1999;;;
2000;;; Renaming variables
2001;;; Most of the work is renaming variables and functions. These are the common
2002;;; ones:
2003;;; Local variables:
2004;;; last-input-start comint-last-input-start
2005;;; last-input-end comint-last-input-end
2006;;; shell-prompt-pattern comint-prompt-regexp
2007;;; shell-set-directory-error-hook <no equivalent>
2008;;; Miscellaneous:
2009;;; shell-set-directory <unnecessary>
2010;;; shell-mode-map comint-mode-map
2011;;; Commands:
2012;;; shell-send-input comint-send-input
2013;;; shell-send-eof comint-delchar-or-maybe-eof
2014;;; kill-shell-input comint-kill-input
2015;;; interrupt-shell-subjob comint-interrupt-subjob
2016;;; stop-shell-subjob comint-stop-subjob
2017;;; quit-shell-subjob comint-quit-subjob
2018;;; kill-shell-subjob comint-kill-subjob
2019;;; kill-output-from-shell comint-kill-output
2020;;; show-output-from-shell comint-show-output
2021;;; copy-last-shell-input Use comint-previous-input/comint-next-input
2022;;;
2023;;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
2024;;; SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-sentinel.
2025;;; Comint mode does not provide functionality equivalent to
2026;;; shell-set-directory-error-hook; it is gone.
2027;;;
2028;;; comint-last-input-start is provided for modes which want to munge
2029;;; the buffer after input is sent, perhaps because the inferior
2030;;; insists on echoing the input. The LAST-INPUT-START variable in
2031;;; the old shell package was used to implement a history mechanism,
2032;;; but you should think twice before using comint-last-input-start
2033;;; for this; the input history ring often does the job better.
2034;;;
2035;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
2036;;; *not* create the comint-mode local variables in your foo-mode function.
2037;;; This is not modular. Instead, call comint-mode, and let *it* create the
2038;;; necessary comint-specific local variables. Then create the
2039;;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
2040;;; be foo-mode-map, and its mode to be foo-mode. Set the comint-mode hooks
2041;;; (comint-prompt-regexp, comint-input-filter, comint-input-sentinel,
2042;;; comint-get-old-input) that need to be different from the defaults. Call
2043;;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
2044;;; comint-mode will take care of it. The following example, from shell.el,
2045;;; is typical:
2046;;;
2047;;; (defvar shell-mode-map '())
2048;;; (cond ((not shell-mode-map)
2049;;; (setq shell-mode-map (full-copy-sparse-keymap comint-mode-map))
2050;;; (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
2051;;; (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
2052;;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
2053;;; (define-key shell-mode-map "\M-?"
2054;;; 'comint-dynamic-list-filename-completions)))
2055;;;
2056;;; (defun shell-mode ()
2057;;; (interactive)
2058;;; (comint-mode)
2059;;; (setq comint-prompt-regexp shell-prompt-pattern)
2060;;; (setq major-mode 'shell-mode)
2061;;; (setq mode-name "Shell")
2062;;; (use-local-map shell-mode-map)
2063;;; (make-local-variable 'shell-directory-stack)
2064;;; (setq shell-directory-stack nil)
2065;;; (setq comint-input-sentinel 'shell-directory-tracker)
2066;;; (run-hooks 'shell-mode-hook))
2067;;;
2068;;;
2069;;; Note that make-comint is different from make-shell in that it
2070;;; doesn't have a default program argument. If you give make-shell
2071;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
2072;;; $ESHELL, $SHELL, or /bin/sh. If you give make-comint a program argument
2073;;; of NIL, it barfs. Adjust your code accordingly...
2074;;;
2075;;; Completion for comint-mode users
2076;;;
2077;;; For modes that use comint-mode, comint-after-partial-filename-command
2078;;; should be set to a function that returns t if the stub before point is to
2079;;; be treated as a filename. By default, if the stub contains a `/', or does
2080;;; not follow the prompt, comint-dynamic-complete-filename-command is called.
2081;;; Otherwise, comint-dynamic-complete-command-command is called. This should
2082;;; also be set to a function that completes whatever the mode calls commands.
2083;;; You could use comint-dynamic-simple-complete to do the bulk of the
2084;;; completion job.
2085\f
2086;;; Do the user's customisation...
2087;;;
2088;;; Isn't this what eval-after-load is for?
2089;;;(defvar comint-load-hook nil
2090;;; "This hook is run when comint is loaded in.
2091;;;This is a good place to put keybindings.")
2092;;;
2093;;;(run-hooks 'comint-load-hook)
2094
2095(provide 'comint)
2096
2097;;; comint.el ends here