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