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