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