1 ;;; comint.el --- general command interpreter in a window stuff
3 ;; Copyright (C) 1988, 1990, 1992, 1993, 1994 Free Software Foundation, Inc.
5 ;; Author: Olin Shivers <shivers@cs.cmu.edu>
6 ;; Adapted-by: Simon Marshall <simon@gnu.ai.mit.edu>
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)
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.
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.
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
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
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.
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-send - 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.
143 Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
144 Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
145 franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
147 shell: \"^[^#$%>\\n]*[#$%>] *\"
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.
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.
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]
350 Entry to this mode runs the hooks on `comint-mode-hook'."
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-variable 'comint-dynamic-complete-functions)
380 (make-local-variable 'comint-completion-fignore)
381 (make-local-variable 'comint-get-old-input)
382 (make-local-variable '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-variable '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))
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)
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))
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))
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).
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 (let ((buffer (get-buffer-create (concat "*" name "*"))))
517 ;; If no process, or nuked process, crank up a new one and put buffer in
518 ;; comint mode. Otherwise, leave buffer and existing process alone.
519 (cond ((not (comint-check-proc buffer))
522 (comint-mode)) ; Install local vars, mode, keymap, ...
523 (comint-exec buffer name program startfile switches)))
527 (defun comint-run (program)
528 "Run PROGRAM in a comint buffer and switch to it.
529 The buffer name is made by surrounding the file name of PROGRAM with `*'s.
530 The file name is used to make a symbol name, such as `comint-sh-hook', and any
531 hooks on this symbol are run in the buffer.
532 See `make-comint' and `comint-exec'."
533 (interactive "sRun program: ")
534 (let ((name (file-name-nondirectory program)))
535 (switch-to-buffer (make-comint name program))
536 (run-hooks (intern-soft (concat "comint-" name "-hook")))))
538 (defun comint-exec (buffer name command startfile switches)
539 "Start up a process in buffer BUFFER for comint modes.
540 Blasts any old process running in the buffer. Doesn't set the buffer mode.
541 You can use this to cheaply run a series of processes in the same comint
542 buffer. The hook `comint-exec-hook' is run after each exec."
545 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
546 (if proc (delete-process proc)))
547 ;; Crank up a new process
550 (open-network-stream name buffer (car command) (cdr command))
551 (comint-exec-1 name buffer command switches))))
552 (set-process-filter proc 'comint-output-filter)
553 (make-local-variable 'comint-ptyp)
554 (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
555 ;; Jump to the end, and set the process mark.
556 (goto-char (point-max))
557 (set-marker (process-mark proc) (point))
558 ;; Feed it the startfile.
560 ;;This is guaranteed to wait long enough
561 ;;but has bad results if the comint does not prompt at all
562 ;; (while (= size (buffer-size))
564 ;;I hope 1 second is enough!
566 (goto-char (point-max))
567 (insert-file-contents startfile)
568 (setq startfile (buffer-substring (point) (point-max)))
569 (delete-region (point) (point-max))
570 (comint-send-string proc startfile)))
571 (run-hooks 'comint-exec-hook)
574 ;;; This auxiliary function cranks up the process for comint-exec in
575 ;;; the appropriate environment.
577 (defun comint-exec-1 (name buffer command switches)
578 (let ((process-environment
580 ;; If using termcap, we specify `emacs' as the terminal type
581 ;; because that lets us specify a width.
582 ;; If using terminfo, we specify `unknown' because that is
583 ;; a defined terminal type. `emacs' is not a defined terminal type
584 ;; and there is no way for us to define it here.
585 ;; Some programs that use terminfo get very confused
586 ;; if TERM is not a valid terminal type.
587 (if (and (boundp 'system-uses-terminfo) system-uses-terminfo)
588 (list "EMACS=t" "TERM=unknown"
589 (format "COLUMNS=%d" (frame-width)))
590 (list "EMACS=t" "TERM=emacs"
591 (format "TERMCAP=emacs:co#%d:tc=unknown:" (frame-width))))
592 process-environment))
594 (if (file-directory-p default-directory)
597 (apply 'start-process name buffer command switches)))
599 ;;; Input history processing in a buffer
600 ;;; ===========================================================================
601 ;;; Useful input history functions, courtesy of the Ergo group.
604 ;;; comint-dynamic-list-input-ring List history in help buffer.
605 ;;; comint-previous-input Previous input...
606 ;;; comint-previous-matching-input ...matching a string.
607 ;;; comint-previous-matching-input-from-input ... matching the current input.
608 ;;; comint-next-input Next input...
609 ;;; comint-next-matching-input ...matching a string.
610 ;;; comint-next-matching-input-from-input ... matching the current input.
611 ;;; comint-backward-matching-input Backwards input...
612 ;;; comint-forward-matching-input ...matching a string.
613 ;;; comint-replace-by-expanded-history Expand history at point;
614 ;;; replace with expanded history.
615 ;;; comint-magic-space Expand history and insert space.
618 ;;; comint-read-input-ring Read into comint-input-ring...
619 ;;; comint-write-input-ring Write to comint-input-ring-file-name.
620 ;;; comint-replace-by-expanded-history-before-point Workhorse function.
622 (defun comint-read-input-ring (&optional silent)
623 "Sets the buffer's `comint-input-ring' from a history file.
624 The name of the file is given by the variable `comint-input-ring-file-name'.
625 The history ring is of size `comint-input-ring-size', regardless of file size.
626 If `comint-input-ring-file-name' is nil this function does nothing.
628 If the optional argument SILENT is non-nil, we say nothing about a
629 failure to read the history file.
631 This function is useful for major mode commands and mode hooks.
633 The structure of the history file should be one input command per line,
634 with the most recent command last.
635 See also `comint-input-ignoredups' and `comint-write-input-ring'."
636 (cond ((or (null comint-input-ring-file-name)
637 (equal comint-input-ring-file-name ""))
639 ((not (file-readable-p comint-input-ring-file-name))
641 (message "Cannot read history file %s"
642 comint-input-ring-file-name)))
644 (let ((history-buf (get-buffer-create " *temp*"))
645 (file comint-input-ring-file-name)
647 (ring (make-ring comint-input-ring-size)))
650 (set-buffer history-buf)
653 (insert-file-contents file)
654 ;; Save restriction in case file is already visited...
655 ;; Watch for those date stamps in history files!
656 (goto-char (point-max))
657 (while (and (< count comint-input-ring-size)
658 (re-search-backward "^[ \t]*\\([^#\n].*\\)[ \t]*$"
660 (let ((history (buffer-substring (match-beginning 1)
662 (if (or (null comint-input-ignoredups)
664 (not (string-equal (ring-ref ring 0) history)))
665 (ring-insert-at-beginning ring history)))
666 (setq count (1+ count))))
667 (kill-buffer history-buf))
668 (setq comint-input-ring ring
669 comint-input-ring-index nil)))))
671 (defun comint-write-input-ring ()
672 "Writes the buffer's `comint-input-ring' to a history file.
673 The name of the file is given by the variable `comint-input-ring-file-name'.
674 The original contents of the file are lost if `comint-input-ring' is not empty.
675 If `comint-input-ring-file-name' is nil this function does nothing.
677 Useful within process sentinels.
679 See also `comint-read-input-ring'."
680 (cond ((or (null comint-input-ring-file-name)
681 (equal comint-input-ring-file-name "")
682 (null comint-input-ring) (ring-empty-p comint-input-ring))
684 ((not (file-writable-p comint-input-ring-file-name))
685 (message "Cannot write history file %s" comint-input-ring-file-name))
687 (let* ((history-buf (get-buffer-create " *Temp Input History*"))
688 (ring comint-input-ring)
689 (file comint-input-ring-file-name)
690 (index (ring-length ring)))
691 ;; Write it all out into a buffer first. Much faster, but messier,
692 ;; than writing it one line at a time.
694 (set-buffer history-buf)
697 (setq index (1- index))
698 (insert (ring-ref ring index) ?\n))
699 (write-region (buffer-string) nil file nil 'no-message)
700 (kill-buffer nil))))))
703 (defun comint-dynamic-list-input-ring ()
704 "List in help buffer the buffer's input history."
706 (if (or (not (ring-p comint-input-ring))
707 (ring-empty-p comint-input-ring))
708 (message "No history")
710 (history-buffer " *Input History*")
711 (index (1- (ring-length comint-input-ring)))
712 (conf (current-window-configuration)))
713 ;; We have to build up a list ourselves from the ring vector.
715 (setq history (cons (ring-ref comint-input-ring index) history)
717 ;; Change "completion" to "history reference"
718 ;; to make the display accurate.
719 (with-output-to-temp-buffer history-buffer
720 (display-completion-list history)
721 (set-buffer history-buffer)
723 (while (search-backward "completion" nil 'move)
724 (replace-match "history reference")))
726 (message "Hit space to flush")
727 (let ((ch (read-event)))
729 (set-window-configuration conf)
730 (setq unread-command-events (list ch)))))))
733 (defun comint-regexp-arg (prompt)
734 ;; Return list of regexp and prefix arg using PROMPT.
735 (let* ((minibuffer-history-sexp-flag nil)
736 ;; Don't clobber this.
737 (last-command last-command)
738 (regexp (read-from-minibuffer prompt nil nil nil
739 'minibuffer-history-search-history)))
740 (list (if (string-equal regexp "")
741 (setcar minibuffer-history-search-history
742 (nth 1 minibuffer-history-search-history))
744 (prefix-numeric-value current-prefix-arg))))
746 (defun comint-search-arg (arg)
747 ;; First make sure there is a ring and that we are after the process mark
748 (cond ((not (comint-after-pmark-p))
749 (error "Not at command line"))
750 ((or (null comint-input-ring)
751 (ring-empty-p comint-input-ring))
752 (error "Empty input ring"))
754 ;; arg of zero resets search from beginning, and uses arg of 1
755 (setq comint-input-ring-index nil)
760 (defun comint-search-start (arg)
761 ;; Index to start a directional search, starting at comint-input-ring-index
762 (if comint-input-ring-index
763 ;; If a search is running, offset by 1 in direction of arg
764 (mod (+ comint-input-ring-index (if (> arg 0) 1 -1))
765 (ring-length comint-input-ring))
766 ;; For a new search, start from beginning or end, as appropriate
768 0 ; First elt for forward search
769 (1- (ring-length comint-input-ring))))) ; Last elt for backward search
771 (defun comint-previous-input-string (arg)
772 "Return the string ARG places along the input ring.
773 Moves relative to `comint-input-ring-index'."
774 (ring-ref comint-input-ring (if comint-input-ring-index
775 (mod (+ arg comint-input-ring-index)
776 (ring-length comint-input-ring))
779 (defun comint-previous-input (arg)
780 "Cycle backwards through input history."
782 (comint-previous-matching-input "." arg))
784 (defun comint-next-input (arg)
785 "Cycle forwards through input history."
787 (comint-previous-input (- arg)))
789 (defun comint-previous-matching-input-string (regexp arg)
790 "Return the string matching REGEXP ARG places along the input ring.
791 Moves relative to `comint-input-ring-index'."
792 (let* ((pos (comint-previous-matching-input-string-position regexp arg)))
793 (if pos (ring-ref comint-input-ring pos))))
795 (defun comint-previous-matching-input-string-position (regexp arg &optional start)
796 "Return the index matching REGEXP ARG places along the input ring.
797 Moves relative to START, or `comint-input-ring-index'."
798 (if (or (not (ring-p comint-input-ring))
799 (ring-empty-p comint-input-ring))
800 (error "No history"))
801 (let* ((len (ring-length comint-input-ring))
802 (motion (if (> arg 0) 1 -1))
803 (n (mod (- (or start (comint-search-start arg)) motion) len))
804 (tried-each-ring-item nil)
806 ;; Do the whole search as many times as the argument says.
807 (while (and (/= arg 0) (not tried-each-ring-item))
810 n (mod (+ n motion) len))
811 ;; If we haven't reached a match, step some more.
812 (while (and (< n len) (not tried-each-ring-item)
813 (not (string-match regexp (ring-ref comint-input-ring n))))
814 (setq n (mod (+ n motion) len)
815 ;; If we have gone all the way around in this search.
816 tried-each-ring-item (= n prev)))
817 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
818 ;; Now that we know which ring element to use, if we found it, return that.
819 (if (string-match regexp (ring-ref comint-input-ring n))
822 (defun comint-previous-matching-input (regexp arg)
823 "Search backwards through input history for match for REGEXP.
824 \(Previous history elements are earlier commands.)
825 With prefix argument N, search for Nth previous match.
826 If N is negative, find the next or Nth next match."
827 (interactive (comint-regexp-arg "Previous input matching (regexp): "))
828 (setq arg (comint-search-arg arg))
829 (let ((pos (comint-previous-matching-input-string-position regexp arg)))
830 ;; Has a match been found?
833 (setq comint-input-ring-index pos)
834 (message "History item: %d" (1+ pos))
836 ;; Can't use kill-region as it sets this-command
837 (process-mark (get-buffer-process (current-buffer))) (point))
838 (insert (ring-ref comint-input-ring pos)))))
840 (defun comint-next-matching-input (regexp arg)
841 "Search forwards through input history for match for REGEXP.
842 \(Later history elements are more recent commands.)
843 With prefix argument N, search for Nth following match.
844 If N is negative, find the previous or Nth previous match."
845 (interactive (comint-regexp-arg "Next input matching (regexp): "))
846 (comint-previous-matching-input regexp (- arg)))
848 (defun comint-previous-matching-input-from-input (arg)
849 "Search backwards through input history for match for current input.
850 \(Previous history elements are earlier commands.)
851 With prefix argument N, search for Nth previous match.
852 If N is negative, search forwards for the -Nth following match."
854 (if (not (memq last-command '(comint-previous-matching-input-from-input
855 comint-next-matching-input-from-input)))
856 ;; Starting a new search
857 (setq comint-matching-input-from-input-string
859 (process-mark (get-buffer-process (current-buffer)))
861 comint-input-ring-index nil))
862 (comint-previous-matching-input
863 (concat "^" (regexp-quote comint-matching-input-from-input-string))
866 (defun comint-next-matching-input-from-input (arg)
867 "Search forwards through input history for match for current input.
868 \(Following history elements are more recent commands.)
869 With prefix argument N, search for Nth following match.
870 If N is negative, search backwards for the -Nth previous match."
872 (comint-previous-matching-input-from-input (- arg)))
875 (defun comint-replace-by-expanded-history (&optional silent)
876 "Expand input command history references before point.
877 Expansion is dependent on the value of `comint-input-autoexpand'.
879 This function depends on the buffer's idea of the input history, which may not
880 match the command interpreter's idea, assuming it has one.
882 Assumes history syntax is like typical Un*x shells'. However, since emacs
883 cannot know the interpreter's idea of input line numbers, assuming it has one,
884 it cannot expand absolute input line number references.
886 If the optional argument SILENT is non-nil, never complain
887 even if history reference seems erroneous.
889 See `comint-magic-space' and `comint-replace-by-expanded-history-before-point'.
891 Returns t if successful."
893 (if (and comint-input-autoexpand
894 (string-match "[!^]" (funcall comint-get-old-input))
895 (save-excursion (beginning-of-line)
896 (looking-at comint-prompt-regexp)))
897 ;; Looks like there might be history references in the command.
898 (let ((previous-modified-tick (buffer-modified-tick)))
899 (message "Expanding history references...")
900 (comint-replace-by-expanded-history-before-point silent)
901 (/= previous-modified-tick (buffer-modified-tick)))))
904 (defun comint-replace-by-expanded-history-before-point (silent)
905 "Expand directory stack reference before point.
906 See `comint-replace-by-expanded-history'. Returns t if successful."
908 (let ((toend (- (save-excursion (end-of-line nil) (point)) (point)))
909 (start (progn (comint-bol nil) (point))))
911 (skip-chars-forward "^!^"
913 (end-of-line nil) (- (point) toend)))
916 (end-of-line nil) (- (point) toend))))
917 ;; This seems a bit complex. We look for references such as !!, !-num,
918 ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
919 ;; If that wasn't enough, the plings can be suffixed with argument
921 ;; Argument ranges are complex too, so we hive off the input line,
922 ;; referenced with plings, with the range string to `comint-args'.
923 (setq comint-input-ring-index nil)
924 (cond ((or (= (preceding-char) ?\\)
925 (comint-within-quotes start (point)))
926 ;; The history is quoted, or we're in quotes.
927 (goto-char (1+ (point))))
928 ((looking-at "![0-9]+\\($\\|[^-]\\)")
929 ;; We cannot know the interpreter's idea of input line numbers.
930 (goto-char (match-end 0))
931 (message "Absolute reference cannot be expanded"))
932 ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
933 ;; Just a number of args from `number' lines backward.
934 (let ((number (1- (string-to-number
935 (buffer-substring (match-beginning 1)
937 (if (<= number (ring-length comint-input-ring))
940 (comint-args (comint-previous-input-string number)
941 (match-beginning 2) (match-end 2))
943 (setq comint-input-ring-index number)
944 (message "History item: %d" (1+ number)))
945 (goto-char (match-end 0))
946 (message "Relative reference exceeds input history size"))))
947 ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
948 ;; Just a number of args from the previous input line.
950 (comint-args (comint-previous-input-string 0)
951 (match-beginning 1) (match-end 1))
953 (message "History item: previous"))
955 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
956 ;; Most recent input starting with or containing (possibly
957 ;; protected) string, maybe just a number of args. Phew.
958 (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
959 (mb2 (match-beginning 2)) (me2 (match-end 2))
960 (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
961 (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
962 (pos (save-match-data
963 (comint-previous-matching-input-string-position
964 (concat pref (regexp-quote exp)) 1))))
967 (goto-char (match-end 0))
969 (progn (message "Not found")
971 (setq comint-input-ring-index pos)
973 (comint-args (ring-ref comint-input-ring pos)
974 (match-beginning 4) (match-end 4))
976 (message "History item: %d" (1+ pos)))))
977 ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
978 ;; Quick substitution on the previous input line.
979 (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
980 (new (buffer-substring (match-beginning 2) (match-end 2)))
982 (replace-match (comint-previous-input-string 0) t t)
984 (goto-char (match-beginning 0))
985 (if (not (search-forward old pos t))
988 (replace-match new t t)
989 (message "History item: substituted"))))
991 (goto-char (match-end 0))))))))
994 (defun comint-magic-space (arg)
995 "Expand input history references before point and insert ARG spaces.
996 A useful command to bind to SPC. See `comint-replace-by-expanded-history'."
998 (comint-replace-by-expanded-history)
999 (self-insert-command arg))
1001 (defun comint-within-quotes (beg end)
1002 "Return t if the number of quotes between BEG and END is odd.
1003 Quotes are single and double."
1004 (let ((countsq (comint-how-many-region "\\(^\\|[^\\\\]\\)\'" beg end))
1005 (countdq (comint-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
1006 (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
1008 (defun comint-how-many-region (regexp beg end)
1009 "Return number of matches for REGEXP from BEG to END."
1014 (while (re-search-forward regexp end t)
1015 (setq count (1+ count)))))
1018 (defun comint-args (string begin end)
1019 ;; From STRING, return the args depending on the range specified in the text
1020 ;; from BEGIN to END. If BEGIN is nil, assume all args. Ignore leading `:'.
1021 ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
1024 (comint-arguments string 0 nil)
1025 (let* ((range (buffer-substring
1026 (if (eq (char-after begin) ?:) (1+ begin) begin) end))
1027 (nth (cond ((string-match "^[*^]" range) 1)
1028 ((string-match "^-" range) 0)
1029 ((string-equal range "$") nil)
1030 (t (string-to-number range))))
1031 (mth (cond ((string-match "[-*$]$" range) nil)
1032 ((string-match "-" range)
1033 (string-to-number (substring range (match-end 0))))
1035 (comint-arguments string nth mth)))))
1037 ;; Return a list of arguments from ARG. Break it up at the
1038 ;; delimiters in comint-delimiter-argument-list. Returned list is backwards.
1039 (defun comint-delim-arg (arg)
1040 (if (null comint-delimiter-argument-list)
1046 (let ((char (aref arg pos))
1048 (if (memq char comint-delimiter-argument-list)
1049 (while (and (< pos len) (eq (aref arg pos) char))
1050 (setq pos (1+ pos)))
1051 (while (and (< pos len)
1052 (not (memq (aref arg pos)
1053 comint-delimiter-argument-list)))
1054 (setq pos (1+ pos))))
1055 (setq args (cons (substring arg start pos) args))))
1058 (defun comint-arguments (string nth mth)
1059 "Return from STRING the NTH to MTH arguments.
1060 NTH and/or MTH can be nil, which means the last argument.
1061 Returned arguments are separated by single spaces.
1062 We assume whitespace separates arguments, except within quotes.
1063 Also, a run of one or more of a single character
1064 in `comint-delimiter-argument-list' is a separate argument.
1065 Argument 0 is the command name."
1066 (let ((argpart "[^ \n\t\"'`]+\\|\\(\"[^\"]*\"\\|'[^']*'\\|`[^`]*`\\)")
1069 beg str value quotes)
1070 ;; Build a list of all the args until we have as many as we want.
1071 (while (and (or (null mth) (<= count mth))
1072 (string-match argpart string pos))
1073 (if (and beg (= pos (match-beginning 0)))
1074 ;; It's contiguous, part of the same arg.
1075 (setq pos (match-end 0)
1076 quotes (or quotes (match-beginning 1)))
1077 ;; It's a new separate arg.
1079 ;; Put the previous arg, if there was one, onto ARGS.
1080 (setq str (substring string beg pos)
1081 args (if quotes (cons str args)
1082 (nconc (comint-delim-arg str) args))
1084 (setq quotes (match-beginning 1))
1085 (setq beg (match-beginning 0))
1086 (setq pos (match-end 0))))
1088 (setq str (substring string beg pos)
1089 args (if quotes (cons str args)
1090 (nconc (comint-delim-arg str) args))
1092 (let ((n (or nth (1- count)))
1093 (m (if mth (1- (- count mth)) 0)))
1095 (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
1098 ;;; Input processing stuff
1101 (defun comint-send-input ()
1102 "Send input to process.
1103 After the process output mark, sends all text from the process mark to
1104 point as input to the process. Before the process output mark, calls value
1105 of variable `comint-get-old-input' to retrieve old input, copies it to the
1106 process mark, and sends it. If variable `comint-process-echoes' is nil,
1107 a terminal newline is also inserted into the buffer and sent to the process
1108 \(if it is non-nil, all text from the process mark to point is deleted,
1109 since it is assumed the remote process will re-echo it).
1111 Any history reference may be expanded depending on the value of the variable
1112 `comint-input-autoexpand'. The list of function names contained in the value
1113 of `comint-input-filter-functions' is called on the input before sending it.
1114 The input is entered into the input history ring, if the value of variable
1115 `comint-input-filter' returns non-nil when called on the input.
1117 If variable `comint-eol-on-send' is non-nil, then point is moved to the
1118 end of line before sending the input.
1120 The values of `comint-get-old-input', `comint-input-filter-functions', and
1121 `comint-input-filter' are chosen according to the command interpreter running
1122 in the buffer. E.g.,
1124 If the interpreter is the csh,
1125 comint-get-old-input is the default: take the current line, discard any
1126 initial string matching regexp comint-prompt-regexp.
1127 comint-input-filter-functions monitors input for \"cd\", \"pushd\", and
1128 \"popd\" commands. When it sees one, it cd's the buffer.
1129 comint-input-filter is the default: returns t if the input isn't all white
1132 If the comint is Lucid Common Lisp,
1133 comint-get-old-input snarfs the sexp ending at point.
1134 comint-input-filter-functions does nothing.
1135 comint-input-filter returns nil if the input matches input-filter-regexp,
1136 which matches (1) all whitespace (2) :a, :c, etc.
1138 Similarly for Soar, Scheme, etc."
1140 ;; Note that the input string does not include its terminal newline.
1141 (let ((proc (get-buffer-process (current-buffer))))
1142 (if (not proc) (error "Current buffer has no process")
1143 (let* ((pmark (process-mark proc))
1144 (intxt (if (>= (point) (marker-position pmark))
1145 (progn (if comint-eol-on-send (end-of-line))
1146 (buffer-substring pmark (point)))
1147 (let ((copy (funcall comint-get-old-input)))
1151 (input (if (not (eq comint-input-autoexpand 'input))
1152 ;; Just whatever's already there
1154 ;; Expand and leave it visible in buffer
1155 (comint-replace-by-expanded-history t)
1156 (buffer-substring pmark (point))))
1157 (history (if (not (eq comint-input-autoexpand 'history))
1159 ;; This is messy 'cos ultimately the original
1160 ;; functions used do insertion, rather than return
1161 ;; strings. We have to expand, then insert back.
1162 (comint-replace-by-expanded-history t)
1163 (let ((copy (buffer-substring pmark (point))))
1164 (delete-region pmark (point))
1167 (if comint-process-echoes
1168 (delete-region pmark (point))
1170 (if (and (funcall comint-input-filter history)
1171 (or (null comint-input-ignoredups)
1172 (not (ring-p comint-input-ring))
1173 (ring-empty-p comint-input-ring)
1174 (not (string-equal (ring-ref comint-input-ring 0)
1176 (ring-insert comint-input-ring history))
1177 (let ((functions comint-input-filter-functions))
1179 (funcall (car functions) (concat input "\n"))
1180 (setq functions (cdr functions))))
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))
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)
1230 (let ((functions comint-output-filter-functions))
1232 (funcall (car functions) string)
1233 (setq functions (cdr functions))))
1234 (set-buffer obuf)))))
1236 (defun comint-preinput-scroll-to-bottom ()
1237 "Go to the end of buffer in all windows showing it.
1238 Movement occurs if point in the selected window is not after the process mark,
1239 and `this-command' is an insertion command. Insertion commands recognised
1240 are `self-insert-command', `comint-magic-space', `yank', and `hilit-yank'.
1241 Depends on the value of `comint-scroll-to-bottom-on-input'.
1243 This function should be a pre-command hook."
1244 (if (and comint-scroll-to-bottom-on-input
1245 (memq this-command '(self-insert-command comint-magic-space yank
1247 (let* ((selected (selected-window))
1248 (current (current-buffer))
1249 (process (get-buffer-process current))
1250 (scroll comint-scroll-to-bottom-on-input))
1251 (if (and process (< (point) (process-mark process)))
1252 (if (eq scroll 'this)
1253 (goto-char (point-max))
1255 (function (lambda (window)
1256 (if (and (eq (window-buffer window) current)
1257 (or (eq scroll t) (eq scroll 'all)))
1259 (select-window window)
1260 (goto-char (point-max))
1261 (select-window selected)))))
1264 (defun comint-postoutput-scroll-to-bottom (string)
1265 "Go to the end of buffer in all windows showing it.
1266 Does not scroll if the current line is the last line in the buffer.
1267 Depends on the value of `comint-scroll-to-bottom-on-output' and
1268 `comint-scroll-show-maximum-output'.
1270 This function should be in the list `comint-output-filter-functions'."
1271 (let* ((selected (selected-window))
1272 (current (current-buffer))
1273 (process (get-buffer-process current))
1274 (scroll comint-scroll-to-bottom-on-output))
1278 (function (lambda (window)
1279 (if (eq (window-buffer window) current)
1281 (select-window window)
1282 (if (and (< (point) (process-mark process))
1283 (or (eq scroll t) (eq scroll 'all)
1284 ;; Maybe user wants point to jump to the end.
1285 (and (eq scroll 'this) (eq selected window))
1286 (and (eq scroll 'others) (not (eq selected window)))
1287 ;; If point was at the end, keep it at the end.
1289 (- (process-mark process) (length string)))))
1290 (goto-char (process-mark process)))
1291 ;; Optionally scroll so that the text
1292 ;; ends at the bottom of the window.
1293 (if (and comint-scroll-show-maximum-output
1294 (>= (point) (process-mark process)))
1296 (goto-char (point-max))
1298 (select-window selected)))))
1300 (set-buffer current))))
1302 (defun comint-truncate-buffer (&optional string)
1303 "Truncate the buffer to `comint-buffer-maximum-size'.
1304 This function could be on `comint-output-filter-functions' or bound to a key."
1307 (goto-char (point-max))
1308 (forward-line (- comint-buffer-maximum-size))
1310 (delete-region (point-min) (point))))
1312 (defun comint-strip-ctrl-m (&optional string)
1313 "Strip trailing `^M' characters from the current output group.
1314 This function could be on `comint-output-filter-functions' or bound to a key."
1316 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1319 (if (interactive-p) comint-last-input-end comint-last-output-start))
1320 (while (re-search-forward "\r+$" pmark t)
1321 (replace-match "" t t)))))
1322 (defalias 'shell-strip-ctrl-m 'comint-strip-ctrl-m)
1324 (defun comint-show-maximum-output ()
1325 "Put the end of the buffer at the bottom of the window."
1327 (goto-char (point-max))
1330 (defun comint-get-old-input-default ()
1331 "Default for `comint-get-old-input'.
1332 Take the current line, and discard any initial text matching
1333 `comint-prompt-regexp'."
1336 (comint-skip-prompt)
1337 (let ((beg (point)))
1339 (buffer-substring beg (point)))))
1341 (defun comint-copy-old-input ()
1342 "Insert after prompt old input at point as new input to be edited.
1343 Calls `comint-get-old-input' to get old input."
1345 (let ((input (funcall comint-get-old-input))
1346 (process (get-buffer-process (current-buffer))))
1348 (error "Current buffer has no process")
1349 (goto-char (process-mark process))
1352 (defun comint-skip-prompt ()
1353 "Skip past the text matching regexp `comint-prompt-regexp'.
1354 If this takes us past the end of the current line, don't skip at all."
1355 (let ((eol (save-excursion (end-of-line) (point))))
1356 (if (and (looking-at comint-prompt-regexp)
1357 (<= (match-end 0) eol))
1358 (goto-char (match-end 0)))))
1360 (defun comint-after-pmark-p ()
1361 "Return t if point is after the process output marker."
1362 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1363 (<= (marker-position pmark) (point))))
1365 (defun comint-simple-send (proc string)
1366 "Default function for sending to PROC input STRING.
1367 This just sends STRING plus a newline. To override this,
1368 set the hook `comint-input-sender'."
1369 (comint-send-string proc string)
1370 (comint-send-string proc "\n"))
1372 (defun comint-bol (arg)
1373 "Goes to the beginning of line, then skips past the prompt, if any.
1374 If prefix argument is given (\\[universal-argument]) the prompt is not skipped.
1376 The prompt skip is done by skipping text matching the regular expression
1377 `comint-prompt-regexp', a buffer local variable."
1380 (if (null arg) (comint-skip-prompt)))
1382 ;;; These three functions are for entering text you don't want echoed or
1383 ;;; saved -- typically passwords to ftp, telnet, or somesuch.
1384 ;;; Just enter m-x send-invisible and type in your line, or add
1385 ;;; `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
1387 (defun comint-read-noecho (prompt &optional stars)
1388 "Read a single line of text from user without echoing, and return it.
1389 Prompt with argument PROMPT, a string. Optional argument STARS causes
1390 input to be echoed with '*' characters on the prompt line. Input ends with
1391 RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line. C-g aborts (if
1392 `inhibit-quit' is set because e.g. this function was called from a process
1393 filter and C-g is pressed, this function returns nil rather than a string).
1395 Note that the keystrokes comprising the text can still be recovered
1396 \(temporarily) with \\[view-lossage]. This may be a security bug for some
1401 (cursor-in-echo-area t)
1402 (message-log-max nil)
1406 (message "%s%s" prompt (make-string (length ans) ?*))
1407 (message "%s" prompt))
1408 ;; Use this instead of `read-char' to avoid "Non-character input-event".
1409 (setq c (read-char-exclusive))
1411 ;; This function may get called from a process filter, where
1412 ;; inhibit-quit is set. In later versions of emacs read-char
1413 ;; may clear quit-flag itself and return C-g. That would make
1414 ;; it impossible to quit this loop in a simple way, so
1415 ;; re-enable it here (for backward-compatibility the check for
1416 ;; quit-flag below would still be necessary, so this seems
1417 ;; like the simplest way to do things).
1420 ((or (= c ?\r) (= c ?\n) (= c ?\e))
1424 ((and (/= c ?\b) (/= c ?\177))
1425 (setq ans (concat ans (char-to-string c))))
1427 (setq ans (substring ans 0 -1)))))
1429 ;; Emulate a true quit, except that we have to return a value.
1431 (setq quit-flag nil)
1437 (defun send-invisible (str)
1438 "Read a string without echoing.
1439 Then send it to the process running in the current buffer. A new-line
1440 is additionally sent. String is not saved on comint input history list.
1441 Security bug: your string can still be temporarily recovered with
1443 (interactive "P") ; Defeat snooping via C-x esc
1444 (let ((proc (get-buffer-process (current-buffer))))
1446 (error "Current buffer has no process")
1448 proc (if (stringp str) str (comint-read-noecho "Non-echoed text: " t)))
1449 (comint-send-string proc "\n"))))
1451 (defun comint-watch-for-password-prompt (string)
1452 "Prompt in the minibuffer for password and send without echoing.
1453 This function uses `send-invisible' to read and send a password to the buffer's
1454 process if STRING contains a password prompt defined by
1455 `comint-password-prompt-regexp'.
1457 This function could be in the list `comint-output-filter-functions'."
1458 (if (string-match comint-password-prompt-regexp string)
1459 (send-invisible nil)))
1461 ;;; Low-level process communication
1463 (defalias 'comint-send-string 'process-send-string)
1464 (defalias 'comint-send-region 'process-send-region)
1466 ;;; Random input hackage
1468 (defun comint-kill-output ()
1469 "Kill all output from interpreter since last input.
1470 Does not delete the prompt."
1472 (let ((proc (get-buffer-process (current-buffer)))
1475 (let ((pmark (progn (goto-char (process-mark proc))
1476 (beginning-of-line nil)
1478 (delete-region comint-last-input-end pmark)
1479 (comint-skip-prompt)
1480 (setq replacement (concat "*** output flushed ***\n"
1481 (buffer-substring pmark (point))))
1482 (delete-region pmark (point))))
1483 ;; Output message and put back prompt
1484 (comint-output-filter proc replacement)))
1486 (defun comint-show-output ()
1487 "Display start of this batch of interpreter output at top of window.
1488 Sets mark to the value of point when this command is run."
1491 (let ((pos (point)))
1492 (goto-char (or (marker-position comint-last-input-end) (point-max)))
1493 (beginning-of-line 0)
1494 (set-window-start (selected-window) (point))
1495 (comint-skip-prompt)))
1497 (defun comint-interrupt-subjob ()
1498 "Interrupt the current subjob."
1500 (interrupt-process nil comint-ptyp))
1502 (defun comint-kill-subjob ()
1503 "Send kill signal to the current subjob."
1505 (kill-process nil comint-ptyp))
1507 (defun comint-quit-subjob ()
1508 "Send quit signal to the current subjob."
1510 (quit-process nil comint-ptyp))
1512 (defun comint-stop-subjob ()
1513 "Stop the current subjob.
1514 WARNING: if there is no current subjob, you can end up suspending
1515 the top-level process running in the buffer. If you accidentally do
1516 this, use \\[comint-continue-subjob] to resume the process. (This
1517 is not a problem with most shells, since they ignore this signal.)"
1519 (stop-process nil comint-ptyp))
1521 (defun comint-continue-subjob ()
1522 "Send CONT signal to process buffer's process group.
1523 Useful if you accidentally suspend the top-level process."
1525 (continue-process nil comint-ptyp))
1527 (defun comint-kill-input ()
1528 "Kill all text from last stuff output by interpreter to point."
1530 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1531 (if (> (point) (marker-position pmark))
1532 (kill-region pmark (point)))))
1534 (defun comint-delchar-or-maybe-eof (arg)
1535 "Delete ARG characters forward, or (if at eob) send an EOF to subprocess."
1541 (defun comint-send-eof ()
1542 "Send an EOF to the current buffer's process."
1547 (defun comint-backward-matching-input (regexp arg)
1548 "Search backward through buffer for match for REGEXP.
1549 Matches are searched for on lines that match `comint-prompt-regexp'.
1550 With prefix argument N, search for Nth previous match.
1551 If N is negative, find the next or Nth next match."
1552 (interactive (comint-regexp-arg "Backward input matching (regexp): "))
1553 (let* ((re (concat comint-prompt-regexp ".*" regexp))
1554 (pos (save-excursion (end-of-line (if (> arg 0) 0 1))
1555 (if (re-search-backward re nil t arg)
1558 (progn (message "Not found")
1563 (defun comint-forward-matching-input (regexp arg)
1564 "Search forward through buffer for match for REGEXP.
1565 Matches are searched for on lines that match `comint-prompt-regexp'.
1566 With prefix argument N, search for Nth following match.
1567 If N is negative, find the previous or Nth previous match."
1568 (interactive (comint-regexp-arg "Forward input matching (regexp): "))
1569 (comint-backward-matching-input regexp (- arg)))
1572 (defun comint-next-prompt (n)
1573 "Move to end of Nth next prompt in the buffer.
1574 See `comint-prompt-regexp'."
1576 (let ((paragraph-start comint-prompt-regexp))
1577 (end-of-line (if (> n 0) 1 0))
1578 (forward-paragraph n)
1579 (comint-skip-prompt)))
1581 (defun comint-previous-prompt (n)
1582 "Move to end of Nth previous prompt in the buffer.
1583 See `comint-prompt-regexp'."
1585 (comint-next-prompt (- n)))
1587 ;;; Support for source-file processing commands.
1588 ;;;============================================================================
1589 ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
1590 ;;; commands that process files of source text (e.g. loading or compiling
1591 ;;; files). So the corresponding process-in-a-buffer modes have commands
1592 ;;; for doing this (e.g., lisp-load-file). The functions below are useful
1593 ;;; for defining these commands.
1595 ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
1596 ;;; and Soar, in that they don't know anything about file extensions.
1597 ;;; So the compile/load interface gets the wrong default occasionally.
1598 ;;; The load-file/compile-file default mechanism could be smarter -- it
1599 ;;; doesn't know about the relationship between filename extensions and
1600 ;;; whether the file is source or executable. If you compile foo.lisp
1601 ;;; with compile-file, then the next load-file should use foo.bin for
1602 ;;; the default, not foo.lisp. This is tricky to do right, particularly
1603 ;;; because the extension for executable files varies so much (.o, .bin,
1604 ;;; .lbin, .mo, .vo, .ao, ...).
1607 ;;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
1610 ;;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
1611 ;;; want to save the buffer before issuing any process requests to the command
1614 ;;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
1615 ;;; for the file to process.
1617 ;;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
1618 ;;;============================================================================
1619 ;;; This function computes the defaults for the load-file and compile-file
1620 ;;; commands for tea, soar, cmulisp, and cmuscheme modes.
1622 ;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
1623 ;;; source-file processing command. NIL if there hasn't been one yet.
1624 ;;; - SOURCE-MODES is a list used to determine what buffers contain source
1625 ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
1626 ;;; Typically, (lisp-mode) or (scheme-mode).
1628 ;;; If the command is given while the cursor is inside a string, *and*
1629 ;;; the string is an existing filename, *and* the filename is not a directory,
1630 ;;; then the string is taken as default. This allows you to just position
1631 ;;; your cursor over a string that's a filename and have it taken as default.
1633 ;;; If the command is given in a file buffer whose major mode is in
1634 ;;; SOURCE-MODES, then the the filename is the default file, and the
1635 ;;; file's directory is the default directory.
1637 ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
1638 ;;; then the default directory & file are what was used in the last source-file
1639 ;;; processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
1640 ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
1641 ;;; is the cwd, with no default file. (\"no default file\" = nil)
1643 ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
1644 ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
1645 ;;; for Soar programs, etc.
1647 ;;; The function returns a pair: (default-directory . default-file).
1649 (defun comint-source-default (previous-dir/file source-modes)
1650 (cond ((and buffer-file-name (memq major-mode source-modes))
1651 (cons (file-name-directory buffer-file-name)
1652 (file-name-nondirectory buffer-file-name)))
1655 (cons default-directory nil))))
1658 ;;; (COMINT-CHECK-SOURCE fname)
1659 ;;;============================================================================
1660 ;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
1661 ;;; process-in-a-buffer modes), this function can be called on the filename.
1662 ;;; If the file is loaded into a buffer, and the buffer is modified, the user
1663 ;;; is queried to see if he wants to save the buffer before proceeding with
1664 ;;; the load or compile.
1666 (defun comint-check-source (fname)
1667 (let ((buff (get-file-buffer fname)))
1669 (buffer-modified-p buff)
1670 (y-or-n-p (format "Save buffer %s first? " (buffer-name buff))))
1672 (let ((old-buffer (current-buffer)))
1675 (set-buffer old-buffer)))))
1678 ;;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
1679 ;;;============================================================================
1680 ;;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
1681 ;;; commands that process source files (like loading or compiling a file).
1682 ;;; It prompts for the filename, provides a default, if there is one,
1683 ;;; and returns the result filename.
1685 ;;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
1687 ;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
1688 ;;; from the last source processing command. SOURCE-MODES is a list of major
1689 ;;; modes used to determine what file buffers contain source files. (These
1690 ;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
1691 ;;; then the filename reader will only accept a file that exists.
1694 ;;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
1695 ;;; '(lisp-mode) t))
1697 ;;; This is pretty stupid about strings. It decides we're in a string
1698 ;;; if there's a quote on both sides of point on the current line.
1699 (defun comint-extract-string ()
1700 "Return string around POINT that starts the current line, or nil."
1702 (let* ((point (point))
1703 (bol (progn (beginning-of-line) (point)))
1704 (eol (progn (end-of-line) (point)))
1705 (start (progn (goto-char point)
1706 (and (search-backward "\"" bol t)
1708 (end (progn (goto-char point)
1709 (and (search-forward "\"" eol t)
1712 (buffer-substring start end)))))
1714 (defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
1715 (let* ((def (comint-source-default prev-dir/file source-modes))
1716 (stringfile (comint-extract-string))
1717 (sfile-p (and stringfile
1719 (file-exists-p stringfile)
1721 (not (file-directory-p stringfile))))
1722 (defdir (if sfile-p (file-name-directory stringfile)
1724 (deffile (if sfile-p (file-name-nondirectory stringfile)
1726 (ans (read-file-name (if deffile (format "%s(default %s) "
1730 (concat defdir deffile)
1732 (list (expand-file-name (substitute-in-file-name ans)))))
1734 ;;; I am somewhat divided on this string-default feature. It seems
1735 ;;; to violate the principle-of-least-astonishment, in that it makes
1736 ;;; the default harder to predict, so you actually have to look and see
1737 ;;; what the default really is before choosing it. This can trip you up.
1738 ;;; On the other hand, it can be useful, I guess. I would appreciate feedback
1743 ;;; Simple process query facility.
1744 ;;; ===========================================================================
1745 ;;; This function is for commands that want to send a query to the process
1746 ;;; and show the response to the user. For example, a command to get the
1747 ;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
1748 ;;; to an inferior Common Lisp process.
1750 ;;; This simple facility just sends strings to the inferior process and pops
1751 ;;; up a window for the process buffer so you can see what the process
1752 ;;; responds with. We don't do anything fancy like try to intercept what the
1753 ;;; process responds with and put it in a pop-up window or on the message
1754 ;;; line. We just display the buffer. Low tech. Simple. Works good.
1756 ;;; Send to the inferior process PROC the string STR. Pop-up but do not select
1757 ;;; a window for the inferior process so that its response can be seen.
1758 (defun comint-proc-query (proc str)
1759 (let* ((proc-buf (process-buffer proc))
1760 (proc-mark (process-mark proc)))
1761 (display-buffer proc-buf)
1762 (set-buffer proc-buf) ; but it's not the selected *window*
1763 (let ((proc-win (get-buffer-window proc-buf))
1764 (proc-pt (marker-position proc-mark)))
1765 (comint-send-string proc str) ; send the query
1766 (accept-process-output proc) ; wait for some output
1767 ;; Try to position the proc window so you can see the answer.
1768 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
1769 ;; I don't know why. Wizards invited to improve it.
1770 (if (not (pos-visible-in-window-p proc-pt proc-win))
1771 (let ((opoint (window-point proc-win)))
1772 (set-window-point proc-win proc-mark)
1774 (if (not (pos-visible-in-window-p opoint proc-win))
1776 (set-window-point proc-win opoint)))))))
1779 ;;; Filename/command/history completion in a buffer
1780 ;;; ===========================================================================
1781 ;;; Useful completion functions, courtesy of the Ergo group.
1784 ;;; comint-dynamic-complete Complete or expand command, filename,
1785 ;;; history at point.
1786 ;;; comint-dynamic-complete-filename Complete filename at point.
1787 ;;; comint-dynamic-list-filename-completions List completions in help buffer.
1788 ;;; comint-replace-by-expanded-filename Expand and complete filename at point;
1789 ;;; replace with expanded/completed name.
1790 ;;; comint-dynamic-simple-complete Complete stub given candidates.
1792 ;;; These are not installed in the comint-mode keymap. But they are
1793 ;;; available for people who want them. Shell-mode installs them:
1794 ;;; (define-key shell-mode-map "\t" 'comint-dynamic-complete)
1795 ;;; (define-key shell-mode-map "\M-?"
1796 ;;; 'comint-dynamic-list-filename-completions)))
1798 ;;; Commands like this are fine things to put in load hooks if you
1799 ;;; want them present in specific modes.
1801 (defvar comint-completion-autolist nil
1802 "*If non-nil, automatically list possiblities on partial completion.
1803 This mirrors the optional behavior of tcsh.")
1805 (defvar comint-completion-addsuffix t
1806 "*If non-nil, add a `/' to completed directories, ` ' to file names.
1807 If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
1808 DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact completion.
1809 This mirrors the optional behavior of tcsh.")
1811 (defvar comint-completion-recexact nil
1812 "*If non-nil, use shortest completion if characters cannot be added.
1813 This mirrors the optional behavior of tcsh.
1815 A non-nil value is useful if `comint-completion-autolist' is non-nil too.")
1817 (defvar comint-completion-fignore nil
1818 "*List of suffixes to be disregarded during file completion.
1819 This mirrors the optional behavior of bash and tcsh.
1821 Note that this applies to `comint-dynamic-complete-filename' only.")
1823 (defvar comint-file-name-prefix ""
1824 "Prefix prepended to absolute file names taken from process input.
1825 This is used by comint's and shell's completion functions, and by shell's
1826 directory tracking functions.")
1828 (defvar comint-file-name-quote-list nil
1829 "List of characters to quote with `\' when in a file name.
1831 This is a good thing to set in mode hooks.")
1834 (defun comint-directory (directory)
1835 ;; Return expanded DIRECTORY, with `comint-file-name-prefix' if absolute.
1836 (expand-file-name (if (file-name-absolute-p directory)
1837 (concat comint-file-name-prefix directory)
1841 (defun comint-word (word-chars)
1842 "Return the word of WORD-CHARS at point, or nil if non is found.
1843 Word constituents are considered to be those in WORD-CHARS, which is like the
1844 inside of a \"[...]\" (see `skip-chars-forward')."
1846 (let ((non-word-chars (concat "[^\\\\" word-chars "]")) (here (point)))
1847 (while (and (re-search-backward non-word-chars nil 'move)
1848 ;(memq (char-after (point)) shell-file-name-quote-list)
1849 (not (bolp)) (eq (char-after (1- (point))) ?\\))
1852 (and (< (point) here) (buffer-substring (point) here)))))
1855 (defun comint-match-partial-filename ()
1856 "Return the filename at point, or nil if non is found.
1857 Environment variables are substituted. See `comint-word'."
1858 (let ((filename (comint-word "~/A-Za-z0-9+@:_.$#%,={}-")))
1859 (and filename (substitute-in-file-name (comint-unquote-filename filename)))))
1862 (defun comint-quote-filename (filename)
1863 "Return FILENAME with magic characters quoted.
1864 Magic characters are those in `comint-file-name-quote-list'."
1865 (if (null comint-file-name-quote-list)
1868 (format "\\(^\\|[^\\]\\)\\([%s]\\)"
1869 (mapconcat 'char-to-string comint-file-name-quote-list ""))))
1871 (while (string-match regexp filename)
1872 (setq filename (replace-match "\\1\\\\\\2" nil nil filename)))
1875 (defun comint-unquote-filename (filename)
1876 "Return FILENAME with quoted characters unquoted."
1877 (if (null comint-file-name-quote-list)
1880 (while (string-match "\\\\\\(.\\)" filename)
1881 (setq filename (replace-match "\\1" nil nil filename)))
1885 (defun comint-dynamic-complete ()
1886 "Dynamically perform completion at point.
1887 Calls the functions in `comint-dynamic-complete-functions' to perform
1888 completion until a function returns non-nil, at which point completion is
1889 assumed to have occurred."
1891 (let ((functions comint-dynamic-complete-functions))
1892 (while (and functions (null (funcall (car functions))))
1893 (setq functions (cdr 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."
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)))
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)
1939 ((eq completion t) ; Means already completed "file".
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")))))))
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'."
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)
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"))
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.
2020 (message "Completed 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)
2028 (message "Partially completed")
2032 (defun comint-dynamic-list-filename-completions ()
2033 "List in help buffer possible completions of the filename at point."
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")
2057 (set-buffer (get-buffer "*Completions*"))
2058 (setq key (read-key-sequence nil)
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.
2067 (mouse-choose-completion first)
2068 (set-window-configuration conf))
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
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>
2088 ;;; shell-set-directory <unnecessary>
2089 ;;; shell-mode-map comint-mode-map
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.
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,
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 ()
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
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
2164 ;;; comint.el ends here