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