home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / lucid / lemacs-19.6 / lisp / ilisp / bridge.el < prev    next >
Encoding:
Text File  |  1992-06-29  |  15.6 KB  |  430 lines

  1. ;;; -*-Emacs-Lisp-*-
  2. ;;;%Header
  3. ;;; Bridge process filter, V1.0
  4. ;;; Copyright (C) 1991 Chris McConnell, ccm@cs.cmu.edu  
  5.  
  6. ;;; This file is part of GNU Emacs.
  7.  
  8. ;;; GNU Emacs is distributed in the hope that it will be useful,
  9. ;;; but WITHOUT ANY WARRANTY.  No author or distributor
  10. ;;; accepts responsibility to anyone for the consequences of using it
  11. ;;; or for whether it serves any particular purpose or works at all,
  12. ;;; unless he says so in writing.  Refer to the GNU Emacs General Public
  13. ;;; License for full details.
  14.  
  15. ;;; Everyone is granted permission to copy, modify and redistribute
  16. ;;; GNU Emacs, but only under the conditions described in the
  17. ;;; GNU Emacs General Public License.   A copy of this license is
  18. ;;; supposed to have been given to you along with GNU Emacs so you
  19. ;;; can know your rights and responsibilities.  It should be in a
  20. ;;; file named COPYING.  Among other things, the copyright notice
  21. ;;; and this notice must be preserved on all copies.
  22.  
  23. ;;; Send any bugs or comments.  Thanks to Todd Kaufmann for rewriting
  24. ;;; the process filter for continuous handlers.
  25.  
  26. ;;; USAGE: M-x install-bridge will add a process output filter to the
  27. ;;; current buffer.  Any output that the process does between
  28. ;;; bridge-start-regexp and bridge-end-regexp will be bundled up and
  29. ;;; passed to the first handler on bridge-handlers that matches the
  30. ;;; output using string-match.  If bridge-prompt-regexp shows up
  31. ;;; before bridge-end-regexp, the bridge will be cancelled.  If no
  32. ;;; handler matches the output, the first symbol in the output is
  33. ;;; assumed to be a buffer name and the rest of the output will be
  34. ;;; sent to that buffer's process.  This can be used to communicate
  35. ;;; between processes or to set up two way interactions between Emacs
  36. ;;; and an inferior process.
  37.  
  38. ;;; You can write handlers that process the output in special ways.
  39. ;;; See bridge-send-handler for the default handler.  The command
  40. ;;; hand-bridge is useful for testing.  Keep in mind that all
  41. ;;; variables are buffer local.
  42.  
  43. ;;; YOUR .EMACS FILE:
  44. ;;;
  45. ;;; ;;; Set up load path to include bridge
  46. ;;; (setq load-path (cons "/bridge-directory/" load-path))
  47. ;;; (autoload 'install-bridge "bridge" "Install a process bridge." t)
  48. ;;; (setq bridge-hook 
  49. ;;;       '(lambda ()
  50. ;;;         ;; Example options
  51. ;;;         (setq bridge-source-insert nil) ;Don't insert in source buffer
  52. ;;;         (setq bridge-destination-insert nil) ;Don't insert in dest buffer
  53. ;;;         ;; Handle copy-it messages yourself
  54. ;;;         (setq bridge-handlers
  55. ;;;          '(("copy-it" . my-copy-handler)))))
  56.  
  57. ;;; EXAMPLE:
  58. ;;; # This pipes stdin to the named buffer in a Unix shell
  59. ;;; alias devgnu '(echo -n "\!* "; cat -; echo -n "")'
  60. ;;;
  61. ;;; ls | devgnu *scratch*
  62.  
  63. ;;;%Parameters
  64. (defvar bridge-hook nil
  65.   "Hook called when a bridge is installed by install-hook.")
  66.  
  67. (defvar bridge-start-regexp ""
  68.   "*Regular expression to match the start of a process bridge in
  69. process output.  It should be followed by a buffer name, the data to
  70. be sent and a bridge-end-regexp.")
  71.  
  72. (defvar bridge-end-regexp ""
  73.   "*Regular expression to match the end of a process bridge in process
  74. output.")
  75.  
  76. (defvar bridge-prompt-regexp nil
  77.   "*Regular expression for detecting a prompt.  If there is a
  78. comint-prompt-regexp, it will be initialized to that.  A prompt before
  79. a bridge-end-regexp will stop the process bridge.")
  80.  
  81. (defvar bridge-handlers nil
  82.   "Alist of (regexp . handler) for handling process output delimited
  83. by bridge-start-regexp and bridge-end-regexp.  The first entry on the
  84. list whose regexp matches the output will be called on the process and
  85. the delimited output.")
  86.  
  87. (defvar bridge-source-insert t
  88.   "*T to insert bridge input in the source buffer minus delimiters.")
  89.  
  90. (defvar bridge-destination-insert t
  91.   "*T for bridge-send-handler to insert bridge input into the
  92. destination buffer minus delimiters.")
  93.  
  94. (defvar bridge-chunk-size 512
  95.   "*Long inputs send to comint processes are broken up into chunks of
  96. this size.  If your process is choking on big inputs, try lowering the
  97. value.")
  98.  
  99. ;;;%Internal variables
  100. (defvar bridge-old-filter nil
  101.   "Old filter for a bridged process buffer.")
  102.  
  103. (defvar bridge-string nil 
  104.   "The current output in the process bridge.")
  105.  
  106. (defvar bridge-in-progress nil
  107.   "The current handler function, if any, that bridge passes strings on to,
  108. or nil if none.")
  109.  
  110. (defvar bridge-send-to-buffer nil
  111.   "The buffer that the default bridge-handler (bridge-send-handler) is
  112. currently sending to, or nil if it hasn't started yet.  Your handler
  113. function can use this variable also.")
  114.  
  115. (defvar bridge-last-failure ()
  116.   "Last thing that broke the bridge handler.  First item is function call
  117. (eval'able); last item is error condition which resulted.  This is provided
  118. to help handler-writers in their debugging.")
  119.  
  120. ;;;%Utilities
  121. (defun bridge-insert (output)
  122.   "Insert process OUTPUT into the current buffer."
  123.   (if output
  124.       (let* ((buffer (current-buffer))
  125.          (process (get-buffer-process buffer))
  126.          (mark (process-mark process))
  127.          (window (selected-window))
  128.          (at-end nil))
  129.     (if (eq (window-buffer window) buffer)
  130.         (setq at-end (= (point) mark))
  131.         (setq window (get-buffer-window buffer)))
  132.     (save-excursion
  133.       (goto-char mark)
  134.       (insert output)
  135.       (set-marker mark (point)))
  136.     (if window 
  137.         (progn
  138.           (if at-end (goto-char mark))
  139.           (if (not (pos-visible-in-window-p (point) window))
  140.           (let ((original (selected-window)))
  141.             (save-excursion
  142.               (select-window window)
  143.               (recenter '(center))
  144.               (select-window original)))))))))
  145.  
  146. ;;;
  147. (defun bridge-send-string (process string)
  148.   "Send PROCESS the contents of STRING as input.
  149. This is equivalent to process-send-string, except that long input strings
  150. are broken up into chunks of size comint-input-chunk-size. Processes
  151. are given a chance to output between chunks. This can help prevent processes
  152. from hanging when you send them long inputs on some OS's."
  153.   (let* ((len (length string))
  154.      (i (min len bridge-chunk-size)))
  155.     (process-send-string process (substring string 0 i))
  156.     (while (< i len)
  157.       (let ((next-i (+ i bridge-chunk-size)))
  158.     (accept-process-output)
  159.     (process-send-string process (substring string i (min len next-i)))
  160.     (setq i next-i)))))
  161.  
  162. ;;;
  163. (defun bridge-call-handler (handler proc string)
  164.   "Funcall HANDLER on PROC, STRING carefully.  Error is caught if happens,
  165. and user is signaled.  State is put in bridge-last-failure.  Returns t if
  166. handler executed without error."
  167.   (let ((inhibit-quit nil)
  168.     (failed nil))
  169.     (condition-case err
  170.     (funcall handler proc string)
  171.       (error
  172.        (ding)
  173.        (setq failed t)
  174.        (message "bridge-handler \"%s\" failed %s (see bridge-last-failure)"
  175.         function err)
  176.        (setq bridge-last-failure
  177.          (` ((funcall '(, handler) '(, proc) (, string))
  178.          "Caused: "
  179.          (, err))))))
  180.     (not failed)))
  181.  
  182. ;;;%Handlers
  183. (defun bridge-send-handler (process input)
  184.   "Send PROCESS INPUT to the buffer name found at the start of the
  185. input.  The input after the buffer name is sent to the buffer's
  186. process if it has one.  If bridge-destination-insert is T, the input
  187. will be inserted into the buffer.  If it does not have a process, it
  188. will be inserted at the end of the buffer."
  189.   (if (null input)
  190.       (setq bridge-send-to-buffer nil)  ; end of bridge
  191.       (let (buffer-and-start buffer-name dest to)
  192.     ;; if this is first time, get the buffer out of the first line
  193.     (cond ((not bridge-send-to-buffer)
  194.            (setq buffer-and-start (read-from-string input)
  195.              buffer-name (format "%s" (car (read-from-string input)))
  196.              dest        (get-buffer buffer-name)
  197.              to          (get-buffer-process dest)
  198.              input (substring input (cdr buffer-and-start)))
  199.            (setq bridge-send-to-buffer dest))
  200.           (t
  201.            (setq buffer-name bridge-send-to-buffer
  202.              dest        (get-buffer buffer-name)
  203.              to          (get-buffer-process dest)
  204.              )))
  205.     (if dest
  206.         (let ((buffer (current-buffer)))
  207.           (if bridge-destination-insert
  208.           (unwind-protect
  209.                (progn
  210.              (set-buffer dest)
  211.              (if to 
  212.                  (bridge-insert input)
  213.                  (goto-char (point-max))
  214.                  (insert input)))
  215.             (set-buffer buffer)))
  216.           (if to (bridge-send-string to input)))
  217.         (error "%s is not a buffer" buffer-name)))))
  218.  
  219. ;;;%Filter
  220. (defun bridge-filter (process output)
  221.   "Given PROCESS and some OUTPUT, check for the presence of
  222. bridge-start-regexp.  Everything prior to this will be passed to the
  223. normal filter function or inserted in the buffer if it is nil.  The
  224. output up to bridge-end-regexp will be sent to the first handler on
  225. bridge-handlers that matches the string.  If no handlers match, the
  226. input will be sent to bridge-send-handler.  If bridge-prompt-regexp is
  227. encountered before the bridge-end-regexp, the bridge will be cancelled."
  228.    (let ((inhibit-quit t)
  229.      (match-data (match-data))
  230.      (buffer (current-buffer))
  231.      (process-buffer (process-buffer process))
  232.      (case-fold-search t)
  233.      (start 0) (end 0)
  234.      function
  235.      b-start b-start-end b-end)
  236.      (set-buffer process-buffer) ;; access locals
  237.      (setq function bridge-in-progress)
  238.  
  239.      ;; How it works:
  240.      ;;
  241.      ;; start, end delimit the part of string we are interested in;
  242.      ;; initially both 0; after an iteration we move them to next string.
  243.  
  244.      ;; b-start, b-end delimit part of string to bridge (possibly whole string);
  245.      ;; this will be string between corresponding regexps.
  246.  
  247.      ;; There are two main cases when we come into loop:
  248.  
  249.      ;;  bridge in progress
  250.      ;;0    setq b-start = start
  251.      ;;1    setq b-end (or end-pattern end)
  252.      ;;4    process string
  253.      ;;5    remove handler if end found
  254.      
  255.      ;;  no bridge in progress
  256.      ;;0    setq b-start if see start-pattern
  257.      ;;1    setq b-end if bstart to (or end-pattern end)
  258.      ;;2    send (substring start b-start)  to normal place
  259.      ;;3    find handler (in b-start, b-end) if not set
  260.      ;;4    process string
  261.      ;;5    remove handler if end found
  262.  
  263.      ;; equivalent sections have the same numbers here;
  264.      ;; we fold them together in this code.
  265.  
  266.      (unwind-protect
  267.     (while (< end (length output))
  268.  
  269.       ;;0    setq b-start if find
  270.       (setq b-start
  271.         (cond (bridge-in-progress
  272.                (setq b-start-end start)
  273.                start)
  274.               ((string-match bridge-start-regexp output start)
  275.                (setq b-start-end (match-end 0))
  276.                (match-beginning 0))
  277.               (t nil)))
  278.       ;;1    setq b-end
  279.       (setq b-end
  280.         (if b-start
  281.             (let ((end-seen (string-match bridge-end-regexp
  282.                           output b-start-end)))
  283.               (if end-seen (setq end (match-end 0)))
  284.               end-seen)))
  285.       (if (not b-end) (setq end   (length output)
  286.                 b-end (length output)))
  287.  
  288.       ;;1.5 - if see prompt before end, remove current
  289.       (if b-start
  290.           (let ((prompt (string-match bridge-prompt-regexp
  291.                       output b-start-end)))
  292.         (if (and prompt (<= (match-end 0) b-end))
  293.             (setq b-start nil  ; b-start-end start
  294.               b-end   start
  295.               end     (match-end 0)
  296.               bridge-in-progress nil
  297.               ))))
  298.  
  299.       ;;2    send (substring start b-start) to old filter, if any
  300.       (if (/= start (or b-start end)) ; don't bother on empty string
  301.           (let ((pass-on (substring output start (or b-start end))))
  302.         (if bridge-old-filter
  303.             (let ((old bridge-old-filter))
  304.               (store-match-data match-data)
  305.               (funcall old process pass-on)
  306.               ;; if filter changed, re-install ourselves
  307.               (let ((new (process-filter process)))
  308.             (if (not (eq new 'bridge-filter))
  309.                 (progn (setq bridge-old-filter new)
  310.                    (set-process-filter process 'bridge-filter)))))
  311.             (set-buffer process-buffer)
  312.             (bridge-insert pass-on))))
  313.  
  314.       ;;3 find handler (in b-start, b-end) if none current
  315.       (if (and b-start (not bridge-in-progress))
  316.           (let ((handlers bridge-handlers))
  317.         (while (and handlers (not function))
  318.           (let* ((handler (car handlers))
  319.              (m (string-match (car handler) output b-start-end)))
  320.             (if (and m (< m b-end))
  321.             (setq function (cdr handler))
  322.             (setq handlers (cdr handlers)))))
  323.         ;; Set default handler if none
  324.         (if (null function)
  325.             (setq function 'bridge-send-handler))
  326.         (setq bridge-in-progress function)))
  327.       ;;4    process string
  328.       (if function
  329.           (let ((ok t))
  330.         (if (/=  b-start-end b-end)
  331.             (let ((send (substring output b-start-end b-end)))
  332.               ;; also, insert the stuff in buffer between
  333.               ;; iff bridge-source-insert.
  334.               (if bridge-source-insert (bridge-insert send))
  335.               ;; call handler on string
  336.               (setq ok (bridge-call-handler function process send))))
  337.         ;;5    remove handler if end found
  338.         ;; if function removed then tell it that's all
  339.         (if (or (not ok) (/= b-end end));; saw end before end-of-string
  340.             (progn
  341.               (bridge-call-handler function process nil)
  342.               ;; have to remove function too for next time around
  343.               (setq function nil
  344.                 bridge-in-progress nil)
  345.               ))
  346.         ))
  347.      
  348.          ;; continue looping, in case there's more string
  349.          (setq start end)
  350.          ))
  351.        ;; protected forms:  restore buffer, match-data
  352.        (set-buffer buffer)
  353.        (store-match-data match-data)
  354.        ))
  355.  
  356. ;;;%Interface
  357. (defun install-bridge ()
  358.   "Set up a process bridge in the current buffer."
  359.   (interactive)
  360.   (if (not (get-buffer-process (current-buffer)))
  361.       (error "%s does not have a process" (buffer-name (current-buffer)))
  362.       (make-local-variable 'bridge-start-regexp)
  363.       (make-local-variable 'bridge-end-regexp)
  364.       (make-local-variable 'bridge-prompt-regexp)
  365.       (make-local-variable 'bridge-handlers)
  366.       (make-local-variable 'bridge-source-insert)
  367.       (make-local-variable 'bridge-destination-insert)
  368.       (make-local-variable 'bridge-chunk-size)
  369.       (make-local-variable 'bridge-old-filter)
  370.       (make-local-variable 'bridge-string)
  371.       (make-local-variable 'bridge-in-progress)
  372.       (make-local-variable 'bridge-send-to-buffer)
  373.       (setq bridge-string nil bridge-in-progress nil
  374.         bridge-send-to-buffer nil)
  375.       (if (boundp 'comint-prompt-regexp)
  376.       (setq bridge-prompt-regexp comint-prompt-regexp))
  377.       (let ((process (get-buffer-process (current-buffer))))
  378.     (if process
  379.         (if (not (eq (process-filter process) 'bridge-filter))
  380.         (progn
  381.           (setq bridge-old-filter (process-filter process))
  382.           (set-process-filter process 'bridge-filter)))
  383.         (error "%s does not have a process" 
  384.            (buffer-name (current-buffer)))))
  385.       (run-hooks 'bridge-hook)
  386.       (message "Process bridge is installed")))
  387.           
  388. ;;;
  389. (defun reset-bridge ()
  390.   "Must be called from the process's buffer.  Removes any active bridge."
  391.   (interactive)
  392.   ;; for when things get wedged
  393.   (if bridge-in-progress
  394.       (unwind-protect
  395.        (funcall bridge-in-progress (get-buffer-process
  396.                     (current-buffer))
  397.             nil)
  398.     (setq bridge-in-progress nil))
  399.       (message "No bridge in progress.")))
  400.  
  401. ;;;
  402. (defun remove-bridge ()
  403.   "Remove bridge from the current buffer."
  404.   (interactive)
  405.   (let ((process (get-buffer-process (current-buffer))))
  406.     (if (or (not process) (not (eq (process-filter process) 'bridge-filter)))
  407.     (error "%s has no bridge" (buffer-name (current-buffer)))
  408.     ;; remove any bridge-in-progress
  409.     (reset-bridge)
  410.     (set-process-filter process bridge-old-filter)
  411.     (funcall bridge-old-filter process bridge-string)
  412.     (message "Process bridge is removed."))))
  413.  
  414. ;;;% Utility for testing
  415. (defun hand-bridge (start end)
  416.   "With point at bridge-start, sends bridge-start + string +
  417. bridge-end to bridge-filter.  With prefix, use current region to send."
  418.   (interactive "r")
  419.   (let ((p0 (if current-prefix-arg (min start end)
  420.         (if (looking-at bridge-start-regexp) (point)
  421.             (error "Not looking at bridge-start-regexp"))))
  422.     (p1 (if current-prefix-arg (max start end)
  423.         (if (re-search-forward bridge-end-regexp nil t)
  424.             (point) (error "Didn't see bridge-end-regexp")))))
  425.     
  426.     (bridge-filter (get-buffer-process (current-buffer))
  427.            (buffer-substring p0 p1))
  428.     ))
  429.  
  430. (provide 'bridge)