]> code.delx.au - gnu-emacs/blob - lisp/comint.el
(Abbrevs): A @node line without explicit Prev, Next, and Up links.
[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-insert-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-insert-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 (set (make-local-variable 'comint-accum-marker) (make-marker))
654 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
655 ;; This behavior is not useful in comint buffers, and is annoying
656 (set (make-local-variable 'next-line-add-newlines) nil))
657
658 (defun comint-check-proc (buffer)
659 "Return non-nil if there is a living process associated w/buffer BUFFER.
660 Living means the status is `open', `run', or `stop'.
661 BUFFER can be either a buffer or the name of one."
662 (let ((proc (get-buffer-process buffer)))
663 (and proc (memq (process-status proc) '(open run stop)))))
664
665 ;;;###autoload
666 (defun make-comint-in-buffer (name buffer program &optional startfile &rest switches)
667 "Make a Comint process NAME in BUFFER, running PROGRAM.
668 If BUFFER is nil, it defaults to NAME surrounded by `*'s.
669 PROGRAM should be either a string denoting an executable program to create
670 via `start-process', or a cons pair of the form (HOST . SERVICE) denoting a TCP
671 connection to be opened via `open-network-stream'. If there is already a
672 running process in that buffer, it is not restarted. Optional fourth arg
673 STARTFILE is the name of a file to send the contents of to the process.
674
675 If PROGRAM is a string, any more args are arguments to PROGRAM."
676 (or (fboundp 'start-process)
677 (error "Multi-processing is not supported for this system"))
678 (setq buffer (get-buffer-create (or buffer (concat "*" name "*"))))
679 ;; If no process, or nuked process, crank up a new one and put buffer in
680 ;; comint mode. Otherwise, leave buffer and existing process alone.
681 (unless (comint-check-proc buffer)
682 (with-current-buffer buffer
683 (unless (derived-mode-p 'comint-mode)
684 (comint-mode))) ; Install local vars, mode, keymap, ...
685 (comint-exec buffer name program startfile switches))
686 buffer)
687
688 ;;;###autoload
689 (defun make-comint (name program &optional startfile &rest switches)
690 "Make a Comint process NAME in a buffer, running PROGRAM.
691 The name of the buffer is made by surrounding NAME with `*'s.
692 PROGRAM should be either a string denoting an executable program to create
693 via `start-process', or a cons pair of the form (HOST . SERVICE) denoting a TCP
694 connection to be opened via `open-network-stream'. If there is already a
695 running process in that buffer, it is not restarted. Optional third arg
696 STARTFILE is the name of a file to send the contents of the process to.
697
698 If PROGRAM is a string, any more args are arguments to PROGRAM."
699 (apply #'make-comint-in-buffer name nil program startfile switches))
700
701 ;;;###autoload
702 (defun comint-run (program)
703 "Run PROGRAM in a Comint buffer and switch to it.
704 The buffer name is made by surrounding the file name of PROGRAM with `*'s.
705 The file name is used to make a symbol name, such as `comint-sh-hook', and any
706 hooks on this symbol are run in the buffer.
707 See `make-comint' and `comint-exec'."
708 (interactive "sRun program: ")
709 (let ((name (file-name-nondirectory program)))
710 (switch-to-buffer (make-comint name program))
711 (run-hooks (intern-soft (concat "comint-" name "-hook")))))
712
713 (defun comint-exec (buffer name command startfile switches)
714 "Start up a process named NAME in buffer BUFFER for Comint modes.
715 Runs the given COMMAND with SWITCHES with output to STARTFILE.
716 Blasts any old process running in the buffer. Doesn't set the buffer mode.
717 You can use this to cheaply run a series of processes in the same Comint
718 buffer. The hook `comint-exec-hook' is run after each exec."
719 (with-current-buffer buffer
720 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
721 (if proc (delete-process proc)))
722 ;; Crank up a new process
723 (let ((proc
724 (if (consp command)
725 (open-network-stream name buffer (car command) (cdr command))
726 (comint-exec-1 name buffer command switches))))
727 (set-process-filter proc 'comint-output-filter)
728 (make-local-variable 'comint-ptyp)
729 (setq comint-ptyp process-connection-type) ; t if pty, nil if pipe.
730 ;; Jump to the end, and set the process mark.
731 (goto-char (point-max))
732 (set-marker (process-mark proc) (point))
733 ;; Feed it the startfile.
734 (cond (startfile
735 ;;This is guaranteed to wait long enough
736 ;;but has bad results if the comint does not prompt at all
737 ;; (while (= size (buffer-size))
738 ;; (sleep-for 1))
739 ;;I hope 1 second is enough!
740 (sleep-for 1)
741 (goto-char (point-max))
742 (insert-file-contents startfile)
743 (setq startfile (buffer-substring (point) (point-max)))
744 (delete-region (point) (point-max))
745 (comint-send-string proc startfile)))
746 (run-hooks 'comint-exec-hook)
747 buffer)))
748
749 ;; This auxiliary function cranks up the process for comint-exec in
750 ;; the appropriate environment.
751
752 (defun comint-exec-1 (name buffer command switches)
753 (let ((process-environment
754 (nconc
755 ;; If using termcap, we specify `emacs' as the terminal type
756 ;; because that lets us specify a width.
757 ;; If using terminfo, we specify `dumb' because that is
758 ;; a defined terminal type. `emacs' is not a defined terminal type
759 ;; and there is no way for us to define it here.
760 ;; Some programs that use terminfo get very confused
761 ;; if TERM is not a valid terminal type.
762 ;; ;; There is similar code in compile.el.
763 (if (and (boundp 'system-uses-terminfo) system-uses-terminfo)
764 (list "TERM=dumb" "TERMCAP="
765 (format "COLUMNS=%d" (window-width)))
766 (list "TERM=emacs"
767 (format "TERMCAP=emacs:co#%d:tc=unknown:" (window-width))))
768 (if (getenv "EMACS") nil (list "EMACS=t"))
769 process-environment))
770 (default-directory
771 (if (file-accessible-directory-p default-directory)
772 default-directory
773 "/"))
774 proc decoding encoding changed)
775 (let ((exec-path (if (file-name-directory command)
776 ;; If the command has slashes, make sure we
777 ;; first look relative to the current directory.
778 (cons default-directory exec-path) exec-path)))
779 (setq proc (apply 'start-process name buffer command switches)))
780 (let ((coding-systems (process-coding-system proc)))
781 (setq decoding (car coding-systems)
782 encoding (cdr coding-systems)))
783 ;; If start-process decided to use some coding system for decoding
784 ;; data sent from the process and the coding system doesn't
785 ;; specify EOL conversion, we had better convert CRLF to LF.
786 (if (vectorp (coding-system-eol-type decoding))
787 (setq decoding (coding-system-change-eol-conversion decoding 'dos)
788 changed t))
789 ;; Even if start-process left the coding system for encoding data
790 ;; sent from the process undecided, we had better use the same one
791 ;; as what we use for decoding. But, we should suppress EOL
792 ;; conversion.
793 (if (and decoding (not encoding))
794 (setq encoding (coding-system-change-eol-conversion decoding 'unix)
795 changed t))
796 (if changed
797 (set-process-coding-system proc decoding encoding))
798 proc))
799
800 (defun comint-insert-input (&optional event)
801 "In a Comint buffer, set the current input to the previous input at point."
802 ;; This doesn't use "e" because it is supposed to work
803 ;; for events without parameters.
804 (interactive (list last-input-event))
805 (let ((pos (point)))
806 (if event (posn-set-point (event-end event)))
807 (if (not (eq (get-char-property (point) 'field) 'input))
808 ;; No input at POS, fall back to the global definition.
809 (let* ((keys (this-command-keys))
810 (last-key (and (vectorp keys) (aref keys (1- (length keys)))))
811 (fun (and last-key (lookup-key global-map (vector last-key)))))
812 (goto-char pos)
813 (and fun (call-interactively fun)))
814 (setq pos (point))
815 ;; There's previous input at POS, insert it at the end of the buffer.
816 (goto-char (point-max))
817 ;; First delete any old unsent input at the end
818 (delete-region
819 (or (marker-position comint-accum-marker)
820 (process-mark (get-buffer-process (current-buffer))))
821 (point))
822 ;; Insert the input at point
823 (insert (buffer-substring-no-properties
824 (previous-single-char-property-change (1+ pos) 'field)
825 (next-single-char-property-change pos 'field))))))
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 ;; Set text-properties for the input field
1521 (add-text-properties
1522 beg end
1523 '(front-sticky t
1524 font-lock-face comint-highlight-input
1525 mouse-face highlight
1526 help-echo "mouse-2: insert after prompt as new input"))
1527 (unless comint-use-prompt-regexp
1528 ;; Give old user input a field property of `input', to
1529 ;; distinguish it from both process output and unsent
1530 ;; input. The terminating newline is put into a special
1531 ;; `boundary' field to make cursor movement between input
1532 ;; and output fields smoother.
1533 (put-text-property beg end '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-skip-prompt ()
1905 "Skip past the text matching regexp `comint-prompt-regexp'.
1906 If this takes us past the end of the current line, don't skip at all."
1907 (if (and (looking-at comint-prompt-regexp)
1908 (<= (match-end 0) (line-end-position)))
1909 (goto-char (match-end 0))))
1910
1911 (defun comint-after-pmark-p ()
1912 "Return t if point is after the process output marker."
1913 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1914 (<= (marker-position pmark) (point))))
1915
1916 (defun comint-simple-send (proc string)
1917 "Default function for sending to PROC input STRING.
1918 This just sends STRING plus a newline. To override this,
1919 set the hook `comint-input-sender'."
1920 (comint-send-string proc string)
1921 (if comint-input-sender-no-newline
1922 (if (not (string-equal string ""))
1923 (process-send-eof))
1924 (comint-send-string proc "\n")))
1925
1926 (defun comint-line-beginning-position ()
1927 "Return the buffer position of the beginning of the line, after any prompt.
1928 If `comint-use-prompt-regexp' is non-nil, then the prompt skip is done by
1929 skipping text matching the regular expression `comint-prompt-regexp',
1930 a buffer local variable."
1931 (if comint-use-prompt-regexp
1932 ;; Use comint-prompt-regexp
1933 (save-excursion
1934 (beginning-of-line)
1935 (comint-skip-prompt)
1936 (point))
1937 ;; Use input fields. Note that, unlike the behavior of
1938 ;; `line-beginning-position' inside a field, this function will
1939 ;; return the position of the end of a prompt, even if the point is
1940 ;; already inside the prompt. In order to do this, it assumes that
1941 ;; if there are two fields on a line, then the first one is the
1942 ;; prompt, and the second one is an input field, and is front-sticky
1943 ;; (as input fields should be).
1944 (constrain-to-field (line-beginning-position) (line-end-position))))
1945
1946 (defun comint-bol (&optional arg)
1947 "Go to the beginning of line, then skip past the prompt, if any.
1948 If prefix argument is given (\\[universal-argument]) the prompt is not skipped.
1949 If `comint-use-prompt-regexp' is non-nil, then the prompt skip is done
1950 by skipping text matching the regular expression `comint-prompt-regexp',
1951 a buffer local variable."
1952 (interactive "P")
1953 (if arg
1954 ;; Unlike `beginning-of-line', forward-line ignores field boundaries
1955 (forward-line 0)
1956 (goto-char (comint-line-beginning-position))))
1957
1958 ;; For compatibility.
1959 (defun comint-read-noecho (prompt &optional ignore)
1960 (read-passwd prompt))
1961
1962 ;; These three functions are for entering text you don't want echoed or
1963 ;; saved -- typically passwords to ftp, telnet, or somesuch.
1964 ;; Just enter m-x send-invisible and type in your line.
1965
1966 (defun send-invisible (&optional prompt)
1967 "Read a string without echoing.
1968 Then send it to the process running in the current buffer.
1969 The string is sent using `comint-input-sender'.
1970 Security bug: your string can still be temporarily recovered with
1971 \\[view-lossage]; `clear-this-command-keys' can fix that."
1972 (interactive "P") ; Defeat snooping via C-x ESC ESC
1973 (let ((proc (get-buffer-process (current-buffer)))
1974 (prefix
1975 (if (eq (window-buffer (selected-window)) (current-buffer))
1976 ""
1977 (format "(In buffer %s) "
1978 (current-buffer)))))
1979 (if proc
1980 (let ((str (read-passwd (concat prefix
1981 (or prompt "Non-echoed text: ")))))
1982 (if (stringp str)
1983 (progn
1984 (comint-snapshot-last-prompt)
1985 (funcall comint-input-sender proc str))
1986 (message "Warning: text will be echoed")))
1987 (error "Buffer %s has no process" (current-buffer)))))
1988
1989 (defun comint-watch-for-password-prompt (string)
1990 "Prompt in the minibuffer for password and send without echoing.
1991 This function uses `send-invisible' to read and send a password to the buffer's
1992 process if STRING contains a password prompt defined by
1993 `comint-password-prompt-regexp'.
1994
1995 This function could be in the list `comint-output-filter-functions'."
1996 (when (string-match comint-password-prompt-regexp string)
1997 (when (string-match "^[ \n\r\t\v\f\b\a]+" string)
1998 (setq string (replace-match "" t t string)))
1999 (send-invisible string)))
2000 \f
2001 ;; Low-level process communication
2002
2003 (defun comint-send-string (process string)
2004 "Like `process-send-string', but also does extra bookkeeping for Comint mode."
2005 (if process
2006 (with-current-buffer (if (processp process)
2007 (process-buffer process)
2008 (get-buffer process))
2009 (comint-snapshot-last-prompt))
2010 (comint-snapshot-last-prompt))
2011 (process-send-string process string))
2012
2013 (defun comint-send-region (process start end)
2014 "Like `process-send-region', but also does extra bookkeeping for Comint mode."
2015 (if process
2016 (with-current-buffer (if (processp process)
2017 (process-buffer process)
2018 (get-buffer process))
2019 (comint-snapshot-last-prompt))
2020 (comint-snapshot-last-prompt))
2021 (process-send-region process start end))
2022
2023 \f
2024 ;; Random input hackage
2025
2026 (defun comint-delete-output ()
2027 "Delete all output from interpreter since last input.
2028 Does not delete the prompt."
2029 (interactive)
2030 (let ((proc (get-buffer-process (current-buffer)))
2031 (replacement nil)
2032 (inhibit-read-only t))
2033 (save-excursion
2034 (let ((pmark (progn (goto-char (process-mark proc))
2035 (forward-line 0)
2036 (point-marker))))
2037 (delete-region comint-last-input-end pmark)
2038 (goto-char (process-mark proc))
2039 (setq replacement (concat "*** output flushed ***\n"
2040 (buffer-substring pmark (point))))
2041 (delete-region pmark (point))))
2042 ;; Output message and put back prompt
2043 (comint-output-filter proc replacement)))
2044 (define-obsolete-function-alias 'comint-kill-output
2045 'comint-delete-output "21.1")
2046
2047 (defun comint-write-output (filename &optional append mustbenew)
2048 "Write output from interpreter since last input to FILENAME.
2049 Any prompt at the end of the output is not written.
2050
2051 If the optional argument APPEND (the prefix argument when interactive)
2052 is non-nil, the output is appended to the file instead.
2053
2054 If the optional argument MUSTBENEW is non-nil, check for an existing
2055 file with the same name. If MUSTBENEW is `excl', that means to get an
2056 error if the file already exists; never overwrite. If MUSTBENEW is
2057 neither nil nor `excl', that means ask for confirmation before
2058 overwriting, but do go ahead and overwrite the file if the user
2059 confirms. When interactive, MUSTBENEW is nil when appending, and t
2060 otherwise."
2061 (interactive
2062 (list (read-file-name
2063 (if current-prefix-arg
2064 "Append output to file: "
2065 "Write output to file: "))
2066 current-prefix-arg
2067 (not current-prefix-arg)))
2068 (save-excursion
2069 (goto-char (process-mark (get-buffer-process (current-buffer))))
2070 (forward-line 0)
2071 (write-region comint-last-input-end (point) filename
2072 append nil nil mustbenew)))
2073
2074 ;; This function exists for the benefit of the menu; from the keyboard,
2075 ;; users can just use `comint-write-output' with a prefix arg.
2076 (defun comint-append-output-to-file (filename)
2077 "Append output from interpreter since last input to FILENAME.
2078 Any prompt at the end of the output is not written."
2079 (interactive "fAppend output to file: ")
2080 (comint-write-output filename t))
2081
2082 (defun comint-show-output ()
2083 "Display start of this batch of interpreter output at top of window.
2084 Sets mark to the value of point when this command is run."
2085 (interactive)
2086 (push-mark)
2087 (let ((pos (or (marker-position comint-last-input-end) (point-max))))
2088 (cond (comint-use-prompt-regexp
2089 (goto-char pos)
2090 (beginning-of-line 0)
2091 (set-window-start (selected-window) (point))
2092 (comint-skip-prompt))
2093 (t
2094 (let* ((beg (field-beginning pos))
2095 (pt (if (= (point-min) beg)
2096 (point-min)
2097 (1+ beg))))
2098 (goto-char pt))
2099 (set-window-start (selected-window) (point))))))
2100
2101
2102 (defun comint-interrupt-subjob ()
2103 "Interrupt the current subjob.
2104 This command also kills the pending input
2105 between the process mark and point."
2106 (interactive)
2107 (comint-skip-input)
2108 (interrupt-process nil comint-ptyp)
2109 ;; (process-send-string nil "\n")
2110 )
2111
2112 (defun comint-kill-subjob ()
2113 "Send kill signal to the current subjob.
2114 This command also kills the pending input
2115 between the process mark and point."
2116 (interactive)
2117 (comint-skip-input)
2118 (kill-process nil comint-ptyp))
2119
2120 (defun comint-quit-subjob ()
2121 "Send quit signal to the current subjob.
2122 This command also kills the pending input
2123 between the process mark and point."
2124 (interactive)
2125 (comint-skip-input)
2126 (quit-process nil comint-ptyp))
2127
2128 (defun comint-stop-subjob ()
2129 "Stop the current subjob.
2130 This command also kills the pending input
2131 between the process mark and point.
2132
2133 WARNING: if there is no current subjob, you can end up suspending
2134 the top-level process running in the buffer. If you accidentally do
2135 this, use \\[comint-continue-subjob] to resume the process. (This
2136 is not a problem with most shells, since they ignore this signal.)"
2137 (interactive)
2138 (comint-skip-input)
2139 (stop-process nil comint-ptyp))
2140
2141 (defun comint-continue-subjob ()
2142 "Send CONT signal to process buffer's process group.
2143 Useful if you accidentally suspend the top-level process."
2144 (interactive)
2145 (continue-process nil comint-ptyp))
2146
2147 (defun comint-skip-input ()
2148 "Skip all pending input, from last stuff output by interpreter to point.
2149 This means mark it as if it had been sent as input, without sending it."
2150 (let ((comint-input-sender 'ignore)
2151 (comint-input-filter-functions nil))
2152 (comint-send-input t t))
2153 (end-of-line)
2154 (let ((pos (point))
2155 (marker (process-mark (get-buffer-process (current-buffer)))))
2156 (insert " " (key-description (this-command-keys)))
2157 (if (= marker pos)
2158 (set-marker marker (point)))))
2159
2160 (defun comint-kill-input ()
2161 "Kill all text from last stuff output by interpreter to point."
2162 (interactive)
2163 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2164 (if (> (point) (marker-position pmark))
2165 (kill-region pmark (point)))))
2166
2167 (defun comint-delchar-or-maybe-eof (arg)
2168 "Delete ARG characters forward or send an EOF to subprocess.
2169 Sends an EOF only if point is at the end of the buffer and there is no input."
2170 (interactive "p")
2171 (let ((proc (get-buffer-process (current-buffer))))
2172 (if (and (eobp) proc (= (point) (marker-position (process-mark proc))))
2173 (comint-send-eof)
2174 (delete-char arg))))
2175
2176 (defun comint-send-eof ()
2177 "Send an EOF to the current buffer's process."
2178 (interactive)
2179 (comint-send-input t t)
2180 (process-send-eof))
2181
2182
2183 (defun comint-backward-matching-input (regexp n)
2184 "Search backward through buffer for input fields that match REGEXP.
2185 If `comint-use-prompt-regexp' is non-nil, then input fields are identified
2186 by lines that match `comint-prompt-regexp'.
2187
2188 With prefix argument N, search for Nth previous match.
2189 If N is negative, find the next or Nth next match."
2190 (interactive (comint-regexp-arg "Backward input matching (regexp): "))
2191 (if comint-use-prompt-regexp
2192 ;; Use comint-prompt-regexp
2193 (let* ((re (concat comint-prompt-regexp ".*" regexp))
2194 (pos (save-excursion (end-of-line (if (> n 0) 0 1))
2195 (if (re-search-backward re nil t n)
2196 (point)))))
2197 (if (null pos)
2198 (progn (message "Not found")
2199 (ding))
2200 (goto-char pos)
2201 (comint-bol nil)))
2202 ;; Use input fields
2203 (let* ((dir (if (< n 0) -1 1))
2204 (pos
2205 (save-excursion
2206 (while (/= n 0)
2207 (unless (re-search-backward regexp nil t dir)
2208 (error "Not found"))
2209 (when (eq (get-char-property (point) 'field) 'input)
2210 (setq n (- n dir))))
2211 (field-beginning))))
2212 (goto-char pos))))
2213
2214
2215 (defun comint-forward-matching-input (regexp n)
2216 "Search forward through buffer for input fields that match REGEXP.
2217 If `comint-use-prompt-regexp' is non-nil, then input fields are identified
2218 by lines that match `comint-prompt-regexp'.
2219
2220 With prefix argument N, search for Nth following match.
2221 If N is negative, find the previous or Nth previous match."
2222 (interactive (comint-regexp-arg "Forward input matching (regexp): "))
2223 (comint-backward-matching-input regexp (- n)))
2224
2225
2226 (defun comint-next-prompt (n)
2227 "Move to end of Nth next prompt in the buffer.
2228 If `comint-use-prompt-regexp' is nil, then this means the beginning of
2229 the Nth next `input' field, otherwise, it means the Nth occurrence of
2230 text matching `comint-prompt-regexp'."
2231 (interactive "p")
2232 (if comint-use-prompt-regexp
2233 ;; Use comint-prompt-regexp
2234 (let ((paragraph-start comint-prompt-regexp))
2235 (end-of-line (if (> n 0) 1 0))
2236 (forward-paragraph n)
2237 (comint-skip-prompt))
2238 ;; Use input fields
2239 (let ((pos (point))
2240 (input-pos nil)
2241 prev-pos)
2242 (while (/= n 0)
2243 (setq prev-pos pos)
2244 (setq pos
2245 (if (> n 0)
2246 (next-single-char-property-change pos 'field)
2247 (previous-single-char-property-change pos 'field)))
2248 (cond ((or (null pos) (= pos prev-pos))
2249 ;; Ran off the end of the buffer.
2250 (when (> n 0)
2251 ;; There's always an input field at the end of the
2252 ;; buffer, but it has a `field' property of nil.
2253 (setq input-pos (point-max)))
2254 ;; stop iterating
2255 (setq n 0))
2256 ((eq (get-char-property pos 'field) 'input)
2257 (setq n (if (< n 0) (1+ n) (1- n)))
2258 (setq input-pos pos))))
2259 (when input-pos
2260 (goto-char input-pos)))))
2261
2262
2263 (defun comint-previous-prompt (n)
2264 "Move to end of Nth previous prompt in the buffer.
2265 If `comint-use-prompt-regexp' is nil, then this means the beginning of
2266 the Nth previous `input' field, otherwise, it means the Nth occurrence of
2267 text matching `comint-prompt-regexp'."
2268 (interactive "p")
2269 (comint-next-prompt (- n)))
2270
2271 ;; State used by `comint-insert-previous-argument' when cycling.
2272 (defvar comint-insert-previous-argument-last-start-pos nil)
2273 (make-variable-buffer-local 'comint-insert-previous-argument-last-start-pos)
2274 (defvar comint-insert-previous-argument-last-index nil)
2275 (make-variable-buffer-local 'comint-insert-previous-argument-last-index)
2276
2277 ;; Needs fixing:
2278 ;; make comint-arguments understand negative indices as bash does
2279 (defun comint-insert-previous-argument (index)
2280 "Insert the INDEXth argument from the previous Comint command-line at point.
2281 Spaces are added at beginning and/or end of the inserted string if
2282 necessary to ensure that it's separated from adjacent arguments.
2283 Interactively, if no prefix argument is given, the last argument is inserted.
2284 Repeated interactive invocations will cycle through the same argument
2285 from progressively earlier commands (using the value of INDEX specified
2286 with the first command).
2287 This command is like `M-.' in bash."
2288 (interactive "P")
2289 (unless (null index)
2290 (setq index (prefix-numeric-value index)))
2291 (cond ((eq last-command this-command)
2292 ;; Delete last input inserted by this command.
2293 (delete-region comint-insert-previous-argument-last-start-pos (point))
2294 (setq index comint-insert-previous-argument-last-index))
2295 (t
2296 ;; This is a non-repeat invocation, so initialize state.
2297 (setq comint-input-ring-index nil)
2298 (setq comint-insert-previous-argument-last-index index)
2299 (when (null comint-insert-previous-argument-last-start-pos)
2300 ;; First usage; initialize to a marker
2301 (setq comint-insert-previous-argument-last-start-pos
2302 (make-marker)))))
2303 ;; Make sure we're not in the prompt, and add a beginning space if necess.
2304 (if (<= (point) (comint-line-beginning-position))
2305 (comint-bol)
2306 (just-one-space))
2307 ;; Remember the beginning of what we insert, so we can delete it if
2308 ;; the command is repeated.
2309 (set-marker comint-insert-previous-argument-last-start-pos (point))
2310 ;; Insert the argument.
2311 (let ((input-string (comint-previous-input-string 0)))
2312 (when (string-match "[ \t\n]*&" input-string)
2313 ;; strip terminating '&'
2314 (setq input-string (substring input-string 0 (match-beginning 0))))
2315 (insert (comint-arguments input-string index index)))
2316 ;; Make next invocation return arg from previous input
2317 (setq comint-input-ring-index (1+ (or comint-input-ring-index 0)))
2318 ;; Add a terminating space if necessary.
2319 (unless (eolp)
2320 (just-one-space)))
2321
2322 \f
2323 ;; Support editing with `comint-prompt-read-only' set to t.
2324
2325 (defun comint-update-fence ()
2326 "Update read-only status of newline before point.
2327 The `fence' read-only property is used to indicate that a newline
2328 is read-only for no other reason than to \"fence off\" a
2329 following front-sticky read-only region. This is used to
2330 implement comint read-only prompts. If the text after a newline
2331 changes, the read-only status of that newline may need updating.
2332 That is what this function does.
2333
2334 This function does nothing if point is not at the beginning of a
2335 line, or is at the beginning of the accessible portion of the buffer.
2336 Otherwise, if the character after point has a front-sticky
2337 read-only property, then the preceding newline is given a
2338 read-only property of `fence', unless it already is read-only.
2339 If the character after point does not have a front-sticky
2340 read-only property, any read-only property of `fence' on the
2341 preceding newline is removed."
2342 (let* ((pt (point)) (lst (get-text-property pt 'front-sticky))
2343 (inhibit-modification-hooks t))
2344 (and (bolp)
2345 (not (bobp))
2346 (if (and (get-text-property pt 'read-only)
2347 (if (listp lst) (memq 'read-only lst) t))
2348 (unless (get-text-property (1- pt) 'read-only)
2349 (put-text-property (1- pt) pt 'read-only 'fence))
2350 (when (eq (get-text-property (1- pt) 'read-only) 'fence)
2351 (remove-list-of-text-properties (1- pt) pt '(read-only)))))))
2352
2353 (defun comint-kill-whole-line (&optional arg)
2354 "Kill current line, ignoring read-only and field properties.
2355 With prefix arg, kill that many lines starting from the current line.
2356 If arg is negative, kill backward. Also kill the preceding newline,
2357 instead of the trailing one. \(This is meant to make \\[repeat] work well
2358 with negative arguments.)
2359 If arg is zero, kill current line but exclude the trailing newline.
2360 The read-only status of newlines is updated with `comint-update-fence',
2361 if necessary."
2362 (interactive "p")
2363 (let ((inhibit-read-only t) (inhibit-field-text-motion t))
2364 (kill-whole-line arg)
2365 (when (>= arg 0) (comint-update-fence))))
2366
2367 (defun comint-kill-region (beg end &optional yank-handler)
2368 "Like `kill-region', but ignores read-only properties, if safe.
2369 This command assumes that the buffer contains read-only
2370 \"prompts\" which are regions with front-sticky read-only
2371 properties at the beginning of a line, with the preceding newline
2372 being read-only to protect the prompt. This is true of the
2373 comint prompts if `comint-prompt-read-only' is non-nil. This
2374 command will not delete the region if this would create mutilated
2375 or out of place prompts. That is, if any part of a prompt is
2376 deleted, the entire prompt must be deleted and all remaining
2377 prompts should stay at the beginning of a line. If this is not
2378 the case, this command just calls `kill-region' with all
2379 read-only properties intact. The read-only status of newlines is
2380 updated using `comint-update-fence', if necessary."
2381 (interactive "r")
2382 (save-excursion
2383 (let* ((true-beg (min beg end))
2384 (true-end (max beg end))
2385 (beg-bolp (progn (goto-char true-beg) (bolp)))
2386 (beg-lst (get-text-property true-beg 'front-sticky))
2387 (beg-bad (and (get-text-property true-beg 'read-only)
2388 (if (listp beg-lst) (memq 'read-only beg-lst) t)))
2389 (end-bolp (progn (goto-char true-end) (bolp)))
2390 (end-lst (get-text-property true-end 'front-sticky))
2391 (end-bad (and (get-text-property true-end 'read-only)
2392 (if (listp end-lst) (memq 'read-only end-lst) t))))
2393 (if (or (and (not beg-bolp) (or beg-bad end-bad))
2394 (and (not end-bolp) end-bad))
2395 (kill-region beg end yank-handler)
2396 (let ((inhibit-read-only t))
2397 (kill-region beg end yank-handler)
2398 (comint-update-fence))))))
2399
2400 \f
2401 ;; Support for source-file processing commands.
2402 ;;============================================================================
2403 ;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
2404 ;; commands that process files of source text (e.g. loading or compiling
2405 ;; files). So the corresponding process-in-a-buffer modes have commands
2406 ;; for doing this (e.g., lisp-load-file). The functions below are useful
2407 ;; for defining these commands.
2408 ;;
2409 ;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
2410 ;; and Soar, in that they don't know anything about file extensions.
2411 ;; So the compile/load interface gets the wrong default occasionally.
2412 ;; The load-file/compile-file default mechanism could be smarter -- it
2413 ;; doesn't know about the relationship between filename extensions and
2414 ;; whether the file is source or executable. If you compile foo.lisp
2415 ;; with compile-file, then the next load-file should use foo.bin for
2416 ;; the default, not foo.lisp. This is tricky to do right, particularly
2417 ;; because the extension for executable files varies so much (.o, .bin,
2418 ;; .lbin, .mo, .vo, .ao, ...).
2419
2420
2421 ;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
2422 ;; commands.
2423 ;;
2424 ;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
2425 ;; want to save the buffer before issuing any process requests to the command
2426 ;; interpreter.
2427 ;;
2428 ;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
2429 ;; for the file to process.
2430
2431 (defun comint-source-default (previous-dir/file source-modes)
2432 "Compute the defaults for `load-file' and `compile-file' commands.
2433
2434 PREVIOUS-DIR/FILE is a pair (DIRECTORY . FILENAME) from the last
2435 source-file processing command, or nil if there hasn't been one yet.
2436 SOURCE-MODES is a list used to determine what buffers contain source
2437 files: if the major mode of the buffer is in SOURCE-MODES, it's source.
2438 Typically, (lisp-mode) or (scheme-mode).
2439
2440 If the command is given while the cursor is inside a string, *and*
2441 the string is an existing filename, *and* the filename is not a directory,
2442 then the string is taken as default. This allows you to just position
2443 your cursor over a string that's a filename and have it taken as default.
2444
2445 If the command is given in a file buffer whose major mode is in
2446 SOURCE-MODES, then the filename is the default file, and the
2447 file's directory is the default directory.
2448
2449 If the buffer isn't a source file buffer (e.g., it's the process buffer),
2450 then the default directory & file are what was used in the last source-file
2451 processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
2452 the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
2453 is the cwd, with no default file. (\"no default file\" = nil)
2454
2455 SOURCE-MODES is typically going to be something like (tea-mode)
2456 for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
2457 for Soar programs, etc.
2458
2459 The function returns a pair: (default-directory . default-file)."
2460 (cond ((and buffer-file-name (memq major-mode source-modes))
2461 (cons (file-name-directory buffer-file-name)
2462 (file-name-nondirectory buffer-file-name)))
2463 (previous-dir/file)
2464 (t
2465 (cons default-directory nil))))
2466
2467
2468 (defun comint-check-source (fname)
2469 "Check whether to save buffers visiting file FNAME.
2470 Prior to loading or compiling (or otherwise processing) a file (in the CMU
2471 process-in-a-buffer modes), this function can be called on the filename.
2472 If the file is loaded into a buffer, and the buffer is modified, the user
2473 is queried to see if he wants to save the buffer before proceeding with
2474 the load or compile."
2475 (let ((buff (get-file-buffer fname)))
2476 (if (and buff
2477 (buffer-modified-p buff)
2478 (y-or-n-p (format "Save buffer %s first? " (buffer-name buff))))
2479 ;; save BUFF.
2480 (let ((old-buffer (current-buffer)))
2481 (set-buffer buff)
2482 (save-buffer)
2483 (set-buffer old-buffer)))))
2484
2485 (defun comint-extract-string ()
2486 "Return string around point, or nil."
2487 (let ((syntax (syntax-ppss)))
2488 (when (nth 3 syntax)
2489 (condition-case ()
2490 (buffer-substring-no-properties (1+ (nth 8 syntax))
2491 (progn (goto-char (nth 8 syntax))
2492 (forward-sexp)
2493 (1- (point))))
2494 (error nil)))))
2495
2496 (defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
2497 "Prompt for filenames in commands that process source files,
2498 e.g. loading or compiling a file.
2499 Provides a default, if there is one, and returns the result filename.
2500
2501 See `comint-source-default' for more on determining defaults.
2502
2503 PROMPT is the prompt string. PREV-DIR/FILE is the (DIRECTORY . FILE) pair
2504 from the last source processing command. SOURCE-MODES is a list of major
2505 modes used to determine what file buffers contain source files. (These
2506 two arguments are used for determining defaults.) If MUSTMATCH-P is true,
2507 then the filename reader will only accept a file that exists.
2508
2509 A typical use:
2510 (interactive (comint-get-source \"Compile file: \" prev-lisp-dir/file
2511 '(lisp-mode) t))"
2512 (let* ((def (comint-source-default prev-dir/file source-modes))
2513 (stringfile (comint-extract-string))
2514 (sfile-p (and stringfile
2515 (condition-case ()
2516 (file-exists-p stringfile)
2517 (error nil))
2518 (not (file-directory-p stringfile))))
2519 (defdir (if sfile-p (file-name-directory stringfile)
2520 (car def)))
2521 (deffile (if sfile-p (file-name-nondirectory stringfile)
2522 (cdr def)))
2523 (ans (read-file-name (if deffile (format "%s(default %s) "
2524 prompt deffile)
2525 prompt)
2526 defdir
2527 (concat defdir deffile)
2528 mustmatch-p)))
2529 (list (expand-file-name (substitute-in-file-name ans)))))
2530
2531 ;; I am somewhat divided on this string-default feature. It seems
2532 ;; to violate the principle-of-least-astonishment, in that it makes
2533 ;; the default harder to predict, so you actually have to look and see
2534 ;; what the default really is before choosing it. This can trip you up.
2535 ;; On the other hand, it can be useful, I guess. I would appreciate feedback
2536 ;; on this.
2537 ;; -Olin
2538
2539 \f
2540 ;; Simple process query facility.
2541 ;; ===========================================================================
2542 ;; This function is for commands that want to send a query to the process
2543 ;; and show the response to the user. For example, a command to get the
2544 ;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
2545 ;; to an inferior Common Lisp process.
2546 ;;
2547 ;; This simple facility just sends strings to the inferior process and pops
2548 ;; up a window for the process buffer so you can see what the process
2549 ;; responds with. We don't do anything fancy like try to intercept what the
2550 ;; process responds with and put it in a pop-up window or on the message
2551 ;; line. We just display the buffer. Low tech. Simple. Works good.
2552
2553 (defun comint-proc-query (proc str)
2554 "Send to the inferior process PROC the string STR.
2555 Pop-up but do not select a window for the inferior process so that
2556 its response can be seen."
2557 (let* ((proc-buf (process-buffer proc))
2558 (proc-mark (process-mark proc)))
2559 (display-buffer proc-buf)
2560 (set-buffer proc-buf) ; but it's not the selected *window*
2561 (let ((proc-win (get-buffer-window proc-buf))
2562 (proc-pt (marker-position proc-mark)))
2563 (comint-send-string proc str) ; send the query
2564 (accept-process-output proc) ; wait for some output
2565 ;; Try to position the proc window so you can see the answer.
2566 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
2567 ;; I don't know why. Wizards invited to improve it.
2568 (unless (pos-visible-in-window-p proc-pt proc-win)
2569 (let ((opoint (window-point proc-win)))
2570 (set-window-point proc-win proc-mark)
2571 (sit-for 0)
2572 (if (not (pos-visible-in-window-p opoint proc-win))
2573 (push-mark opoint)
2574 (set-window-point proc-win opoint)))))))
2575
2576 \f
2577 ;; Filename/command/history completion in a buffer
2578 ;; ===========================================================================
2579 ;; Useful completion functions, courtesy of the Ergo group.
2580
2581 ;; Six commands:
2582 ;; comint-dynamic-complete Complete or expand command, filename,
2583 ;; history at point.
2584 ;; comint-dynamic-complete-filename Complete filename at point.
2585 ;; comint-dynamic-list-filename-completions List completions in help buffer.
2586 ;; comint-replace-by-expanded-filename Expand and complete filename at point;
2587 ;; replace with expanded/completed name.
2588 ;; comint-dynamic-simple-complete Complete stub given candidates.
2589
2590 ;; These are not installed in the comint-mode keymap. But they are
2591 ;; available for people who want them. Shell-mode installs them:
2592 ;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
2593 ;; (define-key shell-mode-map "\M-?"
2594 ;; 'comint-dynamic-list-filename-completions)))
2595 ;;
2596 ;; Commands like this are fine things to put in load hooks if you
2597 ;; want them present in specific modes.
2598
2599 (defcustom comint-completion-autolist nil
2600 "*If non-nil, automatically list possibilities on partial completion.
2601 This mirrors the optional behavior of tcsh."
2602 :type 'boolean
2603 :group 'comint-completion)
2604
2605 (defcustom comint-completion-addsuffix t
2606 "*If non-nil, add a `/' to completed directories, ` ' to file names.
2607 If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
2608 DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact completion.
2609 This mirrors the optional behavior of tcsh."
2610 :type '(choice (const :tag "None" nil)
2611 (const :tag "Add /" t)
2612 (cons :tag "Suffix pair"
2613 (string :tag "Directory suffix")
2614 (string :tag "File suffix")))
2615 :group 'comint-completion)
2616
2617 (defcustom comint-completion-recexact nil
2618 "*If non-nil, use shortest completion if characters cannot be added.
2619 This mirrors the optional behavior of tcsh.
2620
2621 A non-nil value is useful if `comint-completion-autolist' is non-nil too."
2622 :type 'boolean
2623 :group 'comint-completion)
2624
2625 (defcustom comint-completion-fignore nil
2626 "*List of suffixes to be disregarded during file completion.
2627 This mirrors the optional behavior of bash and tcsh.
2628
2629 Note that this applies to `comint-dynamic-complete-filename' only."
2630 :type '(repeat (string :tag "Suffix"))
2631 :group 'comint-completion)
2632
2633 ;;;###autoload
2634 (defvar comint-file-name-prefix ""
2635 "Prefix prepended to absolute file names taken from process input.
2636 This is used by Comint's and shell's completion functions, and by shell's
2637 directory tracking functions.")
2638
2639 (defvar comint-file-name-chars
2640 (if (memq system-type '(ms-dos windows-nt cygwin))
2641 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
2642 "[]~/A-Za-z0-9+@:_.$#%,={}-")
2643 "String of characters valid in a file name.
2644 Note that all non-ASCII characters are considered valid in a file name
2645 regardless of what this variable says.
2646
2647 This is a good thing to set in mode hooks.")
2648
2649 (defvar comint-file-name-quote-list nil
2650 "List of characters to quote with `\\' when in a file name.
2651
2652 This is a good thing to set in mode hooks.")
2653
2654
2655 (defun comint-directory (directory)
2656 "Return expanded DIRECTORY, with `comint-file-name-prefix' if absolute."
2657 (expand-file-name (if (file-name-absolute-p directory)
2658 (concat comint-file-name-prefix directory)
2659 directory)))
2660
2661
2662 (defun comint-word (word-chars)
2663 "Return the word of WORD-CHARS at point, or nil if none is found.
2664 Word constituents are considered to be those in WORD-CHARS, which is like the
2665 inside of a \"[...]\" (see `skip-chars-forward'), plus all non-ASCII characters."
2666 (save-excursion
2667 (let ((here (point))
2668 giveup)
2669 (while (not giveup)
2670 (let ((startpoint (point)))
2671 (skip-chars-backward (concat "\\\\" word-chars))
2672 ;; Fixme: This isn't consistent with Bash, at least -- not
2673 ;; all non-ASCII chars should be word constituents.
2674 (if (and (> (- (point) 2) (point-min))
2675 (= (char-after (- (point) 2)) ?\\))
2676 (forward-char -2))
2677 (if (and (> (- (point) 1) (point-min))
2678 (>= (char-after (- (point) 1)) 128))
2679 (forward-char -1))
2680 (if (= (point) startpoint)
2681 (setq giveup t))))
2682 ;; Set match-data to match the entire string.
2683 (when (< (point) here)
2684 (set-match-data (list (point) here))
2685 (match-string 0)))))
2686
2687 (defun comint-substitute-in-file-name (filename)
2688 "Return FILENAME with environment variables substituted.
2689 Supports additional environment variable syntax of the command
2690 interpreter (e.g., the percent notation of cmd.exe on NT)."
2691 (let ((name (substitute-in-file-name filename)))
2692 (if (memq system-type '(ms-dos windows-nt))
2693 (let (env-var-name
2694 env-var-val)
2695 (save-match-data
2696 (while (string-match "%\\([^\\\\/]*\\)%" name)
2697 (setq env-var-name
2698 (substring name (match-beginning 1) (match-end 1)))
2699 (setq env-var-val (if (getenv env-var-name)
2700 (getenv env-var-name)
2701 ""))
2702 (setq name (replace-match env-var-val t t name))))))
2703 name))
2704
2705 (defun comint-match-partial-filename ()
2706 "Return the filename at point, or nil if none is found.
2707 Environment variables are substituted. See `comint-word'."
2708 (let ((filename (comint-word comint-file-name-chars)))
2709 (and filename (comint-substitute-in-file-name
2710 (comint-unquote-filename filename)))))
2711
2712
2713 (defun comint-quote-filename (filename)
2714 "Return FILENAME with magic characters quoted.
2715 Magic characters are those in `comint-file-name-quote-list'."
2716 (if (null comint-file-name-quote-list)
2717 filename
2718 (let ((regexp
2719 (format "[%s]"
2720 (mapconcat 'char-to-string comint-file-name-quote-list ""))))
2721 (save-match-data
2722 (let ((i 0))
2723 (while (string-match regexp filename i)
2724 (setq filename (replace-match "\\\\\\&" nil nil filename))
2725 (setq i (1+ (match-end 0)))))
2726 filename))))
2727
2728 (defun comint-unquote-filename (filename)
2729 "Return FILENAME with quoted characters unquoted."
2730 (if (null comint-file-name-quote-list)
2731 filename
2732 (save-match-data
2733 (let ((i 0))
2734 (while (string-match "\\\\\\(.\\)" filename i)
2735 (setq filename (replace-match "\\1" nil nil filename))
2736 (setq i (+ 1 (match-beginning 0)))))
2737 filename)))
2738
2739
2740 (defun comint-dynamic-complete ()
2741 "Dynamically perform completion at point.
2742 Calls the functions in `comint-dynamic-complete-functions' to perform
2743 completion until a function returns non-nil, at which point completion is
2744 assumed to have occurred."
2745 (interactive)
2746 (run-hook-with-args-until-success 'comint-dynamic-complete-functions))
2747
2748
2749 (defun comint-dynamic-complete-filename ()
2750 "Dynamically complete the filename at point.
2751 Completes if after a filename. See `comint-match-partial-filename' and
2752 `comint-dynamic-complete-as-filename'.
2753 This function is similar to `comint-replace-by-expanded-filename', except that
2754 it won't change parts of the filename already entered in the buffer; it just
2755 adds completion characters to the end of the filename. A completions listing
2756 may be shown in a help buffer if completion is ambiguous.
2757
2758 Completion is dependent on the value of `comint-completion-addsuffix',
2759 `comint-completion-recexact' and `comint-completion-fignore', and the timing of
2760 completions listing is dependent on the value of `comint-completion-autolist'.
2761
2762 Returns t if successful."
2763 (interactive)
2764 (when (comint-match-partial-filename)
2765 (unless (window-minibuffer-p (selected-window))
2766 (message "Completing file name..."))
2767 (comint-dynamic-complete-as-filename)))
2768
2769 (defun comint-dynamic-complete-as-filename ()
2770 "Dynamically complete at point as a filename.
2771 See `comint-dynamic-complete-filename'. Returns t if successful."
2772 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt cygwin)))
2773 (completion-ignored-extensions comint-completion-fignore)
2774 ;; If we bind this, it breaks remote directory tracking in rlogin.el.
2775 ;; I think it was originally bound to solve file completion problems,
2776 ;; but subsequent changes may have made this unnecessary. sm.
2777 ;;(file-name-handler-alist nil)
2778 (minibuffer-p (window-minibuffer-p (selected-window)))
2779 (success t)
2780 (dirsuffix (cond ((not comint-completion-addsuffix)
2781 "")
2782 ((not (consp comint-completion-addsuffix))
2783 "/")
2784 (t
2785 (car comint-completion-addsuffix))))
2786 (filesuffix (cond ((not comint-completion-addsuffix)
2787 "")
2788 ((not (consp comint-completion-addsuffix))
2789 " ")
2790 (t
2791 (cdr comint-completion-addsuffix))))
2792 (filename (or (comint-match-partial-filename) ""))
2793 (filedir (file-name-directory filename))
2794 (filenondir (file-name-nondirectory filename))
2795 (directory (if filedir (comint-directory filedir) default-directory))
2796 (completion (file-name-completion filenondir directory)))
2797 (cond ((null completion)
2798 (message "No completions of %s" filename)
2799 (setq success nil))
2800 ((eq completion t) ; Means already completed "file".
2801 (insert filesuffix)
2802 (unless minibuffer-p
2803 (message "Sole completion")))
2804 ((string-equal completion "") ; Means completion on "directory/".
2805 (comint-dynamic-list-filename-completions))
2806 (t ; Completion string returned.
2807 (let ((file (concat (file-name-as-directory directory) completion)))
2808 (insert (comint-quote-filename
2809 (substring (directory-file-name completion)
2810 (length filenondir))))
2811 (cond ((symbolp (file-name-completion completion directory))
2812 ;; We inserted a unique completion.
2813 (insert (if (file-directory-p file) dirsuffix filesuffix))
2814 (unless minibuffer-p
2815 (message "Completed")))
2816 ((and comint-completion-recexact comint-completion-addsuffix
2817 (string-equal filenondir completion)
2818 (file-exists-p file))
2819 ;; It's not unique, but user wants shortest match.
2820 (insert (if (file-directory-p file) dirsuffix filesuffix))
2821 (unless minibuffer-p
2822 (message "Completed shortest")))
2823 ((or comint-completion-autolist
2824 (string-equal filenondir completion))
2825 ;; It's not unique, list possible completions.
2826 (comint-dynamic-list-filename-completions))
2827 (t
2828 (unless minibuffer-p
2829 (message "Partially completed")))))))
2830 success))
2831
2832
2833 (defun comint-replace-by-expanded-filename ()
2834 "Dynamically expand and complete the filename at point.
2835 Replace the filename with an expanded, canonicalized and completed replacement.
2836 \"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
2837 with the corresponding directories. \"Canonicalized\" means `..' and `.' are
2838 removed, and the filename is made absolute instead of relative. For expansion
2839 see `expand-file-name' and `substitute-in-file-name'. For completion see
2840 `comint-dynamic-complete-filename'."
2841 (interactive)
2842 (let ((filename (comint-match-partial-filename)))
2843 (when filename
2844 (replace-match (expand-file-name filename) t t)
2845 (comint-dynamic-complete-filename))))
2846
2847
2848 (defun comint-dynamic-simple-complete (stub candidates)
2849 "Dynamically complete STUB from CANDIDATES list.
2850 This function inserts completion characters at point by completing STUB from
2851 the strings in CANDIDATES. A completions listing may be shown in a help buffer
2852 if completion is ambiguous.
2853
2854 Returns nil if no completion was inserted.
2855 Returns `sole' if completed with the only completion match.
2856 Returns `shortest' if completed with the shortest of the completion matches.
2857 Returns `partial' if completed as far as possible with the completion matches.
2858 Returns `listed' if a completion listing was shown.
2859
2860 See also `comint-dynamic-complete-filename'."
2861 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt cygwin)))
2862 (suffix (cond ((not comint-completion-addsuffix) "")
2863 ((not (consp comint-completion-addsuffix)) " ")
2864 (t (cdr comint-completion-addsuffix))))
2865 (completions (all-completions stub candidates)))
2866 (cond ((null completions)
2867 (message "No completions of %s" stub)
2868 nil)
2869 ((= 1 (length completions)) ; Gotcha!
2870 (let ((completion (car completions)))
2871 (if (string-equal completion stub)
2872 (message "Sole completion")
2873 (insert (substring completion (length stub)))
2874 (message "Completed"))
2875 (insert suffix)
2876 'sole))
2877 (t ; There's no unique completion.
2878 (let ((completion (try-completion stub candidates)))
2879 ;; Insert the longest substring.
2880 (insert (substring completion (length stub)))
2881 (cond ((and comint-completion-recexact comint-completion-addsuffix
2882 (string-equal stub completion)
2883 (member completion completions))
2884 ;; It's not unique, but user wants shortest match.
2885 (insert suffix)
2886 (message "Completed shortest")
2887 'shortest)
2888 ((or comint-completion-autolist
2889 (string-equal stub completion))
2890 ;; It's not unique, list possible completions.
2891 (comint-dynamic-list-completions completions)
2892 'listed)
2893 (t
2894 (message "Partially completed")
2895 'partial)))))))
2896
2897
2898 (defun comint-dynamic-list-filename-completions ()
2899 "List in help buffer possible completions of the filename at point."
2900 (interactive)
2901 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt cygwin)))
2902 ;; If we bind this, it breaks remote directory tracking in rlogin.el.
2903 ;; I think it was originally bound to solve file completion problems,
2904 ;; but subsequent changes may have made this unnecessary. sm.
2905 ;;(file-name-handler-alist nil)
2906 (filename (or (comint-match-partial-filename) ""))
2907 (filedir (file-name-directory filename))
2908 (filenondir (file-name-nondirectory filename))
2909 (directory (if filedir (comint-directory filedir) default-directory))
2910 (completions (file-name-all-completions filenondir directory)))
2911 (if (not completions)
2912 (message "No completions of %s" filename)
2913 (comint-dynamic-list-completions
2914 (mapcar 'comint-quote-filename completions)))))
2915
2916
2917 ;; This is bound locally in a *Completions* buffer to the list of
2918 ;; completions displayed, and is used to detect the case where the same
2919 ;; command is repeatedly used without the set of completions changing.
2920 (defvar comint-displayed-dynamic-completions nil)
2921
2922 (defvar comint-dynamic-list-completions-config nil)
2923
2924 (defun comint-dynamic-list-completions (completions)
2925 "List in help buffer sorted COMPLETIONS.
2926 Typing SPC flushes the help buffer."
2927 (let ((window (get-buffer-window "*Completions*")))
2928 (setq completions (sort completions 'string-lessp))
2929 (if (and (eq last-command this-command)
2930 window (window-live-p window) (window-buffer window)
2931 (buffer-name (window-buffer window))
2932 ;; The above tests are not sufficient to detect the case where we
2933 ;; should scroll, because the top-level interactive command may
2934 ;; not have displayed a completions window the last time it was
2935 ;; invoked, and there may be such a window left over from a
2936 ;; previous completion command with a different set of
2937 ;; completions. To detect that case, we also test that the set
2938 ;; of displayed completions is in fact the same as the previously
2939 ;; displayed set.
2940 (equal completions
2941 (buffer-local-value 'comint-displayed-dynamic-completions
2942 (window-buffer window))))
2943 ;; If this command was repeated, and
2944 ;; there's a fresh completion window with a live buffer,
2945 ;; and this command is repeated, scroll that window.
2946 (with-current-buffer (window-buffer window)
2947 (if (pos-visible-in-window-p (point-max) window)
2948 (set-window-start window (point-min))
2949 (save-selected-window
2950 (select-window window)
2951 (scroll-up))))
2952
2953 ;; Display a completion list for the first time.
2954 (setq comint-dynamic-list-completions-config
2955 (current-window-configuration))
2956 (with-output-to-temp-buffer "*Completions*"
2957 (display-completion-list completions))
2958 (message "Type space to flush; repeat completion command to scroll"))
2959
2960 ;; Read the next key, to process SPC.
2961 (let (key first)
2962 (if (with-current-buffer (get-buffer "*Completions*")
2963 (set (make-local-variable 'comint-displayed-dynamic-completions)
2964 completions)
2965 (setq key (read-key-sequence nil)
2966 first (aref key 0))
2967 (and (consp first) (consp (event-start first))
2968 (eq (window-buffer (posn-window (event-start first)))
2969 (get-buffer "*Completions*"))
2970 (eq (key-binding key) 'mouse-choose-completion)))
2971 ;; If the user does mouse-choose-completion with the mouse,
2972 ;; execute the command, then delete the completion window.
2973 (progn
2974 (mouse-choose-completion first)
2975 (set-window-configuration comint-dynamic-list-completions-config))
2976 (if (eq first ?\s)
2977 (set-window-configuration comint-dynamic-list-completions-config)
2978 (setq unread-command-events (listify-key-sequence key)))))))
2979
2980 \f
2981 (defun comint-get-next-from-history ()
2982 "After fetching a line from input history, this fetches the following line.
2983 In other words, this recalls the input line after the line you recalled last.
2984 You can use this to repeat a sequence of input lines."
2985 (interactive)
2986 (if comint-save-input-ring-index
2987 (progn
2988 (setq comint-input-ring-index (1+ comint-save-input-ring-index))
2989 (comint-next-input 1))
2990 (message "No previous history command")))
2991
2992 (defun comint-accumulate ()
2993 "Accumulate a line to send as input along with more lines.
2994 This inserts a newline so that you can enter more text
2995 to be sent along with this line. Use \\[comint-send-input]
2996 to send all the accumulated input, at once.
2997 The entire accumulated text becomes one item in the input history
2998 when you send it."
2999 (interactive)
3000 (insert "\n")
3001 (set-marker comint-accum-marker (point))
3002 (if comint-input-ring-index
3003 (setq comint-save-input-ring-index
3004 (- comint-input-ring-index 1))))
3005
3006 (defun comint-goto-process-mark ()
3007 "Move point to the process mark.
3008 The process mark separates output, and input already sent,
3009 from input that has not yet been sent."
3010 (interactive)
3011 (let ((proc (or (get-buffer-process (current-buffer))
3012 (error "Current buffer has no process"))))
3013 (goto-char (process-mark proc))
3014 (when (interactive-p)
3015 (message "Point is now at the process mark"))))
3016
3017 (defun comint-bol-or-process-mark ()
3018 "Move point to beginning of line (after prompt) or to the process mark.
3019 The first time you use this command, it moves to the beginning of the line
3020 \(but after the prompt, if any). If you repeat it again immediately,
3021 it moves point to the process mark.
3022
3023 The process mark separates the process output, along with input already sent,
3024 from input that has not yet been sent. Ordinarily, the process mark
3025 is at the beginning of the current input line; but if you have
3026 used \\[comint-accumulate] to send multiple lines at once,
3027 the process mark is at the beginning of the accumulated input."
3028 (interactive)
3029 (if (not (eq last-command 'comint-bol-or-process-mark))
3030 (comint-bol nil)
3031 (comint-goto-process-mark)))
3032
3033 (defun comint-set-process-mark ()
3034 "Set the process mark at point."
3035 (interactive)
3036 (let ((proc (or (get-buffer-process (current-buffer))
3037 (error "Current buffer has no process"))))
3038 (set-marker (process-mark proc) (point))
3039 (message "Process mark set")))
3040
3041 \f
3042 ;; Author: Peter Breton <pbreton@cs.umb.edu>
3043
3044 ;; This little add-on for comint is intended to make it easy to get
3045 ;; output from currently active comint buffers into another buffer,
3046 ;; or buffers, and then go back to using the comint shell.
3047 ;;
3048 ;; My particular use is SQL interpreters; I want to be able to execute a
3049 ;; query using the process associated with a comint-buffer, and save that
3050 ;; somewhere else. Because the process might have state (for example, it
3051 ;; could be in an uncommitted transaction), just running starting a new
3052 ;; process and having it execute the query and then finish, would not
3053 ;; work. I'm sure there are other uses as well, although in many cases
3054 ;; starting a new process is the simpler, and thus preferable, approach.
3055 ;;
3056 ;; The basic implementation is as follows: comint-redirect changes the
3057 ;; preoutput filter functions (`comint-preoutput-filter-functions') to use
3058 ;; its own filter. The filter puts the output into the designated buffer,
3059 ;; or buffers, until it sees a regexp that tells it to stop (by default,
3060 ;; this is the prompt for the interpreter, `comint-prompt-regexp'). When it
3061 ;; sees the stop regexp, it restores the old filter functions, and runs
3062 ;; `comint-redirect-hook'.
3063 ;;
3064 ;; Each comint buffer may only use one redirection at a time, but any number
3065 ;; of different comint buffers may be simultaneously redirected.
3066 ;;
3067 ;; NOTE: It is EXTREMELY important that `comint-prompt-regexp' be set to the
3068 ;; correct prompt for your interpreter, or that you supply a regexp that says
3069 ;; when the redirection is finished. Otherwise, redirection will continue
3070 ;; indefinitely. The code now does a sanity check to ensure that it can find
3071 ;; a prompt in the comint buffer; however, it is still important to ensure that
3072 ;; this prompt is set correctly.
3073 ;;
3074 ;; XXX: This doesn't work so well unless `comint-prompt-regexp' is set;
3075 ;; perhaps it should prompt for a terminating string (with an
3076 ;; appropriate magic default by examining what we think is the prompt)?
3077 ;;
3078 ;; Fixme: look for appropriate fields, rather than regexp, if
3079 ;; `comint-use-prompt-regexp' is true.
3080
3081 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3082 ;; Variables
3083 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3084
3085 (defcustom comint-redirect-verbose nil
3086 "*If non-nil, print messages each time the redirection filter is invoked.
3087 Also print a message when redirection is completed."
3088 :group 'comint
3089 :type 'boolean)
3090
3091 ;; Directly analagous to comint-preoutput-filter-functions
3092 (defvar comint-redirect-filter-functions nil
3093 "List of functions to call before inserting redirected process output.
3094 Each function gets one argument, a string containing the text received
3095 from the subprocess. It should return the string to insert, perhaps
3096 the same string that was received, or perhaps a modified or transformed
3097 string.
3098
3099 The functions on the list are called sequentially, and each one is given
3100 the string returned by the previous one. The string returned by the
3101 last function is the text that is actually inserted in the redirection buffer.
3102
3103 You can use `add-hook' to add functions to this list
3104 either globally or locally.")
3105
3106 ;; Internal variables
3107
3108 (defvar comint-redirect-output-buffer nil
3109 "The buffer or list of buffers to put output into.")
3110
3111 (defvar comint-redirect-finished-regexp nil
3112 "Regular expression that determines when to stop redirection in Comint.
3113 When the redirection filter function is given output that matches this regexp,
3114 the output is inserted as usual, and redirection is completed.")
3115
3116 (defvar comint-redirect-insert-matching-regexp nil
3117 "If non-nil, the text that ends a redirection is included in it.
3118 More precisely, the text that matches `comint-redirect-finished-regexp'
3119 and therefore terminates an output redirection is inserted in the
3120 redirection target buffer, along with the preceding output.")
3121
3122 (defvar comint-redirect-echo-input nil
3123 "Non-nil means echo input in the process buffer even during redirection.")
3124
3125 (defvar comint-redirect-completed nil
3126 "Non-nil if redirection has completed in the current buffer.")
3127
3128 (defvar comint-redirect-original-mode-line-process nil
3129 "Original mode line for redirected process.")
3130
3131 (defvar comint-redirect-perform-sanity-check t
3132 "If non-nil, check that redirection is likely to complete successfully.
3133 More precisely, before starting a redirection, verify that the
3134 regular expression `comint-redirect-finished-regexp' that controls
3135 when to terminate it actually matches some text already in the process
3136 buffer. The idea is that this regular expression should match a prompt
3137 string, and that there ought to be at least one copy of your prompt string
3138 in the process buffer already.")
3139
3140 (defvar comint-redirect-original-filter-function nil
3141 "The process filter that was in place when redirection is started.
3142 When redirection is completed, the process filter is restored to
3143 this value.")
3144
3145 (defvar comint-redirect-subvert-readonly nil
3146 "Non-nil means `comint-redirect' can insert into read-only buffers.
3147 This works by binding `inhibit-read-only' around the insertion.
3148 This is useful, for instance, for insertion into Help mode buffers.
3149 You probably want to set it locally to the output buffer.")
3150
3151 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3152 ;; Functions
3153 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3154
3155 (defun comint-redirect-setup (output-buffer
3156 comint-buffer
3157 finished-regexp
3158 &optional echo-input)
3159 "Set up for output redirection.
3160 This function sets local variables that are used by `comint-redirect-filter'
3161 to perform redirection.
3162
3163 Output from COMINT-BUFFER is redirected to OUTPUT-BUFFER, until something
3164 in the output matches FINISHED-REGEXP.
3165
3166 If optional argument ECHO-INPUT is non-nil, output is echoed to the
3167 original Comint buffer.
3168
3169 This function is called by `comint-redirect-send-command-to-process',
3170 and does not normally need to be invoked by the end user or programmer."
3171 (with-current-buffer comint-buffer
3172
3173 (make-local-variable 'comint-redirect-original-mode-line-process)
3174 (setq comint-redirect-original-mode-line-process mode-line-process)
3175
3176 (make-local-variable 'comint-redirect-output-buffer)
3177 (setq comint-redirect-output-buffer output-buffer)
3178
3179 (make-local-variable 'comint-redirect-finished-regexp)
3180 (setq comint-redirect-finished-regexp finished-regexp)
3181
3182 (make-local-variable 'comint-redirect-echo-input)
3183 (setq comint-redirect-echo-input echo-input)
3184
3185 (make-local-variable 'comint-redirect-completed)
3186 (setq comint-redirect-completed nil)
3187
3188 (setq mode-line-process
3189 (if mode-line-process
3190 (list (concat (elt mode-line-process 0) " Redirection"))
3191 (list ":%s Redirection")))))
3192
3193 (defun comint-redirect-cleanup ()
3194 "End a Comint redirection. See `comint-redirect-send-command'."
3195 (interactive)
3196 ;; Restore the process filter
3197 (set-process-filter (get-buffer-process (current-buffer))
3198 comint-redirect-original-filter-function)
3199 ;; Restore the mode line
3200 (setq mode-line-process comint-redirect-original-mode-line-process)
3201 ;; Set the completed flag
3202 (setq comint-redirect-completed t))
3203
3204 ;; Because the cleanup happens as a callback, it's not easy to guarantee
3205 ;; that it really occurs.
3206 (defalias 'comint-redirect-remove-redirection 'comint-redirect-cleanup)
3207
3208 (defun comint-redirect-filter (process input-string)
3209 "Filter function which redirects output from PROCESS to a buffer or buffers.
3210 The variable `comint-redirect-output-buffer' says which buffer(s) to
3211 place output in.
3212
3213 INPUT-STRING is the input from the Comint process.
3214
3215 This function runs as a process filter, and does not need to be invoked by the
3216 end user."
3217 (and process
3218 (with-current-buffer (process-buffer process)
3219 (comint-redirect-preoutput-filter input-string)
3220 ;; If we have to echo output, give it to the original filter function
3221 (and comint-redirect-echo-input
3222 comint-redirect-original-filter-function
3223 (funcall comint-redirect-original-filter-function
3224 process input-string)))))
3225
3226
3227 (defun comint-redirect-preoutput-filter (input-string)
3228 "Comint filter function which redirects Comint output to a buffer or buffers.
3229 The variable `comint-redirect-output-buffer' says which buffer(s) to
3230 place output in.
3231
3232 INPUT-STRING is the input from the Comint process.
3233
3234 This function does not need to be invoked by the end user."
3235 (let ((output-buffer-list
3236 (if (listp comint-redirect-output-buffer)
3237 comint-redirect-output-buffer
3238 (list comint-redirect-output-buffer)))
3239 (filtered-input-string input-string))
3240
3241 ;; If there are any filter functions, give them a chance to modify the string
3242 (let ((functions comint-redirect-filter-functions))
3243 (while (and functions filtered-input-string)
3244 (if (eq (car functions) t)
3245 ;; If a local value says "use the default value too",
3246 ;; do that.
3247 (let ((functions (default-value 'comint-redirect-filter-functions)))
3248 (while (and functions filtered-input-string)
3249 (setq filtered-input-string
3250 (funcall (car functions) filtered-input-string))
3251 (setq functions (cdr functions))))
3252 (setq filtered-input-string
3253 (funcall (car functions) filtered-input-string)))
3254 (setq functions (cdr functions))))
3255
3256 ;; Clobber `comint-redirect-finished-regexp'
3257 (or comint-redirect-insert-matching-regexp
3258 (and (string-match comint-redirect-finished-regexp filtered-input-string)
3259 (setq filtered-input-string
3260 (replace-match "" nil nil filtered-input-string))))
3261
3262 ;; Send output to all registered buffers
3263 (save-excursion
3264 (dolist (buf output-buffer-list)
3265 ;; Set this buffer to the output buffer
3266 (set-buffer (get-buffer-create buf))
3267 ;; Go to the end of the buffer
3268 (goto-char (point-max))
3269 ;; Insert the output
3270 (let ((inhibit-read-only comint-redirect-subvert-readonly))
3271 (insert filtered-input-string))))
3272
3273 ;; Message
3274 (and comint-redirect-verbose
3275 (message "Redirected output to buffer(s) %s"
3276 (mapconcat 'identity output-buffer-list " ")))
3277
3278 ;; If we see the prompt, tidy up
3279 ;; We'll look for the prompt in the original string, so nobody can
3280 ;; clobber it
3281 (and (string-match comint-redirect-finished-regexp input-string)
3282 (progn
3283 (and comint-redirect-verbose
3284 (message "Redirection completed"))
3285 (comint-redirect-cleanup)
3286 (run-hooks 'comint-redirect-hook)))
3287 ;; Echo input?
3288 (if comint-redirect-echo-input
3289 filtered-input-string
3290 "")))
3291
3292 ;;;###autoload
3293 (defun comint-redirect-send-command (command output-buffer echo &optional no-display)
3294 "Send COMMAND to process in current buffer, with output to OUTPUT-BUFFER.
3295 With prefix arg ECHO, echo output in process buffer.
3296
3297 If NO-DISPLAY is non-nil, do not show the output buffer."
3298 (interactive "sCommand: \nBOutput Buffer: \nP")
3299 (let ((process (get-buffer-process (current-buffer))))
3300 (if process
3301 (comint-redirect-send-command-to-process
3302 command output-buffer (current-buffer) echo no-display)
3303 (error "No process for current buffer"))))
3304
3305 ;;;###autoload
3306 (defun comint-redirect-send-command-to-process
3307 (command output-buffer process echo &optional no-display)
3308 "Send COMMAND to PROCESS, with output to OUTPUT-BUFFER.
3309 With prefix arg, echo output in process buffer.
3310
3311 If NO-DISPLAY is non-nil, do not show the output buffer."
3312 (interactive "sCommand: \nBOutput Buffer: \nbProcess Buffer: \nP")
3313 (let* (;; The process buffer
3314 (process-buffer (if (processp process)
3315 (process-buffer process)
3316 process))
3317 (proc (get-buffer-process process-buffer)))
3318 ;; Change to the process buffer
3319 (with-current-buffer process-buffer
3320
3321 ;; Make sure there's a prompt in the current process buffer
3322 (and comint-redirect-perform-sanity-check
3323 (save-excursion
3324 (goto-char (point-max))
3325 (or (re-search-backward comint-prompt-regexp nil t)
3326 (error "No prompt found or `comint-prompt-regexp' not set properly"))))
3327
3328 ;;;;;;;;;;;;;;;;;;;;;
3329 ;; Set up for redirection
3330 ;;;;;;;;;;;;;;;;;;;;;
3331 (comint-redirect-setup
3332 ;; Output Buffer
3333 output-buffer
3334 ;; Comint Buffer
3335 (current-buffer)
3336 ;; Finished Regexp
3337 comint-prompt-regexp
3338 ;; Echo input
3339 echo)
3340
3341 ;;;;;;;;;;;;;;;;;;;;;
3342 ;; Set the filter
3343 ;;;;;;;;;;;;;;;;;;;;;
3344 ;; Save the old filter
3345 (setq comint-redirect-original-filter-function
3346 (process-filter proc))
3347 (set-process-filter proc 'comint-redirect-filter)
3348
3349 ;;;;;;;;;;;;;;;;;;;;;
3350 ;; Send the command
3351 ;;;;;;;;;;;;;;;;;;;;;
3352 (process-send-string
3353 (current-buffer)
3354 (concat command "\n"))
3355
3356 ;;;;;;;;;;;;;;;;;;;;;
3357 ;; Show the output
3358 ;;;;;;;;;;;;;;;;;;;;;
3359 (or no-display
3360 (display-buffer
3361 (get-buffer-create
3362 (if (listp output-buffer)
3363 (car output-buffer)
3364 output-buffer)))))))
3365
3366 ;;;###autoload
3367 (defun comint-redirect-results-list (command regexp regexp-group)
3368 "Send COMMAND to current process.
3369 Return a list of expressions in the output which match REGEXP.
3370 REGEXP-GROUP is the regular expression group in REGEXP to use."
3371 (comint-redirect-results-list-from-process
3372 (get-buffer-process (current-buffer))
3373 command regexp regexp-group))
3374
3375 ;;;###autoload
3376 (defun comint-redirect-results-list-from-process (process command regexp regexp-group)
3377 "Send COMMAND to PROCESS.
3378 Return a list of expressions in the output which match REGEXP.
3379 REGEXP-GROUP is the regular expression group in REGEXP to use."
3380 (let ((output-buffer " *Comint Redirect Work Buffer*")
3381 results)
3382 (save-excursion
3383 (set-buffer (get-buffer-create output-buffer))
3384 (erase-buffer)
3385 (comint-redirect-send-command-to-process command
3386 output-buffer process nil t)
3387 ;; Wait for the process to complete
3388 (set-buffer (process-buffer process))
3389 (while (null comint-redirect-completed)
3390 (accept-process-output nil 1))
3391 ;; Collect the output
3392 (set-buffer output-buffer)
3393 (goto-char (point-min))
3394 ;; Skip past the command, if it was echoed
3395 (and (looking-at command)
3396 (forward-line))
3397 (while (re-search-forward regexp nil t)
3398 (setq results
3399 (cons (buffer-substring-no-properties
3400 (match-beginning regexp-group)
3401 (match-end regexp-group))
3402 results)))
3403 results)))
3404
3405 (mapc (lambda (x)
3406 (add-to-list 'debug-ignored-errors x))
3407 '("^Not at command line$"
3408 "^Empty input ring$"
3409 "^No history$"
3410 "^Not found$" ; Too common?
3411 "^Current buffer has no process$"))
3412
3413 \f
3414 ;; Converting process modes to use comint mode
3415 ;; ===========================================================================
3416 ;; The code in the Emacs 19 distribution has all been modified to use comint
3417 ;; where needed. However, there are `third-party' packages out there that
3418 ;; still use the old shell mode. Here's a guide to conversion.
3419 ;;
3420 ;; Renaming variables
3421 ;; Most of the work is renaming variables and functions. These are the common
3422 ;; ones:
3423 ;; Local variables:
3424 ;; last-input-start comint-last-input-start
3425 ;; last-input-end comint-last-input-end
3426 ;; shell-prompt-pattern comint-prompt-regexp
3427 ;; shell-set-directory-error-hook <no equivalent>
3428 ;; Miscellaneous:
3429 ;; shell-set-directory <unnecessary>
3430 ;; shell-mode-map comint-mode-map
3431 ;; Commands:
3432 ;; shell-send-input comint-send-input
3433 ;; shell-send-eof comint-delchar-or-maybe-eof
3434 ;; kill-shell-input comint-kill-input
3435 ;; interrupt-shell-subjob comint-interrupt-subjob
3436 ;; stop-shell-subjob comint-stop-subjob
3437 ;; quit-shell-subjob comint-quit-subjob
3438 ;; kill-shell-subjob comint-kill-subjob
3439 ;; kill-output-from-shell comint-delete-output
3440 ;; show-output-from-shell comint-show-output
3441 ;; copy-last-shell-input Use comint-previous-input/comint-next-input
3442 ;;
3443 ;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
3444 ;; SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-filter-functions.
3445 ;; Comint mode does not provide functionality equivalent to
3446 ;; shell-set-directory-error-hook; it is gone.
3447 ;;
3448 ;; comint-last-input-start is provided for modes which want to munge
3449 ;; the buffer after input is sent, perhaps because the inferior
3450 ;; insists on echoing the input. The LAST-INPUT-START variable in
3451 ;; the old shell package was used to implement a history mechanism,
3452 ;; but you should think twice before using comint-last-input-start
3453 ;; for this; the input history ring often does the job better.
3454 ;;
3455 ;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
3456 ;; *not* create the comint-mode local variables in your foo-mode function.
3457 ;; This is not modular. Instead, call comint-mode, and let *it* create the
3458 ;; necessary comint-specific local variables. Then create the
3459 ;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
3460 ;; be foo-mode-map, and its mode to be foo-mode. Set the comint-mode hooks
3461 ;; (comint-{prompt-regexp, input-filter, input-filter-functions,
3462 ;; get-old-input) that need to be different from the defaults. Call
3463 ;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
3464 ;; comint-mode will take care of it. The following example, from shell.el,
3465 ;; is typical:
3466 ;;
3467 ;; (defvar shell-mode-map '())
3468 ;; (cond ((not shell-mode-map)
3469 ;; (setq shell-mode-map (copy-keymap comint-mode-map))
3470 ;; (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
3471 ;; (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
3472 ;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
3473 ;; (define-key shell-mode-map "\M-?"
3474 ;; 'comint-dynamic-list-filename-completions)))
3475 ;;
3476 ;; (defun shell-mode ()
3477 ;; (interactive)
3478 ;; (comint-mode)
3479 ;; (setq comint-prompt-regexp shell-prompt-pattern)
3480 ;; (setq major-mode 'shell-mode)
3481 ;; (setq mode-name "Shell")
3482 ;; (use-local-map shell-mode-map)
3483 ;; (make-local-variable 'shell-directory-stack)
3484 ;; (setq shell-directory-stack nil)
3485 ;; (add-hook 'comint-input-filter-functions 'shell-directory-tracker)
3486 ;; (run-mode-hooks 'shell-mode-hook))
3487 ;;
3488 ;;
3489 ;; Completion for comint-mode users
3490 ;;
3491 ;; For modes that use comint-mode, comint-dynamic-complete-functions is the
3492 ;; hook to add completion functions to. Functions on this list should return
3493 ;; non-nil if completion occurs (i.e., further completion should not occur).
3494 ;; You could use comint-dynamic-simple-complete to do the bulk of the
3495 ;; completion job.
3496 \f
3497
3498 (provide 'comint)
3499
3500 ;; arch-tag: 1793314c-09db-40be-9549-9aeae3e75164
3501 ;;; comint.el ends here