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