home *** CD-ROM | disk | FTP | other *** search
/ BCI NET 2 / BCI NET 2.iso / archives / programming / source / a2.0bemacs-src.lha / Emacs-19.25 / lisp / comint.el < prev    next >
Encoding:
Text File  |  1994-05-30  |  87.3 KB  |  2,079 lines

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