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