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