]> code.delx.au - gnu-emacs/blob - lisp/comint.el
(server-visit-files): Bind `minibuffer-auto-raise' to the value of
[gnu-emacs] / lisp / comint.el
1 ;;; comint.el --- general command interpreter in a window stuff
2
3 ;; Copyright (C) 1988, 1990, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 ;; 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
7 ;; Simon Marshall <simon@gnu.org>
8 ;; Maintainer: FSF
9 ;; Keywords: processes
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Commentary:
29
30 ;; This file defines a general command-interpreter-in-a-buffer package
31 ;; (comint mode). The idea is that you can build specific process-in-a-buffer
32 ;; modes on top of comint mode -- e.g., Lisp, shell, scheme, T, soar, ....
33 ;; This way, all these specific packages share a common base functionality,
34 ;; and a common set of bindings, which makes them easier to use (and
35 ;; saves code, implementation time, etc., etc.).
36
37 ;; Several packages are already defined using comint mode:
38 ;; - shell.el defines a shell-in-a-buffer mode.
39 ;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
40 ;;
41 ;; - The file cmuscheme.el defines a scheme-in-a-buffer mode.
42 ;; - The file tea.el tunes scheme and inferior-scheme modes for T.
43 ;; - The file soar.el tunes Lisp and inferior-lisp modes for Soar.
44 ;; - cmutex.el defines TeX and LaTeX modes that invoke TeX, LaTeX, BibTeX,
45 ;; previewers, and printers from within Emacs.
46 ;; - background.el allows csh-like job control inside Emacs.
47 ;; It is pretty easy to make new derived modes for other processes.
48
49 ;; For documentation on the functionality provided by Comint mode, and
50 ;; the hooks available for customising it, see the comments below.
51 ;; For further information on the standard derived modes (shell,
52 ;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
53
54 ;; For hints on converting existing process modes (e.g., tex-mode,
55 ;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
56 ;; instead of shell-mode, see the notes at the end of this file.
57
58 \f
59 ;; Brief Command Documentation:
60 ;;============================================================================
61 ;; Comint Mode Commands: (common to all derived modes, like shell & cmulisp
62 ;; mode)
63 ;;
64 ;; M-p comint-previous-input Cycle backwards in input history
65 ;; M-n comint-next-input Cycle forwards
66 ;; M-r comint-previous-matching-input Previous input matching a regexp
67 ;; M-s comint-next-matching-input Next input that matches
68 ;; M-C-l comint-show-output Show last batch of process output
69 ;; RET comint-send-input
70 ;; C-d comint-delchar-or-maybe-eof Delete char unless at end of buff
71 ;; C-c C-a comint-bol-or-process-mark First time, move point to bol;
72 ;; second time, move to process-mark.
73 ;; C-c C-u comint-kill-input ^u
74 ;; C-c C-w backward-kill-word ^w
75 ;; C-c C-c comint-interrupt-subjob ^c
76 ;; C-c C-z comint-stop-subjob ^z
77 ;; C-c C-\ comint-quit-subjob ^\
78 ;; C-c C-o comint-delete-output Delete last batch of process output
79 ;; C-c C-r comint-show-output Show last batch of process output
80 ;; C-c C-l comint-dynamic-list-input-ring List input history
81 ;;
82 ;; Not bound by default in comint-mode (some are in shell mode)
83 ;; comint-run Run a program under comint-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-list-filename-completions List completions in help buffer.
87 ;; comint-replace-by-expanded-filename Expand and complete filename at point;
88 ;; replace with expanded/completed name.
89 ;; comint-replace-by-expanded-history Expand history at point;
90 ;; replace with expanded name.
91 ;; comint-magic-space Expand history and add (a) space(s).
92 ;; comint-kill-subjob No mercy.
93 ;; comint-show-maximum-output Show as much output as possible.
94 ;; comint-continue-subjob Send CONT signal to buffer's process
95 ;; group. Useful if you accidentally
96 ;; suspend your process (with C-c C-z).
97 ;; comint-get-next-from-history Fetch successive input history lines
98 ;; comint-accumulate Combine lines to send them together
99 ;; as input.
100 ;; comint-goto-process-mark Move point to where process-mark is.
101 ;; comint-set-process-mark Set process-mark to point.
102
103 ;; comint-mode-hook is the Comint mode hook. Basically for your keybindings.
104
105 ;;; Code:
106
107 (require 'ring)
108 \f
109 ;; Buffer Local Variables:
110 ;;============================================================================
111 ;; Comint mode buffer local variables:
112 ;; comint-prompt-regexp string comint-bol uses to match prompt
113 ;; comint-delimiter-argument-list list For delimiters and arguments
114 ;; comint-last-input-start marker Handy if inferior always echoes
115 ;; comint-last-input-end marker For comint-delete-output command
116 ;; comint-input-ring-size integer For the input history
117 ;; comint-input-ring ring mechanism
118 ;; comint-input-ring-index number ...
119 ;; comint-save-input-ring-index number ...
120 ;; comint-input-autoexpand symbol ...
121 ;; comint-input-ignoredups boolean ...
122 ;; comint-dynamic-complete-functions hook For the completion mechanism
123 ;; comint-completion-fignore list ...
124 ;; comint-file-name-chars string ...
125 ;; comint-file-name-quote-list list ...
126 ;; comint-get-old-input function Hooks for specific
127 ;; comint-input-filter-functions hook process-in-a-buffer
128 ;; comint-output-filter-functions hook function modes.
129 ;; comint-preoutput-filter-functions hook
130 ;; comint-input-filter function ...
131 ;; comint-input-sender function ...
132 ;; comint-eol-on-send boolean ...
133 ;; comint-process-echoes boolean ...
134 ;; comint-scroll-to-bottom-on-input symbol For scroll behavior
135 ;; comint-scroll-to-bottom-on-output symbol ...
136 ;; comint-scroll-show-maximum-output boolean ...
137 ;; comint-accum-marker maker For comint-accumulate
138 ;;
139 ;; Comint mode non-buffer local variables:
140 ;; comint-completion-addsuffix boolean/cons For file name
141 ;; comint-completion-autolist boolean completion behavior
142 ;; comint-completion-recexact boolean ...
143
144 (defgroup comint nil
145 "General command interpreter in a window stuff."
146 :group 'processes)
147
148 (defgroup comint-completion nil
149 "Completion facilities in comint."
150 :group 'comint)
151
152 (defgroup comint-source nil
153 "Source finding facilities in comint."
154 :prefix "comint-"
155 :group 'comint)
156
157 (defvar comint-prompt-regexp "^"
158 "Regexp to recognize prompts in the inferior process.
159 Defaults to \"^\", the null string at BOL.
160
161 This variable is only used if the variable
162 `comint-use-prompt-regexp' is non-nil.
163
164 Good choices:
165 Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
166 Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
167 franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
168 kcl: \"^>+ *\"
169 shell: \"^[^#$%>\\n]*[#$%>] *\"
170 T: \"^>+ *\"
171
172 This is a good thing to set in mode hooks.")
173
174 (defcustom comint-prompt-read-only nil
175 "If non-nil, the comint prompt is read only.
176 The read only region includes the newline before the prompt.
177 This does not affect existing prompts.
178 Certain derived modes may override this option.
179
180 If you set this option to t, then the safe way to temporarily
181 override the read-only-ness of comint prompts is to call
182 `comint-kill-whole-line' or `comint-kill-region' with no
183 narrowing in effect. This way you will be certain that none of
184 the remaining prompts will be accidentally messed up. You may
185 wish to put something like the following in your `.emacs' file:
186
187 \(add-hook 'comint-mode-hook
188 (lambda ()
189 (define-key comint-mode-map \"\\C-w\" 'comint-kill-region)
190 (define-key comint-mode-map [C-S-backspace]
191 'comint-kill-whole-line)))
192
193 If you sometimes use comint-mode on text-only terminals or with `emacs -nw',
194 you might wish to use another binding for `comint-kill-whole-line'."
195 :type 'boolean
196 :group 'comint
197 :version "22.1")
198
199 (defvar comint-delimiter-argument-list ()
200 "List of characters to recognize as separate arguments in input.
201 Strings comprising a character in this list will separate the arguments
202 surrounding them, and also be regarded as arguments in their own right (unlike
203 whitespace). See `comint-arguments'.
204 Defaults to the empty list.
205
206 For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?;).
207
208 This is a good thing to set in mode hooks.")
209
210 (defcustom comint-input-autoexpand nil
211 "*If non-nil, expand input command history references on completion.
212 This mirrors the optional behavior of tcsh (its autoexpand and histlist).
213
214 If the value is `input', then the expansion is seen on input.
215 If the value is `history', then the expansion is only when inserting
216 into the buffer's input ring. See also `comint-magic-space' and
217 `comint-dynamic-complete'.
218
219 This variable is buffer-local."
220 :type '(choice (const :tag "off" nil)
221 (const input)
222 (const history)
223 (other :tag "on" t))
224 :group 'comint)
225
226 (defface comint-highlight-input '((t (:weight bold)))
227 "Face to use to highlight user input."
228 :group 'comint)
229
230 (defface comint-highlight-prompt
231 '((((min-colors 88) (background dark)) (:foreground "cyan1"))
232 (((background dark)) (:foreground "cyan"))
233 (t (:foreground "dark blue")))
234 "Face to use to highlight prompts."
235 :group 'comint)
236
237 (defcustom comint-input-ignoredups nil
238 "*If non-nil, don't add input matching the last on the input ring.
239 This mirrors the optional behavior of bash.
240
241 This variable is buffer-local."
242 :type 'boolean
243 :group 'comint)
244
245 (defcustom comint-input-ring-file-name nil
246 "*If non-nil, name of the file to read/write input history.
247 See also `comint-read-input-ring' and `comint-write-input-ring'.
248
249 This variable is buffer-local, and is a good thing to set in mode hooks."
250 :type '(choice (const :tag "nil" nil)
251 file)
252 :group 'comint)
253
254 (defcustom comint-scroll-to-bottom-on-input nil
255 "*Controls whether input to interpreter causes window to scroll.
256 If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
257 If `this', scroll only the selected window.
258
259 The default is nil.
260
261 See `comint-preinput-scroll-to-bottom'. This variable is buffer-local."
262 :type '(choice (const :tag "off" nil)
263 (const t)
264 (const all)
265 (const this))
266 :group 'comint)
267
268 (defcustom comint-move-point-for-output nil
269 "*Controls whether interpreter output moves point to the end of the output.
270 If nil, then output never moves point to the output.
271 (If the output occurs at point, it is inserted before point.)
272 If t or `all', move point in all windows showing the buffer.
273 If `this', move point only the selected window.
274 If `others', move point only in other windows, not in the selected window.
275
276 The default is nil.
277
278 See the variable `comint-scroll-show-maximum-output' and the function
279 `comint-postoutput-scroll-to-bottom'.
280 This variable is buffer-local in all Comint buffers."
281 :type '(choice (const :tag "off" nil)
282 (const t)
283 (const all)
284 (const this)
285 (const others))
286 :group 'comint)
287
288 (defvaralias 'comint-scroll-to-bottom-on-output 'comint-move-point-for-output)
289
290 (defcustom comint-scroll-show-maximum-output t
291 "*Controls how to scroll due to interpreter output.
292 This variable applies when point is at the end of the buffer
293 \(either because it was originally there, or because
294 `comint-move-point-for-output' said to move it there)
295 and output from the subprocess is inserted.
296
297 Non-nil means scroll so that the window is full of text
298 and point is on the last line. A value of nil
299 means don't do anything special--scroll normally.
300
301 See also the variable `comint-move-point-for-output' and the function
302 `comint-postoutput-scroll-to-bottom'.
303 This variable is buffer-local in all Comint buffers."
304 :type 'boolean
305 :group 'comint)
306
307 (defcustom comint-buffer-maximum-size 1024
308 "*The maximum size in lines for Comint buffers.
309 Comint buffers are truncated from the top to be no greater than this number, if
310 the function `comint-truncate-buffer' is on `comint-output-filter-functions'."
311 :type 'integer
312 :group 'comint)
313
314 (defvar comint-input-ring-size 150
315 "Size of input history ring.")
316
317 (defvar comint-input-ring-separator "\n"
318 "Separator between commands in the history file.")
319
320 (defvar comint-input-history-ignore "^#"
321 "Regexp for history entries that should be ignored when Comint initializes.")
322
323 (defcustom comint-process-echoes nil
324 "*If non-nil, assume that the subprocess echoes any input.
325 If so, delete one copy of the input so that only one copy eventually
326 appears in the buffer.
327
328 This variable is buffer-local."
329 :type 'boolean
330 :group 'comint)
331
332 ;; AIX puts the name of the person being su'd to in front of the prompt.
333 ;; kinit prints a prompt like `Password for devnull@GNU.ORG: '.
334 ;; ksu prints a prompt like `Kerberos password for devnull/root@GNU.ORG: '.
335 ;; ssh-add prints a prompt like `Enter passphrase: '.
336 ;; Some implementations of passwd use "Password (again)" as the 2nd prompt.
337 (defcustom comint-password-prompt-regexp
338 "\\(\\([Oo]ld \\|[Nn]ew \\|'s \\|login \\|\
339 Kerberos \\|CVS \\|UNIX \\| SMB \\|^\\)\
340 \[Pp]assword\\( (again)\\)?\\|\
341 pass phrase\\|\\(Enter\\|Repeat\\|Bad\\) passphrase\\)\
342 \\(?:, try again\\)?\\(?: for [^:]+\\)?:\\s *\\'"
343 "*Regexp matching prompts for passwords in the inferior process.
344 This is used by `comint-watch-for-password-prompt'."
345 :type 'regexp
346 :group 'comint)
347
348 ;; Here are the per-interpreter hooks.
349 (defvar comint-get-old-input (function comint-get-old-input-default)
350 "Function that returns old text in Comint mode.
351 This function is called when return is typed while the point is in old
352 text. It returns the text to be submitted as process input. The
353 default is `comint-get-old-input-default', which either grabs the
354 current input field or grabs the current line and strips off leading
355 text matching `comint-prompt-regexp', depending on the value of
356 `comint-use-prompt-regexp'.")
357
358 (defvar comint-dynamic-complete-functions
359 '(comint-replace-by-expanded-history comint-dynamic-complete-filename)
360 "List of functions called to perform completion.
361 Functions should return non-nil if completion was performed.
362 See also `comint-dynamic-complete'.
363
364 This is a good thing to set in mode hooks.")
365
366 (defvar comint-input-filter
367 (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
368 "Predicate for filtering additions to input history.
369 Takes one argument, the input. If non-nil, the input may be saved on the input
370 history list. Default is to save anything that isn't all whitespace.")
371
372 (defvar comint-input-filter-functions '()
373 "Abnormal hook run before input is sent to the process.
374 These functions get one argument, a string containing the text to send.")
375
376 ;;;###autoload
377 (defvar comint-output-filter-functions '(comint-postoutput-scroll-to-bottom comint-watch-for-password-prompt)
378 "Functions to call after output is inserted into the buffer.
379 One possible function is `comint-postoutput-scroll-to-bottom'.
380 These functions get one argument, a string containing the text as originally
381 inserted. Note that this might not be the same as the buffer contents between
382 `comint-last-output-start' and the buffer's `process-mark', if other filter
383 functions have already modified the buffer.
384
385 See also `comint-preoutput-filter-functions'.
386
387 You can use `add-hook' to add functions to this list
388 either globally or locally.")
389
390 (defvar comint-input-sender-no-newline nil
391 "Non-nil directs the `comint-input-sender' function not to send a newline.")
392
393 (defvar comint-input-sender (function comint-simple-send)
394 "Function to actually send to PROCESS the STRING submitted by user.
395 Usually this is just `comint-simple-send', but if your mode needs to
396 massage the input string, put a different function here.
397 `comint-simple-send' just sends the string plus a newline.
398 \(If `comint-input-sender-no-newline' is non-nil, it omits the newline.)
399 This is called from the user command `comint-send-input'.")
400
401 (defcustom comint-eol-on-send t
402 "*Non-nil means go to the end of the line before sending input.
403 See `comint-send-input'."
404 :type 'boolean
405 :group 'comint)
406
407 ;; Note: If it is decided to purge comint-prompt-regexp from the source
408 ;; entirely, searching for uses of this variable will help to identify
409 ;; places that need attention.
410 (defcustom comint-use-prompt-regexp nil
411 "*If non-nil, use `comint-prompt-regexp' to recognize prompts.
412 If nil, then program output and user-input are given different `field'
413 properties, which Emacs commands can use to distinguish them (in
414 particular, common movement commands such as `beginning-of-line'
415 respect field boundaries in a natural way)."
416 :type 'boolean
417 :group 'comint)
418
419 ;; Autoload is necessary for Custom to recognize old alias.
420 ;;;###autoload
421 (define-obsolete-variable-alias 'comint-use-prompt-regexp-instead-of-fields
422 'comint-use-prompt-regexp "22.1")
423
424 (defcustom comint-mode-hook nil
425 "Hook run upon entry to `comint-mode'.
426 This is run before the process is cranked up."
427 :type 'hook
428 :group 'comint)
429
430 (defcustom comint-exec-hook '()
431 "Hook run each time a process is exec'd by `comint-exec'.
432 This is called after the process is cranked up. It is useful for things that
433 must be done each time a process is executed in a Comint mode buffer (e.g.,
434 `(process-kill-without-query)'). In contrast, the `comint-mode-hook' is only
435 executed once when the buffer is created."
436 :type 'hook
437 :group 'comint)
438
439 (defvar comint-mode-map
440 (let ((map (make-sparse-keymap)))
441 ;; Keys:
442 (define-key map "\ep" 'comint-previous-input)
443 (define-key map "\en" 'comint-next-input)
444 (define-key map [C-up] 'comint-previous-input)
445 (define-key map [C-down] 'comint-next-input)
446 (define-key map "\er" 'comint-previous-matching-input)
447 (define-key map "\es" 'comint-next-matching-input)
448 (define-key map [?\C-c ?\M-r] 'comint-previous-matching-input-from-input)
449 (define-key map [?\C-c ?\M-s] 'comint-next-matching-input-from-input)
450 (define-key map "\e\C-l" 'comint-show-output)
451 (define-key map "\C-m" 'comint-send-input)
452 (define-key map "\C-d" 'comint-delchar-or-maybe-eof)
453 (define-key map "\C-c " 'comint-accumulate)
454 (define-key map "\C-c\C-x" 'comint-get-next-from-history)
455 (define-key map "\C-c\C-a" 'comint-bol-or-process-mark)
456 (define-key map "\C-c\C-u" 'comint-kill-input)
457 (define-key map "\C-c\C-w" 'backward-kill-word)
458 (define-key map "\C-c\C-c" 'comint-interrupt-subjob)
459 (define-key map "\C-c\C-z" 'comint-stop-subjob)
460 (define-key map "\C-c\C-\\" 'comint-quit-subjob)
461 (define-key map "\C-c\C-m" 'comint-copy-old-input)
462 (define-key map "\C-c\C-o" 'comint-delete-output)
463 (define-key map "\C-c\C-r" 'comint-show-output)
464 (define-key map "\C-c\C-e" 'comint-show-maximum-output)
465 (define-key map "\C-c\C-l" 'comint-dynamic-list-input-ring)
466 (define-key map "\C-c\C-n" 'comint-next-prompt)
467 (define-key map "\C-c\C-p" 'comint-previous-prompt)
468 (define-key map "\C-c\C-d" 'comint-send-eof)
469 (define-key map "\C-c\C-s" 'comint-write-output)
470 (define-key map "\C-c." 'comint-insert-previous-argument)
471 ;; Mouse Buttons:
472 (define-key map [mouse-2] 'comint-insert-input)
473 ;; Menu bars:
474 ;; completion:
475 (define-key map [menu-bar completion]
476 (cons "Complete" (make-sparse-keymap "Complete")))
477 (define-key map [menu-bar completion complete-expand]
478 '("Expand File Name" . comint-replace-by-expanded-filename))
479 (define-key map [menu-bar completion complete-listing]
480 '("File Completion Listing" . comint-dynamic-list-filename-completions))
481 (define-key map [menu-bar completion complete-file]
482 '("Complete File Name" . comint-dynamic-complete-filename))
483 (define-key map [menu-bar completion complete]
484 '("Complete Before Point" . comint-dynamic-complete))
485 ;; Input history:
486 (define-key map [menu-bar inout]
487 (cons "In/Out" (make-sparse-keymap "In/Out")))
488 (define-key map [menu-bar inout delete-output]
489 '("Delete Current Output Group" . comint-delete-output))
490 (define-key map [menu-bar inout append-output-to-file]
491 '("Append Current Output Group to File" . comint-append-output-to-file))
492 (define-key map [menu-bar inout write-output]
493 '("Write Current Output Group to File" . comint-write-output))
494 (define-key map [menu-bar inout next-prompt]
495 '("Forward Output Group" . comint-next-prompt))
496 (define-key map [menu-bar inout previous-prompt]
497 '("Backward Output Group" . comint-previous-prompt))
498 (define-key map [menu-bar inout show-maximum-output]
499 '("Show Maximum Output" . comint-show-maximum-output))
500 (define-key map [menu-bar inout show-output]
501 '("Show Current Output Group" . comint-show-output))
502 (define-key map [menu-bar inout kill-input]
503 '("Kill Current Input" . comint-kill-input))
504 (define-key map [menu-bar inout copy-input]
505 '("Copy Old Input" . comint-copy-old-input))
506 (define-key map [menu-bar inout forward-matching-history]
507 '("Forward Matching Input..." . comint-forward-matching-input))
508 (define-key map [menu-bar inout backward-matching-history]
509 '("Backward Matching Input..." . comint-backward-matching-input))
510 (define-key map [menu-bar inout next-matching-history]
511 '("Next Matching Input..." . comint-next-matching-input))
512 (define-key map [menu-bar inout previous-matching-history]
513 '("Previous Matching Input..." . comint-previous-matching-input))
514 (define-key map [menu-bar inout next-matching-history-from-input]
515 '("Next Matching Current Input" . comint-next-matching-input-from-input))
516 (define-key map [menu-bar inout previous-matching-history-from-input]
517 '("Previous Matching Current Input" . comint-previous-matching-input-from-input))
518 (define-key map [menu-bar inout next-history]
519 '("Next Input" . comint-next-input))
520 (define-key map [menu-bar inout previous-history]
521 '("Previous Input" . comint-previous-input))
522 (define-key map [menu-bar inout list-history]
523 '("List Input History" . comint-dynamic-list-input-ring))
524 (define-key map [menu-bar inout expand-history]
525 '("Expand History Before Point" . comint-replace-by-expanded-history))
526 ;; Signals
527 (let ((signals-map (make-sparse-keymap "Signals")))
528 (define-key map [menu-bar signals] (cons "Signals" signals-map))
529 (define-key signals-map [eof] '("EOF" . comint-send-eof))
530 (define-key signals-map [kill] '("KILL" . comint-kill-subjob))
531 (define-key signals-map [quit] '("QUIT" . comint-quit-subjob))
532 (define-key signals-map [cont] '("CONT" . comint-continue-subjob))
533 (define-key signals-map [stop] '("STOP" . comint-stop-subjob))
534 (define-key signals-map [break] '("BREAK" . comint-interrupt-subjob)))
535 ;; Put them in the menu bar:
536 (setq menu-bar-final-items (append '(completion inout signals)
537 menu-bar-final-items))
538 map))
539
540 ;; Fixme: Is this still relevant?
541 (defvar comint-ptyp t
542 "Non-nil if communications via pty; false if by pipe. Buffer local.
543 This is to work around a bug in Emacs process signaling.")
544
545 (defvar comint-input-ring nil)
546 (defvar comint-last-input-start nil)
547 (defvar comint-last-input-end nil)
548 (defvar comint-last-output-start nil)
549 (defvar comint-input-ring-index nil
550 "Index of last matched history element.")
551 (defvar comint-matching-input-from-input-string ""
552 "Input previously used to match input history.")
553 (defvar comint-save-input-ring-index
554 "Last input ring index which you copied.
555 This is to support the command \\[comint-get-next-from-history].")
556
557 (defvar comint-accum-marker nil
558 "Non-nil if you are accumulating input lines to send as input together.
559 The command \\[comint-accumulate] sets this.")
560
561 (defvar comint-stored-incomplete-input nil
562 "Stored input for history cycling.")
563
564 (put 'comint-replace-by-expanded-history 'menu-enable 'comint-input-autoexpand)
565 (put 'comint-input-ring 'permanent-local t)
566 (put 'comint-input-ring-index 'permanent-local t)
567 (put 'comint-save-input-ring-index 'permanent-local t)
568 (put 'comint-input-autoexpand 'permanent-local t)
569 (put 'comint-input-filter-functions 'permanent-local t)
570 (put 'comint-output-filter-functions 'permanent-local t)
571 (put 'comint-preoutput-filter-functions 'permanent-local t)
572 (put 'comint-scroll-to-bottom-on-input 'permanent-local t)
573 (put 'comint-move-point-for-output 'permanent-local t)
574 (put 'comint-scroll-show-maximum-output 'permanent-local t)
575 (put 'comint-ptyp 'permanent-local t)
576
577 (put 'comint-mode 'mode-class 'special)
578
579 (define-derived-mode comint-mode fundamental-mode "Comint"
580 "Major mode for interacting with an inferior interpreter.
581 Interpreter name is same as buffer name, sans the asterisks.
582 Return at end of buffer sends line as input.
583 Return not at end copies rest of line to end and sends it.
584 Setting variable `comint-eol-on-send' means jump to the end of the line
585 before submitting new input.
586
587 This mode is customized to create major modes such as Inferior Lisp
588 mode, Shell mode, etc. This can be done by setting the hooks
589 `comint-input-filter-functions', `comint-input-filter', `comint-input-sender'
590 and `comint-get-old-input' to appropriate functions, and the variable
591 `comint-prompt-regexp' to the appropriate regular expression.
592
593 An input history is maintained of size `comint-input-ring-size', and
594 can be accessed with the commands \\[comint-next-input], \\[comint-previous-input], and \\[comint-dynamic-list-input-ring].
595 Input ring history expansion can be achieved with the commands
596 \\[comint-replace-by-expanded-history] or \\[comint-magic-space].
597 Input ring expansion is controlled by the variable `comint-input-autoexpand',
598 and addition is controlled by the variable `comint-input-ignoredups'.
599
600 Commands with no default key bindings include `send-invisible',
601 `comint-dynamic-complete', `comint-dynamic-list-filename-completions', and
602 `comint-magic-space'.
603
604 Input to, and output from, the subprocess can cause the window to scroll to
605 the end of the buffer. See variables `comint-output-filter-functions',
606 `comint-preoutput-filter-functions', `comint-scroll-to-bottom-on-input',
607 and `comint-move-point-for-output'.
608
609 If you accidentally suspend your process, use \\[comint-continue-subjob]
610 to continue it.
611
612 \\{comint-mode-map}
613
614 Entry to this mode runs the hooks on `comint-mode-hook'."
615 (setq mode-line-process '(":%s"))
616 (set (make-local-variable 'comint-last-input-start) (point-min-marker))
617 (set (make-local-variable 'comint-last-input-end) (point-min-marker))
618 (set (make-local-variable 'comint-last-output-start) (make-marker))
619 (make-local-variable 'comint-last-prompt-overlay)
620 (make-local-variable 'comint-prompt-regexp) ; Don't set; default
621 (make-local-variable 'comint-input-ring-size) ; ...to global val.
622 (make-local-variable 'comint-input-ring)
623 (make-local-variable 'comint-input-ring-file-name)
624 (or (and (boundp 'comint-input-ring) comint-input-ring)
625 (setq comint-input-ring (make-ring comint-input-ring-size)))
626 (make-local-variable 'comint-input-ring-index)
627 (make-local-variable 'comint-save-input-ring-index)
628 (or (and (boundp 'comint-input-ring-index) comint-input-ring-index)
629 (setq comint-input-ring-index nil))
630 (or (and (boundp 'comint-save-input-ring-index) comint-save-input-ring-index)
631 (setq comint-save-input-ring-index nil))
632 (make-local-variable 'comint-matching-input-from-input-string)
633 (make-local-variable 'comint-input-autoexpand)
634 (make-local-variable 'comint-input-ignoredups)
635 (make-local-variable 'comint-delimiter-argument-list)
636 (make-local-variable 'comint-completion-fignore)
637 (make-local-variable 'comint-get-old-input)
638 (make-local-variable 'comint-input-filter)
639 (make-local-variable 'comint-input-sender)
640 (make-local-variable 'comint-eol-on-send)
641 (make-local-variable 'comint-scroll-to-bottom-on-input)
642 (make-local-variable 'comint-move-point-for-output)
643 (make-local-variable 'comint-scroll-show-maximum-output)
644 (make-local-variable 'comint-stored-incomplete-input)
645 ;; This makes it really work to keep point at the bottom.
646 (make-local-variable 'scroll-conservatively)
647 (setq scroll-conservatively 10000)
648 (add-hook 'pre-command-hook 'comint-preinput-scroll-to-bottom t t)
649 (make-local-variable 'comint-ptyp)
650 (make-local-variable 'comint-process-echoes)
651 (make-local-variable 'comint-file-name-chars)
652 (make-local-variable 'comint-file-name-quote-list)
653 (make-local-variable 'comint-accum-marker)
654 (setq comint-accum-marker (make-marker))
655 (make-local-variable 'font-lock-defaults)
656 (setq font-lock-defaults '(nil))
657 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
658 ;; This behavior is not useful in comint buffers, and is annoying
659 (set (make-local-variable 'next-line-add-newlines) nil))
660
661 (defun comint-check-proc (buffer)
662 "Return non-nil if there is a living process associated w/buffer BUFFER.
663 Living means the status is `open', `run', or `stop'.
664 BUFFER can be either a buffer or the name of one."
665 (let ((proc (get-buffer-process buffer)))
666 (and proc (memq (process-status proc) '(open run stop)))))
667
668 ;;;###autoload
669 (defun make-comint-in-buffer (name buffer program &optional startfile &rest switches)
670 "Make a Comint process NAME in BUFFER, running PROGRAM.
671 If BUFFER is nil, it defaults to NAME surrounded by `*'s.
672 PROGRAM should be either a string denoting an executable program to create
673 via `start-process', or a cons pair of the form (HOST . SERVICE) denoting a TCP
674 connection to be opened via `open-network-stream'. If there is already a
675 running process in that buffer, it is not restarted. Optional fourth arg
676 STARTFILE is the name of a file to send the contents of to the process.
677
678 If PROGRAM is a string, any more args are arguments to PROGRAM."
679 (or (fboundp 'start-process)
680 (error "Multi-processing is not supported for this system"))
681 (setq buffer (get-buffer-create (or buffer (concat "*" name "*"))))
682 ;; If no process, or nuked process, crank up a new one and put buffer in
683 ;; comint mode. Otherwise, leave buffer and existing process alone.
684 (unless (comint-check-proc buffer)
685 (with-current-buffer buffer
686 (unless (derived-mode-p 'comint-mode)
687 (comint-mode))) ; Install local vars, mode, keymap, ...
688 (comint-exec buffer name program startfile switches))
689 buffer)
690
691 ;;;###autoload
692 (defun make-comint (name program &optional startfile &rest switches)
693 "Make a Comint process NAME in a buffer, running PROGRAM.
694 The name of the buffer is made by surrounding NAME with `*'s.
695 PROGRAM should be either a string denoting an executable program to create
696 via `start-process', or a cons pair of the form (HOST . SERVICE) denoting a TCP
697 connection to be opened via `open-network-stream'. If there is already a
698 running process in that buffer, it is not restarted. Optional third arg
699 STARTFILE is the name of a file to send the contents of the process to.
700
701 If PROGRAM is a string, any more args are arguments to PROGRAM."
702 (apply #'make-comint-in-buffer name nil program startfile switches))
703
704 ;;;###autoload
705 (defun comint-run (program)
706 "Run PROGRAM in a Comint buffer and switch to it.
707 The buffer name is made by surrounding the file name of PROGRAM with `*'s.
708 The file name is used to make a symbol name, such as `comint-sh-hook', and any
709 hooks on this symbol are run in the buffer.
710 See `make-comint' and `comint-exec'."
711 (interactive "sRun program: ")
712 (let ((name (file-name-nondirectory program)))
713 (switch-to-buffer (make-comint name program))
714 (run-hooks (intern-soft (concat "comint-" name "-hook")))))
715
716 (defun comint-exec (buffer name command startfile switches)
717 "Start up a process named NAME in buffer BUFFER for Comint modes.
718 Runs the given COMMAND with SWITCHES with output to STARTFILE.
719 Blasts any old process running in the buffer. Doesn't set the buffer mode.
720 You can use this to cheaply run a series of processes in the same Comint
721 buffer. The hook `comint-exec-hook' is run after each exec."
722 (with-current-buffer buffer
723 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
724 (if proc (delete-process proc)))
725 ;; Crank up a new process
726 (let ((proc
727 (if (consp command)
728 (open-network-stream name buffer (car command) (cdr command))
729 (comint-exec-1 name buffer command switches))))
730 (set-process-filter proc 'comint-output-filter)
731 (make-local-variable 'comint-ptyp)
732 (setq comint-ptyp process-connection-type) ; t if pty, nil if pipe.
733 ;; Jump to the end, and set the process mark.
734 (goto-char (point-max))
735 (set-marker (process-mark proc) (point))
736 ;; Feed it the startfile.
737 (cond (startfile
738 ;;This is guaranteed to wait long enough
739 ;;but has bad results if the comint does not prompt at all
740 ;; (while (= size (buffer-size))
741 ;; (sleep-for 1))
742 ;;I hope 1 second is enough!
743 (sleep-for 1)
744 (goto-char (point-max))
745 (insert-file-contents startfile)
746 (setq startfile (buffer-substring (point) (point-max)))
747 (delete-region (point) (point-max))
748 (comint-send-string proc startfile)))
749 (run-hooks 'comint-exec-hook)
750 buffer)))
751
752 ;; This auxiliary function cranks up the process for comint-exec in
753 ;; the appropriate environment.
754
755 (defun comint-exec-1 (name buffer command switches)
756 (let ((process-environment
757 (nconc
758 ;; If using termcap, we specify `emacs' as the terminal type
759 ;; because that lets us specify a width.
760 ;; If using terminfo, we specify `dumb' because that is
761 ;; a defined terminal type. `emacs' is not a defined terminal type
762 ;; and there is no way for us to define it here.
763 ;; Some programs that use terminfo get very confused
764 ;; if TERM is not a valid terminal type.
765 ;; ;; There is similar code in compile.el.
766 (if (and (boundp 'system-uses-terminfo) system-uses-terminfo)
767 (list "TERM=dumb" "TERMCAP="
768 (format "COLUMNS=%d" (window-width)))
769 (list "TERM=emacs"
770 (format "TERMCAP=emacs:co#%d:tc=unknown:" (window-width))))
771 (unless (getenv "EMACS")
772 (list (concat "EMACS=" invocation-directory invocation-name)))
773 process-environment))
774 (default-directory
775 (if (file-accessible-directory-p default-directory)
776 default-directory
777 "/"))
778 proc decoding encoding changed)
779 (let ((exec-path (if (file-name-directory command)
780 ;; If the command has slashes, make sure we
781 ;; first look relative to the current directory.
782 (cons default-directory exec-path) exec-path)))
783 (setq proc (apply 'start-process name buffer command switches)))
784 (let ((coding-systems (process-coding-system proc)))
785 (setq decoding (car coding-systems)
786 encoding (cdr coding-systems)))
787 ;; If start-process decided to use some coding system for decoding
788 ;; data sent from the process and the coding system doesn't
789 ;; specify EOL conversion, we had better convert CRLF to LF.
790 (if (vectorp (coding-system-eol-type decoding))
791 (setq decoding (coding-system-change-eol-conversion decoding 'dos)
792 changed t))
793 ;; Even if start-process left the coding system for encoding data
794 ;; sent from the process undecided, we had better use the same one
795 ;; as what we use for decoding. But, we should suppress EOL
796 ;; conversion.
797 (if (and decoding (not encoding))
798 (setq encoding (coding-system-change-eol-conversion decoding 'unix)
799 changed t))
800 (if changed
801 (set-process-coding-system proc decoding encoding))
802 proc))
803
804 (defun comint-insert-input (event)
805 "In a Comint buffer, set the current input to the previous input at point."
806 ;; This doesn't use "e" because it is supposed to work
807 ;; for events without parameters.
808 (interactive "e")
809 (mouse-set-point event)
810 (let ((pos (point)))
811 (if (not (eq (field-at-pos pos) 'input))
812 ;; No input at POS, fall back to the global definition.
813 (let* ((keys (this-command-keys))
814 (last-key (and (vectorp keys) (aref keys (1- (length keys)))))
815 (fun (and last-key (lookup-key global-map (vector last-key)))))
816 (and fun (call-interactively fun)))
817 ;; There's previous input at POS, insert it at the end of the buffer.
818 (goto-char (point-max))
819 ;; First delete any old unsent input at the end
820 (delete-region
821 (or (marker-position comint-accum-marker)
822 (process-mark (get-buffer-process (current-buffer))))
823 (point))
824 ;; Insert the input at point
825 (insert (field-string-no-properties pos)))))
826
827 \f
828 ;; Input history processing in a buffer
829 ;; ===========================================================================
830 ;; Useful input history functions, courtesy of the Ergo group.
831
832 ;; Eleven commands:
833 ;; comint-dynamic-list-input-ring List history in help buffer.
834 ;; comint-previous-input Previous input...
835 ;; comint-previous-matching-input ...matching a string.
836 ;; comint-previous-matching-input-from-input ... matching the current input.
837 ;; comint-next-input Next input...
838 ;; comint-next-matching-input ...matching a string.
839 ;; comint-next-matching-input-from-input ... matching the current input.
840 ;; comint-backward-matching-input Backwards input...
841 ;; comint-forward-matching-input ...matching a string.
842 ;; comint-replace-by-expanded-history Expand history at point;
843 ;; replace with expanded history.
844 ;; comint-magic-space Expand history and insert space.
845 ;;
846 ;; Three functions:
847 ;; comint-read-input-ring Read into comint-input-ring...
848 ;; comint-write-input-ring Write to comint-input-ring-file-name.
849 ;; comint-replace-by-expanded-history-before-point Workhorse function.
850
851 (defun comint-read-input-ring (&optional silent)
852 "Set the buffer's `comint-input-ring' from a history file.
853 The name of the file is given by the variable `comint-input-ring-file-name'.
854 The history ring is of size `comint-input-ring-size', regardless of file size.
855 If `comint-input-ring-file-name' is nil this function does nothing.
856
857 If the optional argument SILENT is non-nil, we say nothing about a
858 failure to read the history file.
859
860 This function is useful for major mode commands and mode hooks.
861
862 The commands stored in the history file are separated by the
863 `comint-input-ring-separator', and entries that match
864 `comint-input-history-ignore' are ignored. The most recent command
865 comes last.
866
867 See also `comint-input-ignoredups' and `comint-write-input-ring'."
868 (cond ((or (null comint-input-ring-file-name)
869 (equal comint-input-ring-file-name ""))
870 nil)
871 ((not (file-readable-p comint-input-ring-file-name))
872 (or silent
873 (message "Cannot read history file %s"
874 comint-input-ring-file-name)))
875 (t
876 (let* ((history-buf (get-buffer-create " *temp*"))
877 (file comint-input-ring-file-name)
878 (count 0)
879 (size comint-input-ring-size)
880 (ring (make-ring size)))
881 (unwind-protect
882 (save-excursion
883 (set-buffer history-buf)
884 (widen)
885 (erase-buffer)
886 (insert-file-contents file)
887 ;; Save restriction in case file is already visited...
888 ;; Watch for those date stamps in history files!
889 (goto-char (point-max))
890 (let (start end history)
891 (while (and (< count comint-input-ring-size)
892 (re-search-backward comint-input-ring-separator nil t)
893 (setq end (match-beginning 0)))
894 (if (re-search-backward comint-input-ring-separator nil t)
895 (setq start (match-end 0))
896 (setq start (point-min)))
897 (setq history (buffer-substring start end))
898 (goto-char start)
899 (if (and (not (string-match comint-input-history-ignore history))
900 (or (null comint-input-ignoredups)
901 (ring-empty-p ring)
902 (not (string-equal (ring-ref ring 0) history))))
903 (progn
904 (ring-insert-at-beginning ring history)
905 (setq count (1+ count)))))))
906 (kill-buffer history-buf))
907 (setq comint-input-ring ring
908 comint-input-ring-index nil)))))
909
910 (defun comint-write-input-ring ()
911 "Writes the buffer's `comint-input-ring' to a history file.
912 The name of the file is given by the variable `comint-input-ring-file-name'.
913 The original contents of the file are lost if `comint-input-ring' is not empty.
914 If `comint-input-ring-file-name' is nil this function does nothing.
915
916 Useful within process sentinels.
917
918 See also `comint-read-input-ring'."
919 (cond ((or (null comint-input-ring-file-name)
920 (equal comint-input-ring-file-name "")
921 (null comint-input-ring) (ring-empty-p comint-input-ring))
922 nil)
923 ((not (file-writable-p comint-input-ring-file-name))
924 (message "Cannot write history file %s" comint-input-ring-file-name))
925 (t
926 (let* ((history-buf (get-buffer-create " *Temp Input History*"))
927 (ring comint-input-ring)
928 (file comint-input-ring-file-name)
929 (index (ring-length ring)))
930 ;; Write it all out into a buffer first. Much faster, but messier,
931 ;; than writing it one line at a time.
932 (save-excursion
933 (set-buffer history-buf)
934 (erase-buffer)
935 (while (> index 0)
936 (setq index (1- index))
937 (insert (ring-ref ring index) comint-input-ring-separator))
938 (write-region (buffer-string) nil file nil 'no-message)
939 (kill-buffer nil))))))
940
941
942 (defvar comint-dynamic-list-input-ring-window-conf)
943
944 (defun comint-dynamic-list-input-ring-select ()
945 "Choose the input history entry that point is in or next to."
946 (interactive)
947 (let (beg end completion (buffer completion-reference-buffer)
948 (base-size completion-base-size))
949 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
950 (setq end (point) beg (1+ (point))))
951 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
952 (setq end (1- (point)) beg (point)))
953 (if (null beg)
954 (error "No history entry here"))
955 (setq beg (previous-single-property-change beg 'mouse-face))
956 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
957 (setq completion (buffer-substring beg end))
958 (set-window-configuration comint-dynamic-list-input-ring-window-conf)
959 (choose-completion-string completion buffer base-size)))
960
961 (defun comint-dynamic-list-input-ring ()
962 "List in help buffer the buffer's input history."
963 (interactive)
964 (if (or (not (ring-p comint-input-ring))
965 (ring-empty-p comint-input-ring))
966 (message "No history")
967 (let ((history nil)
968 (history-buffer " *Input History*")
969 (index (1- (ring-length comint-input-ring)))
970 (conf (current-window-configuration)))
971 ;; We have to build up a list ourselves from the ring vector.
972 (while (>= index 0)
973 (setq history (cons (ring-ref comint-input-ring index) history)
974 index (1- index)))
975 ;; Change "completion" to "history reference"
976 ;; to make the display accurate.
977 (with-output-to-temp-buffer history-buffer
978 (display-completion-list history)
979 (set-buffer history-buffer)
980 (let ((keymap (make-sparse-keymap)))
981 (set-keymap-parent keymap (current-local-map))
982 (define-key keymap "\C-m" 'comint-dynamic-list-input-ring-select)
983 (use-local-map keymap))
984 (forward-line 3)
985 (while (search-backward "completion" nil 'move)
986 (replace-match "history reference")))
987 (sit-for 0)
988 (message "Hit space to flush")
989 (setq comint-dynamic-list-input-ring-window-conf conf)
990 (let ((ch (read-event)))
991 (if (eq ch ?\s)
992 (set-window-configuration conf)
993 (setq unread-command-events (list ch)))))))
994
995
996 (defun comint-regexp-arg (prompt)
997 "Return list of regexp and prefix arg using PROMPT."
998 (let* (;; Don't clobber this.
999 (last-command last-command)
1000 (regexp (read-from-minibuffer prompt nil nil nil
1001 'minibuffer-history-search-history)))
1002 (list (if (string-equal regexp "")
1003 (setcar minibuffer-history-search-history
1004 (nth 1 minibuffer-history-search-history))
1005 regexp)
1006 (prefix-numeric-value current-prefix-arg))))
1007
1008 (defun comint-search-arg (arg)
1009 ;; First make sure there is a ring and that we are after the process mark
1010 (cond ((not (comint-after-pmark-p))
1011 (error "Not at command line"))
1012 ((or (null comint-input-ring)
1013 (ring-empty-p comint-input-ring))
1014 (error "Empty input ring"))
1015 ((zerop arg)
1016 ;; arg of zero resets search from beginning, and uses arg of 1
1017 (setq comint-input-ring-index nil)
1018 1)
1019 (t
1020 arg)))
1021
1022 (defun comint-restore-input ()
1023 "Restore unfinished input."
1024 (interactive)
1025 (when comint-input-ring-index
1026 (comint-delete-input)
1027 (when (> (length comint-stored-incomplete-input) 0)
1028 (insert comint-stored-incomplete-input)
1029 (message "Input restored"))
1030 (setq comint-input-ring-index nil)))
1031
1032 (defun comint-search-start (arg)
1033 "Index to start a directional search, starting at `comint-input-ring-index'."
1034 (if comint-input-ring-index
1035 ;; If a search is running, offset by 1 in direction of arg
1036 (mod (+ comint-input-ring-index (if (> arg 0) 1 -1))
1037 (ring-length comint-input-ring))
1038 ;; For a new search, start from beginning or end, as appropriate
1039 (if (>= arg 0)
1040 0 ; First elt for forward search
1041 (1- (ring-length comint-input-ring))))) ; Last elt for backward search
1042
1043 (defun comint-previous-input-string (arg)
1044 "Return the string ARG places along the input ring.
1045 Moves relative to `comint-input-ring-index'."
1046 (ring-ref comint-input-ring (if comint-input-ring-index
1047 (mod (+ arg comint-input-ring-index)
1048 (ring-length comint-input-ring))
1049 arg)))
1050
1051 (defun comint-previous-input (arg)
1052 "Cycle backwards through input history, saving input."
1053 (interactive "*p")
1054 (if (and comint-input-ring-index
1055 (or ;; leaving the "end" of the ring
1056 (and (< arg 0) ; going down
1057 (eq comint-input-ring-index 0))
1058 (and (> arg 0) ; going up
1059 (eq comint-input-ring-index
1060 (1- (ring-length comint-input-ring)))))
1061 comint-stored-incomplete-input)
1062 (comint-restore-input)
1063 (comint-previous-matching-input "." arg)))
1064
1065 (defun comint-next-input (arg)
1066 "Cycle forwards through input history."
1067 (interactive "*p")
1068 (comint-previous-input (- arg)))
1069
1070 (defun comint-previous-matching-input-string (regexp arg)
1071 "Return the string matching REGEXP ARG places along the input ring.
1072 Moves relative to `comint-input-ring-index'."
1073 (let* ((pos (comint-previous-matching-input-string-position regexp arg)))
1074 (if pos (ring-ref comint-input-ring pos))))
1075
1076 (defun comint-previous-matching-input-string-position (regexp arg &optional start)
1077 "Return the index matching REGEXP ARG places along the input ring.
1078 Moves relative to START, or `comint-input-ring-index'."
1079 (if (or (not (ring-p comint-input-ring))
1080 (ring-empty-p comint-input-ring))
1081 (error "No history"))
1082 (let* ((len (ring-length comint-input-ring))
1083 (motion (if (> arg 0) 1 -1))
1084 (n (mod (- (or start (comint-search-start arg)) motion) len))
1085 (tried-each-ring-item nil)
1086 (prev nil))
1087 ;; Do the whole search as many times as the argument says.
1088 (while (and (/= arg 0) (not tried-each-ring-item))
1089 ;; Step once.
1090 (setq prev n
1091 n (mod (+ n motion) len))
1092 ;; If we haven't reached a match, step some more.
1093 (while (and (< n len) (not tried-each-ring-item)
1094 (not (string-match regexp (ring-ref comint-input-ring n))))
1095 (setq n (mod (+ n motion) len)
1096 ;; If we have gone all the way around in this search.
1097 tried-each-ring-item (= n prev)))
1098 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1099 ;; Now that we know which ring element to use, if we found it, return that.
1100 (if (string-match regexp (ring-ref comint-input-ring n))
1101 n)))
1102
1103 (defun comint-delete-input ()
1104 "Delete all input between accumulation or process mark and point."
1105 (delete-region
1106 ;; Can't use kill-region as it sets this-command
1107 (or (marker-position comint-accum-marker)
1108 (process-mark (get-buffer-process (current-buffer))))
1109 (point-max)))
1110
1111 (defun comint-previous-matching-input (regexp n)
1112 "Search backwards through input history for match for REGEXP.
1113 \(Previous history elements are earlier commands.)
1114 With prefix argument N, search for Nth previous match.
1115 If N is negative, find the next or Nth next match."
1116 (interactive (comint-regexp-arg "Previous input matching (regexp): "))
1117 (setq n (comint-search-arg n))
1118 (let ((pos (comint-previous-matching-input-string-position regexp n)))
1119 ;; Has a match been found?
1120 (if (null pos)
1121 (error "Not found")
1122 ;; If leaving the edit line, save partial input
1123 (if (null comint-input-ring-index) ;not yet on ring
1124 (setq comint-stored-incomplete-input
1125 (funcall comint-get-old-input)))
1126 (setq comint-input-ring-index pos)
1127 (message "History item: %d" (1+ pos))
1128 (comint-delete-input)
1129 (insert (ring-ref comint-input-ring pos)))))
1130
1131 (defun comint-next-matching-input (regexp n)
1132 "Search forwards through input history for match for REGEXP.
1133 \(Later history elements are more recent commands.)
1134 With prefix argument N, search for Nth following match.
1135 If N is negative, find the previous or Nth previous match."
1136 (interactive (comint-regexp-arg "Next input matching (regexp): "))
1137 (comint-previous-matching-input regexp (- n)))
1138
1139 (defun comint-previous-matching-input-from-input (n)
1140 "Search backwards through input history for match for current input.
1141 \(Previous history elements are earlier commands.)
1142 With prefix argument N, search for Nth previous match.
1143 If N is negative, search forwards for the -Nth following match."
1144 (interactive "p")
1145 (if (not (memq last-command '(comint-previous-matching-input-from-input
1146 comint-next-matching-input-from-input)))
1147 ;; Starting a new search
1148 (setq comint-matching-input-from-input-string
1149 (buffer-substring
1150 (or (marker-position comint-accum-marker)
1151 (process-mark (get-buffer-process (current-buffer))))
1152 (point))
1153 comint-input-ring-index nil))
1154 (comint-previous-matching-input
1155 (concat "^" (regexp-quote comint-matching-input-from-input-string))
1156 n))
1157
1158 (defun comint-next-matching-input-from-input (n)
1159 "Search forwards through input history for match for current input.
1160 \(Following history elements are more recent commands.)
1161 With prefix argument N, search for Nth following match.
1162 If N is negative, search backwards for the -Nth previous match."
1163 (interactive "p")
1164 (comint-previous-matching-input-from-input (- n)))
1165
1166
1167 (defun comint-replace-by-expanded-history (&optional silent start)
1168 "Expand input command history references before point.
1169 Expansion is dependent on the value of `comint-input-autoexpand'.
1170
1171 This function depends on the buffer's idea of the input history, which may not
1172 match the command interpreter's idea, assuming it has one.
1173
1174 Assumes history syntax is like typical Un*x shells'. However, since Emacs
1175 cannot know the interpreter's idea of input line numbers, assuming it has one,
1176 it cannot expand absolute input line number references.
1177
1178 If the optional argument SILENT is non-nil, never complain
1179 even if history reference seems erroneous.
1180
1181 If the optional argument START is non-nil, that specifies the
1182 start of the text to scan for history references, rather
1183 than the logical beginning of line.
1184
1185 See `comint-magic-space' and `comint-replace-by-expanded-history-before-point'.
1186
1187 Returns t if successful."
1188 (interactive)
1189 (if (and comint-input-autoexpand
1190 (if comint-use-prompt-regexp
1191 ;; Use comint-prompt-regexp
1192 (save-excursion
1193 (beginning-of-line)
1194 (looking-at (concat comint-prompt-regexp "!\\|\\^")))
1195 ;; Use input fields. User input that hasn't been entered
1196 ;; yet, at the end of the buffer, has a nil `field' property.
1197 (and (null (get-char-property (point) 'field))
1198 (string-match "!\\|^\\^" (field-string)))))
1199 ;; Looks like there might be history references in the command.
1200 (let ((previous-modified-tick (buffer-modified-tick)))
1201 (comint-replace-by-expanded-history-before-point silent start)
1202 (/= previous-modified-tick (buffer-modified-tick)))))
1203
1204
1205 (defun comint-replace-by-expanded-history-before-point (silent &optional start)
1206 "Expand directory stack reference before point.
1207 See `comint-replace-by-expanded-history'. Returns t if successful.
1208
1209 If the optional argument START is non-nil, that specifies the
1210 start of the text to scan for history references, rather
1211 than the logical beginning of line."
1212 (save-excursion
1213 (let ((toend (- (line-end-position) (point)))
1214 (start (or start (comint-line-beginning-position))))
1215 (goto-char start)
1216 (while (progn
1217 (skip-chars-forward "^!^" (- (line-end-position) toend))
1218 (< (point) (- (line-end-position) toend)))
1219 ;; This seems a bit complex. We look for references such as !!, !-num,
1220 ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
1221 ;; If that wasn't enough, the plings can be suffixed with argument
1222 ;; range specifiers.
1223 ;; Argument ranges are complex too, so we hive off the input line,
1224 ;; referenced with plings, with the range string to `comint-args'.
1225 (setq comint-input-ring-index nil)
1226 (cond ((or (= (preceding-char) ?\\)
1227 (comint-within-quotes start (point)))
1228 ;; The history is quoted, or we're in quotes.
1229 (goto-char (1+ (point))))
1230 ((looking-at "![0-9]+\\($\\|[^-]\\)")
1231 ;; We cannot know the interpreter's idea of input line numbers.
1232 (goto-char (match-end 0))
1233 (message "Absolute reference cannot be expanded"))
1234 ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
1235 ;; Just a number of args from `number' lines backward.
1236 (let ((number (1- (string-to-number
1237 (buffer-substring (match-beginning 1)
1238 (match-end 1))))))
1239 (if (<= number (ring-length comint-input-ring))
1240 (progn
1241 (replace-match
1242 (comint-args (comint-previous-input-string number)
1243 (match-beginning 2) (match-end 2))
1244 t t)
1245 (setq comint-input-ring-index number)
1246 (message "History item: %d" (1+ number)))
1247 (goto-char (match-end 0))
1248 (message "Relative reference exceeds input history size"))))
1249 ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
1250 ;; Just a number of args from the previous input line.
1251 (replace-match
1252 (comint-args (comint-previous-input-string 0)
1253 (match-beginning 1) (match-end 1))
1254 t t)
1255 (message "History item: previous"))
1256 ((looking-at
1257 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
1258 ;; Most recent input starting with or containing (possibly
1259 ;; protected) string, maybe just a number of args. Phew.
1260 (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
1261 (mb2 (match-beginning 2)) (me2 (match-end 2))
1262 (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
1263 (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
1264 (pos (save-match-data
1265 (comint-previous-matching-input-string-position
1266 (concat pref (regexp-quote exp)) 1))))
1267 (if (null pos)
1268 (progn
1269 (goto-char (match-end 0))
1270 (or silent
1271 (progn (message "Not found")
1272 (ding))))
1273 (setq comint-input-ring-index pos)
1274 (replace-match
1275 (comint-args (ring-ref comint-input-ring pos)
1276 (match-beginning 4) (match-end 4))
1277 t t)
1278 (message "History item: %d" (1+ pos)))))
1279 ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
1280 ;; Quick substitution on the previous input line.
1281 (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
1282 (new (buffer-substring (match-beginning 2) (match-end 2)))
1283 (pos nil))
1284 (replace-match (comint-previous-input-string 0) t t)
1285 (setq pos (point))
1286 (goto-char (match-beginning 0))
1287 (if (not (search-forward old pos t))
1288 (or silent
1289 (error "Not found"))
1290 (replace-match new t t)
1291 (message "History item: substituted"))))
1292 (t
1293 (forward-char 1)))))))
1294
1295
1296 (defun comint-magic-space (arg)
1297 "Expand input history references before point and insert ARG spaces.
1298 A useful command to bind to SPC. See `comint-replace-by-expanded-history'."
1299 (interactive "p")
1300 (comint-replace-by-expanded-history)
1301 (self-insert-command arg))
1302 \f
1303 (defun comint-within-quotes (beg end)
1304 "Return t if the number of quotes between BEG and END is odd.
1305 Quotes are single and double."
1306 (let ((countsq (comint-how-many-region "\\(^\\|[^\\\\]\\)\'" beg end))
1307 (countdq (comint-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
1308 (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
1309
1310 (defun comint-how-many-region (regexp beg end)
1311 "Return number of matches for REGEXP from BEG to END."
1312 (let ((count 0))
1313 (save-excursion
1314 (save-match-data
1315 (goto-char beg)
1316 (while (re-search-forward regexp end t)
1317 (setq count (1+ count)))))
1318 count))
1319
1320 (defun comint-args (string begin end)
1321 ;; From STRING, return the args depending on the range specified in the text
1322 ;; from BEGIN to END. If BEGIN is nil, assume all args. Ignore leading `:'.
1323 ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
1324 (save-match-data
1325 (if (null begin)
1326 (comint-arguments string 0 nil)
1327 (let* ((range (buffer-substring
1328 (if (eq (char-after begin) ?:) (1+ begin) begin) end))
1329 (nth (cond ((string-match "^[*^]" range) 1)
1330 ((string-match "^-" range) 0)
1331 ((string-equal range "$") nil)
1332 (t (string-to-number range))))
1333 (mth (cond ((string-match "[-*$]$" range) nil)
1334 ((string-match "-" range)
1335 (string-to-number (substring range (match-end 0))))
1336 (t nth))))
1337 (comint-arguments string nth mth)))))
1338
1339 (defun comint-delim-arg (arg)
1340 "Return a list of arguments from ARG.
1341 Break it up at the delimiters in `comint-delimiter-argument-list'.
1342 Returned list is backwards."
1343 (if (null comint-delimiter-argument-list)
1344 (list arg)
1345 (let ((args nil)
1346 (pos 0)
1347 (len (length arg)))
1348 (while (< pos len)
1349 (let ((char (aref arg pos))
1350 (start pos))
1351 (if (memq char comint-delimiter-argument-list)
1352 (while (and (< pos len) (eq (aref arg pos) char))
1353 (setq pos (1+ pos)))
1354 (while (and (< pos len)
1355 (not (memq (aref arg pos)
1356 comint-delimiter-argument-list)))
1357 (setq pos (1+ pos))))
1358 (setq args (cons (substring arg start pos) args))))
1359 args)))
1360
1361 (defun comint-arguments (string nth mth)
1362 "Return from STRING the NTH to MTH arguments.
1363 NTH and/or MTH can be nil, which means the last argument.
1364 Returned arguments are separated by single spaces.
1365 We assume whitespace separates arguments, except within quotes
1366 and except for a space or tab that immediately follows a backslash.
1367 Also, a run of one or more of a single character
1368 in `comint-delimiter-argument-list' is a separate argument.
1369 Argument 0 is the command name."
1370 ;; The first line handles ordinary characters and backslash-sequences
1371 ;; (except with w32 msdos-like shells, where backslashes are valid).
1372 ;; The second matches "-quoted strings.
1373 ;; The third matches '-quoted strings.
1374 ;; The fourth matches `-quoted strings.
1375 ;; This seems to fit the syntax of BASH 2.0.
1376 (let* ((first (if (if (fboundp 'w32-shell-dos-semantics)
1377 (w32-shell-dos-semantics))
1378 "[^ \n\t\"'`]+\\|"
1379 "[^ \n\t\"'`\\]+\\|\\\\[\"'`\\ \t]+\\|"))
1380 (argpart (concat first
1381 "\\(\"\\([^\"\\]\\|\\\\.\\)*\"\\|\
1382 '[^']*'\\|\
1383 `[^`]*`\\)"))
1384 (args ()) (pos 0)
1385 (count 0)
1386 beg str quotes)
1387 ;; Build a list of all the args until we have as many as we want.
1388 (while (and (or (null mth) (<= count mth))
1389 (string-match argpart string pos))
1390 (if (and beg (= pos (match-beginning 0)))
1391 ;; It's contiguous, part of the same arg.
1392 (setq pos (match-end 0)
1393 quotes (or quotes (match-beginning 1)))
1394 ;; It's a new separate arg.
1395 (if beg
1396 ;; Put the previous arg, if there was one, onto ARGS.
1397 (setq str (substring string beg pos)
1398 args (if quotes (cons str args)
1399 (nconc (comint-delim-arg str) args))))
1400 (setq count (length args))
1401 (setq quotes (match-beginning 1))
1402 (setq beg (match-beginning 0))
1403 (setq pos (match-end 0))))
1404 (if beg
1405 (setq str (substring string beg pos)
1406 args (if quotes (cons str args)
1407 (nconc (comint-delim-arg str) args))))
1408 (setq count (length args))
1409 (let ((n (or nth (1- count)))
1410 (m (if mth (1- (- count mth)) 0)))
1411 (mapconcat
1412 (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
1413 \f
1414 ;;
1415 ;; Input processing stuff
1416 ;;
1417 (defun comint-add-to-input-history (cmd)
1418 "Add CMD to the input history.
1419 Ignore duplicates if `comint-input-ignoredups' is non-nil."
1420 (if (and (funcall comint-input-filter cmd)
1421 (or (null comint-input-ignoredups)
1422 (not (ring-p comint-input-ring))
1423 (ring-empty-p comint-input-ring)
1424 (not (string-equal (ring-ref comint-input-ring 0)
1425 cmd))))
1426 (ring-insert comint-input-ring cmd)))
1427
1428 (defun comint-send-input (&optional no-newline artificial)
1429 "Send input to process.
1430 After the process output mark, sends all text from the process mark to
1431 point as input to the process. Before the process output mark, calls
1432 value of variable `comint-get-old-input' to retrieve old input, copies
1433 it to the process mark, and sends it.
1434
1435 This command also sends and inserts a final newline, unless
1436 NO-NEWLINE is non-nil.
1437
1438 Any history reference may be expanded depending on the value of the variable
1439 `comint-input-autoexpand'. The list of function names contained in the value
1440 of `comint-input-filter-functions' is called on the input before sending it.
1441 The input is entered into the input history ring, if the value of variable
1442 `comint-input-filter' returns non-nil when called on the input.
1443
1444 If variable `comint-eol-on-send' is non-nil, then point is moved to the
1445 end of line before sending the input.
1446
1447 After the input has been sent, if `comint-process-echoes' is non-nil,
1448 then `comint-send-input' waits to see if the process outputs a string
1449 matching the input, and if so, deletes that part of the output.
1450 If ARTIFICIAL is non-nil, it inhibits such deletion.
1451 Callers sending input not from the user should use ARTIFICIAL = t.
1452
1453 The values of `comint-get-old-input', `comint-input-filter-functions', and
1454 `comint-input-filter' are chosen according to the command interpreter running
1455 in the buffer. E.g.,
1456
1457 If the interpreter is the csh,
1458 `comint-get-old-input' is the default:
1459 If `comint-use-prompt-regexp' is nil, then
1460 either return the current input field, if point is on an input
1461 field, or the current line, if point is on an output field.
1462 If `comint-use-prompt-regexp' is non-nil, then
1463 return the current line with any initial string matching the
1464 regexp `comint-prompt-regexp' removed.
1465 `comint-input-filter-functions' monitors input for \"cd\", \"pushd\", and
1466 \"popd\" commands. When it sees one, it cd's the buffer.
1467 `comint-input-filter' is the default: returns t if the input isn't all white
1468 space.
1469
1470 If the Comint is Lucid Common Lisp,
1471 `comint-get-old-input' snarfs the sexp ending at point.
1472 `comint-input-filter-functions' does nothing.
1473 `comint-input-filter' returns nil if the input matches input-filter-regexp,
1474 which matches (1) all whitespace (2) :a, :c, etc.
1475
1476 Similarly for Soar, Scheme, etc."
1477 (interactive)
1478 ;; Note that the input string does not include its terminal newline.
1479 (let ((proc (get-buffer-process (current-buffer))))
1480 (if (not proc) (error "Current buffer has no process")
1481 (let* ((pmark (process-mark proc))
1482 (intxt (if (>= (point) (marker-position pmark))
1483 (progn (if comint-eol-on-send (end-of-line))
1484 (buffer-substring pmark (point)))
1485 (let ((copy (funcall comint-get-old-input)))
1486 (goto-char pmark)
1487 (insert copy)
1488 copy)))
1489 (input (if (not (eq comint-input-autoexpand 'input))
1490 ;; Just whatever's already there
1491 intxt
1492 ;; Expand and leave it visible in buffer
1493 (comint-replace-by-expanded-history t pmark)
1494 (buffer-substring pmark (point))))
1495 (history (if (not (eq comint-input-autoexpand 'history))
1496 input
1497 ;; This is messy 'cos ultimately the original
1498 ;; functions used do insertion, rather than return
1499 ;; strings. We have to expand, then insert back.
1500 (comint-replace-by-expanded-history t pmark)
1501 (let ((copy (buffer-substring pmark (point)))
1502 (start (point)))
1503 (insert input)
1504 (delete-region pmark start)
1505 copy))))
1506
1507 (unless no-newline
1508 (insert ?\n))
1509
1510 (comint-add-to-input-history history)
1511
1512 (run-hook-with-args 'comint-input-filter-functions
1513 (if no-newline input
1514 (concat input "\n")))
1515
1516 (let ((beg (marker-position pmark))
1517 (end (if no-newline (point) (1- (point))))
1518 (inhibit-modification-hooks t))
1519 (when (> end beg)
1520 (add-text-properties beg end
1521 '(front-sticky t
1522 font-lock-face comint-highlight-input))
1523 (unless comint-use-prompt-regexp
1524 ;; Give old user input a field property of `input', to
1525 ;; distinguish it from both process output and unsent
1526 ;; input. The terminating newline is put into a special
1527 ;; `boundary' field to make cursor movement between input
1528 ;; and output fields smoother.
1529 (add-text-properties
1530 beg end
1531 '(mouse-face highlight
1532 help-echo "mouse-2: insert after prompt as new input"
1533 field input))))
1534 (unless (or no-newline comint-use-prompt-regexp)
1535 ;; Cover the terminating newline
1536 (add-text-properties end (1+ end)
1537 '(rear-nonsticky t
1538 field boundary
1539 inhibit-line-move-field-capture t))))
1540
1541 (comint-snapshot-last-prompt)
1542
1543 (setq comint-save-input-ring-index comint-input-ring-index)
1544 (setq comint-input-ring-index nil)
1545 ;; Update the markers before we send the input
1546 ;; in case we get output amidst sending the input.
1547 (set-marker comint-last-input-start pmark)
1548 (set-marker comint-last-input-end (point))
1549 (set-marker (process-mark proc) (point))
1550 ;; clear the "accumulation" marker
1551 (set-marker comint-accum-marker nil)
1552 (let ((comint-input-sender-no-newline no-newline))
1553 (funcall comint-input-sender proc input))
1554
1555 ;; Optionally delete echoed input (after checking it).
1556 (when (and comint-process-echoes (not artificial))
1557 (let ((echo-len (- comint-last-input-end
1558 comint-last-input-start)))
1559 ;; Wait for all input to be echoed:
1560 (while (and (accept-process-output proc)
1561 (> (+ comint-last-input-end echo-len)
1562 (point-max))
1563 (zerop
1564 (compare-buffer-substrings
1565 nil comint-last-input-start
1566 (- (point-max) echo-len)
1567 ;; Above difference is equivalent to
1568 ;; (+ comint-last-input-start
1569 ;; (- (point-max) comint-last-input-end))
1570 nil comint-last-input-end (point-max)))))
1571 (if (and
1572 (<= (+ comint-last-input-end echo-len)
1573 (point-max))
1574 (zerop
1575 (compare-buffer-substrings
1576 nil comint-last-input-start comint-last-input-end
1577 nil comint-last-input-end
1578 (+ comint-last-input-end echo-len))))
1579 ;; Certain parts of the text to be deleted may have
1580 ;; been mistaken for prompts. We have to prevent
1581 ;; problems when `comint-prompt-read-only' is non-nil.
1582 (let ((inhibit-read-only t))
1583 (delete-region comint-last-input-end
1584 (+ comint-last-input-end echo-len))
1585 (when comint-prompt-read-only
1586 (save-excursion
1587 (goto-char comint-last-input-end)
1588 (comint-update-fence)))))))
1589
1590 ;; This used to call comint-output-filter-functions,
1591 ;; but that scrolled the buffer in undesirable ways.
1592 (run-hook-with-args 'comint-output-filter-functions "")))))
1593
1594 (defvar comint-preoutput-filter-functions nil
1595 "List of functions to call before inserting Comint output into the buffer.
1596 Each function gets one argument, a string containing the text received
1597 from the subprocess. It should return the string to insert, perhaps
1598 the same string that was received, or perhaps a modified or transformed
1599 string.
1600
1601 The functions on the list are called sequentially, and each one is
1602 given the string returned by the previous one. The string returned by
1603 the last function is the text that is actually inserted in the
1604 redirection buffer.
1605
1606 You can use `add-hook' to add functions to this list
1607 either globally or locally.")
1608
1609 (defvar comint-inhibit-carriage-motion nil
1610 "If nil, Comint will interpret `carriage control' characters in output.
1611 See `comint-carriage-motion' for details.")
1612
1613 ;; When non-nil, this is an overlay over the last recognized prompt in
1614 ;; the buffer; it is used when highlighting the prompt.
1615 (defvar comint-last-prompt-overlay nil)
1616
1617 (defun comint-snapshot-last-prompt ()
1618 "`snapshot' any current `comint-last-prompt-overlay'.
1619 Freeze its attributes in place, even when more input comes along
1620 and moves the prompt overlay."
1621 (when comint-last-prompt-overlay
1622 (let ((inhibit-read-only t)
1623 (inhibit-modification-hooks t))
1624 (add-text-properties (overlay-start comint-last-prompt-overlay)
1625 (overlay-end comint-last-prompt-overlay)
1626 (overlay-properties comint-last-prompt-overlay)))))
1627
1628 (defun comint-carriage-motion (start end)
1629 "Interpret carriage control characters in the region from START to END.
1630 Translate carriage return/linefeed sequences to linefeeds.
1631 Make single carriage returns delete to the beginning of the line.
1632 Make backspaces delete the previous character."
1633 (save-excursion
1634 ;; First do a quick check to see if there are any applicable
1635 ;; characters, so we can avoid calling save-match-data and
1636 ;; save-restriction if not.
1637 (goto-char start)
1638 (when (< (skip-chars-forward "^\b\r" end) (- end start))
1639 (save-match-data
1640 (save-restriction
1641 (widen)
1642 (let ((inhibit-field-text-motion t)
1643 (inhibit-read-only t))
1644 ;; CR LF -> LF
1645 ;; Note that this won't work properly when the CR and LF
1646 ;; are in different output chunks, but this is probably an
1647 ;; exceedingly rare case (because they are generally
1648 ;; written as a unit), and to delay interpretation of a
1649 ;; trailing CR in a chunk would result in odd interactive
1650 ;; behavior (and this case is probably far more common).
1651 (while (re-search-forward "\r$" end t)
1652 (delete-char -1))
1653 ;; bare CR -> delete preceding line
1654 (goto-char start)
1655 (while (search-forward "\r" end t)
1656 (delete-region (point) (line-beginning-position)))
1657 ;; BS -> delete preceding character
1658 (goto-char start)
1659 (while (search-forward "\b" end t)
1660 (delete-char -2))))))))
1661
1662 ;; The purpose of using this filter for comint processes
1663 ;; is to keep comint-last-input-end from moving forward
1664 ;; when output is inserted.
1665 (defun comint-output-filter (process string)
1666 (let ((oprocbuf (process-buffer process)))
1667 ;; First check for killed buffer or no input.
1668 (when (and string oprocbuf (buffer-name oprocbuf))
1669 (with-current-buffer oprocbuf
1670 ;; Run preoutput filters
1671 (let ((functions comint-preoutput-filter-functions))
1672 (while (and functions string)
1673 (if (eq (car functions) t)
1674 (let ((functions (default-value 'comint-preoutput-filter-functions)))
1675 (while (and functions string)
1676 (setq string (funcall (car functions) string))
1677 (setq functions (cdr functions))))
1678 (setq string (funcall (car functions) string)))
1679 (setq functions (cdr functions))))
1680
1681 ;; Insert STRING
1682 (let ((inhibit-read-only t)
1683 ;; Avoid the overhead of save-excursion, since we just
1684 ;; fiddle with the point
1685 (saved-point (point-marker)))
1686
1687 ;; The point should float after any insertion we do
1688 (set-marker-insertion-type saved-point t)
1689
1690 ;; We temporarly remove any buffer narrowing, in case the
1691 ;; process mark is outside of the restriction
1692 (save-restriction
1693 (widen)
1694
1695 (goto-char (process-mark process))
1696 (set-marker comint-last-output-start (point))
1697
1698 ;; insert-before-markers is a bad thing. XXX
1699 ;;
1700 ;; It is used here to force window-point markers (used to
1701 ;; store the value of point in non-selected windows) to
1702 ;; advance, but it also screws up any other markers that we
1703 ;; don't _want_ to advance, such as the start-marker of some
1704 ;; of the overlays we create.
1705 ;;
1706 ;; We work around the problem with the overlays by
1707 ;; explicitly adjusting them after we do the insertion, but
1708 ;; in the future this problem should be solved correctly, by
1709 ;; using `insert', and making the insertion-type of
1710 ;; window-point markers settable (via a buffer-local
1711 ;; variable). In comint buffers, this variable would be set
1712 ;; to `t', to cause point in non-select windows to advance.
1713 (insert-before-markers string)
1714 ;; Fixup markers and overlays that got screwed up because we
1715 ;; used `insert-before-markers'.
1716 (let ((old-point (- (point) (length string))))
1717 ;; comint-last-output-start
1718 (set-marker comint-last-output-start old-point)
1719 ;; comint-last-input-end
1720 (when (and comint-last-input-end
1721 (equal (marker-position comint-last-input-end)
1722 (point)))
1723 (set-marker comint-last-input-end old-point))
1724 ;; No overlays we create are set to advance upon insertion
1725 ;; (at the start/end), so we assume that any overlay which
1726 ;; is at the current point was incorrectly advanced by
1727 ;; insert-before-markers. First fixup overlays that might
1728 ;; start at point:
1729 (dolist (over (overlays-at (point)))
1730 (when (= (overlay-start over) (point))
1731 (let ((end (overlay-end over)))
1732 (move-overlay over
1733 old-point
1734 (if (= end (point)) old-point end)))))
1735 ;; Then do overlays that might end at point:
1736 (dolist (over (overlays-at (1- (point))))
1737 (when (= (overlay-end over) (point))
1738 (move-overlay over
1739 (min (overlay-start over) old-point)
1740 old-point))))
1741
1742 ;; Advance process-mark
1743 (set-marker (process-mark process) (point))
1744
1745 (unless comint-inhibit-carriage-motion
1746 ;; Interpret any carriage motion characters (newline, backspace)
1747 (comint-carriage-motion comint-last-output-start (point)))
1748
1749 ;; Run these hooks with point where the user had it.
1750 (goto-char saved-point)
1751 (run-hook-with-args 'comint-output-filter-functions string)
1752 (set-marker saved-point (point))
1753
1754 (goto-char (process-mark process)) ; in case a filter moved it
1755
1756 (unless comint-use-prompt-regexp
1757 (let ((inhibit-read-only t)
1758 (inhibit-modification-hooks t))
1759 (add-text-properties comint-last-output-start (point)
1760 '(rear-nonsticky t
1761 field output
1762 inhibit-line-move-field-capture t))))
1763
1764 ;; Highlight the prompt, where we define `prompt' to mean
1765 ;; the most recent output that doesn't end with a newline.
1766 (let ((prompt-start (save-excursion (forward-line 0) (point)))
1767 (inhibit-read-only t)
1768 (inhibit-modification-hooks t))
1769 (when comint-prompt-read-only
1770 (or (= (point-min) prompt-start)
1771 (get-text-property (1- prompt-start) 'read-only)
1772 (put-text-property
1773 (1- prompt-start) prompt-start 'read-only 'fence))
1774 (add-text-properties
1775 prompt-start (point)
1776 '(read-only t rear-nonsticky t front-sticky (read-only))))
1777 (unless (and (bolp) (null comint-last-prompt-overlay))
1778 ;; Need to create or move the prompt overlay (in the case
1779 ;; where there is no prompt ((bolp) == t), we still do
1780 ;; this if there's already an existing overlay).
1781 (if comint-last-prompt-overlay
1782 ;; Just move an existing overlay
1783 (move-overlay comint-last-prompt-overlay
1784 prompt-start (point))
1785 ;; Need to create the overlay
1786 (setq comint-last-prompt-overlay
1787 (make-overlay prompt-start (point)))
1788 (overlay-put comint-last-prompt-overlay
1789 'font-lock-face 'comint-highlight-prompt))))
1790
1791 (goto-char saved-point)))))))
1792
1793 (defun comint-preinput-scroll-to-bottom ()
1794 "Go to the end of buffer in all windows showing it.
1795 Movement occurs if point in the selected window is not after the process mark,
1796 and `this-command' is an insertion command. Insertion commands recognized
1797 are `self-insert-command', `comint-magic-space', `yank', and `hilit-yank'.
1798 Depends on the value of `comint-scroll-to-bottom-on-input'.
1799
1800 This function should be a pre-command hook."
1801 (if (and comint-scroll-to-bottom-on-input
1802 (memq this-command '(self-insert-command comint-magic-space yank
1803 hilit-yank)))
1804 (let* ((selected (selected-window))
1805 (current (current-buffer))
1806 (process (get-buffer-process current))
1807 (scroll comint-scroll-to-bottom-on-input))
1808 (if (and process (< (point) (process-mark process)))
1809 (if (eq scroll 'this)
1810 (goto-char (point-max))
1811 (walk-windows
1812 (function (lambda (window)
1813 (if (and (eq (window-buffer window) current)
1814 (or (eq scroll t) (eq scroll 'all)))
1815 (progn
1816 (select-window window)
1817 (goto-char (point-max))
1818 (select-window selected)))))
1819 nil t))))))
1820
1821 (defun comint-postoutput-scroll-to-bottom (string)
1822 "Go to the end of buffer in some or all windows showing it.
1823 Does not scroll if the current line is the last line in the buffer.
1824 Depends on the value of `comint-move-point-for-output' and
1825 `comint-scroll-show-maximum-output'.
1826
1827 This function should be in the list `comint-output-filter-functions'."
1828 (let* ((selected (selected-window))
1829 (current (current-buffer))
1830 (process (get-buffer-process current))
1831 (scroll comint-move-point-for-output))
1832 (unwind-protect
1833 (if process
1834 (walk-windows
1835 (function (lambda (window)
1836 (if (eq (window-buffer window) current)
1837 (progn
1838 (select-window window)
1839 (if (and (< (point) (process-mark process))
1840 (or (eq scroll t) (eq scroll 'all)
1841 ;; Maybe user wants point to jump to end.
1842 (and (eq scroll 'this) (eq selected window))
1843 (and (eq scroll 'others) (not (eq selected window)))
1844 ;; If point was at the end, keep it at end.
1845 (and (marker-position comint-last-output-start)
1846 (>= (point) comint-last-output-start))))
1847 (goto-char (process-mark process)))
1848 ;; Optionally scroll so that the text
1849 ;; ends at the bottom of the window.
1850 (if (and comint-scroll-show-maximum-output
1851 (= (point) (point-max)))
1852 (save-excursion
1853 (goto-char (point-max))
1854 (recenter (- -1 scroll-margin))))
1855 (select-window selected)))))
1856 nil t))
1857 (set-buffer current))))
1858
1859 (defun comint-truncate-buffer (&optional string)
1860 "Truncate the buffer to `comint-buffer-maximum-size'.
1861 This function could be on `comint-output-filter-functions' or bound to a key."
1862 (interactive)
1863 (save-excursion
1864 (goto-char (process-mark (get-buffer-process (current-buffer))))
1865 (forward-line (- comint-buffer-maximum-size))
1866 (beginning-of-line)
1867 (let ((inhibit-read-only t))
1868 (delete-region (point-min) (point)))))
1869
1870 (defun comint-strip-ctrl-m (&optional string)
1871 "Strip trailing `^M' characters from the current output group.
1872 This function could be on `comint-output-filter-functions' or bound to a key."
1873 (interactive)
1874 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1875 (save-excursion
1876 (condition-case nil
1877 (goto-char
1878 (if (interactive-p) comint-last-input-end comint-last-output-start))
1879 (error nil))
1880 (while (re-search-forward "\r+$" pmark t)
1881 (replace-match "" t t)))))
1882 (defalias 'shell-strip-ctrl-m 'comint-strip-ctrl-m)
1883
1884 (defun comint-show-maximum-output ()
1885 "Put the end of the buffer at the bottom of the window."
1886 (interactive)
1887 (goto-char (point-max))
1888 (recenter (- -1 scroll-margin)))
1889
1890 (defun comint-get-old-input-default ()
1891 "Default for `comint-get-old-input'.
1892 If `comint-use-prompt-regexp' is nil, then either
1893 return the current input field, if point is on an input field, or the
1894 current line, if point is on an output field.
1895 If `comint-use-prompt-regexp' is non-nil, then return
1896 the current line with any initial string matching the regexp
1897 `comint-prompt-regexp' removed."
1898 (let ((bof (field-beginning)))
1899 (if (eq (get-char-property bof 'field) 'input)
1900 (field-string-no-properties bof)
1901 (comint-bol)
1902 (buffer-substring-no-properties (point) (line-end-position)))))
1903
1904 (defun comint-copy-old-input ()
1905 "Insert after prompt old input at point as new input to be edited.
1906 Calls `comint-get-old-input' to get old input."
1907 (interactive)
1908 (let ((input (funcall comint-get-old-input))
1909 (process (get-buffer-process (current-buffer))))
1910 (if (not process)
1911 (error "Current buffer has no process")
1912 (goto-char (process-mark process))
1913 (insert input))))
1914
1915 (defun comint-skip-prompt ()
1916 "Skip past the text matching regexp `comint-prompt-regexp'.
1917 If this takes us past the end of the current line, don't skip at all."
1918 (if (and (looking-at comint-prompt-regexp)
1919 (<= (match-end 0) (line-end-position)))
1920 (goto-char (match-end 0))))
1921
1922 (defun comint-after-pmark-p ()
1923 "Return t if point is after the process output marker."
1924 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1925 (<= (marker-position pmark) (point))))
1926
1927 (defun comint-simple-send (proc string)
1928 "Default function for sending to PROC input STRING.
1929 This just sends STRING plus a newline. To override this,
1930 set the hook `comint-input-sender'."
1931 (comint-send-string proc string)
1932 (if comint-input-sender-no-newline
1933 (if (not (string-equal string ""))
1934 (process-send-eof))
1935 (comint-send-string proc "\n")))
1936
1937 (defun comint-line-beginning-position ()
1938 "Return the buffer position of the beginning of the line, after any prompt.
1939 If `comint-use-prompt-regexp' is non-nil, then the prompt skip is done by
1940 skipping text matching the regular expression `comint-prompt-regexp',
1941 a buffer local variable."
1942 (if comint-use-prompt-regexp
1943 ;; Use comint-prompt-regexp
1944 (save-excursion
1945 (beginning-of-line)
1946 (comint-skip-prompt)
1947 (point))
1948 ;; Use input fields. Note that, unlike the behavior of
1949 ;; `line-beginning-position' inside a field, this function will
1950 ;; return the position of the end of a prompt, even if the point is
1951 ;; already inside the prompt. In order to do this, it assumes that
1952 ;; if there are two fields on a line, then the first one is the
1953 ;; prompt, and the second one is an input field, and is front-sticky
1954 ;; (as input fields should be).
1955 (constrain-to-field (line-beginning-position) (line-end-position))))
1956
1957 (defun comint-bol (&optional arg)
1958 "Go to the beginning of line, then skip past the prompt, if any.
1959 If prefix argument is given (\\[universal-argument]) the prompt is not skipped.
1960 If `comint-use-prompt-regexp' is non-nil, then the prompt skip is done
1961 by skipping text matching the regular expression `comint-prompt-regexp',
1962 a buffer local variable."
1963 (interactive "P")
1964 (if arg
1965 ;; Unlike `beginning-of-line', forward-line ignores field boundaries
1966 (forward-line 0)
1967 (goto-char (comint-line-beginning-position))))
1968
1969 ;; For compatibility.
1970 (defun comint-read-noecho (prompt &optional ignore)
1971 (read-passwd prompt))
1972
1973 ;; These three functions are for entering text you don't want echoed or
1974 ;; saved -- typically passwords to ftp, telnet, or somesuch.
1975 ;; Just enter m-x send-invisible and type in your line.
1976
1977 (defun send-invisible (&optional prompt)
1978 "Read a string without echoing.
1979 Then send it to the process running in the current buffer.
1980 The string is sent using `comint-input-sender'.
1981 Security bug: your string can still be temporarily recovered with
1982 \\[view-lossage]; `clear-this-command-keys' can fix that."
1983 (interactive "P") ; Defeat snooping via C-x ESC ESC
1984 (let ((proc (get-buffer-process (current-buffer)))
1985 (prefix
1986 (if (eq (window-buffer (selected-window)) (current-buffer))
1987 ""
1988 (format "(In buffer %s) "
1989 (current-buffer)))))
1990 (if proc
1991 (let ((str (read-passwd (concat prefix
1992 (or prompt "Non-echoed text: ")))))
1993 (if (stringp str)
1994 (progn
1995 (comint-snapshot-last-prompt)
1996 (funcall comint-input-sender proc str))
1997 (message "Warning: text will be echoed")))
1998 (error "Buffer %s has no process" (current-buffer)))))
1999
2000 (defun comint-watch-for-password-prompt (string)
2001 "Prompt in the minibuffer for password and send without echoing.
2002 This function uses `send-invisible' to read and send a password to the buffer's
2003 process if STRING contains a password prompt defined by
2004 `comint-password-prompt-regexp'.
2005
2006 This function could be in the list `comint-output-filter-functions'."
2007 (when (string-match comint-password-prompt-regexp string)
2008 (when (string-match "^[ \n\r\t\v\f\b\a]+" string)
2009 (setq string (replace-match "" t t string)))
2010 (send-invisible string)))
2011 \f
2012 ;; Low-level process communication
2013
2014 (defun comint-send-string (process string)
2015 "Like `process-send-string', but also does extra bookkeeping for Comint mode."
2016 (if process
2017 (with-current-buffer (if (processp process)
2018 (process-buffer process)
2019 (get-buffer process))
2020 (comint-snapshot-last-prompt))
2021 (comint-snapshot-last-prompt))
2022 (process-send-string process string))
2023
2024 (defun comint-send-region (process start end)
2025 "Like `process-send-region', but also does extra bookkeeping for Comint mode."
2026 (if process
2027 (with-current-buffer (if (processp process)
2028 (process-buffer process)
2029 (get-buffer process))
2030 (comint-snapshot-last-prompt))
2031 (comint-snapshot-last-prompt))
2032 (process-send-region process start end))
2033
2034 \f
2035 ;; Random input hackage
2036
2037 (defun comint-delete-output ()
2038 "Delete all output from interpreter since last input.
2039 Does not delete the prompt."
2040 (interactive)
2041 (let ((proc (get-buffer-process (current-buffer)))
2042 (replacement nil)
2043 (inhibit-read-only t))
2044 (save-excursion
2045 (let ((pmark (progn (goto-char (process-mark proc))
2046 (forward-line 0)
2047 (point-marker))))
2048 (delete-region comint-last-input-end pmark)
2049 (goto-char (process-mark proc))
2050 (setq replacement (concat "*** output flushed ***\n"
2051 (buffer-substring pmark (point))))
2052 (delete-region pmark (point))))
2053 ;; Output message and put back prompt
2054 (comint-output-filter proc replacement)))
2055 (define-obsolete-function-alias 'comint-kill-output
2056 'comint-delete-output "21.1")
2057
2058 (defun comint-write-output (filename &optional append mustbenew)
2059 "Write output from interpreter since last input to FILENAME.
2060 Any prompt at the end of the output is not written.
2061
2062 If the optional argument APPEND (the prefix argument when interactive)
2063 is non-nil, the output is appended to the file instead.
2064
2065 If the optional argument MUSTBENEW is non-nil, check for an existing
2066 file with the same name. If MUSTBENEW is `excl', that means to get an
2067 error if the file already exists; never overwrite. If MUSTBENEW is
2068 neither nil nor `excl', that means ask for confirmation before
2069 overwriting, but do go ahead and overwrite the file if the user
2070 confirms. When interactive, MUSTBENEW is nil when appending, and t
2071 otherwise."
2072 (interactive
2073 (list (read-file-name
2074 (if current-prefix-arg
2075 "Append output to file: "
2076 "Write output to file: "))
2077 current-prefix-arg
2078 (not current-prefix-arg)))
2079 (save-excursion
2080 (goto-char (process-mark (get-buffer-process (current-buffer))))
2081 (forward-line 0)
2082 (write-region comint-last-input-end (point) filename
2083 append nil nil mustbenew)))
2084
2085 ;; This function exists for the benefit of the menu; from the keyboard,
2086 ;; users can just use `comint-write-output' with a prefix arg.
2087 (defun comint-append-output-to-file (filename)
2088 "Append output from interpreter since last input to FILENAME.
2089 Any prompt at the end of the output is not written."
2090 (interactive "fAppend output to file: ")
2091 (comint-write-output filename t))
2092
2093 (defun comint-show-output ()
2094 "Display start of this batch of interpreter output at top of window.
2095 Sets mark to the value of point when this command is run."
2096 (interactive)
2097 (push-mark)
2098 (let ((pos (or (marker-position comint-last-input-end) (point-max))))
2099 (cond (comint-use-prompt-regexp
2100 (goto-char pos)
2101 (beginning-of-line 0)
2102 (set-window-start (selected-window) (point))
2103 (comint-skip-prompt))
2104 (t
2105 (let* ((beg (field-beginning pos))
2106 (pt (if (= (point-min) beg)
2107 (point-min)
2108 (1+ beg))))
2109 (goto-char pt))
2110 (set-window-start (selected-window) (point))))))
2111
2112
2113 (defun comint-interrupt-subjob ()
2114 "Interrupt the current subjob.
2115 This command also kills the pending input
2116 between the process mark and point."
2117 (interactive)
2118 (comint-skip-input)
2119 (interrupt-process nil comint-ptyp)
2120 ;; (process-send-string nil "\n")
2121 )
2122
2123 (defun comint-kill-subjob ()
2124 "Send kill signal to the current subjob.
2125 This command also kills the pending input
2126 between the process mark and point."
2127 (interactive)
2128 (comint-skip-input)
2129 (kill-process nil comint-ptyp))
2130
2131 (defun comint-quit-subjob ()
2132 "Send quit signal to the current subjob.
2133 This command also kills the pending input
2134 between the process mark and point."
2135 (interactive)
2136 (comint-skip-input)
2137 (quit-process nil comint-ptyp))
2138
2139 (defun comint-stop-subjob ()
2140 "Stop the current subjob.
2141 This command also kills the pending input
2142 between the process mark and point.
2143
2144 WARNING: if there is no current subjob, you can end up suspending
2145 the top-level process running in the buffer. If you accidentally do
2146 this, use \\[comint-continue-subjob] to resume the process. (This
2147 is not a problem with most shells, since they ignore this signal.)"
2148 (interactive)
2149 (comint-skip-input)
2150 (stop-process nil comint-ptyp))
2151
2152 (defun comint-continue-subjob ()
2153 "Send CONT signal to process buffer's process group.
2154 Useful if you accidentally suspend the top-level process."
2155 (interactive)
2156 (continue-process nil comint-ptyp))
2157
2158 (defun comint-skip-input ()
2159 "Skip all pending input, from last stuff output by interpreter to point.
2160 This means mark it as if it had been sent as input, without sending it."
2161 (let ((comint-input-sender 'ignore)
2162 (comint-input-filter-functions nil))
2163 (comint-send-input t t))
2164 (end-of-line)
2165 (let ((pos (point))
2166 (marker (process-mark (get-buffer-process (current-buffer)))))
2167 (insert " " (key-description (this-command-keys)))
2168 (if (= marker pos)
2169 (set-marker marker (point)))))
2170
2171 (defun comint-kill-input ()
2172 "Kill all text from last stuff output by interpreter to point."
2173 (interactive)
2174 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2175 (if (> (point) (marker-position pmark))
2176 (kill-region pmark (point)))))
2177
2178 (defun comint-delchar-or-maybe-eof (arg)
2179 "Delete ARG characters forward or send an EOF to subprocess.
2180 Sends an EOF only if point is at the end of the buffer and there is no input."
2181 (interactive "p")
2182 (let ((proc (get-buffer-process (current-buffer))))
2183 (if (and (eobp) proc (= (point) (marker-position (process-mark proc))))
2184 (comint-send-eof)
2185 (delete-char arg))))
2186
2187 (defun comint-send-eof ()
2188 "Send an EOF to the current buffer's process."
2189 (interactive)
2190 (comint-send-input t t)
2191 (process-send-eof))
2192
2193
2194 (defun comint-backward-matching-input (regexp n)
2195 "Search backward through buffer for input fields that match REGEXP.
2196 If `comint-use-prompt-regexp' is non-nil, then input fields are identified
2197 by lines that match `comint-prompt-regexp'.
2198
2199 With prefix argument N, search for Nth previous match.
2200 If N is negative, find the next or Nth next match."
2201 (interactive (comint-regexp-arg "Backward input matching (regexp): "))
2202 (if comint-use-prompt-regexp
2203 ;; Use comint-prompt-regexp
2204 (let* ((re (concat comint-prompt-regexp ".*" regexp))
2205 (pos (save-excursion (end-of-line (if (> n 0) 0 1))
2206 (if (re-search-backward re nil t n)
2207 (point)))))
2208 (if (null pos)
2209 (progn (message "Not found")
2210 (ding))
2211 (goto-char pos)
2212 (comint-bol nil)))
2213 ;; Use input fields
2214 (let* ((dir (if (< n 0) -1 1))
2215 (pos
2216 (save-excursion
2217 (while (/= n 0)
2218 (unless (re-search-backward regexp nil t dir)
2219 (error "Not found"))
2220 (when (eq (get-char-property (point) 'field) 'input)
2221 (setq n (- n dir))))
2222 (field-beginning))))
2223 (goto-char pos))))
2224
2225
2226 (defun comint-forward-matching-input (regexp n)
2227 "Search forward through buffer for input fields that match REGEXP.
2228 If `comint-use-prompt-regexp' is non-nil, then input fields are identified
2229 by lines that match `comint-prompt-regexp'.
2230
2231 With prefix argument N, search for Nth following match.
2232 If N is negative, find the previous or Nth previous match."
2233 (interactive (comint-regexp-arg "Forward input matching (regexp): "))
2234 (comint-backward-matching-input regexp (- n)))
2235
2236
2237 (defun comint-next-prompt (n)
2238 "Move to end of Nth next prompt in the buffer.
2239 If `comint-use-prompt-regexp' is nil, then this means the beginning of
2240 the Nth next `input' field, otherwise, it means the Nth occurrence of
2241 text matching `comint-prompt-regexp'."
2242 (interactive "p")
2243 (if comint-use-prompt-regexp
2244 ;; Use comint-prompt-regexp
2245 (let ((paragraph-start comint-prompt-regexp))
2246 (end-of-line (if (> n 0) 1 0))
2247 (forward-paragraph n)
2248 (comint-skip-prompt))
2249 ;; Use input fields
2250 (let ((pos (point))
2251 (input-pos nil)
2252 prev-pos)
2253 (while (/= n 0)
2254 (setq prev-pos pos)
2255 (setq pos
2256 (if (> n 0)
2257 (next-single-char-property-change pos 'field)
2258 (previous-single-char-property-change pos 'field)))
2259 (cond ((or (null pos) (= pos prev-pos))
2260 ;; Ran off the end of the buffer.
2261 (when (> n 0)
2262 ;; There's always an input field at the end of the
2263 ;; buffer, but it has a `field' property of nil.
2264 (setq input-pos (point-max)))
2265 ;; stop iterating
2266 (setq n 0))
2267 ((eq (get-char-property pos 'field) 'input)
2268 (setq n (if (< n 0) (1+ n) (1- n)))
2269 (setq input-pos pos))))
2270 (when input-pos
2271 (goto-char input-pos)))))
2272
2273
2274 (defun comint-previous-prompt (n)
2275 "Move to end of Nth previous prompt in the buffer.
2276 If `comint-use-prompt-regexp' is nil, then this means the beginning of
2277 the Nth previous `input' field, otherwise, it means the Nth occurrence of
2278 text matching `comint-prompt-regexp'."
2279 (interactive "p")
2280 (comint-next-prompt (- n)))
2281
2282 ;; State used by `comint-insert-previous-argument' when cycling.
2283 (defvar comint-insert-previous-argument-last-start-pos nil)
2284 (make-variable-buffer-local 'comint-insert-previous-argument-last-start-pos)
2285 (defvar comint-insert-previous-argument-last-index nil)
2286 (make-variable-buffer-local 'comint-insert-previous-argument-last-index)
2287
2288 ;; Needs fixing:
2289 ;; make comint-arguments understand negative indices as bash does
2290 (defun comint-insert-previous-argument (index)
2291 "Insert the INDEXth argument from the previous Comint command-line at point.
2292 Spaces are added at beginning and/or end of the inserted string if
2293 necessary to ensure that it's separated from adjacent arguments.
2294 Interactively, if no prefix argument is given, the last argument is inserted.
2295 Repeated interactive invocations will cycle through the same argument
2296 from progressively earlier commands (using the value of INDEX specified
2297 with the first command).
2298 This command is like `M-.' in bash."
2299 (interactive "P")
2300 (unless (null index)
2301 (setq index (prefix-numeric-value index)))
2302 (cond ((eq last-command this-command)
2303 ;; Delete last input inserted by this command.
2304 (delete-region comint-insert-previous-argument-last-start-pos (point))
2305 (setq index comint-insert-previous-argument-last-index))
2306 (t
2307 ;; This is a non-repeat invocation, so initialize state.
2308 (setq comint-input-ring-index nil)
2309 (setq comint-insert-previous-argument-last-index index)
2310 (when (null comint-insert-previous-argument-last-start-pos)
2311 ;; First usage; initialize to a marker
2312 (setq comint-insert-previous-argument-last-start-pos
2313 (make-marker)))))
2314 ;; Make sure we're not in the prompt, and add a beginning space if necess.
2315 (if (<= (point) (comint-line-beginning-position))
2316 (comint-bol)
2317 (just-one-space))
2318 ;; Remember the beginning of what we insert, so we can delete it if
2319 ;; the command is repeated.
2320 (set-marker comint-insert-previous-argument-last-start-pos (point))
2321 ;; Insert the argument.
2322 (let ((input-string (comint-previous-input-string 0)))
2323 (when (string-match "[ \t\n]*&" input-string)
2324 ;; strip terminating '&'
2325 (setq input-string (substring input-string 0 (match-beginning 0))))
2326 (insert (comint-arguments input-string index index)))
2327 ;; Make next invocation return arg from previous input
2328 (setq comint-input-ring-index (1+ (or comint-input-ring-index 0)))
2329 ;; Add a terminating space if necessary.
2330 (unless (eolp)
2331 (just-one-space)))
2332
2333 \f
2334 ;; Support editing with `comint-prompt-read-only' set to t.
2335
2336 (defun comint-update-fence ()
2337 "Update read-only status of newline before point.
2338 The `fence' read-only property is used to indicate that a newline
2339 is read-only for no other reason than to \"fence off\" a
2340 following front-sticky read-only region. This is used to
2341 implement comint read-only prompts. If the text after a newline
2342 changes, the read-only status of that newline may need updating.
2343 That is what this function does.
2344
2345 This function does nothing if point is not at the beginning of a
2346 line, or is at the beginning of the accessible portion of the buffer.
2347 Otherwise, if the character after point has a front-sticky
2348 read-only property, then the preceding newline is given a
2349 read-only property of `fence', unless it already is read-only.
2350 If the character after point does not have a front-sticky
2351 read-only property, any read-only property of `fence' on the
2352 preceding newline is removed."
2353 (let* ((pt (point)) (lst (get-text-property pt 'front-sticky))
2354 (inhibit-modification-hooks t))
2355 (and (bolp)
2356 (not (bobp))
2357 (if (and (get-text-property pt 'read-only)
2358 (if (listp lst) (memq 'read-only lst) t))
2359 (unless (get-text-property (1- pt) 'read-only)
2360 (put-text-property (1- pt) pt 'read-only 'fence))
2361 (when (eq (get-text-property (1- pt) 'read-only) 'fence)
2362 (remove-list-of-text-properties (1- pt) pt '(read-only)))))))
2363
2364 (defun comint-kill-whole-line (&optional count)
2365 "Kill current line, ignoring read-only and field properties.
2366 With prefix arg COUNT, kill that many lines starting from the current line.
2367 If COUNT is negative, kill backward. Also kill the preceding newline,
2368 instead of the trailing one. \(This is meant to make \\[repeat] work well
2369 with negative arguments.)
2370 If COUNT is zero, kill current line but exclude the trailing newline.
2371 The read-only status of newlines is updated with `comint-update-fence',
2372 if necessary."
2373 (interactive "p")
2374 (let ((inhibit-read-only t) (inhibit-field-text-motion t))
2375 (kill-whole-line count)
2376 (when (>= count 0) (comint-update-fence))))
2377
2378 (defun comint-kill-region (beg end &optional yank-handler)
2379 "Like `kill-region', but ignores read-only properties, if safe.
2380 This command assumes that the buffer contains read-only
2381 \"prompts\" which are regions with front-sticky read-only
2382 properties at the beginning of a line, with the preceding newline
2383 being read-only to protect the prompt. This is true of the
2384 comint prompts if `comint-prompt-read-only' is non-nil. This
2385 command will not delete the region if this would create mutilated
2386 or out of place prompts. That is, if any part of a prompt is
2387 deleted, the entire prompt must be deleted and all remaining
2388 prompts should stay at the beginning of a line. If this is not
2389 the case, this command just calls `kill-region' with all
2390 read-only properties intact. The read-only status of newlines is
2391 updated using `comint-update-fence', if necessary."
2392 (interactive "r")
2393 (save-excursion
2394 (let* ((true-beg (min beg end))
2395 (true-end (max beg end))
2396 (beg-bolp (progn (goto-char true-beg) (bolp)))
2397 (beg-lst (get-text-property true-beg 'front-sticky))
2398 (beg-bad (and (get-text-property true-beg 'read-only)
2399 (if (listp beg-lst) (memq 'read-only beg-lst) t)))
2400 (end-bolp (progn (goto-char true-end) (bolp)))
2401 (end-lst (get-text-property true-end 'front-sticky))
2402 (end-bad (and (get-text-property true-end 'read-only)
2403 (if (listp end-lst) (memq 'read-only end-lst) t))))
2404 (if (or (and (not beg-bolp) (or beg-bad end-bad))
2405 (and (not end-bolp) end-bad))
2406 (kill-region beg end yank-handler)
2407 (let ((inhibit-read-only t))
2408 (kill-region beg end yank-handler)
2409 (comint-update-fence))))))
2410
2411 \f
2412 ;; Support for source-file processing commands.
2413 ;;============================================================================
2414 ;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
2415 ;; commands that process files of source text (e.g. loading or compiling
2416 ;; files). So the corresponding process-in-a-buffer modes have commands
2417 ;; for doing this (e.g., lisp-load-file). The functions below are useful
2418 ;; for defining these commands.
2419 ;;
2420 ;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
2421 ;; and Soar, in that they don't know anything about file extensions.
2422 ;; So the compile/load interface gets the wrong default occasionally.
2423 ;; The load-file/compile-file default mechanism could be smarter -- it
2424 ;; doesn't know about the relationship between filename extensions and
2425 ;; whether the file is source or executable. If you compile foo.lisp
2426 ;; with compile-file, then the next load-file should use foo.bin for
2427 ;; the default, not foo.lisp. This is tricky to do right, particularly
2428 ;; because the extension for executable files varies so much (.o, .bin,
2429 ;; .lbin, .mo, .vo, .ao, ...).
2430
2431
2432 ;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
2433 ;; commands.
2434 ;;
2435 ;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
2436 ;; want to save the buffer before issuing any process requests to the command
2437 ;; interpreter.
2438 ;;
2439 ;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
2440 ;; for the file to process.
2441
2442 (defun comint-source-default (previous-dir/file source-modes)
2443 "Compute the defaults for `load-file' and `compile-file' commands.
2444
2445 PREVIOUS-DIR/FILE is a pair (DIRECTORY . FILENAME) from the last
2446 source-file processing command, or nil if there hasn't been one yet.
2447 SOURCE-MODES is a list used to determine what buffers contain source
2448 files: if the major mode of the buffer is in SOURCE-MODES, it's source.
2449 Typically, (lisp-mode) or (scheme-mode).
2450
2451 If the command is given while the cursor is inside a string, *and*
2452 the string is an existing filename, *and* the filename is not a directory,
2453 then the string is taken as default. This allows you to just position
2454 your cursor over a string that's a filename and have it taken as default.
2455
2456 If the command is given in a file buffer whose major mode is in
2457 SOURCE-MODES, then the filename is the default file, and the
2458 file's directory is the default directory.
2459
2460 If the buffer isn't a source file buffer (e.g., it's the process buffer),
2461 then the default directory & file are what was used in the last source-file
2462 processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
2463 the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
2464 is the cwd, with no default file. (\"no default file\" = nil)
2465
2466 SOURCE-MODES is typically going to be something like (tea-mode)
2467 for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
2468 for Soar programs, etc.
2469
2470 The function returns a pair: (default-directory . default-file)."
2471 (cond ((and buffer-file-name (memq major-mode source-modes))
2472 (cons (file-name-directory buffer-file-name)
2473 (file-name-nondirectory buffer-file-name)))
2474 (previous-dir/file)
2475 (t
2476 (cons default-directory nil))))
2477
2478
2479 (defun comint-check-source (fname)
2480 "Check whether to save buffers visiting file FNAME.
2481 Prior to loading or compiling (or otherwise processing) a file (in the CMU
2482 process-in-a-buffer modes), this function can be called on the filename.
2483 If the file is loaded into a buffer, and the buffer is modified, the user
2484 is queried to see if he wants to save the buffer before proceeding with
2485 the load or compile."
2486 (let ((buff (get-file-buffer fname)))
2487 (if (and buff
2488 (buffer-modified-p buff)
2489 (y-or-n-p (format "Save buffer %s first? " (buffer-name buff))))
2490 ;; save BUFF.
2491 (let ((old-buffer (current-buffer)))
2492 (set-buffer buff)
2493 (save-buffer)
2494 (set-buffer old-buffer)))))
2495
2496 (defun comint-extract-string ()
2497 "Return string around point, or nil."
2498 (let ((syntax (syntax-ppss)))
2499 (when (nth 3 syntax)
2500 (condition-case ()
2501 (buffer-substring-no-properties (1+ (nth 8 syntax))
2502 (progn (goto-char (nth 8 syntax))
2503 (forward-sexp)
2504 (1- (point))))
2505 (error nil)))))
2506
2507 (defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
2508 "Prompt for filenames in commands that process source files,
2509 e.g. loading or compiling a file.
2510 Provides a default, if there is one, and returns the result filename.
2511
2512 See `comint-source-default' for more on determining defaults.
2513
2514 PROMPT is the prompt string. PREV-DIR/FILE is the (DIRECTORY . FILE) pair
2515 from the last source processing command. SOURCE-MODES is a list of major
2516 modes used to determine what file buffers contain source files. (These
2517 two arguments are used for determining defaults.) If MUSTMATCH-P is true,
2518 then the filename reader will only accept a file that exists.
2519
2520 A typical use:
2521 (interactive (comint-get-source \"Compile file: \" prev-lisp-dir/file
2522 '(lisp-mode) t))"
2523 (let* ((def (comint-source-default prev-dir/file source-modes))
2524 (stringfile (comint-extract-string))
2525 (sfile-p (and stringfile
2526 (condition-case ()
2527 (file-exists-p stringfile)
2528 (error nil))
2529 (not (file-directory-p stringfile))))
2530 (defdir (if sfile-p (file-name-directory stringfile)
2531 (car def)))
2532 (deffile (if sfile-p (file-name-nondirectory stringfile)
2533 (cdr def)))
2534 (ans (read-file-name (if deffile (format "%s(default %s) "
2535 prompt deffile)
2536 prompt)
2537 defdir
2538 (concat defdir deffile)
2539 mustmatch-p)))
2540 (list (expand-file-name (substitute-in-file-name ans)))))
2541
2542 ;; I am somewhat divided on this string-default feature. It seems
2543 ;; to violate the principle-of-least-astonishment, in that it makes
2544 ;; the default harder to predict, so you actually have to look and see
2545 ;; what the default really is before choosing it. This can trip you up.
2546 ;; On the other hand, it can be useful, I guess. I would appreciate feedback
2547 ;; on this.
2548 ;; -Olin
2549
2550 \f
2551 ;; Simple process query facility.
2552 ;; ===========================================================================
2553 ;; This function is for commands that want to send a query to the process
2554 ;; and show the response to the user. For example, a command to get the
2555 ;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
2556 ;; to an inferior Common Lisp process.
2557 ;;
2558 ;; This simple facility just sends strings to the inferior process and pops
2559 ;; up a window for the process buffer so you can see what the process
2560 ;; responds with. We don't do anything fancy like try to intercept what the
2561 ;; process responds with and put it in a pop-up window or on the message
2562 ;; line. We just display the buffer. Low tech. Simple. Works good.
2563
2564 (defun comint-proc-query (proc str)
2565 "Send to the inferior process PROC the string STR.
2566 Pop-up but do not select a window for the inferior process so that
2567 its response can be seen."
2568 (let* ((proc-buf (process-buffer proc))
2569 (proc-mark (process-mark proc)))
2570 (display-buffer proc-buf)
2571 (set-buffer proc-buf) ; but it's not the selected *window*
2572 (let ((proc-win (get-buffer-window proc-buf))
2573 (proc-pt (marker-position proc-mark)))
2574 (comint-send-string proc str) ; send the query
2575 (accept-process-output proc) ; wait for some output
2576 ;; Try to position the proc window so you can see the answer.
2577 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
2578 ;; I don't know why. Wizards invited to improve it.
2579 (unless (pos-visible-in-window-p proc-pt proc-win)
2580 (let ((opoint (window-point proc-win)))
2581 (set-window-point proc-win proc-mark)
2582 (sit-for 0)
2583 (if (not (pos-visible-in-window-p opoint proc-win))
2584 (push-mark opoint)
2585 (set-window-point proc-win opoint)))))))
2586
2587 \f
2588 ;; Filename/command/history completion in a buffer
2589 ;; ===========================================================================
2590 ;; Useful completion functions, courtesy of the Ergo group.
2591
2592 ;; Six commands:
2593 ;; comint-dynamic-complete Complete or expand command, filename,
2594 ;; history at point.
2595 ;; comint-dynamic-complete-filename Complete filename at point.
2596 ;; comint-dynamic-list-filename-completions List completions in help buffer.
2597 ;; comint-replace-by-expanded-filename Expand and complete filename at point;
2598 ;; replace with expanded/completed name.
2599 ;; comint-dynamic-simple-complete Complete stub given candidates.
2600
2601 ;; These are not installed in the comint-mode keymap. But they are
2602 ;; available for people who want them. Shell-mode installs them:
2603 ;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
2604 ;; (define-key shell-mode-map "\M-?"
2605 ;; 'comint-dynamic-list-filename-completions)))
2606 ;;
2607 ;; Commands like this are fine things to put in load hooks if you
2608 ;; want them present in specific modes.
2609
2610 (defcustom comint-completion-autolist nil
2611 "*If non-nil, automatically list possibilities on partial completion.
2612 This mirrors the optional behavior of tcsh."
2613 :type 'boolean
2614 :group 'comint-completion)
2615
2616 (defcustom comint-completion-addsuffix t
2617 "*If non-nil, add a `/' to completed directories, ` ' to file names.
2618 If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
2619 DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact completion.
2620 This mirrors the optional behavior of tcsh."
2621 :type '(choice (const :tag "None" nil)
2622 (const :tag "Add /" t)
2623 (cons :tag "Suffix pair"
2624 (string :tag "Directory suffix")
2625 (string :tag "File suffix")))
2626 :group 'comint-completion)
2627
2628 (defcustom comint-completion-recexact nil
2629 "*If non-nil, use shortest completion if characters cannot be added.
2630 This mirrors the optional behavior of tcsh.
2631
2632 A non-nil value is useful if `comint-completion-autolist' is non-nil too."
2633 :type 'boolean
2634 :group 'comint-completion)
2635
2636 (defcustom comint-completion-fignore nil
2637 "*List of suffixes to be disregarded during file completion.
2638 This mirrors the optional behavior of bash and tcsh.
2639
2640 Note that this applies to `comint-dynamic-complete-filename' only."
2641 :type '(repeat (string :tag "Suffix"))
2642 :group 'comint-completion)
2643
2644 ;;;###autoload
2645 (defvar comint-file-name-prefix ""
2646 "Prefix prepended to absolute file names taken from process input.
2647 This is used by Comint's and shell's completion functions, and by shell's
2648 directory tracking functions.")
2649
2650 (defvar comint-file-name-chars
2651 (if (memq system-type '(ms-dos windows-nt cygwin))
2652 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
2653 "[]~/A-Za-z0-9+@:_.$#%,={}-")
2654 "String of characters valid in a file name.
2655 Note that all non-ASCII characters are considered valid in a file name
2656 regardless of what this variable says.
2657
2658 This is a good thing to set in mode hooks.")
2659
2660 (defvar comint-file-name-quote-list nil
2661 "List of characters to quote with `\\' when in a file name.
2662
2663 This is a good thing to set in mode hooks.")
2664
2665
2666 (defun comint-directory (directory)
2667 "Return expanded DIRECTORY, with `comint-file-name-prefix' if absolute."
2668 (expand-file-name (if (file-name-absolute-p directory)
2669 (concat comint-file-name-prefix directory)
2670 directory)))
2671
2672
2673 (defun comint-word (word-chars)
2674 "Return the word of WORD-CHARS at point, or nil if none is found.
2675 Word constituents are considered to be those in WORD-CHARS, which is like the
2676 inside of a \"[...]\" (see `skip-chars-forward'), plus all non-ASCII characters."
2677 (save-excursion
2678 (let ((here (point))
2679 giveup)
2680 (while (not giveup)
2681 (let ((startpoint (point)))
2682 (skip-chars-backward (concat "\\\\" word-chars))
2683 ;; Fixme: This isn't consistent with Bash, at least -- not
2684 ;; all non-ASCII chars should be word constituents.
2685 (if (and (> (- (point) 2) (point-min))
2686 (= (char-after (- (point) 2)) ?\\))
2687 (forward-char -2))
2688 (if (and (> (- (point) 1) (point-min))
2689 (>= (char-after (- (point) 1)) 128))
2690 (forward-char -1))
2691 (if (= (point) startpoint)
2692 (setq giveup t))))
2693 ;; Set match-data to match the entire string.
2694 (when (< (point) here)
2695 (set-match-data (list (point) here))
2696 (match-string 0)))))
2697
2698 (defun comint-substitute-in-file-name (filename)
2699 "Return FILENAME with environment variables substituted.
2700 Supports additional environment variable syntax of the command
2701 interpreter (e.g., the percent notation of cmd.exe on NT)."
2702 (let ((name (substitute-in-file-name filename)))
2703 (if (memq system-type '(ms-dos windows-nt))
2704 (let (env-var-name
2705 env-var-val)
2706 (save-match-data
2707 (while (string-match "%\\([^\\\\/]*\\)%" name)
2708 (setq env-var-name
2709 (substring name (match-beginning 1) (match-end 1)))
2710 (setq env-var-val (if (getenv env-var-name)
2711 (getenv env-var-name)
2712 ""))
2713 (setq name (replace-match env-var-val t t name))))))
2714 name))
2715
2716 (defun comint-match-partial-filename ()
2717 "Return the filename at point, or nil if none is found.
2718 Environment variables are substituted. See `comint-word'."
2719 (let ((filename (comint-word comint-file-name-chars)))
2720 (and filename (comint-substitute-in-file-name
2721 (comint-unquote-filename filename)))))
2722
2723
2724 (defun comint-quote-filename (filename)
2725 "Return FILENAME with magic characters quoted.
2726 Magic characters are those in `comint-file-name-quote-list'."
2727 (if (null comint-file-name-quote-list)
2728 filename
2729 (let ((regexp
2730 (format "[%s]"
2731 (mapconcat 'char-to-string comint-file-name-quote-list ""))))
2732 (save-match-data
2733 (let ((i 0))
2734 (while (string-match regexp filename i)
2735 (setq filename (replace-match "\\\\\\&" nil nil filename))
2736 (setq i (1+ (match-end 0)))))
2737 filename))))
2738
2739 (defun comint-unquote-filename (filename)
2740 "Return FILENAME with quoted characters unquoted."
2741 (if (null comint-file-name-quote-list)
2742 filename
2743 (save-match-data
2744 (let ((i 0))
2745 (while (string-match "\\\\\\(.\\)" filename i)
2746 (setq filename (replace-match "\\1" nil nil filename))
2747 (setq i (+ 1 (match-beginning 0)))))
2748 filename)))
2749
2750
2751 (defun comint-dynamic-complete ()
2752 "Dynamically perform completion at point.
2753 Calls the functions in `comint-dynamic-complete-functions' to perform
2754 completion until a function returns non-nil, at which point completion is
2755 assumed to have occurred."
2756 (interactive)
2757 (run-hook-with-args-until-success 'comint-dynamic-complete-functions))
2758
2759
2760 (defun comint-dynamic-complete-filename ()
2761 "Dynamically complete the filename at point.
2762 Completes if after a filename. See `comint-match-partial-filename' and
2763 `comint-dynamic-complete-as-filename'.
2764 This function is similar to `comint-replace-by-expanded-filename', except that
2765 it won't change parts of the filename already entered in the buffer; it just
2766 adds completion characters to the end of the filename. A completions listing
2767 may be shown in a help buffer if completion is ambiguous.
2768
2769 Completion is dependent on the value of `comint-completion-addsuffix',
2770 `comint-completion-recexact' and `comint-completion-fignore', and the timing of
2771 completions listing is dependent on the value of `comint-completion-autolist'.
2772
2773 Returns t if successful."
2774 (interactive)
2775 (when (comint-match-partial-filename)
2776 (unless (window-minibuffer-p (selected-window))
2777 (message "Completing file name..."))
2778 (comint-dynamic-complete-as-filename)))
2779
2780 (defun comint-dynamic-complete-as-filename ()
2781 "Dynamically complete at point as a filename.
2782 See `comint-dynamic-complete-filename'. Returns t if successful."
2783 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt cygwin)))
2784 (completion-ignored-extensions comint-completion-fignore)
2785 ;; If we bind this, it breaks remote directory tracking in rlogin.el.
2786 ;; I think it was originally bound to solve file completion problems,
2787 ;; but subsequent changes may have made this unnecessary. sm.
2788 ;;(file-name-handler-alist nil)
2789 (minibuffer-p (window-minibuffer-p (selected-window)))
2790 (success t)
2791 (dirsuffix (cond ((not comint-completion-addsuffix)
2792 "")
2793 ((not (consp comint-completion-addsuffix))
2794 "/")
2795 (t
2796 (car comint-completion-addsuffix))))
2797 (filesuffix (cond ((not comint-completion-addsuffix)
2798 "")
2799 ((not (consp comint-completion-addsuffix))
2800 " ")
2801 (t
2802 (cdr comint-completion-addsuffix))))
2803 (filename (or (comint-match-partial-filename) ""))
2804 (filedir (file-name-directory filename))
2805 (filenondir (file-name-nondirectory filename))
2806 (directory (if filedir (comint-directory filedir) default-directory))
2807 (completion (file-name-completion filenondir directory)))
2808 (cond ((null completion)
2809 (message "No completions of %s" filename)
2810 (setq success nil))
2811 ((eq completion t) ; Means already completed "file".
2812 (insert filesuffix)
2813 (unless minibuffer-p
2814 (message "Sole completion")))
2815 ((string-equal completion "") ; Means completion on "directory/".
2816 (comint-dynamic-list-filename-completions))
2817 (t ; Completion string returned.
2818 (let ((file (concat (file-name-as-directory directory) completion)))
2819 (insert (comint-quote-filename
2820 (substring (directory-file-name completion)
2821 (length filenondir))))
2822 (cond ((symbolp (file-name-completion completion directory))
2823 ;; We inserted a unique completion.
2824 (insert (if (file-directory-p file) dirsuffix filesuffix))
2825 (unless minibuffer-p
2826 (message "Completed")))
2827 ((and comint-completion-recexact comint-completion-addsuffix
2828 (string-equal filenondir completion)
2829 (file-exists-p file))
2830 ;; It's not unique, but user wants shortest match.
2831 (insert (if (file-directory-p file) dirsuffix filesuffix))
2832 (unless minibuffer-p
2833 (message "Completed shortest")))
2834 ((or comint-completion-autolist
2835 (string-equal filenondir completion))
2836 ;; It's not unique, list possible completions.
2837 (comint-dynamic-list-filename-completions))
2838 (t
2839 (unless minibuffer-p
2840 (message "Partially completed")))))))
2841 success))
2842
2843
2844 (defun comint-replace-by-expanded-filename ()
2845 "Dynamically expand and complete the filename at point.
2846 Replace the filename with an expanded, canonicalized and completed replacement.
2847 \"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
2848 with the corresponding directories. \"Canonicalized\" means `..' and `.' are
2849 removed, and the filename is made absolute instead of relative. For expansion
2850 see `expand-file-name' and `substitute-in-file-name'. For completion see
2851 `comint-dynamic-complete-filename'."
2852 (interactive)
2853 (let ((filename (comint-match-partial-filename)))
2854 (when filename
2855 (replace-match (expand-file-name filename) t t)
2856 (comint-dynamic-complete-filename))))
2857
2858
2859 (defun comint-dynamic-simple-complete (stub candidates)
2860 "Dynamically complete STUB from CANDIDATES list.
2861 This function inserts completion characters at point by completing STUB from
2862 the strings in CANDIDATES. A completions listing may be shown in a help buffer
2863 if completion is ambiguous.
2864
2865 Returns nil if no completion was inserted.
2866 Returns `sole' if completed with the only completion match.
2867 Returns `shortest' if completed with the shortest of the completion matches.
2868 Returns `partial' if completed as far as possible with the completion matches.
2869 Returns `listed' if a completion listing was shown.
2870
2871 See also `comint-dynamic-complete-filename'."
2872 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt cygwin)))
2873 (suffix (cond ((not comint-completion-addsuffix) "")
2874 ((not (consp comint-completion-addsuffix)) " ")
2875 (t (cdr comint-completion-addsuffix))))
2876 (completions (all-completions stub candidates)))
2877 (cond ((null completions)
2878 (message "No completions of %s" stub)
2879 nil)
2880 ((= 1 (length completions)) ; Gotcha!
2881 (let ((completion (car completions)))
2882 (if (string-equal completion stub)
2883 (message "Sole completion")
2884 (insert (substring completion (length stub)))
2885 (message "Completed"))
2886 (insert suffix)
2887 'sole))
2888 (t ; There's no unique completion.
2889 (let ((completion (try-completion stub candidates)))
2890 ;; Insert the longest substring.
2891 (insert (substring completion (length stub)))
2892 (cond ((and comint-completion-recexact comint-completion-addsuffix
2893 (string-equal stub completion)
2894 (member completion completions))
2895 ;; It's not unique, but user wants shortest match.
2896 (insert suffix)
2897 (message "Completed shortest")
2898 'shortest)
2899 ((or comint-completion-autolist
2900 (string-equal stub completion))
2901 ;; It's not unique, list possible completions.
2902 (comint-dynamic-list-completions completions)
2903 'listed)
2904 (t
2905 (message "Partially completed")
2906 'partial)))))))
2907
2908
2909 (defun comint-dynamic-list-filename-completions ()
2910 "List in help buffer possible completions of the filename at point."
2911 (interactive)
2912 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt cygwin)))
2913 ;; If we bind this, it breaks remote directory tracking in rlogin.el.
2914 ;; I think it was originally bound to solve file completion problems,
2915 ;; but subsequent changes may have made this unnecessary. sm.
2916 ;;(file-name-handler-alist nil)
2917 (filename (or (comint-match-partial-filename) ""))
2918 (filedir (file-name-directory filename))
2919 (filenondir (file-name-nondirectory filename))
2920 (directory (if filedir (comint-directory filedir) default-directory))
2921 (completions (file-name-all-completions filenondir directory)))
2922 (if (not completions)
2923 (message "No completions of %s" filename)
2924 (comint-dynamic-list-completions
2925 (mapcar 'comint-quote-filename completions)))))
2926
2927
2928 ;; This is bound locally in a *Completions* buffer to the list of
2929 ;; completions displayed, and is used to detect the case where the same
2930 ;; command is repeatedly used without the set of completions changing.
2931 (defvar comint-displayed-dynamic-completions nil)
2932
2933 (defvar comint-dynamic-list-completions-config nil)
2934
2935 (defun comint-dynamic-list-completions (completions)
2936 "List in help buffer sorted COMPLETIONS.
2937 Typing SPC flushes the help buffer."
2938 (let ((window (get-buffer-window "*Completions*")))
2939 (setq completions (sort completions 'string-lessp))
2940 (if (and (eq last-command this-command)
2941 window (window-live-p window) (window-buffer window)
2942 (buffer-name (window-buffer window))
2943 ;; The above tests are not sufficient to detect the case where we
2944 ;; should scroll, because the top-level interactive command may
2945 ;; not have displayed a completions window the last time it was
2946 ;; invoked, and there may be such a window left over from a
2947 ;; previous completion command with a different set of
2948 ;; completions. To detect that case, we also test that the set
2949 ;; of displayed completions is in fact the same as the previously
2950 ;; displayed set.
2951 (equal completions
2952 (buffer-local-value 'comint-displayed-dynamic-completions
2953 (window-buffer window))))
2954 ;; If this command was repeated, and
2955 ;; there's a fresh completion window with a live buffer,
2956 ;; and this command is repeated, scroll that window.
2957 (with-current-buffer (window-buffer window)
2958 (if (pos-visible-in-window-p (point-max) window)
2959 (set-window-start window (point-min))
2960 (save-selected-window
2961 (select-window window)
2962 (scroll-up))))
2963
2964 ;; Display a completion list for the first time.
2965 (setq comint-dynamic-list-completions-config
2966 (current-window-configuration))
2967 (with-output-to-temp-buffer "*Completions*"
2968 (display-completion-list completions))
2969 (message "Type space to flush; repeat completion command to scroll"))
2970
2971 ;; Read the next key, to process SPC.
2972 (let (key first)
2973 (if (with-current-buffer (get-buffer "*Completions*")
2974 (set (make-local-variable 'comint-displayed-dynamic-completions)
2975 completions)
2976 (setq key (read-key-sequence nil)
2977 first (aref key 0))
2978 (and (consp first) (consp (event-start first))
2979 (eq (window-buffer (posn-window (event-start first)))
2980 (get-buffer "*Completions*"))
2981 (eq (key-binding key) 'mouse-choose-completion)))
2982 ;; If the user does mouse-choose-completion with the mouse,
2983 ;; execute the command, then delete the completion window.
2984 (progn
2985 (mouse-choose-completion first)
2986 (set-window-configuration comint-dynamic-list-completions-config))
2987 (if (eq first ?\s)
2988 (set-window-configuration comint-dynamic-list-completions-config)
2989 (setq unread-command-events (listify-key-sequence key)))))))
2990
2991 \f
2992 (defun comint-get-next-from-history ()
2993 "After fetching a line from input history, this fetches the following line.
2994 In other words, this recalls the input line after the line you recalled last.
2995 You can use this to repeat a sequence of input lines."
2996 (interactive)
2997 (if comint-save-input-ring-index
2998 (progn
2999 (setq comint-input-ring-index (1+ comint-save-input-ring-index))
3000 (comint-next-input 1))
3001 (message "No previous history command")))
3002
3003 (defun comint-accumulate ()
3004 "Accumulate a line to send as input along with more lines.
3005 This inserts a newline so that you can enter more text
3006 to be sent along with this line. Use \\[comint-send-input]
3007 to send all the accumulated input, at once.
3008 The entire accumulated text becomes one item in the input history
3009 when you send it."
3010 (interactive)
3011 (insert "\n")
3012 (set-marker comint-accum-marker (point))
3013 (if comint-input-ring-index
3014 (setq comint-save-input-ring-index
3015 (- comint-input-ring-index 1))))
3016
3017 (defun comint-goto-process-mark ()
3018 "Move point to the process mark.
3019 The process mark separates output, and input already sent,
3020 from input that has not yet been sent."
3021 (interactive)
3022 (let ((proc (or (get-buffer-process (current-buffer))
3023 (error "Current buffer has no process"))))
3024 (goto-char (process-mark proc))
3025 (when (interactive-p)
3026 (message "Point is now at the process mark"))))
3027
3028 (defun comint-bol-or-process-mark ()
3029 "Move point to beginning of line (after prompt) or to the process mark.
3030 The first time you use this command, it moves to the beginning of the line
3031 \(but after the prompt, if any). If you repeat it again immediately,
3032 it moves point to the process mark.
3033
3034 The process mark separates the process output, along with input already sent,
3035 from input that has not yet been sent. Ordinarily, the process mark
3036 is at the beginning of the current input line; but if you have
3037 used \\[comint-accumulate] to send multiple lines at once,
3038 the process mark is at the beginning of the accumulated input."
3039 (interactive)
3040 (if (not (eq last-command 'comint-bol-or-process-mark))
3041 (comint-bol nil)
3042 (comint-goto-process-mark)))
3043
3044 (defun comint-set-process-mark ()
3045 "Set the process mark at point."
3046 (interactive)
3047 (let ((proc (or (get-buffer-process (current-buffer))
3048 (error "Current buffer has no process"))))
3049 (set-marker (process-mark proc) (point))
3050 (message "Process mark set")))
3051
3052 \f
3053 ;; Author: Peter Breton <pbreton@cs.umb.edu>
3054
3055 ;; This little add-on for comint is intended to make it easy to get
3056 ;; output from currently active comint buffers into another buffer,
3057 ;; or buffers, and then go back to using the comint shell.
3058 ;;
3059 ;; My particular use is SQL interpreters; I want to be able to execute a
3060 ;; query using the process associated with a comint-buffer, and save that
3061 ;; somewhere else. Because the process might have state (for example, it
3062 ;; could be in an uncommitted transaction), just running starting a new
3063 ;; process and having it execute the query and then finish, would not
3064 ;; work. I'm sure there are other uses as well, although in many cases
3065 ;; starting a new process is the simpler, and thus preferable, approach.
3066 ;;
3067 ;; The basic implementation is as follows: comint-redirect changes the
3068 ;; preoutput filter functions (`comint-preoutput-filter-functions') to use
3069 ;; its own filter. The filter puts the output into the designated buffer,
3070 ;; or buffers, until it sees a regexp that tells it to stop (by default,
3071 ;; this is the prompt for the interpreter, `comint-prompt-regexp'). When it
3072 ;; sees the stop regexp, it restores the old filter functions, and runs
3073 ;; `comint-redirect-hook'.
3074 ;;
3075 ;; Each comint buffer may only use one redirection at a time, but any number
3076 ;; of different comint buffers may be simultaneously redirected.
3077 ;;
3078 ;; NOTE: It is EXTREMELY important that `comint-prompt-regexp' be set to the
3079 ;; correct prompt for your interpreter, or that you supply a regexp that says
3080 ;; when the redirection is finished. Otherwise, redirection will continue
3081 ;; indefinitely. The code now does a sanity check to ensure that it can find
3082 ;; a prompt in the comint buffer; however, it is still important to ensure that
3083 ;; this prompt is set correctly.
3084 ;;
3085 ;; XXX: This doesn't work so well unless `comint-prompt-regexp' is set;
3086 ;; perhaps it should prompt for a terminating string (with an
3087 ;; appropriate magic default by examining what we think is the prompt)?
3088 ;;
3089 ;; Fixme: look for appropriate fields, rather than regexp, if
3090 ;; `comint-use-prompt-regexp' is true.
3091
3092 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3093 ;; Variables
3094 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3095
3096 (defcustom comint-redirect-verbose nil
3097 "*If non-nil, print messages each time the redirection filter is invoked.
3098 Also print a message when redirection is completed."
3099 :group 'comint
3100 :type 'boolean)
3101
3102 ;; Directly analagous to comint-preoutput-filter-functions
3103 (defvar comint-redirect-filter-functions nil
3104 "List of functions to call before inserting redirected process output.
3105 Each function gets one argument, a string containing the text received
3106 from the subprocess. It should return the string to insert, perhaps
3107 the same string that was received, or perhaps a modified or transformed
3108 string.
3109
3110 The functions on the list are called sequentially, and each one is given
3111 the string returned by the previous one. The string returned by the
3112 last function is the text that is actually inserted in the redirection buffer.
3113
3114 You can use `add-hook' to add functions to this list
3115 either globally or locally.")
3116
3117 ;; Internal variables
3118
3119 (defvar comint-redirect-output-buffer nil
3120 "The buffer or list of buffers to put output into.")
3121
3122 (defvar comint-redirect-finished-regexp nil
3123 "Regular expression that determines when to stop redirection in Comint.
3124 When the redirection filter function is given output that matches this regexp,
3125 the output is inserted as usual, and redirection is completed.")
3126
3127 (defvar comint-redirect-insert-matching-regexp nil
3128 "If non-nil, the text that ends a redirection is included in it.
3129 More precisely, the text that matches `comint-redirect-finished-regexp'
3130 and therefore terminates an output redirection is inserted in the
3131 redirection target buffer, along with the preceding output.")
3132
3133 (defvar comint-redirect-echo-input nil
3134 "Non-nil means echo input in the process buffer even during redirection.")
3135
3136 (defvar comint-redirect-completed nil
3137 "Non-nil if redirection has completed in the current buffer.")
3138
3139 (defvar comint-redirect-original-mode-line-process nil
3140 "Original mode line for redirected process.")
3141
3142 (defvar comint-redirect-perform-sanity-check t
3143 "If non-nil, check that redirection is likely to complete successfully.
3144 More precisely, before starting a redirection, verify that the
3145 regular expression `comint-redirect-finished-regexp' that controls
3146 when to terminate it actually matches some text already in the process
3147 buffer. The idea is that this regular expression should match a prompt
3148 string, and that there ought to be at least one copy of your prompt string
3149 in the process buffer already.")
3150
3151 (defvar comint-redirect-original-filter-function nil
3152 "The process filter that was in place when redirection is started.
3153 When redirection is completed, the process filter is restored to
3154 this value.")
3155
3156 (defvar comint-redirect-subvert-readonly nil
3157 "Non-nil means `comint-redirect' can insert into read-only buffers.
3158 This works by binding `inhibit-read-only' around the insertion.
3159 This is useful, for instance, for insertion into Help mode buffers.
3160 You probably want to set it locally to the output buffer.")
3161
3162 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3163 ;; Functions
3164 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3165
3166 (defun comint-redirect-setup (output-buffer
3167 comint-buffer
3168 finished-regexp
3169 &optional echo-input)
3170 "Set up for output redirection.
3171 This function sets local variables that are used by `comint-redirect-filter'
3172 to perform redirection.
3173
3174 Output from COMINT-BUFFER is redirected to OUTPUT-BUFFER, until something
3175 in the output matches FINISHED-REGEXP.
3176
3177 If optional argument ECHO-INPUT is non-nil, output is echoed to the
3178 original Comint buffer.
3179
3180 This function is called by `comint-redirect-send-command-to-process',
3181 and does not normally need to be invoked by the end user or programmer."
3182 (with-current-buffer comint-buffer
3183
3184 (make-local-variable 'comint-redirect-original-mode-line-process)
3185 (setq comint-redirect-original-mode-line-process mode-line-process)
3186
3187 (make-local-variable 'comint-redirect-output-buffer)
3188 (setq comint-redirect-output-buffer output-buffer)
3189
3190 (make-local-variable 'comint-redirect-finished-regexp)
3191 (setq comint-redirect-finished-regexp finished-regexp)
3192
3193 (make-local-variable 'comint-redirect-echo-input)
3194 (setq comint-redirect-echo-input echo-input)
3195
3196 (make-local-variable 'comint-redirect-completed)
3197 (setq comint-redirect-completed nil)
3198
3199 (setq mode-line-process
3200 (if mode-line-process
3201 (list (concat (elt mode-line-process 0) " Redirection"))
3202 (list ":%s Redirection")))))
3203
3204 (defun comint-redirect-cleanup ()
3205 "End a Comint redirection. See `comint-redirect-send-command'."
3206 (interactive)
3207 ;; Restore the process filter
3208 (set-process-filter (get-buffer-process (current-buffer))
3209 comint-redirect-original-filter-function)
3210 ;; Restore the mode line
3211 (setq mode-line-process comint-redirect-original-mode-line-process)
3212 ;; Set the completed flag
3213 (setq comint-redirect-completed t))
3214
3215 ;; Because the cleanup happens as a callback, it's not easy to guarantee
3216 ;; that it really occurs.
3217 (defalias 'comint-redirect-remove-redirection 'comint-redirect-cleanup)
3218
3219 (defun comint-redirect-filter (process input-string)
3220 "Filter function which redirects output from PROCESS to a buffer or buffers.
3221 The variable `comint-redirect-output-buffer' says which buffer(s) to
3222 place output in.
3223
3224 INPUT-STRING is the input from the Comint process.
3225
3226 This function runs as a process filter, and does not need to be invoked by the
3227 end user."
3228 (and process
3229 (with-current-buffer (process-buffer process)
3230 (comint-redirect-preoutput-filter input-string)
3231 ;; If we have to echo output, give it to the original filter function
3232 (and comint-redirect-echo-input
3233 comint-redirect-original-filter-function
3234 (funcall comint-redirect-original-filter-function
3235 process input-string)))))
3236
3237
3238 (defun comint-redirect-preoutput-filter (input-string)
3239 "Comint filter function which redirects Comint output to a buffer or buffers.
3240 The variable `comint-redirect-output-buffer' says which buffer(s) to
3241 place output in.
3242
3243 INPUT-STRING is the input from the Comint process.
3244
3245 This function does not need to be invoked by the end user."
3246 (let ((output-buffer-list
3247 (if (listp comint-redirect-output-buffer)
3248 comint-redirect-output-buffer
3249 (list comint-redirect-output-buffer)))
3250 (filtered-input-string input-string))
3251
3252 ;; If there are any filter functions, give them a chance to modify the string
3253 (let ((functions comint-redirect-filter-functions))
3254 (while (and functions filtered-input-string)
3255 (if (eq (car functions) t)
3256 ;; If a local value says "use the default value too",
3257 ;; do that.
3258 (let ((functions (default-value 'comint-redirect-filter-functions)))
3259 (while (and functions filtered-input-string)
3260 (setq filtered-input-string
3261 (funcall (car functions) filtered-input-string))
3262 (setq functions (cdr functions))))
3263 (setq filtered-input-string
3264 (funcall (car functions) filtered-input-string)))
3265 (setq functions (cdr functions))))
3266
3267 ;; Clobber `comint-redirect-finished-regexp'
3268 (or comint-redirect-insert-matching-regexp
3269 (and (string-match comint-redirect-finished-regexp filtered-input-string)
3270 (setq filtered-input-string
3271 (replace-match "" nil nil filtered-input-string))))
3272
3273 ;; Send output to all registered buffers
3274 (save-excursion
3275 (dolist (buf output-buffer-list)
3276 ;; Set this buffer to the output buffer
3277 (set-buffer (get-buffer-create buf))
3278 ;; Go to the end of the buffer
3279 (goto-char (point-max))
3280 ;; Insert the output
3281 (let ((inhibit-read-only comint-redirect-subvert-readonly))
3282 (insert filtered-input-string))))
3283
3284 ;; Message
3285 (and comint-redirect-verbose
3286 (message "Redirected output to buffer(s) %s"
3287 (mapconcat 'identity output-buffer-list " ")))
3288
3289 ;; If we see the prompt, tidy up
3290 ;; We'll look for the prompt in the original string, so nobody can
3291 ;; clobber it
3292 (and (string-match comint-redirect-finished-regexp input-string)
3293 (progn
3294 (and comint-redirect-verbose
3295 (message "Redirection completed"))
3296 (comint-redirect-cleanup)
3297 (run-hooks 'comint-redirect-hook)))
3298 ;; Echo input?
3299 (if comint-redirect-echo-input
3300 filtered-input-string
3301 "")))
3302
3303 ;;;###autoload
3304 (defun comint-redirect-send-command (command output-buffer echo &optional no-display)
3305 "Send COMMAND to process in current buffer, with output to OUTPUT-BUFFER.
3306 With prefix arg ECHO, echo output in process buffer.
3307
3308 If NO-DISPLAY is non-nil, do not show the output buffer."
3309 (interactive "sCommand: \nBOutput Buffer: \nP")
3310 (let ((process (get-buffer-process (current-buffer))))
3311 (if process
3312 (comint-redirect-send-command-to-process
3313 command output-buffer (current-buffer) echo no-display)
3314 (error "No process for current buffer"))))
3315
3316 ;;;###autoload
3317 (defun comint-redirect-send-command-to-process
3318 (command output-buffer process echo &optional no-display)
3319 "Send COMMAND to PROCESS, with output to OUTPUT-BUFFER.
3320 With prefix arg, echo output in process buffer.
3321
3322 If NO-DISPLAY is non-nil, do not show the output buffer."
3323 (interactive "sCommand: \nBOutput Buffer: \nbProcess Buffer: \nP")
3324 (let* (;; The process buffer
3325 (process-buffer (if (processp process)
3326 (process-buffer process)
3327 process))
3328 (proc (get-buffer-process process-buffer)))
3329 ;; Change to the process buffer
3330 (with-current-buffer process-buffer
3331
3332 ;; Make sure there's a prompt in the current process buffer
3333 (and comint-redirect-perform-sanity-check
3334 (save-excursion
3335 (goto-char (point-max))
3336 (or (re-search-backward comint-prompt-regexp nil t)
3337 (error "No prompt found or `comint-prompt-regexp' not set properly"))))
3338
3339 ;;;;;;;;;;;;;;;;;;;;;
3340 ;; Set up for redirection
3341 ;;;;;;;;;;;;;;;;;;;;;
3342 (comint-redirect-setup
3343 ;; Output Buffer
3344 output-buffer
3345 ;; Comint Buffer
3346 (current-buffer)
3347 ;; Finished Regexp
3348 comint-prompt-regexp
3349 ;; Echo input
3350 echo)
3351
3352 ;;;;;;;;;;;;;;;;;;;;;
3353 ;; Set the filter
3354 ;;;;;;;;;;;;;;;;;;;;;
3355 ;; Save the old filter
3356 (setq comint-redirect-original-filter-function
3357 (process-filter proc))
3358 (set-process-filter proc 'comint-redirect-filter)
3359
3360 ;;;;;;;;;;;;;;;;;;;;;
3361 ;; Send the command
3362 ;;;;;;;;;;;;;;;;;;;;;
3363 (process-send-string
3364 (current-buffer)
3365 (concat command "\n"))
3366
3367 ;;;;;;;;;;;;;;;;;;;;;
3368 ;; Show the output
3369 ;;;;;;;;;;;;;;;;;;;;;
3370 (or no-display
3371 (display-buffer
3372 (get-buffer-create
3373 (if (listp output-buffer)
3374 (car output-buffer)
3375 output-buffer)))))))
3376
3377 ;;;###autoload
3378 (defun comint-redirect-results-list (command regexp regexp-group)
3379 "Send COMMAND to current process.
3380 Return a list of expressions in the output which match REGEXP.
3381 REGEXP-GROUP is the regular expression group in REGEXP to use."
3382 (comint-redirect-results-list-from-process
3383 (get-buffer-process (current-buffer))
3384 command regexp regexp-group))
3385
3386 ;;;###autoload
3387 (defun comint-redirect-results-list-from-process (process command regexp regexp-group)
3388 "Send COMMAND to PROCESS.
3389 Return a list of expressions in the output which match REGEXP.
3390 REGEXP-GROUP is the regular expression group in REGEXP to use."
3391 (let ((output-buffer " *Comint Redirect Work Buffer*")
3392 results)
3393 (save-excursion
3394 (set-buffer (get-buffer-create output-buffer))
3395 (erase-buffer)
3396 (comint-redirect-send-command-to-process command
3397 output-buffer process nil t)
3398 ;; Wait for the process to complete
3399 (set-buffer (process-buffer process))
3400 (while (null comint-redirect-completed)
3401 (accept-process-output nil 1))
3402 ;; Collect the output
3403 (set-buffer output-buffer)
3404 (goto-char (point-min))
3405 ;; Skip past the command, if it was echoed
3406 (and (looking-at command)
3407 (forward-line))
3408 (while (re-search-forward regexp nil t)
3409 (setq results
3410 (cons (buffer-substring-no-properties
3411 (match-beginning regexp-group)
3412 (match-end regexp-group))
3413 results)))
3414 results)))
3415
3416 (mapc (lambda (x)
3417 (add-to-list 'debug-ignored-errors x))
3418 '("^Not at command line$"
3419 "^Empty input ring$"
3420 "^No history$"
3421 "^Not found$" ; Too common?
3422 "^Current buffer has no process$"))
3423
3424 \f
3425 ;; Converting process modes to use comint mode
3426 ;; ===========================================================================
3427 ;; The code in the Emacs 19 distribution has all been modified to use comint
3428 ;; where needed. However, there are `third-party' packages out there that
3429 ;; still use the old shell mode. Here's a guide to conversion.
3430 ;;
3431 ;; Renaming variables
3432 ;; Most of the work is renaming variables and functions. These are the common
3433 ;; ones:
3434 ;; Local variables:
3435 ;; last-input-start comint-last-input-start
3436 ;; last-input-end comint-last-input-end
3437 ;; shell-prompt-pattern comint-prompt-regexp
3438 ;; shell-set-directory-error-hook <no equivalent>
3439 ;; Miscellaneous:
3440 ;; shell-set-directory <unnecessary>
3441 ;; shell-mode-map comint-mode-map
3442 ;; Commands:
3443 ;; shell-send-input comint-send-input
3444 ;; shell-send-eof comint-delchar-or-maybe-eof
3445 ;; kill-shell-input comint-kill-input
3446 ;; interrupt-shell-subjob comint-interrupt-subjob
3447 ;; stop-shell-subjob comint-stop-subjob
3448 ;; quit-shell-subjob comint-quit-subjob
3449 ;; kill-shell-subjob comint-kill-subjob
3450 ;; kill-output-from-shell comint-delete-output
3451 ;; show-output-from-shell comint-show-output
3452 ;; copy-last-shell-input Use comint-previous-input/comint-next-input
3453 ;;
3454 ;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
3455 ;; SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-filter-functions.
3456 ;; Comint mode does not provide functionality equivalent to
3457 ;; shell-set-directory-error-hook; it is gone.
3458 ;;
3459 ;; comint-last-input-start is provided for modes which want to munge
3460 ;; the buffer after input is sent, perhaps because the inferior
3461 ;; insists on echoing the input. The LAST-INPUT-START variable in
3462 ;; the old shell package was used to implement a history mechanism,
3463 ;; but you should think twice before using comint-last-input-start
3464 ;; for this; the input history ring often does the job better.
3465 ;;
3466 ;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
3467 ;; *not* create the comint-mode local variables in your foo-mode function.
3468 ;; This is not modular. Instead, call comint-mode, and let *it* create the
3469 ;; necessary comint-specific local variables. Then create the
3470 ;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
3471 ;; be foo-mode-map, and its mode to be foo-mode. Set the comint-mode hooks
3472 ;; (comint-{prompt-regexp, input-filter, input-filter-functions,
3473 ;; get-old-input) that need to be different from the defaults. Call
3474 ;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
3475 ;; comint-mode will take care of it. The following example, from shell.el,
3476 ;; is typical:
3477 ;;
3478 ;; (defvar shell-mode-map '())
3479 ;; (cond ((not shell-mode-map)
3480 ;; (setq shell-mode-map (copy-keymap comint-mode-map))
3481 ;; (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
3482 ;; (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
3483 ;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
3484 ;; (define-key shell-mode-map "\M-?"
3485 ;; 'comint-dynamic-list-filename-completions)))
3486 ;;
3487 ;; (defun shell-mode ()
3488 ;; (interactive)
3489 ;; (comint-mode)
3490 ;; (setq comint-prompt-regexp shell-prompt-pattern)
3491 ;; (setq major-mode 'shell-mode)
3492 ;; (setq mode-name "Shell")
3493 ;; (use-local-map shell-mode-map)
3494 ;; (make-local-variable 'shell-directory-stack)
3495 ;; (setq shell-directory-stack nil)
3496 ;; (add-hook 'comint-input-filter-functions 'shell-directory-tracker)
3497 ;; (run-mode-hooks 'shell-mode-hook))
3498 ;;
3499 ;;
3500 ;; Completion for comint-mode users
3501 ;;
3502 ;; For modes that use comint-mode, comint-dynamic-complete-functions is the
3503 ;; hook to add completion functions to. Functions on this list should return
3504 ;; non-nil if completion occurs (i.e., further completion should not occur).
3505 ;; You could use comint-dynamic-simple-complete to do the bulk of the
3506 ;; completion job.
3507 \f
3508
3509 (provide 'comint)
3510
3511 ;; arch-tag: 1793314c-09db-40be-9549-9aeae3e75164
3512 ;;; comint.el ends here