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