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