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