home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / MacHaskell 2.2 / emacs-tools / comint.el next >
Encoding:
Text File  |  1994-09-27  |  54.9 KB  |  1,515 lines  |  [TEXT/ttxt]

  1. aster source.
  2. ;;;     - Olin Shivers (shivers@cs.cmu.edu)
  3.  
  4. ;;; This hopefully generalises shell mode, lisp mode, tea mode, soar mode,...
  5. ;;; This file defines a general command-interpreter-in-a-buffer package
  6. ;;; (comint mode). The idea is that you can build specific process-in-a-buffer
  7. ;;; modes on top of comint mode -- e.g., lisp, shell, scheme, T, soar, ....
  8. ;;; This way, all these specific packages share a common base functionality, 
  9. ;;; and a common set of bindings, which makes them easier to use (and
  10. ;;; saves code, implementation time, etc., etc.).
  11.  
  12. ;;; Several packages are already defined using comint mode:
  13. ;;; - cmushell.el defines a shell-in-a-buffer mode.
  14. ;;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
  15. ;;; Cmushell and cmulisp mode are similar to, and intended to replace,
  16. ;;; their counterparts in the standard gnu emacs release (in shell.el). 
  17. ;;; These replacements are more featureful, robust, and uniform than the 
  18. ;;; released versions. The key bindings in lisp mode are also more compatible
  19. ;;; with the bindings of Hemlock and Zwei (the Lisp Machine emacs).
  20. ;;;
  21. ;;; - The file cmuscheme.el defines a scheme-in-a-buffer mode.
  22. ;;; - The file tea.el tunes scheme and inferior-scheme modes for T.
  23. ;;; - The file soar.el tunes lisp and inferior-lisp modes for Soar.
  24. ;;; - cmutex.el defines tex and latex modes that invoke tex, latex, bibtex,
  25. ;;;   previewers, and printers from within emacs.
  26. ;;; - background.el allows csh-like job control inside emacs.
  27. ;;; It is pretty easy to make new derived modes for other processes.
  28.  
  29. ;;; For documentation on the functionality provided by comint mode, and
  30. ;;; the hooks available for customising it, see the comments below.
  31. ;;; For further information on the standard derived modes (shell, 
  32. ;;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
  33.  
  34. ;;; For hints on converting existing process modes (e.g., tex-mode,
  35. ;;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
  36. ;;; instead of shell-mode, see the notes at the end of this file.
  37.  
  38. (provide 'comint)
  39. (defconst comint-version "2.01")
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61. ;;; Brief Command Documentation:
  62. ;;;============================================================================
  63. ;;; Comint Mode Commands: (common to all derived modes, like cmushell & cmulisp
  64. ;;; mode)
  65. ;;;
  66. ;;; m-p        comint-previous-input            Cycle backwards in input history
  67. ;;; m-n        comint-next-input                  Cycle forwards
  68. ;;; m-s     comint-previous-similar-input   Previous similar input
  69. ;;; c-c r   comint-previous-input-matching  Search backwards in input history
  70. ;;; return  comint-send-input
  71. ;;; c-a     comint-bol                      Beginning of line; skip prompt.
  72. ;;; c-d        comint-delchar-or-maybe-eof     Delete char unless at end of buff.
  73. ;;; c-c c-u comint-kill-input                ^u
  74. ;;; c-c c-w backward-kill-word            ^w
  75. ;;; c-c c-c comint-interrupt-subjob         ^c
  76. ;;; c-c c-z comint-stop-subjob                ^z
  77. ;;; c-c c-\ comint-quit-subjob                ^\
  78. ;;; c-c c-o comint-kill-output            Delete last batch of process output
  79. ;;; c-c c-r comint-show-output            Show last batch of process output
  80. ;;;
  81. ;;; Not bound by default in comint-mode
  82. ;;; send-invisible            Read a line w/o echo, and send to proc
  83. ;;; (These are bound in shell-mode)
  84. ;;; comint-dynamic-complete        Complete filename at point.
  85. ;;; comint-dynamic-list-completions    List completions in help buffer.
  86. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  87. ;;;                    replace with expanded/completed name.
  88. ;;; comint-kill-subjob            No mercy.
  89. ;;; comint-continue-subjob        Send CONT signal to buffer's process
  90. ;;;                    group. Useful if you accidentally
  91. ;;;                    suspend your process (with C-c C-z).
  92. ;;;
  93. ;;; Bound for RMS -- I prefer the input history stuff, but you might like 'em.
  94. ;;; m-P       comint-msearch-input        Search backwards for prompt
  95. ;;; m-N    comint-psearch-input        Search forwards for prompt
  96. ;;; C-cR   comint-msearch-input-matching Search backwards for prompt & string
  97.  
  98. ;;; comint-mode-hook is the comint mode hook. Basically for your keybindings.
  99. ;;; comint-load-hook is run after loading in this package.
  100.  
  101.  
  102.  
  103.  
  104.  
  105. ;;; Buffer Local Variables:
  106. ;;;============================================================================
  107. ;;; Comint mode buffer local variables:
  108. ;;;     comint-prompt-regexp    - string       comint-bol uses to match prompt.
  109. ;;;     comint-last-input-end   - marker       For comint-kill-output command
  110. ;;;     input-ring-size         - integer      For the input history
  111. ;;;     input-ring              - ring             mechanism
  112. ;;;     input-ring-index        - marker           ...
  113. ;;;     comint-last-input-match - string           ...
  114. ;;;     comint-get-old-input    - function     Hooks for specific 
  115. ;;;     comint-input-sentinel   - function         process-in-a-buffer
  116. ;;;     comint-input-filter     - function         modes.
  117. ;;;     comint-input-send    - function
  118. ;;;     comint-eol-on-send    - boolean
  119.  
  120. (defvar comint-prompt-regexp "^"
  121.   "Regexp to recognise prompts in the inferior process.
  122. Defaults to \"^\", the null string at BOL.
  123.  
  124. Good choices:
  125.   Canonical Lisp: \"^[^> ]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
  126.   Lucid Common Lisp: \"^\\(>\\|\\(->\\)+\\) *\"
  127.   franz: \"^\\(->\\|<[0-9]*>:\\) *\"
  128.   kcl: \"^>+ *\"
  129.   shell: \"^[^#$%>]*[#$%>] *\"
  130.   T: \"^>+ *\"
  131.  
  132. This is a good thing to set in mode hooks.")
  133.  
  134. (defvar input-ring-size 30
  135.   "Size of input history ring.")
  136.  
  137. ;;; Here are the per-interpreter hooks.
  138. (defvar comint-get-old-input (function comint-get-old-input-default)
  139.   "Function that submits old text in comint mode.
  140. This function is called when return is typed while the point is in old text.
  141. It returns the text to be submitted as process input.  The default is
  142. comint-get-old-input-default, which grabs the current line, and strips off
  143. leading text matching comint-prompt-regexp")
  144.  
  145. (defvar comint-input-sentinel (function ignore)
  146.   "Called on each input submitted to comint mode process by comint-send-input.
  147. Thus it can, for instance, track cd/pushd/popd commands issued to the csh.")
  148.  
  149. (defvar comint-input-filter
  150.   (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
  151.   "Predicate for filtering additions to input history.
  152. Only inputs answering true to this function are saved on the input
  153. history list. Default is to save anything that isn't all whitespace")
  154.  
  155. (defvar comint-input-sender (function comint-simple-send)
  156.   "Function to actually send to PROCESS the STRING submitted by user.
  157. Usually this is just 'comint-simple-send, but if your mode needs to 
  158. massage the input string, this is your hook. This is called from
  159. the user command comint-send-input. comint-simple-send just sends
  160. the string plus a newline.")
  161.  
  162. (defvar comint-eol-on-send 'T
  163.   "If non-nil, then jump to the end of the line before sending input to process.
  164. See COMINT-SEND-INPUT")
  165.  
  166. (defvar comint-mode-hook '()
  167.   "Called upon entry into comint-mode")
  168.  
  169. (defvar comint-mode-map nil)
  170.  
  171. (defun comint-mode ()
  172.   "Major mode for interacting with an inferior interpreter.
  173. Interpreter name is same as buffer name, sans the asterisks.
  174. Return at end of buffer sends line as input.
  175. Return not at end copies rest of line to end and sends it.
  176. Setting mode variable comint-eol-on-send means jump to the end of the line
  177. before submitting new input.
  178.  
  179. This mode is typically customised to create inferior-lisp-mode,
  180. shell-mode, etc.. This can be done by setting the hooks
  181. comint-input-sentinel, comint-input-filter, comint-input-sender and
  182. comint-get-old-input to appropriate functions, and the variable
  183. comint-prompt-regexp to the appropriate regular expression.
  184.  
  185. An input history is maintained of size input-ring-size, and
  186. can be accessed with the commands comint-next-input [\\[comint-next-input]] and 
  187. comint-previous-input [\\[comint-previous-input]]. Commands not keybound by
  188. default are send-invisible, comint-dynamic-complete, and 
  189. comint-list-dynamic-completions.
  190.  
  191. If you accidentally suspend your process, use \\[comint-continue-subjob]
  192. to continue it.
  193.  
  194. \\{comint-mode-map}
  195.  
  196. Entry to this mode runs the hooks on comint-mode-hook"
  197.   (interactive)
  198.   (let ((old-ring (and (assq 'input-ring (buffer-local-variables))
  199.                (boundp 'input-ring)
  200.                input-ring))
  201.     (old-ptyp comint-ptyp)) ; preserve across local var kill. gross.
  202.     (kill-all-local-variables)
  203.     (setq major-mode 'comint-mode)
  204.     (setq mode-name "Comint")
  205.     (setq mode-line-process '(": %s"))
  206.     (use-local-map comint-mode-map)
  207.     (make-local-variable 'comint-last-input-end)
  208.     (setq comint-last-input-end (make-marker))
  209.     (make-local-variable 'comint-last-input-match)
  210.     (setq comint-last-input-match "")
  211.     (make-local-variable 'comint-prompt-regexp) ; Don't set; default
  212.     (make-local-variable 'input-ring-size)      ; ...to global val.
  213.     (make-local-variable 'input-ring)
  214.     (make-local-variable 'input-ring-index)
  215.     (setq input-ring-index 0)
  216.     (make-local-variable 'comint-get-old-input)
  217.     (make-local-variable 'comint-input-sentinel)
  218.     (make-local-variable 'comint-input-filter)  
  219.     (make-local-variable 'comint-input-sender)
  220.     (make-local-variable 'comint-eol-on-send)
  221.     (make-local-variable 'comint-ptyp)
  222.     (setq comint-ptyp old-ptyp)
  223.     (run-hooks 'comint-mode-hook)
  224.     ;Do this after the hook so the user can mung INPUT-RING-SIZE w/his hook.
  225.     ;The test is so we don't lose history if we run comint-mode twice in
  226.     ;a buffer.
  227.     (setq input-ring (if (ring-p old-ring) old-ring
  228.              (make-ring input-ring-size)))))
  229.  
  230. ;;; The old-ptyp stuff above is because we have to preserve the value of
  231. ;;; comint-ptyp across calls to comint-mode, in spite of the
  232. ;;; kill-all-local-variables that it does. Blech. Hopefully, this will all
  233. ;;; go away when a later release fixes the signalling bug.
  234.  
  235. (if comint-mode-map
  236.     nil
  237.   (setq comint-mode-map (make-sparse-keymap))
  238.   (define-key comint-mode-map "\ep" 'comint-previous-input)
  239.   (define-key comint-mode-map "\en" 'comint-next-input)
  240.   (define-key comint-mode-map "\es" 'comint-previous-similar-input)
  241.   (define-key comint-mode-map "\C-m" 'comint-send-input)
  242.   (define-key comint-mode-map "\C-d" 'comint-delchar-or-maybe-eof)
  243.   (define-key comint-mode-map "\C-a" 'comint-bol)
  244.   (define-key comint-mode-map "\C-c\C-u" 'comint-kill-input)
  245.   (define-key comint-mode-map "\C-c\C-w" 'backward-kill-word)
  246.   (define-key comint-mode-map "\C-c\C-c" 'comint-interrupt-subjob)
  247.   (define-key comint-mode-map "\C-c\C-z" 'comint-stop-subjob)
  248.   (define-key comint-mode-map "\C-c\C-\\" 'comint-quit-subjob)
  249.   (define-key comint-mode-map "\C-c\C-o" 'comint-kill-output)
  250.   (define-key comint-mode-map "\C-cr"    'comint-previous-input-matching)
  251.   (define-key comint-mode-map "\C-c\C-r" 'comint-show-output)
  252.   ;;; Here's the prompt-search stuff I installed for RMS to try...
  253.   (define-key comint-mode-map "\eP" 'comint-msearch-input)
  254.   (define-key comint-mode-map "\eN" 'comint-psearch-input)
  255.   (define-key comint-mode-map "\C-cR" 'comint-msearch-input-matching))
  256.  
  257.  
  258. ;;; This function is used to make a full copy of the comint mode map,
  259. ;;; so that client modes won't interfere with each other. This function
  260. ;;; isn't necessary in emacs 18.5x, but we keep it around for 18.4x versions.
  261. (defun full-copy-sparse-keymap (km)
  262.   "Recursively copy the sparse keymap KM"
  263.   (cond ((consp km)
  264.      (cons (full-copy-sparse-keymap (car km))
  265.            (full-copy-sparse-keymap (cdr km))))
  266.     (t km)))
  267.  
  268. (defun comint-check-proc (buffer-name)
  269.   "True if there is a process associated w/buffer BUFFER-NAME, and
  270. it is alive (status RUN or STOP)."
  271.   (let ((proc (get-buffer-process buffer-name)))
  272.     (and proc (memq (process-status proc) '(run stop)))))
  273.  
  274. ;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
  275. ;;; for the second argument (program).
  276. (defun make-comint (name program &optional startfile &rest switches)
  277.   (let* ((buffer (get-buffer-create (concat "*" name "*")))
  278.      (proc (get-buffer-process buffer)))
  279.     ;; If no process, or nuked process, crank up a new one and put buffer in
  280.     ;; comint mode. Otherwise, leave buffer and existing process alone.
  281.     (cond ((or (not proc) (not (memq (process-status proc) '(run stop))))
  282.        (save-excursion
  283.          (set-buffer buffer)
  284.          (comint-mode)) ; Install local vars, mode, keymap, ...
  285.        (comint-exec buffer name program startfile switches)))
  286.     buffer))
  287.  
  288. (defvar comint-ptyp t
  289.   "True if communications via pty; false if by pipe. Buffer local.
  290. This is to work around a bug in emacs process signalling.")
  291.  
  292. (defun comint-exec (buffer name command startfile switches)
  293.   "Fires up a process in buffer for comint modes.
  294. Blasts any old process running in the buffer. Doesn't set the buffer mode.
  295. You can use this to cheaply run a series of processes in the same comint
  296. buffer."
  297.   (save-excursion
  298.     (set-buffer buffer)
  299.     (let ((proc (get-buffer-process buffer)))    ; Blast any old process.
  300.       (if proc (delete-process proc)))
  301.     ;; Crank up a new process
  302.     (let ((proc (comint-exec-1 name buffer command switches)))
  303.       (make-local-variable 'comint-ptyp)
  304.       (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
  305.       ;; Jump to the end, and set the process mark.
  306.       (goto-char (point-max))
  307.       (set-marker (process-mark proc) (point)))
  308.       ;; Feed it the startfile.
  309.       (cond (startfile
  310.          ;;This is guaranteed to wait long enough
  311.          ;;but has bad results if the comint does not prompt at all
  312.          ;;         (while (= size (buffer-size))
  313.          ;;           (sleep-for 1))
  314.          ;;I hope 1 second is enough!
  315.          (sleep-for 1)
  316.          (goto-char (point-max))
  317.          (insert-file-contents startfile)
  318.          (setq startfile (buffer-substring (point) (point-max)))
  319.          (delete-region (point) (point-max))
  320.          (comint-send-string proc startfile)))
  321.     buffer))
  322.  
  323. ;;; This auxiliary function cranks up the process for comint-exec in
  324. ;;; the appropriate environment. It is twice as long as it should be
  325. ;;; because emacs has two distinct mechanisms for manipulating the
  326. ;;; process environment, selected at compile time with the
  327. ;;; MAINTAIN-ENVIRONMENT #define. In one case, process-environment
  328. ;;; is bound; in the other it isn't.
  329.  
  330. (defun comint-exec-1 (name buffer command switches)
  331.   (if (boundp 'process-environment) ; Not a completely reliable test.
  332.       (let ((process-environment
  333.          (comint-update-env process-environment
  334.                 (list (format "TERMCAP=emacs:co#%d:tc=unknown"
  335.                           (screen-width))
  336.                       "TERM=emacs"
  337.                       "EMACS=t"))))
  338.     (apply 'start-process name buffer command switches))
  339.  
  340.       (let ((tcapv (getenv "TERMCAP"))
  341.         (termv (getenv "TERM"))
  342.         (emv   (getenv "EMACS")))
  343.     (unwind-protect
  344.          (progn (setenv "TERMCAP" (format "emacs:co#%d:tc=unknown"
  345.                           (screen-width)))
  346.             (setenv "TERM" "emacs")
  347.             (setenv "EMACS" "t")
  348.             (apply 'start-process name buffer command switches))
  349.       (setenv "TERMCAP" tcapv)
  350.       (setenv "TERM"    termv)
  351.       (setenv "EMACS"   emv)))))
  352.          
  353.  
  354.  
  355. ;; This is just (append new old-env) that compresses out shadowed entries.
  356. ;; It's also pretty ugly, mostly due to elisp's horrible iteration structures.
  357. (defun comint-update-env (old-env new)
  358.   (let ((ans (reverse new))
  359.     (vars (mapcar (function (lambda (vv)
  360.             (and (string-match "^[^=]*=" vv)
  361.                  (substring vv 0 (match-end 0)))))
  362.               new)))
  363.     (while old-env
  364.       (let* ((vv (car old-env)) ; vv is var=value
  365.          (var (and (string-match "^[^=]*=" vv)
  366.                (substring vv 0 (match-end 0)))))
  367.     (setq old-env (cdr old-env))
  368.     (cond ((not (and var (comint-mem var vars)))
  369.            (if var (setq var (cons var vars)))
  370.            (setq ans (cons vv ans))))))
  371.     (nreverse ans)))
  372.  
  373. ;;; This should be in emacs, but it isn't.
  374. (defun comint-mem (item list &optional elt=)
  375.   "Test to see if ITEM is equal to an item in LIST.
  376. Option comparison function ELT= defaults to equal."
  377.   (let ((elt= (or elt= (function equal)))
  378.     (done nil))
  379.     (while (and list (not done))
  380.       (if (funcall elt= item (car list))
  381.       (setq done list)
  382.       (setq list (cdr list))))
  383.     done))
  384.  
  385.  
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.  
  401.  
  402.  
  403.  
  404.  
  405.  
  406.  
  407.  
  408.  
  409.  
  410.  
  411.  
  412.  
  413. ;;; Ring Code
  414. ;;;============================================================================
  415. ;;; This code defines a ring data structure. A ring is a 
  416. ;;;     (hd-index tl-index . vector) 
  417. ;;; list. You can insert to, remove from, and rotate a ring. When the ring
  418. ;;; fills up, insertions cause the oldest elts to be quietly dropped.
  419. ;;;
  420. ;;; HEAD = index of the newest item on the ring.
  421. ;;; TAIL = index of the oldest item on the ring.
  422. ;;;
  423. ;;; These functions are used by the input history mechanism, but they can
  424. ;;; be used for other purposes as well.
  425.  
  426. (defun ring-p (x) 
  427.   "T if X is a ring; NIL otherwise."
  428.   (and (consp x) (integerp (car x))
  429.        (consp (cdr x)) (integerp (car (cdr x)))
  430.        (vectorp (cdr (cdr x)))))
  431.  
  432. (defun make-ring (size)
  433.   "Make a ring that can contain SIZE elts"
  434.   (cons 1 (cons 0 (make-vector (+ size 1) nil))))
  435.  
  436. (defun ring-plus1 (index veclen)
  437.   "INDEX+1, with wraparound"
  438.   (let ((new-index (+ index 1)))
  439.     (if (= new-index veclen) 0 new-index)))
  440.  
  441. (defun ring-minus1 (index veclen)
  442.   "INDEX-1, with wraparound"
  443.   (- (if (= 0 index) veclen index) 1))
  444.  
  445. (defun ring-length (ring)
  446.   "Number of elts in the ring."
  447.   (let ((hd (car ring)) (tl (car (cdr ring)))  (siz (length (cdr (cdr ring)))))
  448.     (let ((len (if (<= hd tl) (+ 1 (- tl hd)) (+ 1 tl (- siz hd)))))
  449.       (if (= len siz) 0 len))))
  450.  
  451. (defun ring-empty-p (ring)
  452.   (= 0 (ring-length ring)))
  453.  
  454. (defun ring-insert (ring item)
  455.   "Insert a new item onto the ring. If the ring is full, dump the oldest
  456. item to make room."       
  457.   (let* ((vec (cdr (cdr ring)))  (len (length vec))
  458.      (new-hd (ring-minus1 (car ring) len)))
  459.       (setcar ring new-hd)
  460.       (aset vec new-hd item)
  461.       (if (ring-empty-p ring) ;overflow -- dump one off the tail.
  462.       (setcar (cdr ring) (ring-minus1 (car (cdr ring)) len)))))
  463.  
  464. (defun ring-remove (ring)
  465.   "Remove the oldest item retained on the ring."
  466.   (if (ring-empty-p ring) (error "Ring empty")
  467.       (let ((tl (car (cdr ring)))  (vec (cdr (cdr ring))))
  468.     (set-car (cdr ring) (ring-minus1 tl (length vec)))
  469.     (aref vec tl))))
  470.  
  471. ;;; This isn't actually used in this package. I just threw it in in case
  472. ;;; someone else wanted it. If you want rotating-ring behavior on your history
  473. ;;; retrieval (analagous to kill ring behavior), this function is what you
  474. ;;; need. I should write the yank-input and yank-pop-input-or-kill to go with
  475. ;;; this, and not bind it to a key by default, so it would be available to
  476. ;;; people who want to bind it to a key. But who would want it? Blech.
  477. (defun ring-rotate (ring n)
  478.   (if (not (= n 0))
  479.       (if (ring-empty-p ring) ;Is this the right error check?
  480.       (error "ring empty")
  481.       (let ((hd (car ring))  (tl (car (cdr ring)))  (vec (cdr (cdr ring))))
  482.         (let ((len (length vec)))
  483.           (while (> n 0)
  484.         (setq tl (ring-plus1 tl len))
  485.         (aset ring tl (aref ring hd))
  486.         (setq hd (ring-plus1 hd len))
  487.         (setq n (- n 1)))
  488.           (while (< n 0)
  489.         (setq hd (ring-minus1 hd len))
  490.         (aset vec hd (aref vec tl))
  491.         (setq tl (ring-minus1 tl len))
  492.         (setq n (- n 1))))
  493.         (set-car ring hd)
  494.         (set-car (cdr ring) tl)))))
  495.  
  496. (defun comint-mod (n m)
  497.   "Returns N mod M. M is positive. Answer is guaranteed to be non-negative, 
  498. and less than m."
  499.   (let ((n (% n m)))
  500.     (if (>= n 0) n
  501.     (+ n
  502.        (if (>= m 0) m (- m)))))) ; (abs m)
  503.  
  504. (defun ring-ref (ring index)
  505.   (let ((numelts (ring-length ring)))
  506.     (if (= numelts 0) (error "indexed empty ring")
  507.     (let* ((hd (car ring))  (tl (car (cdr ring)))  (vec (cdr (cdr ring)))
  508.            (index (comint-mod index numelts))
  509.            (vec-index (comint-mod (+ index hd) 
  510.                       (length vec))))
  511.       (aref vec vec-index)))))
  512.  
  513.  
  514. ;;; Input history retrieval commands
  515. ;;; M-p -- previous input    M-n -- next input
  516. ;;; C-c r -- previous input matching
  517. ;;; ===========================================================================
  518.  
  519. (defun comint-previous-input (arg)
  520.   "Cycle backwards through input history."
  521.   (interactive "*p")
  522.   (let ((len (ring-length input-ring)))
  523.     (cond ((<= len 0)
  524.        (message "Empty input ring")
  525.        (ding))
  526.       ((not (comint-after-pmark-p))
  527.        (message "Not after process mark")
  528.        (ding))
  529.       (t
  530.        (cond ((eq last-command 'comint-previous-input)
  531.           (delete-region (mark) (point)))
  532.          ((eq last-command 'comint-previous-similar-input)
  533.           (delete-region 
  534.            (process-mark (get-buffer-process (current-buffer)))
  535.            (point)))
  536.          (t                          
  537.           (setq input-ring-index
  538.             (if (> arg 0) -1
  539.                 (if (< arg 0) 1 0)))
  540.           (push-mark (point))))
  541.        (setq input-ring-index (comint-mod (+ input-ring-index arg) len))
  542.        (message "%d" (1+ input-ring-index))
  543.        (insert (ring-ref input-ring input-ring-index))
  544.        (setq this-command 'comint-previous-input)))))
  545.      
  546. (defun comint-next-input (arg)
  547.   "Cycle forwards through input history."
  548.   (interactive "*p")
  549.   (comint-previous-input (- arg)))
  550.  
  551. (defvar comint-last-input-match ""
  552.   "Last string searched for by comint input history search, for defaulting.
  553. Buffer local variable.") 
  554.  
  555. (defun comint-previous-input-matching (str)
  556.   "Searches backwards through input history for substring match."
  557.   (interactive (let* ((last-command last-command) ; preserve around r-f-m
  558.               (s (read-from-minibuffer 
  559.              (format "Command substring (default %s): "
  560.                  comint-last-input-match))))
  561.          (list (if (string= s "") comint-last-input-match s))))
  562. ; (interactive "sCommand substring: ")
  563.   (setq comint-last-input-match str) ; update default
  564.   (if (not (eq last-command 'comint-previous-input))
  565.       (setq input-ring-index -1))
  566.   (let ((str (regexp-quote str))
  567.         (len (ring-length input-ring))
  568.     (n (+ input-ring-index 1)))
  569.     (while (and (< n len) (not (string-match str (ring-ref input-ring n))))
  570.       (setq n (+ n 1)))
  571.     (cond ((< n len)
  572.        (comint-previous-input (- n input-ring-index)))
  573.       (t (if (eq last-command 'comint-previous-input) 
  574.          (setq this-command 'comint-previous-input))
  575.          (message "Not found.")
  576.          (ding)))))
  577.  
  578.  
  579. ;;; These next three commands are alternatives to the input history commands --
  580. ;;; comint-next-input, comint-previous-input and 
  581. ;;; comint-previous-input-matching. They search through the process buffer
  582. ;;; text looking for occurrences of the prompt. RMS likes them better;
  583. ;;; I don't. Bound to M-P, M-N, and C-c R (uppercase P, N, and R) for
  584. ;;; now. Try'em out. Go with what you like...
  585.  
  586. ;;; comint-msearch-input-matching prompts for a string, not a regexp.
  587. ;;; This could be considered to be the wrong thing. I decided to keep it
  588. ;;; simple, and not make the user worry about regexps. This, of course,
  589. ;;; limits functionality.
  590.  
  591. (defun comint-psearch-input ()
  592.   "Search forwards for next occurrence of prompt and skip to end of line.
  593. \(prompt is anything matching regexp comint-prompt-regexp)"
  594.   (interactive)
  595.   (if (re-search-forward comint-prompt-regexp (point-max) t)
  596.       (end-of-line)
  597.       (error "No occurrence of prompt found")))
  598.  
  599. (defun comint-msearch-input ()
  600.   "Search backwards for previous occurrence of prompt and skip to end of line.
  601. Search starts from beginning of current line."
  602.   (interactive)
  603.   (let ((p (save-excursion
  604.          (beginning-of-line)
  605.          (cond ((re-search-backward comint-prompt-regexp (point-min) t)
  606.             (end-of-line)
  607.             (point))
  608.            (t nil)))))
  609.     (if p (goto-char p)
  610.     (error "No occurrence of prompt found"))))
  611.  
  612. (defun comint-msearch-input-matching (str)
  613.   "Search backwards for occurrence of prompt followed by STRING.
  614. STRING is prompted for, and is NOT a regular expression."
  615.   (interactive (let ((s (read-from-minibuffer 
  616.              (format "Command (default %s): "
  617.                  comint-last-input-match))))
  618.          (list (if (string= s "") comint-last-input-match s))))
  619. ; (interactive "sCommand: ")
  620.   (setq comint-last-input-match str) ; update default
  621.   (let* ((r (concat comint-prompt-regexp (regexp-quote str)))
  622.      (p (save-excursion
  623.           (beginning-of-line)
  624.           (cond ((re-search-backward r (point-min) t)
  625.              (end-of-line)
  626.              (point))
  627.             (t nil)))))
  628.     (if p (goto-char p)
  629.     (error "No match"))))
  630.  
  631. ;;;
  632. ;;; Similar input -- contributed by ccm and highly winning.
  633. ;;;
  634. ;;; Reenter input, removing back to the last insert point if it exists. 
  635. ;;;
  636. (defvar comint-last-similar-string "" 
  637.   "The string last used in a similar string search.")
  638. (defun comint-previous-similar-input (arg)
  639.   "Reenters the last input that matches the string typed so far.  If repeated 
  640. successively older inputs are reentered.  If arg is 1, it will go back
  641. in the history, if -1 it will go forward."
  642.   (interactive "p")
  643.   (if (not (comint-after-pmark-p))
  644.       (error "Not after process mark"))
  645.   (if (not (eq last-command 'comint-previous-similar-input))
  646.       (setq input-ring-index -1
  647.         comint-last-similar-string 
  648.         (buffer-substring 
  649.          (process-mark (get-buffer-process (current-buffer)))
  650.          (point))))
  651.   (let* ((size (length comint-last-similar-string))
  652.      (len (ring-length input-ring))
  653.      (n (+ input-ring-index arg))
  654.      entry)
  655.     (while (and (< n len) 
  656.         (or (< (length (setq entry (ring-ref input-ring n))) size)
  657.             (not (equal comint-last-similar-string 
  658.                 (substring entry 0 size)))))
  659.       (setq n (+ n arg)))
  660.     (cond ((< n len)
  661.        (setq input-ring-index n)
  662.        (if (eq last-command 'comint-previous-similar-input)
  663.            (delete-region (mark) (point)) ; repeat
  664.            (push-mark (point)))          ; 1st time
  665.        (insert (substring entry size)))
  666.       (t (message "Not found.") (ding) (sit-for 1)))
  667.     (message "%d" (1+ input-ring-index))))
  668.  
  669.  
  670.  
  671.  
  672.  
  673.  
  674.  
  675.  
  676.  
  677. (defun comint-send-input () 
  678.   "Send input to process.  After the process output mark, sends all text
  679. from the process mark to point as input to the process.  Before the
  680. process output mark, calls value of variable comint-get-old-input to retrieve
  681. old input, copies it to the end of the buffer, and sends it.  A terminal
  682. newline is also inserted into the buffer and sent to the process.  In either
  683. case, value of variable comint-input-sentinel is called on the input before
  684. sending it.  The input is entered into the input history ring, if value of
  685. variable comint-input-filter returns non-nil when called on the input.
  686.  
  687. If variable comint-eol-on-send is non-nil, then point is moved to the end of
  688. line before sending the input.
  689.  
  690. comint-get-old-input, comint-input-sentinel, and comint-input-filter are chosen
  691. according to the command interpreter running in the buffer. E.g.,
  692. If the interpreter is the csh,
  693.     comint-get-old-input is the default: take the current line, discard any
  694.         initial string matching regexp comint-prompt-regexp.
  695.     comint-input-sentinel monitors input for \"cd\", \"pushd\", and \"popd\" 
  696.         commands. When it sees one, it cd's the buffer.
  697.     comint-input-filter is the default: returns T if the input isn't all white
  698.     space.
  699.  
  700. If the comint is Lucid Common Lisp, 
  701.     comint-get-old-input snarfs the sexp ending at point.
  702.     comint-input-sentinel does nothing.
  703.     comint-input-filter returns NIL if the input matches input-filter-regexp,
  704.         which matches (1) all whitespace (2) :a, :c, etc.
  705.  
  706. Similarly for Soar, Scheme, etc.."
  707.   (interactive)
  708.   ;; Note that the input string does not include its terminal newline.
  709.   (let ((proc (get-buffer-process (current-buffer))))
  710.     (if (not proc) (error "Current buffer has no process")
  711.     (let* ((pmark (process-mark proc))
  712.            (pmark-val (marker-position pmark))
  713.            (input (if (>= (point) pmark-val)
  714.               (progn (if comint-eol-on-send (end-of-line))
  715.                  (buffer-substring pmark (point)))
  716.               (let ((copy (funcall comint-get-old-input)))
  717.                 (goto-char pmark)
  718.                 (insert copy)
  719.                 copy))))
  720.       (insert ?\n)
  721.       (if (funcall comint-input-filter input) (ring-insert input-ring input))
  722.       (funcall comint-input-sentinel input)
  723.       (funcall comint-input-sender proc input)
  724.       (set-marker (process-mark proc) (point))
  725.       (set-marker comint-last-input-end (point))))))
  726.  
  727. (defun comint-get-old-input-default ()
  728.   "Default for comint-get-old-input: take the current line, and discard
  729. any initial text matching comint-prompt-regexp."
  730.   (save-excursion
  731.     (beginning-of-line)
  732.     (comint-skip-prompt)
  733.     (let ((beg (point)))
  734.       (end-of-line)
  735.       (buffer-substring beg (point)))))
  736.  
  737. (defun comint-skip-prompt ()
  738.   "Skip past the text matching regexp comint-prompt-regexp. 
  739. If this takes us past the end of the current line, don't skip at all."
  740.   (let ((eol (save-excursion (end-of-line) (point))))
  741.     (if (and (looking-at comint-prompt-regexp)
  742.          (<= (match-end 0) eol))
  743.     (goto-char (match-end 0)))))
  744.  
  745.  
  746. (defun comint-after-pmark-p ()
  747.   "Is point after the process output marker?"
  748.   ;; Since output could come into the buffer after we looked at the point
  749.   ;; but before we looked at the process marker's value, we explicitly 
  750.   ;; serialise. This is just because I don't know whether or not emacs
  751.   ;; services input during execution of lisp commands.
  752.   (let ((proc-pos (marker-position
  753.            (process-mark (get-buffer-process (current-buffer))))))
  754.     (<= proc-pos (point))))
  755.  
  756. (defun comint-simple-send (proc string)
  757.   "Default function for sending to PROC input STRING.
  758. This just sends STRING plus a newline. To override this,
  759. set the hook COMINT-INPUT-SENDER."
  760.   (comint-send-string proc string)
  761.   (comint-send-string proc "\n"))
  762.  
  763. (defun comint-bol (arg)
  764.   "Goes to the beginning of line, then skips past the prompt, if any.
  765. If a prefix argument is given (\\[universal-argument]), then no prompt skip 
  766. -- go straight to column 0.
  767.  
  768. The prompt skip is done by skipping text matching the regular expression
  769. comint-prompt-regexp, a buffer local variable.
  770.  
  771. If you don't like this command, reset c-a to beginning-of-line 
  772. in your hook, comint-mode-hook."
  773.   (interactive "P")
  774.   (beginning-of-line)
  775.   (if (null arg) (comint-skip-prompt)))
  776.  
  777. ;;; These two functions are for entering text you don't want echoed or
  778. ;;; saved -- typically passwords to ftp, telnet, or somesuch.
  779. ;;; Just enter m-x send-invisible and type in your line.
  780.  
  781. (defun comint-read-noecho (prompt)
  782.   "Prompt the user with argument PROMPT. Read a single line of text
  783. without echoing, and return it. Note that the keystrokes comprising
  784. the text can still be recovered (temporarily) with \\[view-lossage]. This
  785. may be a security bug for some applications."
  786.   (let ((echo-keystrokes 0)
  787.     (answ "")
  788.     tem)
  789.     (if (and (stringp prompt) (not (string= (message prompt) "")))
  790.     (message prompt))
  791.     (while (not(or  (= (setq tem (read-char)) ?\^m)
  792.             (= tem ?\n)))
  793.       (setq answ (concat answ (char-to-string tem))))
  794.     (message "")
  795.     answ))
  796.  
  797. (defun send-invisible (str)
  798.   "Read a string without echoing, and send it to the process running
  799. in the current buffer. A new-line is additionally sent. String is not 
  800. saved on comint input history list.
  801. Security bug: your string can still be temporarily recovered with
  802. \\[view-lossage]."
  803. ; (interactive (list (comint-read-noecho "Enter non-echoed text")))
  804.   (interactive "P") ; Defeat snooping via C-x esc
  805.   (let ((proc (get-buffer-process (current-buffer))))
  806.     (if (not proc) (error "Current buffer has no process")
  807.     (comint-send-string proc
  808.                 (if (stringp str) str
  809.                 (comint-read-noecho "Enter non-echoed text")))
  810.     (comint-send-string proc "\n"))))
  811.  
  812.  
  813.  
  814.  
  815.  
  816.  
  817.  
  818.  
  819.  
  820.  
  821.  
  822.  
  823.  
  824.  
  825.  
  826.  
  827.  
  828.  
  829.  
  830.  
  831.  
  832.  
  833.  
  834.  
  835.  
  836.  
  837.  
  838.  
  839.  
  840.  
  841.  
  842.  
  843.  
  844.  
  845.  
  846.  
  847.  
  848.  
  849.  
  850.  
  851.  
  852.  
  853. ;;; Low-level process communication
  854.  
  855. (defvar comint-input-chunk-size 512
  856.   "*Long inputs send to comint processes are broken up into chunks of this size.
  857. If your process is choking on big inputs, try lowering the value.")
  858.  
  859. (defun comint-send-string (proc str)
  860.   "Send PROCESS the contents of STRING as input.
  861. This is equivalent to process-send-string, except that long input strings
  862. are broken up into chunks of size comint-input-chunk-size. Processes
  863. are given a chance to output between chunks. This can help prevent processes
  864. from hanging when you send them long inputs on some OS's."
  865.   (let* ((len (length str))
  866.      (i (min len comint-input-chunk-size)))
  867.     (process-send-string proc (substring str 0 i))
  868.     (while (< i len)
  869.       (let ((next-i (+ i comint-input-chunk-size)))
  870.     (accept-process-output)
  871.     (process-send-string proc (substring str i (min len next-i)))
  872.     (setq i next-i)))))
  873.  
  874. (defun comint-send-region (proc start end)
  875.   "Sends to PROC the region delimited by START and END.
  876. This is a replacement for process-send-region that tries to keep
  877. your process from hanging on long inputs. See comint-send-string."
  878.   (comint-send-string proc (buffer-substring start end)))
  879.  
  880.  
  881.  
  882.  
  883.  
  884.  
  885.  
  886.  
  887.  
  888.  
  889.  
  890.  
  891.  
  892.  
  893.  
  894.  
  895.  
  896.  
  897. ;;; Random input hackage
  898.  
  899. (defun comint-kill-output ()
  900.   "Kill all output from interpreter since last input."
  901.   (interactive)
  902.   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
  903.     (kill-region comint-last-input-end pmark)
  904.     (goto-char pmark)    
  905.     (insert "*** output flushed ***\n")
  906.     (set-marker pmark (point))))
  907.  
  908. (defun comint-show-output ()
  909.   "Display start of this batch of interpreter output at top of window.
  910. Also put cursor there."
  911.   (interactive)
  912.   (goto-char comint-last-input-end)
  913.   (backward-char)
  914.   (beginning-of-line)
  915.   (set-window-start (selected-window) (point))
  916.   (end-of-line))
  917.  
  918. (defun comint-interrupt-subjob ()
  919.   "Interrupt the current subjob."
  920.   (interactive)
  921.   (interrupt-process nil comint-ptyp))
  922.  
  923. (defun comint-kill-subjob ()
  924.   "Send kill signal to the current subjob."
  925.   (interactive)
  926.   (kill-process nil comint-ptyp))
  927.  
  928. (defun comint-quit-subjob ()
  929.   "Send quit signal to the current subjob."
  930.   (interactive)
  931.   (quit-process nil comint-ptyp))
  932.  
  933. (defun comint-stop-subjob ()
  934.   "Stop the current subjob.
  935. WARNING: if there is no current subjob, you can end up suspending
  936. the top-level process running in the buffer. If you accidentally do
  937. this, use \\[comint-continue-subjob] to resume the process. (This
  938. is not a problem with most shells, since they ignore this signal.)"
  939.   (interactive)
  940.   (stop-process nil comint-ptyp))
  941.  
  942. (defun comint-continue-subjob ()
  943.   "Send CONT signal to process buffer's process group.
  944. Useful if you accidentally suspend the top-level process."
  945.   (interactive)
  946.   (continue-process nil comint-ptyp))
  947.  
  948. (defun comint-kill-input ()
  949.   "Kill all text from last stuff output by interpreter to point."
  950.   (interactive)
  951.   (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
  952.      (p-pos (marker-position pmark)))
  953.     (if (> (point) p-pos)
  954.     (kill-region pmark (point)))))
  955.  
  956. (defun comint-delchar-or-maybe-eof (arg)
  957.   "Delete ARG characters forward, or send an EOF to process if at end of buffer."
  958.   (interactive "p")
  959.   (if (eobp)
  960.       (process-send-eof)
  961.       (delete-char arg)))
  962.  
  963.  
  964.  
  965.  
  966.  
  967.  
  968.  
  969.  
  970.  
  971.  
  972.  
  973.  
  974.  
  975.  
  976.  
  977.  
  978.  
  979.  
  980.  
  981.  
  982.  
  983.  
  984.  
  985. ;;; Support for source-file processing commands.
  986. ;;;============================================================================
  987. ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
  988. ;;; commands that process files of source text (e.g. loading or compiling
  989. ;;; files). So the corresponding process-in-a-buffer modes have commands
  990. ;;; for doing this (e.g., lisp-load-file). The functions below are useful
  991. ;;; for defining these commands.
  992. ;;;
  993. ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
  994. ;;; and Soar, in that they don't know anything about file extensions.
  995. ;;; So the compile/load interface gets the wrong default occasionally.
  996. ;;; The load-file/compile-file default mechanism could be smarter -- it
  997. ;;; doesn't know about the relationship between filename extensions and
  998. ;;; whether the file is source or executable. If you compile foo.lisp
  999. ;;; with compile-file, then the next load-file should use foo.bin for
  1000. ;;; the default, not foo.lisp. This is tricky to do right, particularly
  1001. ;;; because the extension for executable files varies so much (.o, .bin,
  1002. ;;; .lbin, .mo, .vo, .ao, ...).
  1003.  
  1004.  
  1005. ;;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
  1006. ;;; commands.
  1007. ;;;
  1008. ;;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
  1009. ;;; want to save the buffer before issuing any process requests to the command
  1010. ;;; interpreter.
  1011. ;;;
  1012. ;;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
  1013. ;;; for the file to process.
  1014.  
  1015. ;;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
  1016. ;;;============================================================================
  1017. ;;; This function computes the defaults for the load-file and compile-file
  1018. ;;; commands for tea, soar, cmulisp, and cmuscheme modes. 
  1019. ;;; 
  1020. ;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last 
  1021. ;;; source-file processing command. NIL if there hasn't been one yet.
  1022. ;;; - SOURCE-MODES is a list used to determine what buffers contain source
  1023. ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
  1024. ;;; Typically, (lisp-mode) or (scheme-mode).
  1025. ;;; 
  1026. ;;; If the command is given while the cursor is inside a string, *and*
  1027. ;;; the string is an existing filename, *and* the filename is not a directory,
  1028. ;;; then the string is taken as default. This allows you to just position
  1029. ;;; your cursor over a string that's a filename and have it taken as default.
  1030. ;;;
  1031. ;;; If the command is given in a file buffer whose major mode is in
  1032. ;;; SOURCE-MODES, then the the filename is the default file, and the
  1033. ;;; file's directory is the default directory.
  1034. ;;; 
  1035. ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
  1036. ;;; then the default directory & file are what was used in the last source-file
  1037. ;;; processing command (i.e., PREVIOUS-DIR/FILE).  If this is the first time
  1038. ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
  1039. ;;; is the cwd, with no default file. (\"no default file\" = nil)
  1040. ;;; 
  1041. ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
  1042. ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
  1043. ;;; for Soar programs, etc.
  1044. ;;; 
  1045. ;;; The function returns a pair: (default-directory . default-file).
  1046.  
  1047. (defun comint-source-default (previous-dir/file source-modes)
  1048.   (cond ((and buffer-file-name (memq major-mode source-modes))
  1049.      (cons (file-name-directory    buffer-file-name)
  1050.            (file-name-nondirectory buffer-file-name)))
  1051.     (previous-dir/file)
  1052.     (t
  1053.      (cons default-directory nil))))
  1054.  
  1055.  
  1056. ;;; (COMINT-CHECK-SOURCE fname)
  1057. ;;;============================================================================
  1058. ;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
  1059. ;;; process-in-a-buffer modes), this function can be called on the filename.
  1060. ;;; If the file is loaded into a buffer, and the buffer is modified, the user
  1061. ;;; is queried to see if he wants to save the buffer before proceeding with
  1062. ;;; the load or compile.
  1063.  
  1064. (defun comint-check-source (fname)
  1065.   (let ((buff (get-file-buffer fname)))
  1066.     (if (and buff
  1067.          (buffer-modified-p buff)
  1068.          (y-or-n-p (format "Save buffer %s first? "
  1069.                    (buffer-name buff))))
  1070.     ;; save BUFF.
  1071.     (let ((old-buffer (current-buffer)))
  1072.       (set-buffer buff)
  1073.       (save-buffer)
  1074.       (set-buffer old-buffer)))))
  1075.  
  1076.  
  1077. ;;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
  1078. ;;;============================================================================
  1079. ;;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
  1080. ;;; commands that process source files (like loading or compiling a file).
  1081. ;;; It prompts for the filename, provides a default, if there is one,
  1082. ;;; and returns the result filename.
  1083. ;;; 
  1084. ;;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
  1085. ;;; 
  1086. ;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
  1087. ;;; from the last source processing command.  SOURCE-MODES is a list of major
  1088. ;;; modes used to determine what file buffers contain source files.  (These
  1089. ;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
  1090. ;;; then the filename reader will only accept a file that exists.
  1091. ;;; 
  1092. ;;; A typical use:
  1093. ;;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
  1094. ;;;                                 '(lisp-mode) t))
  1095.  
  1096. ;;; This is pretty stupid about strings. It decides we're in a string
  1097. ;;; if there's a quote on both sides of point on the current line.
  1098. (defun comint-extract-string ()
  1099.   "Returns string around point that starts the current line or nil." 
  1100.   (save-excursion
  1101.     (let* ((point (point))
  1102.        (bol (progn (beginning-of-line) (point)))
  1103.        (eol (progn (end-of-line) (point)))
  1104.        (start (progn (goto-char point) 
  1105.              (and (search-backward "\"" bol t) 
  1106.                   (1+ (point)))))
  1107.        (end (progn (goto-char point)
  1108.                (and (search-forward "\"" eol t)
  1109.                 (1- (point))))))
  1110.       (and start end
  1111.        (buffer-substring start end)))))
  1112.  
  1113. (defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
  1114.   (let* ((def (comint-source-default prev-dir/file source-modes))
  1115.          (stringfile (comint-extract-string))
  1116.      (sfile-p (and stringfile
  1117.                (file-exists-p stringfile)
  1118.                (not (file-directory-p stringfile))))
  1119.      (defdir  (if sfile-p (file-name-directory stringfile)
  1120.                       (car def)))
  1121.      (deffile (if sfile-p (file-name-nondirectory stringfile)
  1122.                       (cdr def)))
  1123.      (ans (read-file-name (if deffile (format "%s(default %s) "
  1124.                           prompt    deffile)
  1125.                   prompt)
  1126.                   defdir
  1127.                   (concat defdir deffile)
  1128.                   mustmatch-p)))
  1129.     (list (expand-file-name (substitute-in-file-name ans)))))
  1130.  
  1131. ;;; I am somewhat divided on this string-default feature. It seems
  1132. ;;; to violate the principle-of-least-astonishment, in that it makes
  1133. ;;; the default harder to predict, so you actually have to look and see
  1134. ;;; what the default really is before choosing it. This can trip you up.
  1135. ;;; On the other hand, it can be useful, I guess. I would appreciate feedback
  1136. ;;; on this.
  1137. ;;;     -Olin
  1138.  
  1139.  
  1140.  
  1141.  
  1142.  
  1143.  
  1144.  
  1145.  
  1146.  
  1147.  
  1148.  
  1149.  
  1150.  
  1151.  
  1152.  
  1153.  
  1154.  
  1155.  
  1156.  
  1157.  
  1158.  
  1159.  
  1160.  
  1161. ;;; Simple process query facility.
  1162. ;;; ===========================================================================
  1163. ;;; This function is for commands that want to send a query to the process
  1164. ;;; and show the response to the user. For example, a command to get the
  1165. ;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
  1166. ;;; to an inferior Common Lisp process.
  1167. ;;; 
  1168. ;;; This simple facility just sends strings to the inferior process and pops
  1169. ;;; up a window for the process buffer so you can see what the process
  1170. ;;; responds with.  We don't do anything fancy like try to intercept what the
  1171. ;;; process responds with and put it in a pop-up window or on the message
  1172. ;;; line. We just display the buffer. Low tech. Simple. Works good.
  1173.  
  1174. ;;; Send to the inferior process PROC the string STR. Pop-up but do not select
  1175. ;;; a window for the inferior process so that its response can be seen.
  1176. (defun comint-proc-query (proc str)
  1177.   (let* ((proc-buf (process-buffer proc))
  1178.      (proc-mark (process-mark proc)))
  1179.     (display-buffer proc-buf)
  1180.     (set-buffer proc-buf) ; but it's not the selected *window*
  1181.     (let ((proc-win (get-buffer-window proc-buf))
  1182.       (proc-pt (marker-position proc-mark)))
  1183.       (comint-send-string proc str) ; send the query
  1184.       (accept-process-output proc)  ; wait for some output
  1185.       ;; Try to position the proc window so you can see the answer.
  1186.       ;; This is bogus code. If you delete the (sit-for 0), it breaks.
  1187.       ;; I don't know why. Wizards invited to improve it.
  1188.       (if (not (pos-visible-in-window-p proc-pt proc-win))
  1189.       (let ((opoint (window-point proc-win)))
  1190.         (set-window-point proc-win proc-mark) (sit-for 0)
  1191.         (if (not (pos-visible-in-window-p opoint proc-win))
  1192.         (push-mark opoint)
  1193.         (set-window-point proc-win opoint)))))))
  1194.  
  1195.  
  1196.  
  1197.  
  1198.  
  1199.  
  1200.  
  1201.  
  1202.  
  1203.  
  1204.  
  1205. ;;; Filename completion in a buffer
  1206. ;;; ===========================================================================
  1207. ;;; Useful completion functions, courtesy of the Ergo group.
  1208. ;;; M-<Tab> will complete the filename at the cursor as much as possible
  1209. ;;; M-? will display a list of completions in the help buffer.
  1210.  
  1211. ;;; Three commands:
  1212. ;;; comint-dynamic-complete        Complete filename at point.
  1213. ;;; comint-dynamic-list-completions    List completions in help buffer.
  1214. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  1215. ;;;                    replace with expanded/completed name.
  1216.  
  1217. ;;; These are not installed in the comint-mode keymap. But they are
  1218. ;;; available for people who want them. Shell-mode installs them:
  1219. ;;; (define-key cmushell-mode-map "\M-\t" 'comint-dynamic-complete)
  1220. ;;; (define-key cmushell-mode-map "\M-?"  'comint-dynamic-list-completions)))
  1221. ;;;
  1222. ;;; Commands like this are fine things to put in load hooks if you
  1223. ;;; want them present in specific modes. Example:
  1224. ;;; (setq cmushell-load-hook
  1225. ;;;       '((lambda () (define-key lisp-mode-map "\M-\t"
  1226. ;;;                   'comint-replace-by-expanded-filename))))
  1227. ;;;          
  1228.  
  1229.  
  1230. (defun comint-match-partial-pathname ()
  1231.   "Returns the string of an existing filename or causes an error."
  1232.   (if (save-excursion (backward-char 1) (looking-at "\\s ")) ""
  1233.       (save-excursion
  1234.     (re-search-backward "[^~/A-Za-z0-9---_.$#,]+")
  1235.     (re-search-forward "[~/A-Za-z0-9---_.$#,]+")
  1236.     (substitute-in-file-name 
  1237.       (buffer-substring (match-beginning 0) (match-end 0))))))
  1238.  
  1239.  
  1240. (defun comint-replace-by-expanded-filename ()
  1241. "Replace the filename at point with an expanded, canonicalised, and
  1242. completed replacement.
  1243. \"Expanded\" means environment variables (e.g., $HOME) and ~'s are
  1244. replaced with the corresponding directories.  \"Canonicalised\" means ..
  1245. and \. are removed, and the filename is made absolute instead of relative.
  1246. See functions expand-file-name and substitute-in-file-name. See also
  1247. comint-dynamic-complete."
  1248.   (interactive)
  1249.   (let* ((pathname (comint-match-partial-pathname))
  1250.      (pathdir (file-name-directory pathname))
  1251.      (pathnondir (file-name-nondirectory pathname))
  1252.      (completion (file-name-completion pathnondir
  1253.                        (or pathdir default-directory))))
  1254.     (cond ((null completion)
  1255.        (message "No completions of %s." pathname)
  1256.        (ding))
  1257.       ((eql completion t)
  1258.        (message "Unique completion."))
  1259.       (t                ; this means a string was returned.
  1260.        (delete-region (match-beginning 0) (match-end 0))
  1261.        (insert (expand-file-name (concat pathdir completion)))))))
  1262.  
  1263.  
  1264. (defun comint-dynamic-complete ()
  1265.   "Dynamically complete the filename at point.
  1266. This function is similar to comint-replace-by-expanded-filename, except
  1267. that it won't change parts of the filename already entered in the buffer; 
  1268. it just adds completion characters to the end of the filename."
  1269.   (interactive)
  1270.   (let* ((pathname (comint-match-partial-pathname))
  1271.      (pathdir (file-name-directory pathname))
  1272.      (pathnondir (file-name-nondirectory pathname))
  1273.      (completion (file-name-completion  pathnondir
  1274.                        (or pathdir default-directory))))
  1275.     (cond ((null completion)
  1276.        (message "No completions of %s." pathname)
  1277.        (ding))
  1278.       ((eql completion t)
  1279.        (message "Unique completion."))
  1280.       (t                ; this means a string was returned.
  1281.        (goto-char (match-end 0))
  1282.        (insert (substring completion (length pathnondir)))))))
  1283.  
  1284. (defun comint-dynamic-list-completions ()
  1285.   "List in help buffer all possible completions of the filename at point."
  1286.   (interactive)
  1287.   (let* ((pathname (comint-match-partial-pathname))
  1288.      (pathdir (file-name-directory pathname))
  1289.      (pathnondir (file-name-nondirectory pathname))
  1290.      (completions
  1291.       (file-name-all-completions pathnondir
  1292.                      (or pathdir default-directory))))
  1293.     (cond ((null completions)
  1294.        (message "No completions of %s." pathname)
  1295.        (ding))
  1296.       (t
  1297.        (let ((conf (current-window-configuration)))
  1298.          (with-output-to-temp-buffer "*Help*"
  1299.            (display-completion-list completions))
  1300.          (sit-for 0)
  1301.          (message "Hit space to flush.")
  1302.          (let ((ch (read-char)))
  1303.            (if (= ch ?\ )
  1304.            (set-window-configuration conf)
  1305.            (setq unread-command-char ch))))))))
  1306.  
  1307. ; Ergo bindings
  1308. ; (global-set-key "\M-\t" 'comint-replace-by-expanded-filename)
  1309. ; (global-set-key "\M-?" 'comint-dynamic-list-completions)
  1310. ; (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
  1311.  
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.  
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.  
  1325.  
  1326.  
  1327.  
  1328.  
  1329.  
  1330.  
  1331.  
  1332.  
  1333.  
  1334.  
  1335.  
  1336.  
  1337. ;;; Converting process modes to use comint mode
  1338. ;;; ===========================================================================
  1339. ;;; Several gnu packages (tex-mode, background, dbx, gdb, kermit, prolog, 
  1340. ;;; telnet are some) use the shell package as clients. Most of them would
  1341. ;;; be better off using the comint package, but they predate it. 
  1342. ;;;
  1343. ;;; Altering these packages to use comint mode should greatly
  1344. ;;; improve their functionality, and is fairly easy.
  1345. ;;; 
  1346. ;;; Renaming variables
  1347. ;;; Most of the work is renaming variables and functions. These are the common
  1348. ;;; ones:
  1349. ;;; Local variables:
  1350. ;;;     last-input-end        comint-last-input-end
  1351. ;;;    last-input-start    <unnecessary>
  1352. ;;;    shell-prompt-pattern    comint-prompt-regexp
  1353. ;;;     shell-set-directory-error-hook <no equivalent>
  1354. ;;; Miscellaneous:
  1355. ;;;    shell-set-directory    <unnecessary>
  1356. ;;;     shell-mode-map        comint-mode-map
  1357. ;;; Commands:
  1358. ;;;    shell-send-input    comint-send-input
  1359. ;;;    shell-send-eof        comint-delchar-or-maybe-eof
  1360. ;;;     kill-shell-input    comint-kill-input
  1361. ;;;    interrupt-shell-subjob    comint-interrupt-subjob
  1362. ;;;    stop-shell-subjob    comint-stop-subjob
  1363. ;;;    quit-shell-subjob    comint-quit-subjob
  1364. ;;;    kill-shell-subjob    comint-kill-subjob
  1365. ;;;    kill-output-from-shell    comint-kill-output
  1366. ;;;    show-output-from-shell    comint-show-output
  1367. ;;;    copy-last-shell-input    Use comint-previous-input/comint-next-input
  1368. ;;;
  1369. ;;; LAST-INPUT-START is no longer necessary because inputs are stored on the
  1370. ;;; input history ring. SHELL-SET-DIRECTORY is gone, its functionality taken
  1371. ;;; over by SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-sentinel.
  1372. ;;; Comint mode does not provide functionality equivalent to 
  1373. ;;; shell-set-directory-error-hook; it is gone.
  1374. ;;; 
  1375. ;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
  1376. ;;; *not* create the comint-mode local variables in your foo-mode function.
  1377. ;;; This is not modular.  Instead, call comint-mode, and let *it* create the
  1378. ;;; necessary comint-specific local variables. Then create the
  1379. ;;; foo-mode-specific local variables in foo-mode.  Set the buffer's keymap to
  1380. ;;; be foo-mode-map, and its mode to be foo-mode.  Set the comint-mode hooks
  1381. ;;; (comint-prompt-regexp, comint-input-filter, comint-input-sentinel,
  1382. ;;; comint-get-old-input) that need to be different from the defaults.  Call
  1383. ;;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
  1384. ;;; comint-mode will take care of it. The following example, from cmushell.el,
  1385. ;;; is typical:
  1386. ;;; 
  1387. ;;; (defun shell-mode ()
  1388. ;;;   (interactive)
  1389. ;;;   (comint-mode)
  1390. ;;;   (setq comint-prompt-regexp shell-prompt-pattern)
  1391. ;;;   (setq major-mode 'shell-mode)
  1392. ;;;   (setq mode-name "Shell")
  1393. ;;;   (cond ((not shell-mode-map)
  1394. ;;;          (setq shell-mode-map (full-copy-sparse-keymap comint-mode-map))
  1395. ;;;          (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
  1396. ;;;          (define-key shell-mode-map "\M-?"
  1397. ;;;                      'comint-dynamic-list-completions)))
  1398. ;;;   (use-local-map shell-mode-map)
  1399. ;;;   (make-local-variable 'shell-directory-stack)
  1400. ;;;   (setq shell-directory-stack nil)
  1401. ;;;   (setq comint-input-sentinel 'shell-directory-tracker)
  1402. ;;;   (run-hooks 'shell-mode-hook))
  1403. ;;;
  1404. ;;;
  1405. ;;; Note that make-comint is different from make-shell in that it
  1406. ;;; doesn't have a default program argument. If you give make-shell
  1407. ;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
  1408. ;;; $ESHELL, $SHELL, or /bin/sh. If you give make-comint a program argument
  1409. ;;; of NIL, it barfs. Adjust your code accordingly...
  1410. ;;;
  1411.  
  1412.  
  1413.  
  1414.  
  1415.  
  1416.  
  1417.  
  1418.  
  1419.  
  1420.  
  1421.  
  1422.  
  1423.  
  1424.  
  1425. ;;; Do the user's customisation...
  1426.  
  1427. (defvar comint-load-hook nil
  1428.   "This hook is run when comint is loaded in.
  1429. This is a good place to put keybindings.")
  1430.     
  1431. (run-hooks 'comint-load-hook)
  1432.  
  1433. ;;; Change log:
  1434. ;;; 9/12/89 
  1435. ;;;  - Souped up the filename expansion procedures.
  1436. ;;;    Doc strings are much clearer and more detailed.
  1437. ;;;    Fixed a bug where doing a filename completion when the point
  1438. ;;;    was in the middle of the filename instead of at the end would lose.
  1439. ;;;
  1440. ;;; 2/17/90 
  1441. ;;;  - Souped up the command history stuff so that text inserted
  1442. ;;;    by comint-previous-input-matching is removed by following
  1443. ;;;    command history recalls. comint-next/previous-input-matching
  1444. ;;;    is now much more smoothly integrated w/the command history stuff.
  1445. ;;;  - Added comint-eol-on-send flag and comint-input-sender hook.
  1446. ;;;    Comint-input-sender based on code contributed by Jeff Peck
  1447. ;;;    (peck@sun.com).
  1448. ;;;
  1449. ;;; 3/13/90 ccm@cmu.cs.edu
  1450. ;;;  - Added comint-previous-similar-input for looking up similar inputs.
  1451. ;;;  - Added comint-send-and-get-output to allow snarfing input from
  1452. ;;;    buffer. 
  1453. ;;;  - Added the ability to pick up a source file by positioning over
  1454. ;;;    a string in comint-get-source.
  1455. ;;;  - Added add-hook to make it a little easier for the user to use
  1456. ;;;    multiple hooks.
  1457. ;;;  
  1458. ;;; 5/22/90 shivers
  1459. ;;; - Moved Chris' multiplexed ipc stuff to comint-ipc.el.
  1460. ;;; - Altered Chris' comint-get-source string feature. The string
  1461. ;;;   is only offered as a default if it names an existing file.
  1462. ;;; - Changed comint-exec to directly crank up the process, instead
  1463. ;;;   of calling the env program. This made background.el happy.
  1464. ;;; - Added new buffer-local var comint-ptyp. The problem is that
  1465. ;;;   the signalling functions don't work as advertised. If you are
  1466. ;;;   communicating via pipes, the CURRENT-GROUP arg is supposed to
  1467. ;;;   be ignored, but, unfortunately it seems to be the case that you
  1468. ;;;   must pass a NIL for this arg in the pipe case. COMINT-PTYP
  1469. ;;;   is a flag that tells whether the process is communicating
  1470. ;;;   via pipes or a pty. The comint signalling functions use it
  1471. ;;;   to determine the necessary CURRENT-GROUP arg value. The bug
  1472. ;;;   has been reported to the Gnu folks.
  1473. ;;; - comint-dynamic-complete flushes the help window if you hit space
  1474. ;;;   after you execute it.
  1475. ;;; - Added functions comint-send-string, comint-send-region and var 
  1476. ;;;   comint-input-chunk-size.  comint-send-string tries to prevent processes
  1477. ;;;   from hanging when you send them long strings by breaking them into
  1478. ;;;   chunks and allowing process output between chunks. I got the idea from
  1479. ;;;   Eero Simoncelli's Common Lisp package. Note that using
  1480. ;;;   comint-send-string means that the process buffer's contents can change
  1481. ;;;   during a call!  If you depend on process output only happening between
  1482. ;;;   toplevel commands, this could be a problem. In such a case, use
  1483. ;;;   process-send-string instead. If this is a problem for people, I'd like
  1484. ;;;   to hear about it.
  1485. ;;; - Added comint-proc-query as a simple mechanism for commands that
  1486. ;;;   want to query an inferior process and display its response. For a
  1487. ;;;   typical use, see lisp-show-arglist in cmulisp.el.
  1488. ;;; - Added constant comint-version, which is now "2.01".
  1489. ;;;
  1490. ;;; 6/14/90 shivers
  1491. ;;; - Had comint-update-env defined twice. Removed extra copy. Also
  1492. ;;;   renamed mem to be comint-mem, for modularity. The duplication
  1493. ;;;   was reported by Michael Meissner.
  1494. ;;; 6/16/90 shivers
  1495. ;;; - Emacs has two different mechanisms for maintaining the process
  1496. ;;;   environment, determined at compile time by the MAINTAIN-ENVIRONMENT
  1497. ;;;   #define. One uses the process-environment global variable, and
  1498. ;;;   one uses a getenv/setenv interface. comint-exec assumed the
  1499. ;;;   process-environment interface; it has been generalised (with
  1500. ;;;   comint-exec-1) to handle both cases. Pretty bogus. We could,
  1501. ;;;   of course, skip all this and just use the etc/env program to
  1502. ;;;   handle the environment tweaking, but that obscures process
  1503. ;;;   queries that other modules (like background.el) depend on. etc/env
  1504. ;;;   is also fairly bogus. This bug, and some of the fix code was
  1505. ;;;   reported by Dan Pierson.
  1506. ;;;
  1507. ;;; 9/5/90 shivers
  1508. ;;; - Changed make-variable-buffer-local's to make-local-variable's.
  1509. ;;;   This leaves non-comint-mode buffers alone. Stephane Payrard
  1510. ;;;   reported the sloppy useage.
  1511. ;;; - You can now go from comint-previous-similar-input to
  1512. ;;;   comint-previous-input with no problem.
  1513.  
  1514.  
  1515.