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