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