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