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