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