Fix indentation. Fix typo.
[bpt/emacs.git] / lisp / comint.el
CommitLineData
c0274f38 1;;; comint.el --- general command interpreter in a window stuff
e41b2db1 2
9cc68f10 3;; Copyright (C) 1988, 90, 92, 93, 94, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
c0274f38 4
f8604035
SM
5;; Author: Olin Shivers <shivers@cs.cmu.edu> then
6;; Simon Marshall <simon@gnu.ai.mit.edu>
7;; Maintainer: FSF
e9571d2a 8;; Keywords: processes
3a801d0c 9
1586b965 10;; This file is part of GNU Emacs.
be9b65ac 11
1586b965
RS
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation; either version 2, or (at your option)
15;; any later version.
be9b65ac 16
1586b965
RS
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
be9b65ac 21
1586b965 22;; You should have received a copy of the GNU General Public License
b578f267
EN
23;; along with GNU Emacs; see the file COPYING. If not, write to the
24;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25;; Boston, MA 02111-1307, USA.
be9b65ac 26
e5167999
ER
27;;; Commentary:
28
b578f267
EN
29;; Please send me bug reports, bug fixes, and extensions, so that I can
30;; merge them into the master source.
31;; - Olin Shivers (shivers@cs.cmu.edu)
32;; - Simon Marshall (simon@gnu.ai.mit.edu)
33
34;; This file defines a general command-interpreter-in-a-buffer package
35;; (comint mode). The idea is that you can build specific process-in-a-buffer
36;; modes on top of comint mode -- e.g., lisp, shell, scheme, T, soar, ....
37;; This way, all these specific packages share a common base functionality,
38;; and a common set of bindings, which makes them easier to use (and
39;; saves code, implementation time, etc., etc.).
40
41;; Several packages are already defined using comint mode:
42;; - shell.el defines a shell-in-a-buffer mode.
43;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
44;;
45;; - The file cmuscheme.el defines a scheme-in-a-buffer mode.
46;; - The file tea.el tunes scheme and inferior-scheme modes for T.
47;; - The file soar.el tunes lisp and inferior-lisp modes for Soar.
48;; - cmutex.el defines tex and latex modes that invoke tex, latex, bibtex,
49;; previewers, and printers from within emacs.
50;; - background.el allows csh-like job control inside emacs.
51;; It is pretty easy to make new derived modes for other processes.
52
53;; For documentation on the functionality provided by comint mode, and
54;; the hooks available for customising it, see the comments below.
55;; For further information on the standard derived modes (shell,
56;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
57
58;; For hints on converting existing process modes (e.g., tex-mode,
59;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
60;; instead of shell-mode, see the notes at the end of this file.
be9b65ac 61
be9b65ac 62\f
b578f267
EN
63;; Brief Command Documentation:
64;;============================================================================
65;; Comint Mode Commands: (common to all derived modes, like shell & cmulisp
66;; mode)
67;;
361ecbf2
RS
68;; m-p comint-previous-input Cycle backwards in input history
69;; m-n comint-next-input Cycle forwards
b578f267
EN
70;; m-r comint-previous-matching-input Previous input matching a regexp
71;; m-s comint-next-matching-input Next input that matches
361ecbf2 72;; m-c-l comint-show-output Show last batch of process output
b578f267 73;; return comint-send-input
361ecbf2
RS
74;; c-d comint-delchar-or-maybe-eof Delete char unless at end of buff
75;; c-c c-a comint-bol-or-process-mark First time, move point to bol;
76;; second time, move to process-mark.
b578f267
EN
77;; c-c c-u comint-kill-input ^u
78;; c-c c-w backward-kill-word ^w
79;; c-c c-c comint-interrupt-subjob ^c
80;; c-c c-z comint-stop-subjob ^z
81;; c-c c-\ comint-quit-subjob ^\
82;; c-c c-o comint-kill-output Delete last batch of process output
83;; c-c c-r comint-show-output Show last batch of process output
84;; c-c c-l comint-dynamic-list-input-ring List input history
85;;
86;; Not bound by default in comint-mode (some are in shell mode)
87;; comint-run Run a program under comint-mode
88;; send-invisible Read a line w/o echo, and send to proc
89;; comint-dynamic-complete-filename Complete filename at point.
90;; comint-dynamic-complete-variable Complete variable name at point.
91;; comint-dynamic-list-filename-completions List completions in help buffer.
92;; comint-replace-by-expanded-filename Expand and complete filename at point;
93;; replace with expanded/completed name.
94;; comint-replace-by-expanded-history Expand history at point;
95;; replace with expanded name.
96;; comint-magic-space Expand history and add (a) space(s).
97;; comint-kill-subjob No mercy.
98;; comint-show-maximum-output Show as much output as possible.
99;; comint-continue-subjob Send CONT signal to buffer's process
100;; group. Useful if you accidentally
101;; suspend your process (with C-c C-z).
361ecbf2
RS
102;; comint-get-next-from-history Fetch successive input history lines
103;; comint-accumulate Combine lines to send them together
104;; as input.
105;; comint-goto-process-mark Move point to where process-mark is.
106;; comint-set-process-mark Set process-mark to point.
b578f267
EN
107
108;; comint-mode-hook is the comint mode hook. Basically for your keybindings.
be9b65ac 109
e5167999
ER
110;;; Code:
111
c9706a52 112(require 'ring)
be9b65ac 113\f
b578f267
EN
114;; Buffer Local Variables:
115;;============================================================================
116;; Comint mode buffer local variables:
107d7589
SM
117;; comint-prompt-regexp string comint-bol uses to match prompt
118;; comint-delimiter-argument-list list For delimiters and arguments
119;; comint-last-input-start marker Handy if inferior always echoes
120;; comint-last-input-end marker For comint-kill-output command
121;; comint-input-ring-size integer For the input history
122;; comint-input-ring ring mechanism
123;; comint-input-ring-index number ...
361ecbf2 124;; comint-save-input-ring-index number ...
107d7589
SM
125;; comint-input-autoexpand symbol ...
126;; comint-input-ignoredups boolean ...
127;; comint-last-input-match string ...
128;; comint-dynamic-complete-functions hook For the completion mechanism
129;; comint-completion-fignore list ...
2d4382e5 130;; comint-file-name-chars string ...
107d7589
SM
131;; comint-file-name-quote-list list ...
132;; comint-get-old-input function Hooks for specific
133;; comint-input-filter-functions hook process-in-a-buffer
134;; comint-output-filter-functions hook function modes.
d4321160 135;; comint-preoutput-filter-functions hook
107d7589
SM
136;; comint-input-filter function ...
137;; comint-input-sender function ...
138;; comint-eol-on-send boolean ...
139;; comint-process-echoes boolean ...
140;; comint-scroll-to-bottom-on-input symbol For scroll behavior
141;; comint-scroll-to-bottom-on-output symbol ...
142;; comint-scroll-show-maximum-output boolean ...
361ecbf2 143;; comint-accum-marker maker For comint-accumulate
b578f267
EN
144;;
145;; Comint mode non-buffer local variables:
107d7589
SM
146;; comint-completion-addsuffix boolean/cons For file name
147;; comint-completion-autolist boolean completion behavior
148;; comint-completion-recexact boolean ...
be9b65ac 149
ed366e87
RS
150(defgroup comint nil
151 "General command interpreter in a window stuff."
152 :group 'processes)
153
154(defgroup comint-completion nil
155 "Completion facilities in comint"
156 :group 'comint)
157
158(defgroup comint-source nil
159 "Source finding facilities in comint"
160 :prefix "comint-"
161 :group 'comint)
162
163
49116ac0
JB
164(defvar comint-prompt-regexp "^"
165 "Regexp to recognise prompts in the inferior process.
166Defaults to \"^\", the null string at BOL.
be9b65ac
DL
167
168Good choices:
d637fa56 169 Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
41752cf1
JB
170 Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
171 franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
49116ac0 172 kcl: \"^>+ *\"
d637fa56 173 shell: \"^[^#$%>\\n]*[#$%>] *\"
49116ac0 174 T: \"^>+ *\"
be9b65ac 175
49116ac0 176This is a good thing to set in mode hooks.")
be9b65ac 177
3ee91e68
RS
178(defvar comint-delimiter-argument-list ()
179 "List of characters to recognise as separate arguments in input.
180Strings comprising a character in this list will separate the arguments
181surrounding them, and also be regarded as arguments in their own right (unlike
182whitespace). See `comint-arguments'.
3f4b7c36 183Defaults to the empty list.
3ee91e68 184
3f4b7c36 185For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?;).
3ee91e68
RS
186
187This is a good thing to set in mode hooks.")
188
ed366e87 189(defcustom comint-input-autoexpand nil
3ee91e68 190 "*If non-nil, expand input command history references on completion.
fdb7791d 191This mirrors the optional behavior of tcsh (its autoexpand and histlit).
3ee91e68
RS
192
193If the value is `input', then the expansion is seen on input.
194If the value is `history', then the expansion is only when inserting
195into the buffer's input ring. See also `comint-magic-space' and
196`comint-dynamic-complete'.
197
ed366e87
RS
198This variable is buffer-local."
199 :type '(choice (const :tag "off" nil)
ed366e87 200 (const input)
0560c209
AS
201 (const history)
202 (other :tag "on" t))
ed366e87
RS
203 :group 'comint)
204
ed366e87 205(defcustom comint-input-ignoredups nil
3ee91e68 206 "*If non-nil, don't add input matching the last on the input ring.
fdb7791d 207This mirrors the optional behavior of bash.
3ee91e68 208
ed366e87
RS
209This variable is buffer-local."
210 :type 'boolean
211 :group 'comint)
3ee91e68 212
ed366e87 213(defcustom comint-input-ring-file-name nil
3ee91e68
RS
214 "*If non-nil, name of the file to read/write input history.
215See also `comint-read-input-ring' and `comint-write-input-ring'.
216
ed366e87
RS
217This variable is buffer-local, and is a good thing to set in mode hooks."
218 :type 'boolean
219 :group 'comint)
3ee91e68 220
ed366e87 221(defcustom comint-scroll-to-bottom-on-input nil
3ee91e68
RS
222 "*Controls whether input to interpreter causes window to scroll.
223If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
224If `this', scroll only the selected window.
225
91d75282 226The default is nil.
f4ef65c7 227
ed366e87
RS
228See `comint-preinput-scroll-to-bottom'. This variable is buffer-local."
229 :type '(choice (const :tag "off" nil)
230 (const t)
231 (const all)
232 (const this))
233 :group 'comint)
3ee91e68 234
ed366e87 235(defcustom comint-scroll-to-bottom-on-output nil
3ee91e68
RS
236 "*Controls whether interpreter output causes window to scroll.
237If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
238If `this', scroll only the selected window.
239If `others', scroll only those that are not the selected window.
91d75282
RS
240
241The default is nil.
f4ef65c7 242
3ee91e68 243See variable `comint-scroll-show-maximum-output' and function
ed366e87
RS
244`comint-postoutput-scroll-to-bottom'. This variable is buffer-local."
245 :type '(choice (const :tag "off" nil)
246 (const t)
247 (const all)
248 (const this)
249 (const others))
250 :group 'comint)
251
252(defcustom comint-scroll-show-maximum-output nil
3ee91e68
RS
253 "*Controls how interpreter output causes window to scroll.
254If non-nil, then show the maximum output when the window is scrolled.
91d75282 255
3ee91e68 256See variable `comint-scroll-to-bottom-on-output' and function
ed366e87
RS
257`comint-postoutput-scroll-to-bottom'. This variable is buffer-local."
258 :type 'boolean
259 :group 'comint)
91d75282 260
ed366e87 261(defcustom comint-buffer-maximum-size 1024
39a185a9
SM
262 "*The maximum size in lines for comint buffers.
263Comint buffers are truncated from the top to be no greater than this number, if
ed366e87
RS
264the function `comint-truncate-buffer' is on `comint-output-filter-functions'."
265 :type 'integer
266 :group 'comint)
39a185a9 267
3ee91e68 268(defvar comint-input-ring-size 32
49116ac0 269 "Size of input history ring.")
be9b65ac 270
ed366e87 271(defcustom comint-process-echoes nil
cccd719e 272 "*If non-nil, assume that the subprocess echoes any input.
8ae3bc9f 273If so, delete one copy of the input so that only one copy eventually
3ee91e68 274appears in the buffer.
8ae3bc9f 275
ed366e87
RS
276This variable is buffer-local."
277 :type 'boolean
278 :group 'comint)
8ae3bc9f 279
3a320e54 280;; AIX puts the name of the person being su'd to in front of the prompt.
9cc68f10 281;; kinit prints a prompt like `Password for devnull@GNU.ORG: '.
163b46fa
JWI
282;; ksu prints a prompt like `Kerberos password for devnull/root@GNU.ORG: '.
283;; ssh-add prints a prompt like `Enter passphrase: '.
ed366e87 284(defcustom comint-password-prompt-regexp
163b46fa 285 "\\(\\([Oo]ld \\|[Nn]ew \\|Kerberos \\|'s \\|login \\|^\\)[Pp]assword\\|pass phrase\\|Enter passphrase\\)\
db4a79ae 286\\( for [^@ \t\n]+@[^@ \t\n]+\\)?:\\s *\\'"
654d89d7 287 "*Regexp matching prompts for passwords in the inferior process.
ed366e87
RS
288This is used by `comint-watch-for-password-prompt'."
289 :type 'regexp
290 :group 'comint)
654d89d7 291
b578f267 292;; Here are the per-interpreter hooks.
49116ac0 293(defvar comint-get-old-input (function comint-get-old-input-default)
3ee91e68 294 "Function that returns old text in comint mode.
be9b65ac
DL
295This function is called when return is typed while the point is in old text.
296It returns the text to be submitted as process input. The default is
cccd719e
RS
297`comint-get-old-input-default', which grabs the current line, and strips off
298leading text matching `comint-prompt-regexp'.")
be9b65ac 299
1b421826
RS
300(defvar comint-dynamic-complete-functions
301 '(comint-replace-by-expanded-history comint-dynamic-complete-filename)
302 "List of functions called to perform completion.
303Functions should return non-nil if completion was performed.
304See also `comint-dynamic-complete'.
3ee91e68
RS
305
306This is a good thing to set in mode hooks.")
307
49116ac0
JB
308(defvar comint-input-filter
309 (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
310 "Predicate for filtering additions to input history.
3ee91e68
RS
311Takes one argument, the input. If non-nil, the input may be saved on the input
312history list. Default is to save anything that isn't all whitespace.")
313
fb9ab28a 314(defvar comint-input-filter-functions '()
1b421826
RS
315 "Functions to call before input is sent to the process.
316These functions get one argument, a string containing the text to send.
317
318This variable is buffer-local.")
319
fb9ab28a 320(defvar comint-output-filter-functions '(comint-postoutput-scroll-to-bottom)
3ee91e68 321 "Functions to call after output is inserted into the buffer.
c1da5c03 322One possible function is `comint-postoutput-scroll-to-bottom'.
107d7589
SM
323These functions get one argument, a string containing the text as originally
324inserted. Note that this might not be the same as the buffer contents between
325`comint-last-output-start' and the buffer's `process-mark', if other filter
326functions have already modified the buffer.
3ee91e68 327
d4321160
RS
328See also `comint-preoutput-filter-functions'.
329
3ee91e68 330This variable is buffer-local.")
49116ac0
JB
331
332(defvar comint-input-sender (function comint-simple-send)
333 "Function to actually send to PROCESS the STRING submitted by user.
cccd719e
RS
334Usually this is just `comint-simple-send', but if your mode needs to
335massage the input string, put a different function here.
336`comint-simple-send' just sends the string plus a newline.
337This is called from the user command `comint-send-input'.")
49116ac0 338
ed366e87 339(defcustom comint-eol-on-send t
3ee91e68 340 "*Non-nil means go to the end of the line before sending input.
ed366e87
RS
341See `comint-send-input'."
342 :type 'boolean
343 :group 'comint)
be9b65ac 344
ed366e87 345(defcustom comint-mode-hook '()
49116ac0 346 "Called upon entry into comint-mode
ed366e87
RS
347This is run before the process is cranked up."
348 :type 'hook
349 :group 'comint)
49116ac0 350
ed366e87 351(defcustom comint-exec-hook '()
cccd719e 352 "Called each time a process is exec'd by `comint-exec'.
49116ac0 353This is called after the process is cranked up. It is useful for things that
cccd719e
RS
354must be done each time a process is executed in a comint mode buffer (e.g.,
355`(process-kill-without-query)'). In contrast, the `comint-mode-hook' is only
ed366e87
RS
356executed once when the buffer is created."
357 :type 'hook
358 :group 'comint)
49116ac0
JB
359
360(defvar comint-mode-map nil)
be9b65ac 361
c9706a52 362(defvar comint-ptyp t
3ee91e68 363 "Non-nil if communications via pty; false if by pipe. Buffer local.
5ef2f81f 364This is to work around a bug in Emacs process signaling.")
c9706a52 365
0bcb5285 366(defvar comint-input-ring nil)
e6dfdce5
RS
367(defvar comint-last-input-start)
368(defvar comint-last-input-end)
7d5d472e 369(defvar comint-last-output-start)
3ee91e68
RS
370(defvar comint-input-ring-index nil
371 "Index of last matched history element.")
372(defvar comint-matching-input-from-input-string ""
373 "Input previously used to match input history.")
361ecbf2
RS
374(defvar comint-save-input-ring-index
375 "Last input ring index which you copied.
376This is to support the command \\[comint-get-next-from-history].")
377
378(defvar comint-accum-marker nil
379 "Non-nil if you are accumulating input lines to send as input together.
380The command \\[comint-accumulate] sets this.")
21d9bf27
RS
381
382(put 'comint-replace-by-expanded-history 'menu-enable 'comint-input-autoexpand)
c9706a52 383(put 'comint-input-ring 'permanent-local t)
3ee91e68 384(put 'comint-input-ring-index 'permanent-local t)
361ecbf2 385(put 'comint-save-input-ring-index 'permanent-local t)
3ee91e68 386(put 'comint-input-autoexpand 'permanent-local t)
fb9ab28a
RS
387(put 'comint-input-filter-functions 'permanent-local t)
388(put 'comint-output-filter-functions 'permanent-local t)
d4321160 389(put 'comint-preoutput-filter-functions 'permanent-local t)
3ee91e68
RS
390(put 'comint-scroll-to-bottom-on-input 'permanent-local t)
391(put 'comint-scroll-to-bottom-on-output 'permanent-local t)
392(put 'comint-scroll-show-maximum-output 'permanent-local t)
c9706a52 393(put 'comint-ptyp 'permanent-local t)
e6dfdce5 394
158cfdd2
RS
395(put 'comint-mode 'mode-class 'special)
396
be9b65ac
DL
397(defun comint-mode ()
398 "Major mode for interacting with an inferior interpreter.
399Interpreter name is same as buffer name, sans the asterisks.
400Return at end of buffer sends line as input.
401Return not at end copies rest of line to end and sends it.
cccd719e 402Setting variable `comint-eol-on-send' means jump to the end of the line
49116ac0 403before submitting new input.
be9b65ac 404
3ee91e68
RS
405This mode is customised to create major modes such as Inferior Lisp
406mode, Shell mode, etc. This can be done by setting the hooks
fb9ab28a 407`comint-input-filter-functions', `comint-input-filter', `comint-input-sender'
3ee91e68 408and `comint-get-old-input' to appropriate functions, and the variable
cccd719e 409`comint-prompt-regexp' to the appropriate regular expression.
be9b65ac 410
cccd719e 411An input history is maintained of size `comint-input-ring-size', and
3ee91e68
RS
412can be accessed with the commands \\[comint-next-input], \\[comint-previous-input], and \\[comint-dynamic-list-input-ring].
413Input ring history expansion can be achieved with the commands
414\\[comint-replace-by-expanded-history] or \\[comint-magic-space].
415Input ring expansion is controlled by the variable `comint-input-autoexpand',
416and addition is controlled by the variable `comint-input-ignoredups'.
417
cccd719e 418Commands with no default key bindings include `send-invisible',
21d9bf27 419`comint-dynamic-complete', `comint-dynamic-list-filename-completions', and
3ee91e68
RS
420`comint-magic-space'.
421
422Input to, and output from, the subprocess can cause the window to scroll to
fb9ab28a 423the end of the buffer. See variables `comint-output-filter-functions',
d4321160
RS
424`comint-preoutput-filter-functions', `comint-scroll-to-bottom-on-input',
425and `comint-scroll-to-bottom-on-output'.
be9b65ac
DL
426
427If you accidentally suspend your process, use \\[comint-continue-subjob]
428to continue it.
429
430\\{comint-mode-map}
431
3ee91e68 432Entry to this mode runs the hooks on `comint-mode-hook'."
be9b65ac 433 (interactive)
3ee91e68
RS
434 ;; Do not remove this. All major modes must do this.
435 (kill-all-local-variables)
436 (setq major-mode 'comint-mode)
437 (setq mode-name "Comint")
baae3c4e 438 (setq mode-line-process '(":%s"))
3ee91e68
RS
439 (use-local-map comint-mode-map)
440 (make-local-variable 'comint-last-input-start)
441 (setq comint-last-input-start (make-marker))
a9a6f83f 442 (set-marker comint-last-input-start (point-min))
3ee91e68
RS
443 (make-local-variable 'comint-last-input-end)
444 (setq comint-last-input-end (make-marker))
a9a6f83f 445 (set-marker comint-last-input-end (point-min))
3ee91e68
RS
446 (make-local-variable 'comint-last-output-start)
447 (setq comint-last-output-start (make-marker))
448 (make-local-variable 'comint-prompt-regexp) ; Don't set; default
449 (make-local-variable 'comint-input-ring-size) ; ...to global val.
450 (make-local-variable 'comint-input-ring)
451 (make-local-variable 'comint-input-ring-file-name)
452 (or (and (boundp 'comint-input-ring) comint-input-ring)
453 (setq comint-input-ring (make-ring comint-input-ring-size)))
454 (make-local-variable 'comint-input-ring-index)
361ecbf2 455 (make-local-variable 'comint-save-input-ring-index)
3ee91e68
RS
456 (or (and (boundp 'comint-input-ring-index) comint-input-ring-index)
457 (setq comint-input-ring-index nil))
361ecbf2
RS
458 (or (and (boundp 'comint-save-input-ring-index) comint-save-input-ring-index)
459 (setq comint-save-input-ring-index nil))
3ee91e68
RS
460 (make-local-variable 'comint-matching-input-from-input-string)
461 (make-local-variable 'comint-input-autoexpand)
462 (make-local-variable 'comint-input-ignoredups)
463 (make-local-variable 'comint-delimiter-argument-list)
155fd027 464 (make-local-hook 'comint-dynamic-complete-functions)
497513ad 465 (make-local-variable 'comint-completion-fignore)
3ee91e68 466 (make-local-variable 'comint-get-old-input)
155fd027 467 (make-local-hook 'comint-input-filter-functions)
3ee91e68
RS
468 (make-local-variable 'comint-input-filter)
469 (make-local-variable 'comint-input-sender)
470 (make-local-variable 'comint-eol-on-send)
471 (make-local-variable 'comint-scroll-to-bottom-on-input)
472 (make-local-variable 'comint-scroll-to-bottom-on-output)
473 (make-local-variable 'comint-scroll-show-maximum-output)
d2b251aa
SM
474 (make-local-hook 'pre-command-hook)
475 (add-hook 'pre-command-hook 'comint-preinput-scroll-to-bottom t t)
155fd027 476 (make-local-hook 'comint-output-filter-functions)
d2b251aa 477 (make-local-hook 'comint-exec-hook)
3ee91e68 478 (make-local-variable 'comint-ptyp)
3ee91e68 479 (make-local-variable 'comint-process-echoes)
2d4382e5 480 (make-local-variable 'comint-file-name-chars)
59f36b08 481 (make-local-variable 'comint-file-name-quote-list)
361ecbf2
RS
482 (make-local-variable 'comint-accum-marker)
483 (setq comint-accum-marker (make-marker))
484 (set-marker comint-accum-marker nil)
3ee91e68 485 (run-hooks 'comint-mode-hook))
be9b65ac 486
49116ac0
JB
487(if comint-mode-map
488 nil
3ee91e68 489 ;; Keys:
49116ac0
JB
490 (setq comint-mode-map (make-sparse-keymap))
491 (define-key comint-mode-map "\ep" 'comint-previous-input)
492 (define-key comint-mode-map "\en" 'comint-next-input)
cf7c8463
RS
493 (define-key comint-mode-map [C-up] 'comint-previous-input)
494 (define-key comint-mode-map [C-down] 'comint-next-input)
0c5c1f34
RS
495 (define-key comint-mode-map "\er" 'comint-previous-matching-input)
496 (define-key comint-mode-map "\es" 'comint-next-matching-input)
fb597fe8
RS
497 (define-key comint-mode-map [?\C-c ?\M-r] 'comint-previous-matching-input-from-input)
498 (define-key comint-mode-map [?\C-c ?\M-s] 'comint-next-matching-input-from-input)
d637fa56 499 (define-key comint-mode-map "\e\C-l" 'comint-show-output)
49116ac0
JB
500 (define-key comint-mode-map "\C-m" 'comint-send-input)
501 (define-key comint-mode-map "\C-d" 'comint-delchar-or-maybe-eof)
361ecbf2 502 (define-key comint-mode-map "\C-c " 'comint-accumulate)
fb597fe8 503 (define-key comint-mode-map "\C-c\C-x" 'comint-get-next-from-history)
361ecbf2 504 (define-key comint-mode-map "\C-c\C-a" 'comint-bol-or-process-mark)
49116ac0
JB
505 (define-key comint-mode-map "\C-c\C-u" 'comint-kill-input)
506 (define-key comint-mode-map "\C-c\C-w" 'backward-kill-word)
507 (define-key comint-mode-map "\C-c\C-c" 'comint-interrupt-subjob)
508 (define-key comint-mode-map "\C-c\C-z" 'comint-stop-subjob)
509 (define-key comint-mode-map "\C-c\C-\\" 'comint-quit-subjob)
3ee91e68 510 (define-key comint-mode-map "\C-c\C-m" 'comint-copy-old-input)
49116ac0 511 (define-key comint-mode-map "\C-c\C-o" 'comint-kill-output)
49116ac0 512 (define-key comint-mode-map "\C-c\C-r" 'comint-show-output)
3ee91e68 513 (define-key comint-mode-map "\C-c\C-e" 'comint-show-maximum-output)
4bec19b2 514 (define-key comint-mode-map "\C-c\C-l" 'comint-dynamic-list-input-ring)
1de80a34 515 (define-key comint-mode-map "\C-c\C-n" 'comint-next-prompt)
3ee91e68 516 (define-key comint-mode-map "\C-c\C-p" 'comint-previous-prompt)
1de80a34 517 (define-key comint-mode-map "\C-c\C-d" 'comint-send-eof)
3ee91e68
RS
518 ;; Menu bars:
519 ;; completion:
520 (define-key comint-mode-map [menu-bar completion]
dcab7fbd 521 (cons "Complete" (make-sparse-keymap "Complete")))
3ee91e68
RS
522 (define-key comint-mode-map [menu-bar completion complete-expand]
523 '("Expand File Name" . comint-replace-by-expanded-filename))
524 (define-key comint-mode-map [menu-bar completion complete-listing]
525 '("File Completion Listing" . comint-dynamic-list-filename-completions))
3ee91e68
RS
526 (define-key comint-mode-map [menu-bar completion complete-file]
527 '("Complete File Name" . comint-dynamic-complete-filename))
528 (define-key comint-mode-map [menu-bar completion complete]
529 '("Complete Before Point" . comint-dynamic-complete))
530 ;; Input history:
5c07a950 531 (define-key comint-mode-map [menu-bar inout]
dcab7fbd 532 (cons "In/Out" (make-sparse-keymap "In/Out")))
5c07a950 533 (define-key comint-mode-map [menu-bar inout kill-output]
dcab7fbd 534 '("Kill Current Output Group" . comint-kill-output))
5c07a950 535 (define-key comint-mode-map [menu-bar inout next-prompt]
dcab7fbd 536 '("Forward Output Group" . comint-next-prompt))
5c07a950 537 (define-key comint-mode-map [menu-bar inout previous-prompt]
dcab7fbd 538 '("Backward Output Group" . comint-previous-prompt))
5c07a950 539 (define-key comint-mode-map [menu-bar inout show-maximum-output]
dcab7fbd 540 '("Show Maximum Output" . comint-show-maximum-output))
5c07a950 541 (define-key comint-mode-map [menu-bar inout show-output]
dcab7fbd 542 '("Show Current Output Group" . comint-show-output))
5c07a950 543 (define-key comint-mode-map [menu-bar inout kill-input]
3ee91e68 544 '("Kill Current Input" . comint-kill-input))
5c07a950 545 (define-key comint-mode-map [menu-bar inout copy-input]
3ee91e68 546 '("Copy Old Input" . comint-copy-old-input))
5c07a950 547 (define-key comint-mode-map [menu-bar inout forward-matching-history]
dcab7fbd 548 '("Forward Matching Input..." . comint-forward-matching-input))
5c07a950 549 (define-key comint-mode-map [menu-bar inout backward-matching-history]
dcab7fbd 550 '("Backward Matching Input..." . comint-backward-matching-input))
5c07a950 551 (define-key comint-mode-map [menu-bar inout next-matching-history]
3ee91e68 552 '("Next Matching Input..." . comint-next-matching-input))
5c07a950 553 (define-key comint-mode-map [menu-bar inout previous-matching-history]
3ee91e68 554 '("Previous Matching Input..." . comint-previous-matching-input))
5c07a950 555 (define-key comint-mode-map [menu-bar inout next-matching-history-from-input]
3ee91e68 556 '("Next Matching Current Input" . comint-next-matching-input-from-input))
5c07a950 557 (define-key comint-mode-map [menu-bar inout previous-matching-history-from-input]
3ee91e68 558 '("Previous Matching Current Input" . comint-previous-matching-input-from-input))
5c07a950 559 (define-key comint-mode-map [menu-bar inout next-history]
3ee91e68 560 '("Next Input" . comint-next-input))
5c07a950 561 (define-key comint-mode-map [menu-bar inout previous-history]
3ee91e68 562 '("Previous Input" . comint-previous-input))
5c07a950 563 (define-key comint-mode-map [menu-bar inout list-history]
3ee91e68 564 '("List Input History" . comint-dynamic-list-input-ring))
5c07a950 565 (define-key comint-mode-map [menu-bar inout expand-history]
3ee91e68 566 '("Expand History Before Point" . comint-replace-by-expanded-history))
3ee91e68
RS
567 ;; Signals
568 (define-key comint-mode-map [menu-bar signals]
569 (cons "Signals" (make-sparse-keymap "Signals")))
570 (define-key comint-mode-map [menu-bar signals eof]
571 '("EOF" . comint-send-eof))
572 (define-key comint-mode-map [menu-bar signals kill]
573 '("KILL" . comint-kill-subjob))
574 (define-key comint-mode-map [menu-bar signals quit]
575 '("QUIT" . comint-quit-subjob))
576 (define-key comint-mode-map [menu-bar signals cont]
577 '("CONT" . comint-continue-subjob))
578 (define-key comint-mode-map [menu-bar signals stop]
579 '("STOP" . comint-stop-subjob))
580 (define-key comint-mode-map [menu-bar signals break]
581 '("BREAK" . comint-interrupt-subjob))
582 ;; Put them in the menu bar:
5c07a950 583 (setq menu-bar-final-items (append '(completion inout signals)
3ee91e68 584 menu-bar-final-items))
49116ac0
JB
585 )
586
49116ac0 587(defun comint-check-proc (buffer)
3ee91e68 588 "Return t if there is a living process associated w/buffer BUFFER.
1a4086d2 589Living means the status is `open', `run', or `stop'.
cccd719e 590BUFFER can be either a buffer or the name of one."
49116ac0 591 (let ((proc (get-buffer-process buffer)))
1a4086d2 592 (and proc (memq (process-status proc) '(open run stop)))))
be9b65ac 593
87206843 594;;;###autoload
be9b65ac 595(defun make-comint (name program &optional startfile &rest switches)
14a08856
RM
596 "Make a comint process NAME in a buffer, running PROGRAM.
597The name of the buffer is made by surrounding NAME with `*'s.
1a4086d2
RS
598PROGRAM should be either a string denoting an executable program to create
599via `start-process', or a cons pair of the form (HOST . SERVICE) denoting a TCP
600connection to be opened via `open-network-stream'. If there is already a
601running process in that buffer, it is not restarted. Optional third arg
602STARTFILE is the name of a file to send the contents of to the process.
603
604If PROGRAM is a string, any more args are arguments to PROGRAM."
af37b2e6
RS
605 (or (fboundp 'start-process)
606 (error "Multi-processing is not supported for this system"))
49116ac0 607 (let ((buffer (get-buffer-create (concat "*" name "*"))))
be9b65ac 608 ;; If no process, or nuked process, crank up a new one and put buffer in
14a08856 609 ;; comint mode. Otherwise, leave buffer and existing process alone.
1ff6cf10 610 (cond ((not (comint-check-proc buffer))
49116ac0 611 (save-excursion
be9b65ac
DL
612 (set-buffer buffer)
613 (comint-mode)) ; Install local vars, mode, keymap, ...
614 (comint-exec buffer name program startfile switches)))
615 buffer))
616
87206843 617;;;###autoload
21d9bf27
RS
618(defun comint-run (program)
619 "Run PROGRAM in a comint buffer and switch to it.
620The buffer name is made by surrounding the file name of PROGRAM with `*'s.
621The file name is used to make a symbol name, such as `comint-sh-hook', and any
622hooks on this symbol are run in the buffer.
623See `make-comint' and `comint-exec'."
624 (interactive "sRun program: ")
625 (let ((name (file-name-nondirectory program)))
626 (switch-to-buffer (make-comint name program))
627 (run-hooks (intern-soft (concat "comint-" name "-hook")))))
628
be9b65ac 629(defun comint-exec (buffer name command startfile switches)
cccd719e 630 "Start up a process in buffer BUFFER for comint modes.
14a08856 631Blasts any old process running in the buffer. Doesn't set the buffer mode.
49116ac0 632You can use this to cheaply run a series of processes in the same comint
cccd719e 633buffer. The hook `comint-exec-hook' is run after each exec."
be9b65ac
DL
634 (save-excursion
635 (set-buffer buffer)
636 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
637 (if proc (delete-process proc)))
638 ;; Crank up a new process
1a4086d2
RS
639 (let ((proc
640 (if (consp command)
641 (open-network-stream name buffer (car command) (cdr command))
642 (comint-exec-1 name buffer command switches))))
3ee91e68 643 (set-process-filter proc 'comint-output-filter)
49116ac0
JB
644 (make-local-variable 'comint-ptyp)
645 (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
be9b65ac 646 ;; Jump to the end, and set the process mark.
49116ac0 647 (goto-char (point-max))
87ef29fd 648 (set-marker (process-mark proc) (point))
be9b65ac
DL
649 ;; Feed it the startfile.
650 (cond (startfile
651 ;;This is guaranteed to wait long enough
652 ;;but has bad results if the comint does not prompt at all
653 ;; (while (= size (buffer-size))
654 ;; (sleep-for 1))
655 ;;I hope 1 second is enough!
656 (sleep-for 1)
657 (goto-char (point-max))
658 (insert-file-contents startfile)
659 (setq startfile (buffer-substring (point) (point-max)))
660 (delete-region (point) (point-max))
49116ac0
JB
661 (comint-send-string proc startfile)))
662 (run-hooks 'comint-exec-hook)
87ef29fd 663 buffer)))
be9b65ac 664
b578f267
EN
665;; This auxiliary function cranks up the process for comint-exec in
666;; the appropriate environment.
be9b65ac
DL
667
668(defun comint-exec-1 (name buffer command switches)
1b421826 669 (let ((process-environment
1f9e761d 670 (nconc
a4ab7e69
RS
671 ;; If using termcap, we specify `emacs' as the terminal type
672 ;; because that lets us specify a width.
36990caa 673 ;; If using terminfo, we specify `dumb' because that is
a4ab7e69
RS
674 ;; a defined terminal type. `emacs' is not a defined terminal type
675 ;; and there is no way for us to define it here.
676 ;; Some programs that use terminfo get very confused
677 ;; if TERM is not a valid terminal type.
1f9e761d 678 (if (and (boundp 'system-uses-terminfo) system-uses-terminfo)
4a11114d 679 (list "TERM=dumb" "TERMCAP="
1f9e761d 680 (format "COLUMNS=%d" (frame-width)))
f3b0a431 681 (list "TERM=emacs"
9dbfa8cf 682 (format "TERMCAP=emacs:co#%d:tc=unknown:" (frame-width))))
f3b0a431 683 (if (getenv "EMACS") nil (list "EMACS=t"))
1347899b
RS
684 process-environment))
685 (default-directory
e1d409fe 686 (if (file-accessible-directory-p default-directory)
1347899b 687 default-directory
33ba5485
RS
688 (char-to-string directory-sep-char)))
689 proc decoding encoding changed)
690 (setq proc (apply 'start-process name buffer command switches))
691 (let ((coding-systems (process-coding-system proc)))
692 (setq decoding (car coding-systems)
693 encoding (cdr coding-systems)))
694 ;; If start-process decided to use some coding system for decoding
695 ;; data sent form the process and the coding system doesn't
696 ;; specify EOL conversion, we had better convert CRLF to LF.
697 (if (vectorp (coding-system-eol-type decoding))
698 (setq decoding (coding-system-change-eol-conversion decoding 'dos)
699 changed t))
700 ;; Even if start-process left the coding system for encoding data
701 ;; sent from the process undecided, we had better use the same one
702 ;; as what we use for decoding. But, we should suppress EOL
703 ;; conversion.
704 (if (and decoding (not encoding))
705 (setq encoding (coding-system-change-eol-conversion decoding 'unix)
706 changed t))
707 (if changed
708 (set-process-coding-system proc decoding encoding))
709 proc))
be9b65ac 710\f
b578f267
EN
711;; Input history processing in a buffer
712;; ===========================================================================
713;; Useful input history functions, courtesy of the Ergo group.
714
715;; Eleven commands:
716;; comint-dynamic-list-input-ring List history in help buffer.
717;; comint-previous-input Previous input...
718;; comint-previous-matching-input ...matching a string.
719;; comint-previous-matching-input-from-input ... matching the current input.
720;; comint-next-input Next input...
721;; comint-next-matching-input ...matching a string.
722;; comint-next-matching-input-from-input ... matching the current input.
723;; comint-backward-matching-input Backwards input...
724;; comint-forward-matching-input ...matching a string.
725;; comint-replace-by-expanded-history Expand history at point;
726;; replace with expanded history.
727;; comint-magic-space Expand history and insert space.
728;;
729;; Three functions:
730;; comint-read-input-ring Read into comint-input-ring...
731;; comint-write-input-ring Write to comint-input-ring-file-name.
732;; comint-replace-by-expanded-history-before-point Workhorse function.
3ee91e68 733
d637fa56 734(defun comint-read-input-ring (&optional silent)
3ee91e68
RS
735 "Sets the buffer's `comint-input-ring' from a history file.
736The name of the file is given by the variable `comint-input-ring-file-name'.
737The history ring is of size `comint-input-ring-size', regardless of file size.
738If `comint-input-ring-file-name' is nil this function does nothing.
739
d637fa56
RS
740If the optional argument SILENT is non-nil, we say nothing about a
741failure to read the history file.
3ee91e68 742
d637fa56
RS
743This function is useful for major mode commands and mode hooks.
744
745The structure of the history file should be one input command per line,
746with the most recent command last.
3ee91e68 747See also `comint-input-ignoredups' and `comint-write-input-ring'."
07ccf0bc
RS
748 (cond ((or (null comint-input-ring-file-name)
749 (equal comint-input-ring-file-name ""))
3ee91e68
RS
750 nil)
751 ((not (file-readable-p comint-input-ring-file-name))
d637fa56
RS
752 (or silent
753 (message "Cannot read history file %s"
754 comint-input-ring-file-name)))
3ee91e68 755 (t
dc0825db
RS
756 (let ((history-buf (get-buffer-create " *temp*"))
757 (file comint-input-ring-file-name)
758 (count 0)
3ee91e68 759 (ring (make-ring comint-input-ring-size)))
dc0825db
RS
760 (unwind-protect
761 (save-excursion
762 (set-buffer history-buf)
3ee91e68 763 (widen)
dc0825db
RS
764 (erase-buffer)
765 (insert-file-contents file)
766 ;; Save restriction in case file is already visited...
767 ;; Watch for those date stamps in history files!
768 (goto-char (point-max))
769 (while (and (< count comint-input-ring-size)
770 (re-search-backward "^[ \t]*\\([^#\n].*\\)[ \t]*$"
771 nil t))
3ee91e68
RS
772 (let ((history (buffer-substring (match-beginning 1)
773 (match-end 1))))
774 (if (or (null comint-input-ignoredups)
775 (ring-empty-p ring)
776 (not (string-equal (ring-ref ring 0) history)))
dc0825db
RS
777 (ring-insert-at-beginning ring history)))
778 (setq count (1+ count))))
779 (kill-buffer history-buf))
3ee91e68
RS
780 (setq comint-input-ring ring
781 comint-input-ring-index nil)))))
782
783(defun comint-write-input-ring ()
784 "Writes the buffer's `comint-input-ring' to a history file.
785The name of the file is given by the variable `comint-input-ring-file-name'.
786The original contents of the file are lost if `comint-input-ring' is not empty.
787If `comint-input-ring-file-name' is nil this function does nothing.
788
789Useful within process sentinels.
790
791See also `comint-read-input-ring'."
792 (cond ((or (null comint-input-ring-file-name)
07ccf0bc 793 (equal comint-input-ring-file-name "")
3ee91e68
RS
794 (null comint-input-ring) (ring-empty-p comint-input-ring))
795 nil)
796 ((not (file-writable-p comint-input-ring-file-name))
797 (message "Cannot write history file %s" comint-input-ring-file-name))
798 (t
799 (let* ((history-buf (get-buffer-create " *Temp Input History*"))
800 (ring comint-input-ring)
801 (file comint-input-ring-file-name)
802 (index (ring-length ring)))
803 ;; Write it all out into a buffer first. Much faster, but messier,
804 ;; than writing it one line at a time.
805 (save-excursion
806 (set-buffer history-buf)
807 (erase-buffer)
808 (while (> index 0)
809 (setq index (1- index))
810 (insert (ring-ref ring index) ?\n))
811 (write-region (buffer-string) nil file nil 'no-message)
812 (kill-buffer nil))))))
813
814
815(defun comint-dynamic-list-input-ring ()
816 "List in help buffer the buffer's input history."
817 (interactive)
818 (if (or (not (ring-p comint-input-ring))
819 (ring-empty-p comint-input-ring))
820 (message "No history")
821 (let ((history nil)
822 (history-buffer " *Input History*")
823 (index (1- (ring-length comint-input-ring)))
824 (conf (current-window-configuration)))
825 ;; We have to build up a list ourselves from the ring vector.
826 (while (>= index 0)
827 (setq history (cons (ring-ref comint-input-ring index) history)
828 index (1- index)))
829 ;; Change "completion" to "history reference"
830 ;; to make the display accurate.
831 (with-output-to-temp-buffer history-buffer
832 (display-completion-list history)
833 (set-buffer history-buffer)
834 (forward-line 3)
835 (while (search-backward "completion" nil 'move)
836 (replace-match "history reference")))
837 (sit-for 0)
838 (message "Hit space to flush")
839 (let ((ch (read-event)))
840 (if (eq ch ?\ )
841 (set-window-configuration conf)
842 (setq unread-command-events (list ch)))))))
843
844
845(defun comint-regexp-arg (prompt)
846 ;; Return list of regexp and prefix arg using PROMPT.
9f8ac7f9 847 (let* (;; Don't clobber this.
3ee91e68
RS
848 (last-command last-command)
849 (regexp (read-from-minibuffer prompt nil nil nil
850 'minibuffer-history-search-history)))
851 (list (if (string-equal regexp "")
852 (setcar minibuffer-history-search-history
853 (nth 1 minibuffer-history-search-history))
854 regexp)
855 (prefix-numeric-value current-prefix-arg))))
856
857(defun comint-search-arg (arg)
858 ;; First make sure there is a ring and that we are after the process mark
859 (cond ((not (comint-after-pmark-p))
860 (error "Not at command line"))
861 ((or (null comint-input-ring)
862 (ring-empty-p comint-input-ring))
863 (error "Empty input ring"))
864 ((zerop arg)
865 ;; arg of zero resets search from beginning, and uses arg of 1
866 (setq comint-input-ring-index nil)
867 1)
868 (t
869 arg)))
870
871(defun comint-search-start (arg)
872 ;; Index to start a directional search, starting at comint-input-ring-index
873 (if comint-input-ring-index
874 ;; If a search is running, offset by 1 in direction of arg
875 (mod (+ comint-input-ring-index (if (> arg 0) 1 -1))
876 (ring-length comint-input-ring))
877 ;; For a new search, start from beginning or end, as appropriate
878 (if (>= arg 0)
879 0 ; First elt for forward search
880 (1- (ring-length comint-input-ring))))) ; Last elt for backward search
881
882(defun comint-previous-input-string (arg)
883 "Return the string ARG places along the input ring.
884Moves relative to `comint-input-ring-index'."
885 (ring-ref comint-input-ring (if comint-input-ring-index
886 (mod (+ arg comint-input-ring-index)
887 (ring-length comint-input-ring))
888 arg)))
be9b65ac
DL
889
890(defun comint-previous-input (arg)
891 "Cycle backwards through input history."
892 (interactive "*p")
3ee91e68 893 (comint-previous-matching-input "." arg))
1586b965 894
be9b65ac
DL
895(defun comint-next-input (arg)
896 "Cycle forwards through input history."
897 (interactive "*p")
898 (comint-previous-input (- arg)))
899
3ee91e68
RS
900(defun comint-previous-matching-input-string (regexp arg)
901 "Return the string matching REGEXP ARG places along the input ring.
902Moves relative to `comint-input-ring-index'."
903 (let* ((pos (comint-previous-matching-input-string-position regexp arg)))
904 (if pos (ring-ref comint-input-ring pos))))
905
906(defun comint-previous-matching-input-string-position (regexp arg &optional start)
907 "Return the index matching REGEXP ARG places along the input ring.
908Moves relative to START, or `comint-input-ring-index'."
909 (if (or (not (ring-p comint-input-ring))
910 (ring-empty-p comint-input-ring))
911 (error "No history"))
912 (let* ((len (ring-length comint-input-ring))
913 (motion (if (> arg 0) 1 -1))
914 (n (mod (- (or start (comint-search-start arg)) motion) len))
915 (tried-each-ring-item nil)
916 (prev nil))
917 ;; Do the whole search as many times as the argument says.
918 (while (and (/= arg 0) (not tried-each-ring-item))
919 ;; Step once.
920 (setq prev n
921 n (mod (+ n motion) len))
922 ;; If we haven't reached a match, step some more.
923 (while (and (< n len) (not tried-each-ring-item)
924 (not (string-match regexp (ring-ref comint-input-ring n))))
925 (setq n (mod (+ n motion) len)
926 ;; If we have gone all the way around in this search.
927 tried-each-ring-item (= n prev)))
928 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
929 ;; Now that we know which ring element to use, if we found it, return that.
930 (if (string-match regexp (ring-ref comint-input-ring n))
931 n)))
932
0c5c1f34
RS
933(defun comint-previous-matching-input (regexp arg)
934 "Search backwards through input history for match for REGEXP.
935\(Previous history elements are earlier commands.)
936With prefix argument N, search for Nth previous match.
937If N is negative, find the next or Nth next match."
3ee91e68
RS
938 (interactive (comint-regexp-arg "Previous input matching (regexp): "))
939 (setq arg (comint-search-arg arg))
940 (let ((pos (comint-previous-matching-input-string-position regexp arg)))
941 ;; Has a match been found?
942 (if (null pos)
943 (error "Not found")
944 (setq comint-input-ring-index pos)
945 (message "History item: %d" (1+ pos))
946 (delete-region
947 ;; Can't use kill-region as it sets this-command
361ecbf2
RS
948 (or (marker-position comint-accum-marker)
949 (process-mark (get-buffer-process (current-buffer))))
950 (point))
3ee91e68 951 (insert (ring-ref comint-input-ring pos)))))
0c5c1f34
RS
952
953(defun comint-next-matching-input (regexp arg)
954 "Search forwards through input history for match for REGEXP.
955\(Later history elements are more recent commands.)
956With prefix argument N, search for Nth following match.
957If N is negative, find the previous or Nth previous match."
3ee91e68 958 (interactive (comint-regexp-arg "Next input matching (regexp): "))
0c5c1f34 959 (comint-previous-matching-input regexp (- arg)))
be9b65ac 960
3ee91e68
RS
961(defun comint-previous-matching-input-from-input (arg)
962 "Search backwards through input history for match for current input.
963\(Previous history elements are earlier commands.)
964With prefix argument N, search for Nth previous match.
3f849529 965If N is negative, search forwards for the -Nth following match."
3ee91e68
RS
966 (interactive "p")
967 (if (not (memq last-command '(comint-previous-matching-input-from-input
968 comint-next-matching-input-from-input)))
969 ;; Starting a new search
970 (setq comint-matching-input-from-input-string
971 (buffer-substring
361ecbf2
RS
972 (or (marker-position comint-accum-marker)
973 (process-mark (get-buffer-process (current-buffer))))
3ee91e68
RS
974 (point))
975 comint-input-ring-index nil))
976 (comint-previous-matching-input
977 (concat "^" (regexp-quote comint-matching-input-from-input-string))
978 arg))
979
980(defun comint-next-matching-input-from-input (arg)
981 "Search forwards through input history for match for current input.
3f849529
RS
982\(Following history elements are more recent commands.)
983With prefix argument N, search for Nth following match.
984If N is negative, search backwards for the -Nth previous match."
3ee91e68
RS
985 (interactive "p")
986 (comint-previous-matching-input-from-input (- arg)))
987
988
17ac4966 989(defun comint-replace-by-expanded-history (&optional silent start)
3ee91e68 990 "Expand input command history references before point.
1b421826
RS
991Expansion is dependent on the value of `comint-input-autoexpand'.
992
3ee91e68
RS
993This function depends on the buffer's idea of the input history, which may not
994match the command interpreter's idea, assuming it has one.
995
996Assumes history syntax is like typical Un*x shells'. However, since emacs
997cannot know the interpreter's idea of input line numbers, assuming it has one,
998it cannot expand absolute input line number references.
999
d637fa56
RS
1000If the optional argument SILENT is non-nil, never complain
1001even if history reference seems erroneous.
1002
17ac4966
RS
1003If the optional argument START is non-nil, that specifies the
1004start of the text to scan for history references, rather
1005than the logical beginning of line.
1006
1b421826
RS
1007See `comint-magic-space' and `comint-replace-by-expanded-history-before-point'.
1008
1009Returns t if successful."
3ee91e68 1010 (interactive)
1b421826 1011 (if (and comint-input-autoexpand
107d7589 1012 (string-match "!\\|^\\^" (funcall comint-get-old-input))
8d3d2a0c
KH
1013 (save-excursion (beginning-of-line)
1014 (looking-at comint-prompt-regexp)))
1b421826
RS
1015 ;; Looks like there might be history references in the command.
1016 (let ((previous-modified-tick (buffer-modified-tick)))
17ac4966 1017 (comint-replace-by-expanded-history-before-point silent start)
1b421826
RS
1018 (/= previous-modified-tick (buffer-modified-tick)))))
1019
1020
17ac4966 1021(defun comint-replace-by-expanded-history-before-point (silent &optional start)
1b421826 1022 "Expand directory stack reference before point.
17ac4966
RS
1023See `comint-replace-by-expanded-history'. Returns t if successful.
1024
1025If the optional argument START is non-nil, that specifies the
1026start of the text to scan for history references, rather
1027than the logical beginning of line."
3ee91e68
RS
1028 (save-excursion
1029 (let ((toend (- (save-excursion (end-of-line nil) (point)) (point)))
17ac4966 1030 (start (or start (progn (comint-bol nil) (point)))))
d637fa56
RS
1031 (while (progn
1032 (skip-chars-forward "^!^"
1033 (save-excursion
1034 (end-of-line nil) (- (point) toend)))
1035 (< (point)
1036 (save-excursion
1037 (end-of-line nil) (- (point) toend))))
3ee91e68
RS
1038 ;; This seems a bit complex. We look for references such as !!, !-num,
1039 ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
1040 ;; If that wasn't enough, the plings can be suffixed with argument
1041 ;; range specifiers.
1042 ;; Argument ranges are complex too, so we hive off the input line,
1043 ;; referenced with plings, with the range string to `comint-args'.
1044 (setq comint-input-ring-index nil)
3ee91e68
RS
1045 (cond ((or (= (preceding-char) ?\\)
1046 (comint-within-quotes start (point)))
1047 ;; The history is quoted, or we're in quotes.
d637fa56 1048 (goto-char (1+ (point))))
3ee91e68
RS
1049 ((looking-at "![0-9]+\\($\\|[^-]\\)")
1050 ;; We cannot know the interpreter's idea of input line numbers.
1051 (goto-char (match-end 0))
1052 (message "Absolute reference cannot be expanded"))
1053 ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
1054 ;; Just a number of args from `number' lines backward.
1055 (let ((number (1- (string-to-number
1056 (buffer-substring (match-beginning 1)
1057 (match-end 1))))))
1058 (if (<= number (ring-length comint-input-ring))
1059 (progn
1060 (replace-match
1061 (comint-args (comint-previous-input-string number)
fb9ab28a
RS
1062 (match-beginning 2) (match-end 2))
1063 t t)
3ee91e68
RS
1064 (setq comint-input-ring-index number)
1065 (message "History item: %d" (1+ number)))
1066 (goto-char (match-end 0))
1067 (message "Relative reference exceeds input history size"))))
1068 ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
1069 ;; Just a number of args from the previous input line.
1070 (replace-match
1071 (comint-args (comint-previous-input-string 0)
fb9ab28a
RS
1072 (match-beginning 1) (match-end 1))
1073 t t)
1b421826 1074 (message "History item: previous"))
3ee91e68
RS
1075 ((looking-at
1076 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
1077 ;; Most recent input starting with or containing (possibly
1078 ;; protected) string, maybe just a number of args. Phew.
1079 (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
1080 (mb2 (match-beginning 2)) (me2 (match-end 2))
1081 (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
1082 (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
1083 (pos (save-match-data
1084 (comint-previous-matching-input-string-position
1085 (concat pref (regexp-quote exp)) 1))))
1086 (if (null pos)
5a336c13
KH
1087 (progn
1088 (goto-char (match-end 0))
1089 (or silent
1090 (progn (message "Not found")
1091 (ding))))
3ee91e68 1092 (setq comint-input-ring-index pos)
3ee91e68
RS
1093 (replace-match
1094 (comint-args (ring-ref comint-input-ring pos)
fb9ab28a
RS
1095 (match-beginning 4) (match-end 4))
1096 t t)
1b421826 1097 (message "History item: %d" (1+ pos)))))
3ee91e68
RS
1098 ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
1099 ;; Quick substitution on the previous input line.
1100 (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
1101 (new (buffer-substring (match-beginning 2) (match-end 2)))
1102 (pos nil))
1103 (replace-match (comint-previous-input-string 0) t t)
1104 (setq pos (point))
1105 (goto-char (match-beginning 0))
1b421826
RS
1106 (if (not (search-forward old pos t))
1107 (or silent
1108 (error "Not found"))
1109 (replace-match new t t)
1110 (message "History item: substituted"))))
3ee91e68 1111 (t
2ac86cc0 1112 (forward-char 1)))))))
3ee91e68
RS
1113
1114
1115(defun comint-magic-space (arg)
1116 "Expand input history references before point and insert ARG spaces.
1117A useful command to bind to SPC. See `comint-replace-by-expanded-history'."
1118 (interactive "p")
1119 (comint-replace-by-expanded-history)
1120 (self-insert-command arg))
1121\f
1122(defun comint-within-quotes (beg end)
1123 "Return t if the number of quotes between BEG and END is odd.
1124Quotes are single and double."
1125 (let ((countsq (comint-how-many-region "\\(^\\|[^\\\\]\\)\'" beg end))
1126 (countdq (comint-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
1127 (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
1128
1129(defun comint-how-many-region (regexp beg end)
1130 "Return number of matches for REGEXP from BEG to END."
1131 (let ((count 0))
1132 (save-excursion
1133 (save-match-data
1134 (goto-char beg)
1135 (while (re-search-forward regexp end t)
1136 (setq count (1+ count)))))
1137 count))
1138
1139(defun comint-args (string begin end)
1140 ;; From STRING, return the args depending on the range specified in the text
1141 ;; from BEGIN to END. If BEGIN is nil, assume all args. Ignore leading `:'.
1142 ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
1143 (save-match-data
1144 (if (null begin)
1145 (comint-arguments string 0 nil)
1146 (let* ((range (buffer-substring
1147 (if (eq (char-after begin) ?:) (1+ begin) begin) end))
1148 (nth (cond ((string-match "^[*^]" range) 1)
1149 ((string-match "^-" range) 0)
1150 ((string-equal range "$") nil)
1151 (t (string-to-number range))))
1152 (mth (cond ((string-match "[-*$]$" range) nil)
1153 ((string-match "-" range)
1154 (string-to-number (substring range (match-end 0))))
1155 (t nth))))
1156 (comint-arguments string nth mth)))))
1157
3f4b7c36
RS
1158;; Return a list of arguments from ARG. Break it up at the
1159;; delimiters in comint-delimiter-argument-list. Returned list is backwards.
3ee91e68 1160(defun comint-delim-arg (arg)
3f4b7c36 1161 (if (null comint-delimiter-argument-list)
3ee91e68 1162 (list arg)
3f4b7c36
RS
1163 (let ((args nil)
1164 (pos 0)
1165 (len (length arg)))
1166 (while (< pos len)
1167 (let ((char (aref arg pos))
1168 (start pos))
1169 (if (memq char comint-delimiter-argument-list)
1170 (while (and (< pos len) (eq (aref arg pos) char))
1171 (setq pos (1+ pos)))
1172 (while (and (< pos len)
1173 (not (memq (aref arg pos)
1174 comint-delimiter-argument-list)))
1175 (setq pos (1+ pos))))
1176 (setq args (cons (substring arg start pos) args))))
3ee91e68
RS
1177 args)))
1178
1179(defun comint-arguments (string nth mth)
1180 "Return from STRING the NTH to MTH arguments.
1181NTH and/or MTH can be nil, which means the last argument.
3f4b7c36
RS
1182Returned arguments are separated by single spaces.
1183We assume whitespace separates arguments, except within quotes.
1184Also, a run of one or more of a single character
1185in `comint-delimiter-argument-list' is a separate argument.
3ee91e68 1186Argument 0 is the command name."
21a003b9
GV
1187 ;; The first line handles ordinary characters and backslash-sequences
1188 ;; (except with w32 msdos-like shells, where backslashes are valid).
ec569127
RS
1189 ;; The second matches "-quoted strings.
1190 ;; The third matches '-quoted strings.
1191 ;; The fourth matches `-quoted strings.
1192 ;; This seems to fit the syntax of BASH 2.0.
21a003b9
GV
1193 (let* ((first (if (and (eq system-type 'windows-nt)
1194 (w32-shell-dos-semantics))
1195 "[^ \n\t\"'`]+\\|"
1196 "[^ \n\t\"'`\\]+\\|\\\\[\"'`\\]+\\|"))
1197 (argpart (concat first
1198 "\\(\"\\([^\"\\]\\|\\\\.\\)*\"\\|\
ec569127 1199'[^']*'\\|\
21a003b9
GV
1200`[^`]*`\\)"))
1201 (args ()) (pos 0)
1202 (count 0)
1203 beg str value quotes)
d91f490d
RS
1204 ;; Build a list of all the args until we have as many as we want.
1205 (while (and (or (null mth) (<= count mth))
1206 (string-match argpart string pos))
1207 (if (and beg (= pos (match-beginning 0)))
1208 ;; It's contiguous, part of the same arg.
1209 (setq pos (match-end 0)
1210 quotes (or quotes (match-beginning 1)))
1211 ;; It's a new separate arg.
1212 (if beg
1213 ;; Put the previous arg, if there was one, onto ARGS.
1214 (setq str (substring string beg pos)
1215 args (if quotes (cons str args)
1216 (nconc (comint-delim-arg str) args))
1217 count (1+ count)))
1218 (setq quotes (match-beginning 1))
1219 (setq beg (match-beginning 0))
1220 (setq pos (match-end 0))))
1221 (if beg
1222 (setq str (substring string beg pos)
1223 args (if quotes (cons str args)
1224 (nconc (comint-delim-arg str) args))
1225 count (1+ count)))
1226 (let ((n (or nth (1- count)))
1227 (m (if mth (1- (- count mth)) 0)))
3ee91e68
RS
1228 (mapconcat
1229 (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
1230\f
b578f267
EN
1231;;
1232;; Input processing stuff
1233;;
3ee91e68 1234
49116ac0 1235(defun comint-send-input ()
c2ced5d8
CZ
1236 "Send input to process.
1237After the process output mark, sends all text from the process mark to
1238point as input to the process. Before the process output mark, calls value
8ae3bc9f 1239of variable `comint-get-old-input' to retrieve old input, copies it to the
cccd719e 1240process mark, and sends it. If variable `comint-process-echoes' is nil,
8ae3bc9f 1241a terminal newline is also inserted into the buffer and sent to the process
cccd719e
RS
1242\(if it is non-nil, all text from the process mark to point is deleted,
1243since it is assumed the remote process will re-echo it).
8ae3bc9f 1244
3ee91e68 1245Any history reference may be expanded depending on the value of the variable
1b421826 1246`comint-input-autoexpand'. The list of function names contained in the value
fb9ab28a 1247of `comint-input-filter-functions' is called on the input before sending it.
1b421826
RS
1248The input is entered into the input history ring, if the value of variable
1249`comint-input-filter' returns non-nil when called on the input.
cccd719e
RS
1250
1251If variable `comint-eol-on-send' is non-nil, then point is moved to the
8ae3bc9f
NF
1252end of line before sending the input.
1253
fb9ab28a 1254The values of `comint-get-old-input', `comint-input-filter-functions', and
1b421826
RS
1255`comint-input-filter' are chosen according to the command interpreter running
1256in the buffer. E.g.,
1257
be9b65ac 1258If the interpreter is the csh,
49116ac0
JB
1259 comint-get-old-input is the default: take the current line, discard any
1260 initial string matching regexp comint-prompt-regexp.
fb9ab28a 1261 comint-input-filter-functions monitors input for \"cd\", \"pushd\", and
1b421826 1262 \"popd\" commands. When it sees one, it cd's the buffer.
3ee91e68 1263 comint-input-filter is the default: returns t if the input isn't all white
49116ac0 1264 space.
be9b65ac
DL
1265
1266If the comint is Lucid Common Lisp,
49116ac0 1267 comint-get-old-input snarfs the sexp ending at point.
fb9ab28a 1268 comint-input-filter-functions does nothing.
3ee91e68 1269 comint-input-filter returns nil if the input matches input-filter-regexp,
be9b65ac
DL
1270 which matches (1) all whitespace (2) :a, :c, etc.
1271
1586b965 1272Similarly for Soar, Scheme, etc."
be9b65ac
DL
1273 (interactive)
1274 ;; Note that the input string does not include its terminal newline.
49116ac0
JB
1275 (let ((proc (get-buffer-process (current-buffer))))
1276 (if (not proc) (error "Current buffer has no process")
1277 (let* ((pmark (process-mark proc))
3ee91e68 1278 (intxt (if (>= (point) (marker-position pmark))
49116ac0
JB
1279 (progn (if comint-eol-on-send (end-of-line))
1280 (buffer-substring pmark (point)))
87ef29fd
JB
1281 (let ((copy (funcall comint-get-old-input)))
1282 (goto-char pmark)
1283 (insert copy)
3ee91e68
RS
1284 copy)))
1285 (input (if (not (eq comint-input-autoexpand 'input))
1286 ;; Just whatever's already there
1287 intxt
1288 ;; Expand and leave it visible in buffer
17ac4966 1289 (comint-replace-by-expanded-history t pmark)
3ee91e68
RS
1290 (buffer-substring pmark (point))))
1291 (history (if (not (eq comint-input-autoexpand 'history))
5f46b51a 1292 input
3ee91e68
RS
1293 ;; This is messy 'cos ultimately the original
1294 ;; functions used do insertion, rather than return
1295 ;; strings. We have to expand, then insert back.
17ac4966 1296 (comint-replace-by-expanded-history t pmark)
ff6318be
SM
1297 (let ((copy (buffer-substring pmark (point)))
1298 (start (point)))
1299 (insert input)
1300 (delete-region pmark start)
5f46b51a 1301 copy))))
8ae3bc9f
NF
1302 (if comint-process-echoes
1303 (delete-region pmark (point))
d2a49350 1304 (insert-before-markers ?\n))
3ee91e68
RS
1305 (if (and (funcall comint-input-filter history)
1306 (or (null comint-input-ignoredups)
1307 (not (ring-p comint-input-ring))
1308 (ring-empty-p comint-input-ring)
1309 (not (string-equal (ring-ref comint-input-ring 0)
1310 history))))
1311 (ring-insert comint-input-ring history))
155fd027
KH
1312 (run-hook-with-args 'comint-input-filter-functions
1313 (concat input "\n"))
361ecbf2 1314 (setq comint-save-input-ring-index comint-input-ring-index)
1586b965 1315 (setq comint-input-ring-index nil)
dcdc526c
RS
1316 ;; Update the markers before we send the input
1317 ;; in case we get output amidst sending the input.
87ef29fd
JB
1318 (set-marker comint-last-input-start pmark)
1319 (set-marker comint-last-input-end (point))
3ee91e68 1320 (set-marker (process-mark proc) (point))
361ecbf2
RS
1321 ;; clear the "accumulation" marker
1322 (set-marker comint-accum-marker nil)
dcdc526c 1323 (funcall comint-input-sender proc input)
6aac2ab0
RS
1324 ;; This used to call comint-output-filter-functions,
1325 ;; but that scrolled the buffer in undesirable ways.
1326 (run-hook-with-args 'comint-output-filter-functions "")))))
be9b65ac 1327
d4321160 1328(defvar comint-preoutput-filter-functions nil
e7654b4a 1329 "Functions to call before output is inserted into the buffer.
d4321160
RS
1330These functions get one argument, a string containing the text to be
1331inserted. They return the string as it should be inserted.
1332
1333This variable is buffer-local.")
1334
3ee91e68 1335;; The purpose of using this filter for comint processes
5511e411
RS
1336;; is to keep comint-last-input-end from moving forward
1337;; when output is inserted.
3ee91e68
RS
1338(defun comint-output-filter (process string)
1339 ;; First check for killed buffer
91d75282 1340 (let ((oprocbuf (process-buffer process)))
d4321160
RS
1341 (let ((functions comint-preoutput-filter-functions))
1342 (while (and functions string)
1343 (setq string (funcall (car functions) string))
1344 (setq functions (cdr functions))))
1345 (if (and string oprocbuf (buffer-name oprocbuf))
91d75282
RS
1346 (let ((obuf (current-buffer))
1347 (opoint nil) (obeg nil) (oend nil))
1348 (set-buffer oprocbuf)
1349 (setq opoint (point))
1350 (setq obeg (point-min))
1351 (setq oend (point-max))
1352 (let ((buffer-read-only nil)
1353 (nchars (length string))
1354 (ostart nil))
1355 (widen)
1356 (goto-char (process-mark process))
1357 (setq ostart (point))
1358 (if (<= (point) opoint)
1359 (setq opoint (+ opoint nchars)))
1360 ;; Insert after old_begv, but before old_zv.
1361 (if (< (point) obeg)
1362 (setq obeg (+ obeg nchars)))
1363 (if (<= (point) oend)
1364 (setq oend (+ oend nchars)))
1365 (insert-before-markers string)
1366 ;; Don't insert initial prompt outside the top of the window.
1367 (if (= (window-start (selected-window)) (point))
1368 (set-window-start (selected-window) (- (point) (length string))))
1369 (if (and comint-last-input-end
1370 (marker-buffer comint-last-input-end)
1371 (= (point) comint-last-input-end))
1372 (set-marker comint-last-input-end (- comint-last-input-end nchars)))
1373 (set-marker comint-last-output-start ostart)
1374 (set-marker (process-mark process) (point))
1375 (force-mode-line-update))
1376
1377 (narrow-to-region obeg oend)
1378 (goto-char opoint)
155fd027 1379 (run-hook-with-args 'comint-output-filter-functions string)
91d75282 1380 (set-buffer obuf)))))
3ee91e68 1381
c1da5c03 1382(defun comint-preinput-scroll-to-bottom ()
3ee91e68
RS
1383 "Go to the end of buffer in all windows showing it.
1384Movement occurs if point in the selected window is not after the process mark,
1385and `this-command' is an insertion command. Insertion commands recognised
d637fa56 1386are `self-insert-command', `comint-magic-space', `yank', and `hilit-yank'.
3ee91e68
RS
1387Depends on the value of `comint-scroll-to-bottom-on-input'.
1388
c1da5c03 1389This function should be a pre-command hook."
3ee91e68 1390 (if (and comint-scroll-to-bottom-on-input
91d75282 1391 (memq this-command '(self-insert-command comint-magic-space yank
d637fa56 1392 hilit-yank)))
3ee91e68
RS
1393 (let* ((selected (selected-window))
1394 (current (current-buffer))
1395 (process (get-buffer-process current))
1396 (scroll comint-scroll-to-bottom-on-input))
d637fa56 1397 (if (and process (< (point) (process-mark process)))
0744bf64
RS
1398 (if (eq scroll 'this)
1399 (goto-char (point-max))
1400 (walk-windows
1401 (function (lambda (window)
1402 (if (and (eq (window-buffer window) current)
d637fa56 1403 (or (eq scroll t) (eq scroll 'all)))
0744bf64
RS
1404 (progn
1405 (select-window window)
1406 (goto-char (point-max))
1407 (select-window selected)))))
d637fa56 1408 nil t))))))
3ee91e68 1409
c1da5c03 1410(defun comint-postoutput-scroll-to-bottom (string)
3ee91e68
RS
1411 "Go to the end of buffer in all windows showing it.
1412Does not scroll if the current line is the last line in the buffer.
1413Depends on the value of `comint-scroll-to-bottom-on-output' and
1414`comint-scroll-show-maximum-output'.
1415
fb9ab28a 1416This function should be in the list `comint-output-filter-functions'."
3ee91e68
RS
1417 (let* ((selected (selected-window))
1418 (current (current-buffer))
1419 (process (get-buffer-process current))
1420 (scroll comint-scroll-to-bottom-on-output))
d637fa56
RS
1421 (unwind-protect
1422 (if process
1423 (walk-windows
1424 (function (lambda (window)
1425 (if (eq (window-buffer window) current)
1426 (progn
1427 (select-window window)
1428 (if (and (< (point) (process-mark process))
1429 (or (eq scroll t) (eq scroll 'all)
107d7589 1430 ;; Maybe user wants point to jump to end.
d637fa56
RS
1431 (and (eq scroll 'this) (eq selected window))
1432 (and (eq scroll 'others) (not (eq selected window)))
107d7589 1433 ;; If point was at the end, keep it at end.
2c3d5985
RS
1434 (and (marker-position comint-last-output-start)
1435 (>= (point) comint-last-output-start))))
d637fa56
RS
1436 (goto-char (process-mark process)))
1437 ;; Optionally scroll so that the text
1438 ;; ends at the bottom of the window.
1439 (if (and comint-scroll-show-maximum-output
1440 (>= (point) (process-mark process)))
1441 (save-excursion
1442 (goto-char (point-max))
1443 (recenter -1)))
1444 (select-window selected)))))
1445 nil t))
1446 (set-buffer current))))
3ee91e68 1447
39a185a9
SM
1448(defun comint-truncate-buffer (&optional string)
1449 "Truncate the buffer to `comint-buffer-maximum-size'.
1450This function could be on `comint-output-filter-functions' or bound to a key."
1451 (interactive)
1452 (save-excursion
107d7589 1453 (goto-char (process-mark (get-buffer-process (current-buffer))))
39a185a9
SM
1454 (forward-line (- comint-buffer-maximum-size))
1455 (beginning-of-line)
1456 (delete-region (point-min) (point))))
1457
efcec33f
RS
1458(defun comint-strip-ctrl-m (&optional string)
1459 "Strip trailing `^M' characters from the current output group.
39a185a9 1460This function could be on `comint-output-filter-functions' or bound to a key."
efcec33f
RS
1461 (interactive)
1462 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1463 (save-excursion
71a895c6
KH
1464 (condition-case nil
1465 (goto-char
1466 (if (interactive-p) comint-last-input-end comint-last-output-start))
1467 (error nil))
efcec33f
RS
1468 (while (re-search-forward "\r+$" pmark t)
1469 (replace-match "" t t)))))
1470(defalias 'shell-strip-ctrl-m 'comint-strip-ctrl-m)
1471
3ee91e68
RS
1472(defun comint-show-maximum-output ()
1473 "Put the end of the buffer at the bottom of the window."
1474 (interactive)
1475 (goto-char (point-max))
1476 (recenter -1))
5511e411 1477
be9b65ac 1478(defun comint-get-old-input-default ()
cccd719e 1479 "Default for `comint-get-old-input'.
c2ced5d8 1480Take the current line, and discard any initial text matching
cccd719e 1481`comint-prompt-regexp'."
be9b65ac 1482 (save-excursion
49116ac0
JB
1483 (beginning-of-line)
1484 (comint-skip-prompt)
1485 (let ((beg (point)))
1486 (end-of-line)
1487 (buffer-substring beg (point)))))
1488
3ee91e68
RS
1489(defun comint-copy-old-input ()
1490 "Insert after prompt old input at point as new input to be edited.
1491Calls `comint-get-old-input' to get old input."
1492 (interactive)
1493 (let ((input (funcall comint-get-old-input))
1494 (process (get-buffer-process (current-buffer))))
1495 (if (not process)
1496 (error "Current buffer has no process")
1497 (goto-char (process-mark process))
1498 (insert input))))
1499
49116ac0 1500(defun comint-skip-prompt ()
cccd719e 1501 "Skip past the text matching regexp `comint-prompt-regexp'.
49116ac0
JB
1502If this takes us past the end of the current line, don't skip at all."
1503 (let ((eol (save-excursion (end-of-line) (point))))
1504 (if (and (looking-at comint-prompt-regexp)
1505 (<= (match-end 0) eol))
1506 (goto-char (match-end 0)))))
1507
49116ac0 1508(defun comint-after-pmark-p ()
3ee91e68
RS
1509 "Return t if point is after the process output marker."
1510 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1511 (<= (marker-position pmark) (point))))
49116ac0
JB
1512
1513(defun comint-simple-send (proc string)
1514 "Default function for sending to PROC input STRING.
1515This just sends STRING plus a newline. To override this,
cccd719e 1516set the hook `comint-input-sender'."
49116ac0
JB
1517 (comint-send-string proc string)
1518 (comint-send-string proc "\n"))
be9b65ac
DL
1519
1520(defun comint-bol (arg)
1521 "Goes to the beginning of line, then skips past the prompt, if any.
3ee91e68 1522If prefix argument is given (\\[universal-argument]) the prompt is not skipped.
be9b65ac 1523
49116ac0 1524The prompt skip is done by skipping text matching the regular expression
a77db92b 1525`comint-prompt-regexp', a buffer local variable."
be9b65ac
DL
1526 (interactive "P")
1527 (beginning-of-line)
49116ac0 1528 (if (null arg) (comint-skip-prompt)))
be9b65ac 1529
b578f267
EN
1530;; These three functions are for entering text you don't want echoed or
1531;; saved -- typically passwords to ftp, telnet, or somesuch.
1532;; Just enter m-x send-invisible and type in your line, or add
1533;; `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
49116ac0 1534
87ef29fd 1535(defun comint-read-noecho (prompt &optional stars)
4be9a25f
NF
1536 "Read a single line of text from user without echoing, and return it.
1537Prompt with argument PROMPT, a string. Optional argument STARS causes
1538input to be echoed with '*' characters on the prompt line. Input ends with
1539RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line. C-g aborts (if
cccd719e
RS
1540`inhibit-quit' is set because e.g. this function was called from a process
1541filter and C-g is pressed, this function returns nil rather than a string).
4be9a25f
NF
1542
1543Note that the keystrokes comprising the text can still be recovered
dc81e166
RS
1544\(temporarily) with \\[view-lossage]. Some people find this worrysome.
1545Once the caller uses the password, it can erase the password
1546by doing (fillarray STRING 0)."
4be9a25f 1547 (let ((ans "")
dc81e166 1548 (newans nil)
4be9a25f
NF
1549 (c 0)
1550 (echo-keystrokes 0)
87ef29fd 1551 (cursor-in-echo-area t)
23cb053e
KH
1552 (message-log-max nil)
1553 (done nil))
4be9a25f
NF
1554 (while (not done)
1555 (if stars
84a99e73
KH
1556 (message "%s%s" prompt (make-string (length ans) ?*))
1557 (message "%s" prompt))
af171fd0
RS
1558 ;; Use this instead of `read-char' to avoid "Non-character input-event".
1559 (setq c (read-char-exclusive))
4be9a25f 1560 (cond ((= c ?\C-g)
59f36b08
SM
1561 ;; This function may get called from a process filter, where
1562 ;; inhibit-quit is set. In later versions of emacs read-char
1563 ;; may clear quit-flag itself and return C-g. That would make
1564 ;; it impossible to quit this loop in a simple way, so
1565 ;; re-enable it here (for backward-compatibility the check for
1566 ;; quit-flag below would still be necessary, so this seems
1567 ;; like the simplest way to do things).
1568 (setq quit-flag t
1569 done t))
1570 ((or (= c ?\r) (= c ?\n) (= c ?\e))
1571 (setq done t))
1572 ((= c ?\C-u)
dc81e166 1573 (fillarray ans 0)
59f36b08
SM
1574 (setq ans ""))
1575 ((and (/= c ?\b) (/= c ?\177))
dc81e166
RS
1576 (setq newans (concat ans (char-to-string c)))
1577 (fillarray ans 0)
1578 (setq ans newans))
59f36b08 1579 ((> (length ans) 0)
dc81e166 1580 (aset ans (1- (length ans)) 0)
59f36b08 1581 (setq ans (substring ans 0 -1)))))
4be9a25f
NF
1582 (if quit-flag
1583 ;; Emulate a true quit, except that we have to return a value.
1584 (prog1
1585 (setq quit-flag nil)
1586 (message "Quit")
1587 (beep t))
1588 (message "")
1589 ans)))
87ef29fd 1590
be9b65ac 1591(defun send-invisible (str)
c2ced5d8 1592 "Read a string without echoing.
6152f5f0
SM
1593Then send it to the process running in the current buffer.
1594The string is sent using `comint-input-sender'.
49116ac0
JB
1595Security bug: your string can still be temporarily recovered with
1596\\[view-lossage]."
4a11114d 1597 (interactive "P") ; Defeat snooping via C-x ESC ESC
be9b65ac 1598 (let ((proc (get-buffer-process (current-buffer))))
4a11114d
SM
1599 (cond ((not proc)
1600 (error "Current buffer has no process"))
1601 ((stringp str)
1602 (funcall comint-input-sender proc str))
1603 (t
1604 (let ((str (comint-read-noecho "Non-echoed text: " t)))
1605 (if (stringp str)
1606 (send-invisible str)
1607 (message "Warning: text will be echoed")))))))
21d9bf27
RS
1608
1609(defun comint-watch-for-password-prompt (string)
1610 "Prompt in the minibuffer for password and send without echoing.
1611This function uses `send-invisible' to read and send a password to the buffer's
654d89d7
NF
1612process if STRING contains a password prompt defined by
1613`comint-password-prompt-regexp'.
21d9bf27
RS
1614
1615This function could be in the list `comint-output-filter-functions'."
654d89d7 1616 (if (string-match comint-password-prompt-regexp string)
21d9bf27 1617 (send-invisible nil)))
be9b65ac 1618\f
b578f267 1619;; Low-level process communication
be9b65ac 1620
7df7d5b3
RS
1621(defalias 'comint-send-string 'process-send-string)
1622(defalias 'comint-send-region 'process-send-region)
be9b65ac 1623\f
b578f267 1624;; Random input hackage
be9b65ac 1625
49116ac0 1626(defun comint-kill-output ()
3ee91e68
RS
1627 "Kill all output from interpreter since last input.
1628Does not delete the prompt."
be9b65ac 1629 (interactive)
a9a6f83f
RS
1630 (let ((proc (get-buffer-process (current-buffer)))
1631 (replacement nil))
1632 (save-excursion
1633 (let ((pmark (progn (goto-char (process-mark proc))
1634 (beginning-of-line nil)
1635 (point-marker))))
1636 (delete-region comint-last-input-end pmark)
37a9a675 1637 (goto-char (process-mark proc))
a9a6f83f
RS
1638 (setq replacement (concat "*** output flushed ***\n"
1639 (buffer-substring pmark (point))))
1640 (delete-region pmark (point))))
1641 ;; Output message and put back prompt
1642 (comint-output-filter proc replacement)))
be9b65ac
DL
1643
1644(defun comint-show-output ()
49116ac0 1645 "Display start of this batch of interpreter output at top of window.
21d9bf27 1646Sets mark to the value of point when this command is run."
be9b65ac 1647 (interactive)
815c1a20 1648 (push-mark)
3ee91e68 1649 (let ((pos (point)))
42453245 1650 (goto-char (or (marker-position comint-last-input-end) (point-max)))
3ee91e68
RS
1651 (beginning-of-line 0)
1652 (set-window-start (selected-window) (point))
815c1a20 1653 (comint-skip-prompt)))
be9b65ac
DL
1654
1655(defun comint-interrupt-subjob ()
1a94abea
RS
1656 "Interrupt the current subjob.
1657This command also kills the pending input
1658between the process-mark and point."
be9b65ac 1659 (interactive)
1a94abea 1660 (comint-kill-input)
49116ac0 1661 (interrupt-process nil comint-ptyp))
be9b65ac
DL
1662
1663(defun comint-kill-subjob ()
1a94abea
RS
1664 "Send kill signal to the current subjob.
1665This command also kills the pending input
1666between the process-mark and point."
be9b65ac 1667 (interactive)
1a94abea 1668 (comint-kill-input)
49116ac0 1669 (kill-process nil comint-ptyp))
be9b65ac
DL
1670
1671(defun comint-quit-subjob ()
1a94abea
RS
1672 "Send quit signal to the current subjob.
1673This command also kills the pending input
1674between the process-mark and point."
be9b65ac 1675 (interactive)
1a94abea 1676 (comint-kill-input)
49116ac0 1677 (quit-process nil comint-ptyp))
be9b65ac
DL
1678
1679(defun comint-stop-subjob ()
49116ac0 1680 "Stop the current subjob.
1a94abea
RS
1681This command also kills the pending input
1682between the process-mark and point.
1683
be9b65ac 1684WARNING: if there is no current subjob, you can end up suspending
49116ac0
JB
1685the top-level process running in the buffer. If you accidentally do
1686this, use \\[comint-continue-subjob] to resume the process. (This
1687is not a problem with most shells, since they ignore this signal.)"
be9b65ac 1688 (interactive)
1a94abea 1689 (comint-kill-input)
49116ac0 1690 (stop-process nil comint-ptyp))
be9b65ac
DL
1691
1692(defun comint-continue-subjob ()
49116ac0 1693 "Send CONT signal to process buffer's process group.
be9b65ac
DL
1694Useful if you accidentally suspend the top-level process."
1695 (interactive)
49116ac0 1696 (continue-process nil comint-ptyp))
be9b65ac
DL
1697
1698(defun comint-kill-input ()
49116ac0 1699 "Kill all text from last stuff output by interpreter to point."
be9b65ac 1700 (interactive)
3ee91e68
RS
1701 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1702 (if (> (point) (marker-position pmark))
49116ac0 1703 (kill-region pmark (point)))))
be9b65ac
DL
1704
1705(defun comint-delchar-or-maybe-eof (arg)
4a11114d
SM
1706 "Delete ARG characters forward or send an EOF to subprocess.
1707Sends an EOF only if point is at the end of the buffer and there is no input."
be9b65ac 1708 (interactive "p")
90d6bfb9
KH
1709 (let ((proc (get-buffer-process (current-buffer))))
1710 (if (and (eobp) proc (= (point) (marker-position (process-mark proc))))
4a11114d
SM
1711 (process-send-eof)
1712 (delete-char arg))))
49116ac0 1713
1de80a34
RM
1714(defun comint-send-eof ()
1715 "Send an EOF to the current buffer's process."
1716 (interactive)
1717 (process-send-eof))
49116ac0 1718
3ee91e68
RS
1719
1720(defun comint-backward-matching-input (regexp arg)
1721 "Search backward through buffer for match for REGEXP.
1722Matches are searched for on lines that match `comint-prompt-regexp'.
1723With prefix argument N, search for Nth previous match.
1724If N is negative, find the next or Nth next match."
1725 (interactive (comint-regexp-arg "Backward input matching (regexp): "))
1726 (let* ((re (concat comint-prompt-regexp ".*" regexp))
1727 (pos (save-excursion (end-of-line (if (> arg 0) 0 1))
1728 (if (re-search-backward re nil t arg)
1729 (point)))))
1730 (if (null pos)
1731 (progn (message "Not found")
1732 (ding))
1733 (goto-char pos)
1734 (comint-bol nil))))
1735
1736(defun comint-forward-matching-input (regexp arg)
1737 "Search forward through buffer for match for REGEXP.
1738Matches are searched for on lines that match `comint-prompt-regexp'.
1739With prefix argument N, search for Nth following match.
1740If N is negative, find the previous or Nth previous match."
1741 (interactive (comint-regexp-arg "Forward input matching (regexp): "))
1742 (comint-backward-matching-input regexp (- arg)))
1743
1744
1de80a34 1745(defun comint-next-prompt (n)
3ee91e68 1746 "Move to end of Nth next prompt in the buffer.
1de80a34
RM
1747See `comint-prompt-regexp'."
1748 (interactive "p")
3ee91e68
RS
1749 (let ((paragraph-start comint-prompt-regexp))
1750 (end-of-line (if (> n 0) 1 0))
1751 (forward-paragraph n)
1752 (comint-skip-prompt)))
49116ac0 1753
3ee91e68
RS
1754(defun comint-previous-prompt (n)
1755 "Move to end of Nth previous prompt in the buffer.
1de80a34
RM
1756See `comint-prompt-regexp'."
1757 (interactive "p")
3ee91e68 1758 (comint-next-prompt (- n)))
be9b65ac 1759\f
b578f267
EN
1760;; Support for source-file processing commands.
1761;;============================================================================
1762;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
1763;; commands that process files of source text (e.g. loading or compiling
1764;; files). So the corresponding process-in-a-buffer modes have commands
1765;; for doing this (e.g., lisp-load-file). The functions below are useful
1766;; for defining these commands.
1767;;
1768;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
1769;; and Soar, in that they don't know anything about file extensions.
1770;; So the compile/load interface gets the wrong default occasionally.
1771;; The load-file/compile-file default mechanism could be smarter -- it
1772;; doesn't know about the relationship between filename extensions and
1773;; whether the file is source or executable. If you compile foo.lisp
1774;; with compile-file, then the next load-file should use foo.bin for
1775;; the default, not foo.lisp. This is tricky to do right, particularly
1776;; because the extension for executable files varies so much (.o, .bin,
1777;; .lbin, .mo, .vo, .ao, ...).
1778
1779
1780;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
1781;; commands.
1782;;
1783;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
1784;; want to save the buffer before issuing any process requests to the command
1785;; interpreter.
1786;;
1787;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
1788;; for the file to process.
1789
1790;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
1791;;============================================================================
1792;; This function computes the defaults for the load-file and compile-file
1793;; commands for tea, soar, cmulisp, and cmuscheme modes.
1794;;
1795;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
1796;; source-file processing command. NIL if there hasn't been one yet.
1797;; - SOURCE-MODES is a list used to determine what buffers contain source
1798;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
1799;; Typically, (lisp-mode) or (scheme-mode).
1800;;
1801;; If the command is given while the cursor is inside a string, *and*
1802;; the string is an existing filename, *and* the filename is not a directory,
1803;; then the string is taken as default. This allows you to just position
1804;; your cursor over a string that's a filename and have it taken as default.
1805;;
1806;; If the command is given in a file buffer whose major mode is in
1807;; SOURCE-MODES, then the the filename is the default file, and the
1808;; file's directory is the default directory.
1809;;
1810;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
1811;; then the default directory & file are what was used in the last source-file
1812;; processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
1813;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
1814;; is the cwd, with no default file. (\"no default file\" = nil)
1815;;
1816;; SOURCE-REGEXP is typically going to be something like (tea-mode)
1817;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
1818;; for Soar programs, etc.
1819;;
1820;; The function returns a pair: (default-directory . default-file).
be9b65ac
DL
1821
1822(defun comint-source-default (previous-dir/file source-modes)
1823 (cond ((and buffer-file-name (memq major-mode source-modes))
1824 (cons (file-name-directory buffer-file-name)
1825 (file-name-nondirectory buffer-file-name)))
1826 (previous-dir/file)
1827 (t
1828 (cons default-directory nil))))
1829
49116ac0 1830
b578f267
EN
1831;; (COMINT-CHECK-SOURCE fname)
1832;;============================================================================
1833;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
1834;; process-in-a-buffer modes), this function can be called on the filename.
1835;; If the file is loaded into a buffer, and the buffer is modified, the user
1836;; is queried to see if he wants to save the buffer before proceeding with
1837;; the load or compile.
be9b65ac
DL
1838
1839(defun comint-check-source (fname)
1840 (let ((buff (get-file-buffer fname)))
1841 (if (and buff
1842 (buffer-modified-p buff)
3ee91e68 1843 (y-or-n-p (format "Save buffer %s first? " (buffer-name buff))))
be9b65ac
DL
1844 ;; save BUFF.
1845 (let ((old-buffer (current-buffer)))
1846 (set-buffer buff)
1847 (save-buffer)
1848 (set-buffer old-buffer)))))
1849
49116ac0 1850
b578f267
EN
1851;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
1852;;============================================================================
1853;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
1854;; commands that process source files (like loading or compiling a file).
1855;; It prompts for the filename, provides a default, if there is one,
1856;; and returns the result filename.
1857;;
1858;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
1859;;
1860;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
1861;; from the last source processing command. SOURCE-MODES is a list of major
1862;; modes used to determine what file buffers contain source files. (These
1863;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
1864;; then the filename reader will only accept a file that exists.
1865;;
1866;; A typical use:
1867;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
1868;; '(lisp-mode) t))
1869
1870;; This is pretty stupid about strings. It decides we're in a string
1871;; if there's a quote on both sides of point on the current line.
be9b65ac 1872(defun comint-extract-string ()
cccd719e 1873 "Return string around POINT that starts the current line, or nil."
be9b65ac
DL
1874 (save-excursion
1875 (let* ((point (point))
1876 (bol (progn (beginning-of-line) (point)))
1877 (eol (progn (end-of-line) (point)))
1878 (start (progn (goto-char point)
1879 (and (search-backward "\"" bol t)
1880 (1+ (point)))))
1881 (end (progn (goto-char point)
1882 (and (search-forward "\"" eol t)
1883 (1- (point))))))
1884 (and start end
1885 (buffer-substring start end)))))
1886
1887(defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
1888 (let* ((def (comint-source-default prev-dir/file source-modes))
1889 (stringfile (comint-extract-string))
1890 (sfile-p (and stringfile
49116ac0
JB
1891 (condition-case ()
1892 (file-exists-p stringfile)
1893 (error nil))
be9b65ac
DL
1894 (not (file-directory-p stringfile))))
1895 (defdir (if sfile-p (file-name-directory stringfile)
1896 (car def)))
1897 (deffile (if sfile-p (file-name-nondirectory stringfile)
1898 (cdr def)))
1899 (ans (read-file-name (if deffile (format "%s(default %s) "
1900 prompt deffile)
1901 prompt)
1902 defdir
1903 (concat defdir deffile)
1904 mustmatch-p)))
1905 (list (expand-file-name (substitute-in-file-name ans)))))
1906
b578f267
EN
1907;; I am somewhat divided on this string-default feature. It seems
1908;; to violate the principle-of-least-astonishment, in that it makes
1909;; the default harder to predict, so you actually have to look and see
1910;; what the default really is before choosing it. This can trip you up.
1911;; On the other hand, it can be useful, I guess. I would appreciate feedback
1912;; on this.
1913;; -Olin
49116ac0 1914
be9b65ac 1915\f
b578f267
EN
1916;; Simple process query facility.
1917;; ===========================================================================
1918;; This function is for commands that want to send a query to the process
1919;; and show the response to the user. For example, a command to get the
1920;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
1921;; to an inferior Common Lisp process.
1922;;
1923;; This simple facility just sends strings to the inferior process and pops
1924;; up a window for the process buffer so you can see what the process
1925;; responds with. We don't do anything fancy like try to intercept what the
1926;; process responds with and put it in a pop-up window or on the message
1927;; line. We just display the buffer. Low tech. Simple. Works good.
1928
1929;; Send to the inferior process PROC the string STR. Pop-up but do not select
1930;; a window for the inferior process so that its response can be seen.
be9b65ac
DL
1931(defun comint-proc-query (proc str)
1932 (let* ((proc-buf (process-buffer proc))
1933 (proc-mark (process-mark proc)))
1934 (display-buffer proc-buf)
1935 (set-buffer proc-buf) ; but it's not the selected *window*
1936 (let ((proc-win (get-buffer-window proc-buf))
1937 (proc-pt (marker-position proc-mark)))
1938 (comint-send-string proc str) ; send the query
1939 (accept-process-output proc) ; wait for some output
1940 ;; Try to position the proc window so you can see the answer.
1941 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
1942 ;; I don't know why. Wizards invited to improve it.
17193f89
SM
1943 (unless (pos-visible-in-window-p proc-pt proc-win)
1944 (let ((opoint (window-point proc-win)))
1945 (set-window-point proc-win proc-mark)
1946 (sit-for 0)
1947 (if (not (pos-visible-in-window-p opoint proc-win))
1948 (push-mark opoint)
1949 (set-window-point proc-win opoint)))))))
be9b65ac
DL
1950
1951\f
b578f267
EN
1952;; Filename/command/history completion in a buffer
1953;; ===========================================================================
1954;; Useful completion functions, courtesy of the Ergo group.
1955
1956;; Six commands:
1957;; comint-dynamic-complete Complete or expand command, filename,
1958;; history at point.
1959;; comint-dynamic-complete-filename Complete filename at point.
1960;; comint-dynamic-list-filename-completions List completions in help buffer.
1961;; comint-replace-by-expanded-filename Expand and complete filename at point;
1962;; replace with expanded/completed name.
1963;; comint-dynamic-simple-complete Complete stub given candidates.
1964
1965;; These are not installed in the comint-mode keymap. But they are
1966;; available for people who want them. Shell-mode installs them:
1967;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
1968;; (define-key shell-mode-map "\M-?"
1969;; 'comint-dynamic-list-filename-completions)))
1970;;
1971;; Commands like this are fine things to put in load hooks if you
1972;; want them present in specific modes.
49116ac0 1973
ed366e87 1974(defcustom comint-completion-autolist nil
5ef2f81f 1975 "*If non-nil, automatically list possibilities on partial completion.
ed366e87
RS
1976This mirrors the optional behavior of tcsh."
1977 :type 'boolean
1978 :group 'comint-completion)
3ee91e68 1979
ed366e87 1980(defcustom comint-completion-addsuffix t
3ee91e68 1981 "*If non-nil, add a `/' to completed directories, ` ' to file names.
59f36b08
SM
1982If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
1983DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact completion.
ed366e87
RS
1984This mirrors the optional behavior of tcsh."
1985 :type 'boolean
1986 :group 'comint-completion)
3ee91e68 1987
ed366e87 1988(defcustom comint-completion-recexact nil
3ee91e68 1989 "*If non-nil, use shortest completion if characters cannot be added.
fdb7791d 1990This mirrors the optional behavior of tcsh.
3ee91e68 1991
ed366e87
RS
1992A non-nil value is useful if `comint-completion-autolist' is non-nil too."
1993 :type 'boolean
1994 :group 'comint-completion)
3ee91e68 1995
ed366e87 1996(defcustom comint-completion-fignore nil
497513ad
RS
1997 "*List of suffixes to be disregarded during file completion.
1998This mirrors the optional behavior of bash and tcsh.
1999
ed366e87
RS
2000Note that this applies to `comint-dynamic-complete-filename' only."
2001 :type '(repeat (string :tag "Suffix"))
2002 :group 'comint-completion)
497513ad 2003
3ee91e68
RS
2004(defvar comint-file-name-prefix ""
2005 "Prefix prepended to absolute file names taken from process input.
2006This is used by comint's and shell's completion functions, and by shell's
2007directory tracking functions.")
be9b65ac 2008
2d4382e5 2009(defvar comint-file-name-chars
da418b28
GV
2010 (if (memq system-type '(ms-dos windows-nt))
2011 "~/A-Za-z0-9_^$!#%&{}@`'.,:()-"
2012 "~/A-Za-z0-9+@:_.$#%,={}-")
2d4382e5 2013 "String of characters valid in a file name.
af898b0f
RS
2014Note that all non-ASCII characters are considered valid in a file name
2015regardless of what this variable says.
107d7589
SM
2016
2017This is a good thing to set in mode hooks.")
2018
59f36b08 2019(defvar comint-file-name-quote-list nil
6d2a6ce6 2020 "List of characters to quote with `\\' when in a file name.
59f36b08
SM
2021
2022This is a good thing to set in mode hooks.")
2023
3ee91e68
RS
2024
2025(defun comint-directory (directory)
2026 ;; Return expanded DIRECTORY, with `comint-file-name-prefix' if absolute.
2027 (expand-file-name (if (file-name-absolute-p directory)
2028 (concat comint-file-name-prefix directory)
2029 directory)))
2030
2031
1b421826
RS
2032(defun comint-word (word-chars)
2033 "Return the word of WORD-CHARS at point, or nil if non is found.
2034Word constituents are considered to be those in WORD-CHARS, which is like the
af898b0f
RS
2035inside of a \"[...]\" (see `skip-chars-forward'),
2036plus all non-ASCII characters."
3ee91e68 2037 (save-excursion
59f36b08
SM
2038 (let ((non-word-chars (concat "[^\\\\" word-chars "]")) (here (point)))
2039 (while (and (re-search-backward non-word-chars nil 'move)
af898b0f
RS
2040 ;;(memq (char-after (point)) shell-file-name-quote-list)
2041 (or (>= (following-char) 128)
2042 (eq (preceding-char) ?\\)))
59f36b08 2043 (backward-char 1))
4288965c 2044 ;; Don't go forward over a word-char (this can happen if we're at bob).
17193f89
SM
2045 (when (or (not (bobp)) (looking-at non-word-chars))
2046 (forward-char 1))
4288965c 2047 ;; Set match-data to match the entire string.
17193f89 2048 (when (< (point) here)
e4947876 2049 (set-match-data (list (point) here))
17193f89 2050 (match-string 0)))))
3ee91e68 2051
7a35a067
RS
2052(defun comint-substitute-in-file-name (filename)
2053 "Return FILENAME with environment variables substituted.
2054Supports additional environment variable syntax of the command
2055interpreter (e.g., the percent notation of cmd.exe on NT)."
2056 (let ((name (substitute-in-file-name filename)))
2057 (if (memq system-type '(ms-dos windows-nt))
2058 (let (env-var-name
2059 env-var-val)
2060 (save-match-data
2061 (while (string-match "%\\([^\\\\/]*\\)%" name)
2062 (setq env-var-name
2063 (substring name (match-beginning 1) (match-end 1)))
2064 (setq env-var-val (if (getenv env-var-name)
2065 (getenv env-var-name)
2066 ""))
2067 (setq name (replace-match env-var-val nil nil name))))))
2068 name))
3ee91e68 2069
1b421826
RS
2070(defun comint-match-partial-filename ()
2071 "Return the filename at point, or nil if non is found.
2072Environment variables are substituted. See `comint-word'."
2d4382e5 2073 (let ((filename (comint-word comint-file-name-chars)))
7a35a067
RS
2074 (and filename (comint-substitute-in-file-name
2075 (comint-unquote-filename filename)))))
59f36b08
SM
2076
2077
2078(defun comint-quote-filename (filename)
2079 "Return FILENAME with magic characters quoted.
2080Magic characters are those in `comint-file-name-quote-list'."
2081 (if (null comint-file-name-quote-list)
2082 filename
2083 (let ((regexp
2084 (format "\\(^\\|[^\\]\\)\\([%s]\\)"
2085 (mapconcat 'char-to-string comint-file-name-quote-list ""))))
2086 (save-match-data
2087 (while (string-match regexp filename)
2088 (setq filename (replace-match "\\1\\\\\\2" nil nil filename)))
2089 filename))))
2090
2091(defun comint-unquote-filename (filename)
2092 "Return FILENAME with quoted characters unquoted."
2093 (if (null comint-file-name-quote-list)
2094 filename
2095 (save-match-data
dbdfff7f
RS
2096 (let ((i 0))
2097 (while (string-match "\\\\\\(.\\)" filename i)
2098 (setq filename (replace-match "\\1" nil nil filename))
2099 (setq i (+ 1 (match-beginning 0)))))
59f36b08 2100 filename)))
be9b65ac 2101
49116ac0 2102
be9b65ac 2103(defun comint-dynamic-complete ()
1b421826
RS
2104 "Dynamically perform completion at point.
2105Calls the functions in `comint-dynamic-complete-functions' to perform
2106completion until a function returns non-nil, at which point completion is
2107assumed to have occurred."
3ee91e68 2108 (interactive)
155fd027 2109 (run-hook-with-args-until-success 'comint-dynamic-complete-functions))
3ee91e68
RS
2110
2111
2112(defun comint-dynamic-complete-filename ()
49116ac0 2113 "Dynamically complete the filename at point.
1b421826
RS
2114Completes if after a filename. See `comint-match-partial-filename' and
2115`comint-dynamic-complete-as-filename'.
3ee91e68
RS
2116This function is similar to `comint-replace-by-expanded-filename', except that
2117it won't change parts of the filename already entered in the buffer; it just
2118adds completion characters to the end of the filename. A completions listing
2119may be shown in a help buffer if completion is ambiguous.
2120
497513ad
RS
2121Completion is dependent on the value of `comint-completion-addsuffix',
2122`comint-completion-recexact' and `comint-completion-fignore', and the timing of
2123completions listing is dependent on the value of `comint-completion-autolist'.
1b421826
RS
2124
2125Returns t if successful."
3ee91e68 2126 (interactive)
17193f89
SM
2127 (when (comint-match-partial-filename)
2128 (unless (window-minibuffer-p (selected-window))
2129 (message "Completing file name..."))
2130 (comint-dynamic-complete-as-filename)))
1b421826
RS
2131
2132(defun comint-dynamic-complete-as-filename ()
2133 "Dynamically complete at point as a filename.
2134See `comint-dynamic-complete-filename'. Returns t if successful."
107d7589 2135 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt)))
497513ad 2136 (completion-ignored-extensions comint-completion-fignore)
107d7589
SM
2137 ;; If we bind this, it breaks remote directory tracking in rlogin.el.
2138 ;; I think it was originally bound to solve file completion problems,
2139 ;; but subsequent changes may have made this unnecessary. sm.
2140 ;;(file-name-handler-alist nil)
81fb2771 2141 (minibuffer-p (window-minibuffer-p (selected-window)))
1b421826 2142 (success t)
17193f89
SM
2143 (dirsuffix (cond ((not comint-completion-addsuffix)
2144 "")
2145 ((not (consp comint-completion-addsuffix))
2146 (char-to-string directory-sep-char))
2147 (t
2148 (car comint-completion-addsuffix))))
2149 (filesuffix (cond ((not comint-completion-addsuffix)
2150 "")
2151 ((not (consp comint-completion-addsuffix))
2152 " ")
2153 (t
2154 (cdr comint-completion-addsuffix))))
f79f58bc
KH
2155 (filename (or (comint-match-partial-filename) ""))
2156 (pathdir (file-name-directory filename))
2157 (pathnondir (file-name-nondirectory filename))
2158 (directory (if pathdir (comint-directory pathdir) default-directory))
81fb2771 2159 (completion (file-name-completion pathnondir directory)))
3ee91e68
RS
2160 (cond ((null completion)
2161 (message "No completions of %s" filename)
1b421826 2162 (setq success nil))
3ee91e68 2163 ((eq completion t) ; Means already completed "file".
59f36b08 2164 (insert filesuffix)
17193f89
SM
2165 (unless minibuffer-p
2166 (message "Sole completion")))
3ee91e68
RS
2167 ((string-equal completion "") ; Means completion on "directory/".
2168 (comint-dynamic-list-filename-completions))
2169 (t ; Completion string returned.
2170 (let ((file (concat (file-name-as-directory directory) completion)))
59f36b08
SM
2171 (insert (comint-quote-filename
2172 (substring (directory-file-name completion)
2173 (length pathnondir))))
3ee91e68
RS
2174 (cond ((symbolp (file-name-completion completion directory))
2175 ;; We inserted a unique completion.
59f36b08 2176 (insert (if (file-directory-p file) dirsuffix filesuffix))
17193f89
SM
2177 (unless minibuffer-p
2178 (message "Completed")))
3ee91e68
RS
2179 ((and comint-completion-recexact comint-completion-addsuffix
2180 (string-equal pathnondir completion)
2181 (file-exists-p file))
2182 ;; It's not unique, but user wants shortest match.
59f36b08 2183 (insert (if (file-directory-p file) dirsuffix filesuffix))
17193f89
SM
2184 (unless minibuffer-p
2185 (message "Completed shortest")))
3ee91e68
RS
2186 ((or comint-completion-autolist
2187 (string-equal pathnondir completion))
2188 ;; It's not unique, list possible completions.
2189 (comint-dynamic-list-filename-completions))
2190 (t
17193f89
SM
2191 (unless minibuffer-p
2192 (message "Partially completed")))))))
1b421826 2193 success))
3ee91e68
RS
2194
2195
2196(defun comint-replace-by-expanded-filename ()
2197 "Dynamically expand and complete the filename at point.
2198Replace the filename with an expanded, canonicalised and completed replacement.
2199\"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
2200with the corresponding directories. \"Canonicalised\" means `..' and `.' are
2201removed, and the filename is made absolute instead of relative. For expansion
2202see `expand-file-name' and `substitute-in-file-name'. For completion see
2203`comint-dynamic-complete-filename'."
be9b65ac 2204 (interactive)
3ee91e68
RS
2205 (replace-match (expand-file-name (comint-match-partial-filename)) t t)
2206 (comint-dynamic-complete-filename))
2207
2208
3ee91e68
RS
2209(defun comint-dynamic-simple-complete (stub candidates)
2210 "Dynamically complete STUB from CANDIDATES list.
2211This function inserts completion characters at point by completing STUB from
2212the strings in CANDIDATES. A completions listing may be shown in a help buffer
2213if completion is ambiguous.
2214
1b421826
RS
2215Returns nil if no completion was inserted.
2216Returns `sole' if completed with the only completion match.
2217Returns `shortest' if completed with the shortest of the completion matches.
2218Returns `partial' if completed as far as possible with the completion matches.
2219Returns `listed' if a completion listing was shown.
2220
3ee91e68 2221See also `comint-dynamic-complete-filename'."
107d7589 2222 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt)))
59f36b08
SM
2223 (suffix (cond ((not comint-completion-addsuffix) "")
2224 ((not (consp comint-completion-addsuffix)) " ")
2225 (t (cdr comint-completion-addsuffix))))
3ee91e68
RS
2226 (candidates (mapcar (function (lambda (x) (list x))) candidates))
2227 (completions (all-completions stub candidates)))
be9b65ac 2228 (cond ((null completions)
3ee91e68 2229 (message "No completions of %s" stub)
1b421826 2230 nil)
3ee91e68
RS
2231 ((= 1 (length completions)) ; Gotcha!
2232 (let ((completion (car completions)))
2233 (if (string-equal completion stub)
2234 (message "Sole completion")
2235 (insert (substring completion (length stub)))
2236 (message "Completed"))
59f36b08 2237 (insert suffix)
1b421826 2238 'sole))
3ee91e68
RS
2239 (t ; There's no unique completion.
2240 (let ((completion (try-completion stub candidates)))
2241 ;; Insert the longest substring.
2242 (insert (substring completion (length stub)))
2243 (cond ((and comint-completion-recexact comint-completion-addsuffix
2244 (string-equal stub completion)
2245 (member completion completions))
2246 ;; It's not unique, but user wants shortest match.
59f36b08 2247 (insert suffix)
1b421826
RS
2248 (message "Completed shortest")
2249 'shortest)
3ee91e68
RS
2250 ((or comint-completion-autolist
2251 (string-equal stub completion))
2252 ;; It's not unique, list possible completions.
1b421826
RS
2253 (comint-dynamic-list-completions completions)
2254 'listed)
3ee91e68 2255 (t
1b421826
RS
2256 (message "Partially completed")
2257 'partial)))))))
3ee91e68
RS
2258
2259
2260(defun comint-dynamic-list-filename-completions ()
2261 "List in help buffer possible completions of the filename at point."
2262 (interactive)
107d7589
SM
2263 (let* ((completion-ignore-case (memq system-type '(ms-dos windows-nt)))
2264 ;; If we bind this, it breaks remote directory tracking in rlogin.el.
2265 ;; I think it was originally bound to solve file completion problems,
2266 ;; but subsequent changes may have made this unnecessary. sm.
2267 ;;(file-name-handler-alist nil)
1b421826 2268 (filename (or (comint-match-partial-filename) ""))
3ee91e68
RS
2269 (pathdir (file-name-directory filename))
2270 (pathnondir (file-name-nondirectory filename))
2271 (directory (if pathdir (comint-directory pathdir) default-directory))
2272 (completions (file-name-all-completions pathnondir directory)))
59f36b08
SM
2273 (if (not completions)
2274 (message "No completions of %s" filename)
2275 (comint-dynamic-list-completions
2276 (mapcar 'comint-quote-filename completions)))))
3ee91e68
RS
2277
2278
2279(defun comint-dynamic-list-completions (completions)
2280 "List in help buffer sorted COMPLETIONS.
2281Typing SPC flushes the help buffer."
2282 (let ((conf (current-window-configuration)))
dd3038f6 2283 (with-output-to-temp-buffer "*Completions*"
3ee91e68 2284 (display-completion-list (sort completions 'string-lessp)))
3ee91e68 2285 (message "Hit space to flush")
7d5d472e
RS
2286 (let (key first)
2287 (if (save-excursion
dd3038f6 2288 (set-buffer (get-buffer "*Completions*"))
7d5d472e
RS
2289 (setq key (read-key-sequence nil)
2290 first (aref key 0))
eb6c110a 2291 (and (consp first) (consp (event-start first))
7d5d472e 2292 (eq (window-buffer (posn-window (event-start first)))
dd3038f6 2293 (get-buffer "*Completions*"))
7d5d472e
RS
2294 (eq (key-binding key) 'mouse-choose-completion)))
2295 ;; If the user does mouse-choose-completion with the mouse,
2296 ;; execute the command, then delete the completion window.
2297 (progn
2298 (mouse-choose-completion first)
2299 (set-window-configuration conf))
2300 (if (eq first ?\ )
2301 (set-window-configuration conf)
2b5a5ed3 2302 (setq unread-command-events (listify-key-sequence key)))))))
be9b65ac 2303\f
361ecbf2
RS
2304(defun comint-get-next-from-history ()
2305 "After fetching a line from input history, this fetches the following line.
2306In other words, this recalls the input line after the line you recalled last.
2307You can use this to repeat a sequence of input lines."
2308 (interactive)
2309 (if comint-save-input-ring-index
2310 (progn
2311 (setq comint-input-ring-index (1+ comint-save-input-ring-index))
2312 (comint-next-input 1))
2313 (message "No previous history command")))
2314
2315(defun comint-accumulate ()
2316 "Accumulate a line to send as input along with more lines.
2317This inserts a newline so that you can enter more text
2318to be sent along with this line. Use \\[comint-send-input]
2319to send all the accumulated input, at once.
2320The entire accumulated text becomes one item in the input history
2321when you send it."
2322 (interactive)
2323 (insert "\n")
2324 (set-marker comint-accum-marker (point))
2325 (if comint-input-ring-index
2326 (setq comint-save-input-ring-index
2327 (- comint-input-ring-index 1))))
2328
2329(defun comint-goto-process-mark ()
2330 "Move point to the process mark.
2331The process mark separates output, and input already sent,
2332from input that has not yet been sent."
2333 (interactive)
2334 (let ((proc (or (get-buffer-process (current-buffer))
2335 (error "Current buffer has no process"))))
2336 (goto-char (process-mark proc))
2337 (message "Point is now at the process mark")))
2338
2339(defun comint-bol-or-process-mark ()
37dbcd5c 2340 "Move point to beginning of line (after prompt) or to the process mark.
361ecbf2
RS
2341The first time you use this command, it moves to the beginning of the line
2342\(but after the prompt, if any). If you repeat it again immediately,
2343it moves point to the process mark.
2344
2345The process mark separates the process output, along with input already sent,
2346from input that has not yet been sent. Ordinarily, the process mark
2347is at the beginning of the current input line; but if you have
2348used \\[comint-accumulate] to send multiple lines at once,
2349the process mark is at the beginning of the accumulated input."
2350 (interactive)
c2705d61 2351 (if (not (eq last-command 'comint-bol-or-process-mark))
361ecbf2
RS
2352 (comint-bol nil)
2353 (comint-goto-process-mark)))
2354
2355(defun comint-set-process-mark ()
2356 "Set the process mark at point."
2357 (interactive)
2358 (let ((proc (or (get-buffer-process (current-buffer))
2359 (error "Current buffer has no process"))))
2360 (set-marker (process-mark proc) (point))
2361 (message "Process mark set")))
2362
2363\f
b578f267
EN
2364;; Converting process modes to use comint mode
2365;; ===========================================================================
2366;; The code in the Emacs 19 distribution has all been modified to use comint
2367;; where needed. However, there are `third-party' packages out there that
2368;; still use the old shell mode. Here's a guide to conversion.
2369;;
2370;; Renaming variables
2371;; Most of the work is renaming variables and functions. These are the common
2372;; ones:
2373;; Local variables:
2374;; last-input-start comint-last-input-start
2375;; last-input-end comint-last-input-end
2376;; shell-prompt-pattern comint-prompt-regexp
2377;; shell-set-directory-error-hook <no equivalent>
2378;; Miscellaneous:
2379;; shell-set-directory <unnecessary>
2380;; shell-mode-map comint-mode-map
2381;; Commands:
2382;; shell-send-input comint-send-input
2383;; shell-send-eof comint-delchar-or-maybe-eof
2384;; kill-shell-input comint-kill-input
2385;; interrupt-shell-subjob comint-interrupt-subjob
2386;; stop-shell-subjob comint-stop-subjob
2387;; quit-shell-subjob comint-quit-subjob
2388;; kill-shell-subjob comint-kill-subjob
2389;; kill-output-from-shell comint-kill-output
2390;; show-output-from-shell comint-show-output
2391;; copy-last-shell-input Use comint-previous-input/comint-next-input
2392;;
2393;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
2394;; SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-filter-functions.
2395;; Comint mode does not provide functionality equivalent to
2396;; shell-set-directory-error-hook; it is gone.
2397;;
2398;; comint-last-input-start is provided for modes which want to munge
2399;; the buffer after input is sent, perhaps because the inferior
2400;; insists on echoing the input. The LAST-INPUT-START variable in
2401;; the old shell package was used to implement a history mechanism,
2402;; but you should think twice before using comint-last-input-start
2403;; for this; the input history ring often does the job better.
2404;;
2405;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
2406;; *not* create the comint-mode local variables in your foo-mode function.
2407;; This is not modular. Instead, call comint-mode, and let *it* create the
2408;; necessary comint-specific local variables. Then create the
2409;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
2410;; be foo-mode-map, and its mode to be foo-mode. Set the comint-mode hooks
2411;; (comint-{prompt-regexp, input-filter, input-filter-functions,
2412;; get-old-input) that need to be different from the defaults. Call
2413;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
2414;; comint-mode will take care of it. The following example, from shell.el,
2415;; is typical:
2416;;
2417;; (defvar shell-mode-map '())
2418;; (cond ((not shell-mode-map)
2419;; (setq shell-mode-map (copy-keymap comint-mode-map))
2420;; (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
2421;; (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
2422;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
2423;; (define-key shell-mode-map "\M-?"
2424;; 'comint-dynamic-list-filename-completions)))
2425;;
2426;; (defun shell-mode ()
2427;; (interactive)
2428;; (comint-mode)
2429;; (setq comint-prompt-regexp shell-prompt-pattern)
2430;; (setq major-mode 'shell-mode)
2431;; (setq mode-name "Shell")
2432;; (use-local-map shell-mode-map)
2433;; (make-local-variable 'shell-directory-stack)
2434;; (setq shell-directory-stack nil)
2435;; (add-hook 'comint-input-filter-functions 'shell-directory-tracker)
2436;; (run-hooks 'shell-mode-hook))
2437;;
2438;;
b578f267
EN
2439;; Completion for comint-mode users
2440;;
2441;; For modes that use comint-mode, comint-dynamic-complete-functions is the
2442;; hook to add completion functions to. Functions on this list should return
2443;; non-nil if completion occurs (i.e., further completion should not occur).
2444;; You could use comint-dynamic-simple-complete to do the bulk of the
2445;; completion job.
49116ac0 2446\f
49116ac0 2447(provide 'comint)
c0274f38 2448
b578f267 2449;; comint.el ends here