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