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