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