home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / languages / elisp / modes / S.shar / comint.el next >
Encoding:
Text File  |  1990-07-22  |  39.8 KB  |  983 lines

  1. ;;; -*-Emacs-Lisp-*- General command interpreter in a window stuff
  2. ;;; Copyright Olin Shivers (1988).
  3. ;;; Please imagine a long, tedious, legalistic 5-page gnu-style copyright
  4. ;;; notice appearing here to the effect that you may use this code any
  5. ;;; way you like, as long as you don't charge money for it, remove this
  6. ;;; notice, or hold me liable for its results.
  7.  
  8. ;;; This hopefully generalises shell mode, lisp mode, tea mode, soar mode,...
  9. ;;; Hacked from tea.el and shell.el by Olin Shivers (shivers@cs.cmu.edu). 8/88
  10.  
  11. ;;; This file defines a general command-interpreter-in-a-buffer package
  12. ;;; (comint mode). The idea is that you can build specific process-in-a-buffer
  13. ;;; modes on top of comint mode -- e.g., lisp, shell, scheme, T, soar, ....
  14. ;;; This way, all these specific packages share a common base functionality, 
  15. ;;; and a common set of bindings, which makes them easier to use (and
  16. ;;; saves code, implementation time, etc., etc.).
  17. ;;; 
  18. ;;; Several packages are already defined using comint mode:
  19. ;;; - The file cmushell.el defines cmushell and cmulisp mode.
  20. ;;; Cmushell and cmulisp mode are similar to, and intended to replace,
  21. ;;; their counterparts in the standard gnu emacs release (in shell.el). 
  22. ;;; These replacements are more featureful, robust, and uniform than the 
  23. ;;; released versions. The key bindings in lisp mode are also more compatible
  24. ;;; with the bindings of Hemlock and Zwei (the Lisp Machine emacs).
  25. ;;;
  26. ;;; - The file cmuscheme.el defines inferior-scheme mode.
  27. ;;; - The file tea.el tunes scheme and inferior-scheme modes for T.
  28. ;;; - The file soar.el tunes lisp and inferior-lisp modes for Soar.
  29.  
  30. ;;; For documentation on the functionality provided by comint mode, and
  31. ;;; the hooks available for customising it, see the comments below.
  32. ;;; For further information on the standard derived modes (shell, 
  33. ;;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
  34.  
  35. ;;; Please send me bug reports, bug fixes, and extensions, so that I can
  36. ;;; merge them into the master source.
  37.  
  38. ;;; For hints on converting existing process modes (e.g., tex-mode,
  39. ;;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
  40. ;;; instead of shell-mode, see the notes at the end of this file.
  41.  
  42. (provide 'comint)
  43.  
  44.  
  45. ;;; Brief Command Documentation:
  46. ;;;============================================================================
  47. ;;; Comint Mode Commands: (common to all derived modes, like cmushell & cmulisp
  48. ;;; mode)
  49. ;;;
  50. ;;; m-p        comint-previous-input            Cycle backwards in input history
  51. ;;; m-n        comint-next-input                  Cycle forwards
  52. ;;; c-c r   comint-previous-input-matching  Search backwards in input history
  53. ;;; return  comint-send-input
  54. ;;; c-a     comint-bol                      Beginning of line; skip prompt.
  55. ;;; c-d        comint-delchar-or-maybe-eof     Delete char unless at end of buff.
  56. ;;; c-c c-u comint-kill-input                ^u
  57. ;;; c-c c-w backward-kill-word            ^w
  58. ;;; c-c c-c comint-interrupt-subjob         ^c
  59. ;;; c-c c-z comint-stop-subjob                ^z
  60. ;;; c-c c-\ comint-quit-subjob                ^\
  61. ;;; c-c c-o comint-kill-output            Delete last batch of process output
  62. ;;; c-c c-r comint-show-output            Show last batch of process output
  63. ;;;
  64. ;;; Not bound by default in comint-mode
  65. ;;; send-invisible            Read a line w/o echo, and send to proc
  66. ;;; (These are bound in shell-mode)
  67. ;;; comint-dynamic-complete        Complete filename at point.
  68. ;;; comint-dynamic-list-completions    List completions in help buffer.
  69. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  70. ;;;                    replace with expanded/completed name.
  71. ;;; comint-kill-subjob            No mercy.
  72. ;;; comint-continue-subjob        Send CONT signal to buffer's process
  73. ;;;                    group. Useful if you accidentally
  74. ;;;                    suspend your process (with C-c C-z).
  75. ;;;
  76. ;;; Bound for RMS -- I prefer the input history stuff, but you might like 'em.
  77. ;;; m-P       comint-msearch-input        Search backwards for prompt
  78. ;;; m-N    comint-psearch-input        Search forwards for prompt
  79. ;;; C-cR   comint-msearch-input-matching Search backwards for prompt & string
  80.  
  81. ;;; comint-mode-hook is the comint mode hook. Basically for your keybindings.
  82. ;;; comint-load-hook is run after loading in this package.
  83.  
  84.  
  85. ;;; Buffer Local Variables:
  86. ;;;============================================================================
  87. ;;; Comint mode buffer local variables:
  88. ;;;     comint-prompt-regexp    - string       comint-bol uses to match prompt.
  89. ;;;     comint-last-input-end   - marker       For comint-kill-output command
  90. ;;;     input-ring-size         - integer      For the input history
  91. ;;;     input-ring              - ring             mechanism
  92. ;;;     input-ring-index        - marker           ...
  93. ;;;     comint-last-input-match - string           ...
  94. ;;;     comint-get-old-input    - function     Hooks for specific 
  95. ;;;     comint-input-sentinel   - function         process-in-a-buffer
  96. ;;;     comint-input-filter     - function         modes.
  97. (defvar comint-prompt-regexp "^"
  98.   "Regexp to recognise prompts in the inferior process.
  99. Defaults to \"^\", the null string at BOL.
  100.  
  101. Good choices:
  102.   Canonical Lisp: \"^[^> ]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
  103.   Lucid Common Lisp: \"^\\(>\\|\\(->\\)+\\) *\"
  104.   franz: \"^\\(->\\|<[0-9]*>:\\) *\"
  105.   kcl: \"^>+ *\"
  106.   shell: \"^[^#$%>]*[#$%>] *\"
  107.   T: \"^>+ *\"
  108.  
  109. This is a good thing to set in mode hooks.")
  110.  
  111. (defvar input-ring-size 30
  112.   "Size of input history ring.")
  113.  
  114. ;;; Here are the per-interpreter hooks.
  115. (defvar comint-get-old-input (function comint-get-old-input-default)
  116.   "Function that submits old text in comint mode.
  117. This function is called when return is typed while the point is in old text.
  118. It returns the text to be submitted as process input.  The default is
  119. comint-get-old-input-default, which grabs the current line, and strips off
  120. leading text matching comint-prompt-regexp")
  121.  
  122. (defvar comint-input-sentinel (function ignore)
  123.   "Called on each input submitted to comint mode process by comint-send-input.
  124. Thus it can, for instance, track cd/pushd/popd commands issued to the csh.")
  125.  
  126. (defvar comint-input-filter
  127.   (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
  128.   "Predicate for filtering additions to input history.
  129. Only inputs answering true to this function are saved on the input
  130. history list. Default is to save anything that isn't all whitespace")
  131.  
  132. (defvar comint-mode-hook '()
  133.   "Called upon entry into comint-mode")
  134.  
  135. (defvar comint-mode-map nil)
  136.  
  137. (defun comint-mode ()
  138.   "Major mode for interacting with an inferior interpreter.
  139. Interpreter name is same as buffer name, sans the asterisks.
  140. Return at end of buffer sends line as input.
  141. Return not at end copies rest of line to end and sends it.
  142.  
  143. This mode is typically customised to create inferior-lisp-mode,
  144. shell-mode, etc.. This can be done by setting the hooks
  145. comint-input-sentinel, comint-input-filter, and comint-get-old-input to
  146. appropriate functions, and the variable comint-prompt-regexp to
  147. the appropriate regular expression.
  148.  
  149. An input history is maintained of size input-ring-size, and
  150. can be accessed with the commands comint-next-input [\\[comint-next-input]] and 
  151. comint-previous-input [\\[comint-previous-input]]. Commands not keybound by
  152. default are send-invisible, comint-dynamic-complete, and 
  153. comint-list-dynamic-completions.
  154. \\{comint-mode-map}
  155. If you accidentally suspend your process, use \\[comint-continue-subjob]
  156. to continue it.
  157.  
  158. Entry to this mode runs the hooks on comint-mode-hook"
  159.   (interactive)
  160.   (let ((old-ring (and (assq 'input-ring (buffer-local-variables))
  161.                (boundp 'input-ring)
  162.                input-ring)))
  163.     (kill-all-local-variables)
  164.     (setq major-mode 'comint-mode)
  165.     (setq mode-name "Comint")
  166.     (setq mode-line-process '(": %s"))
  167.     (use-local-map comint-mode-map)
  168.     (make-local-variable 'comint-last-input-end)
  169.     (setq comint-last-input-end (make-marker))
  170.     (make-local-variable 'comint-last-input-match)
  171.     (setq comint-last-input-match "")
  172.     (make-variable-buffer-local 'comint-prompt-regexp) ; Don't set; default
  173.     (make-variable-buffer-local 'input-ring-size)      ; ...to global val.
  174.     (make-local-variable 'input-ring)
  175.     (make-local-variable 'input-ring-index)
  176.     (setq input-ring-index 0)
  177.     (make-variable-buffer-local 'comint-get-old-input)
  178.     (make-variable-buffer-local 'comint-input-sentinel)
  179.     (make-variable-buffer-local 'comint-input-filter)  
  180.     (run-hooks 'comint-mode-hook)
  181.     ;Do this after the hook so the user can mung INPUT-RING-SIZE w/his hook.
  182.     ;The test is so we don't lose history if we run comint-mode twice in
  183.     ;a buffer.
  184.     (setq input-ring (if (ring-p old-ring) old-ring
  185.              (make-ring input-ring-size)))))
  186.  
  187. (if comint-mode-map
  188.     nil
  189.   (setq comint-mode-map (make-sparse-keymap))
  190.   (define-key comint-mode-map "\ep" 'comint-previous-input)
  191.   (define-key comint-mode-map "\en" 'comint-next-input)
  192.   (define-key comint-mode-map "\C-m" 'comint-send-input)
  193.   (define-key comint-mode-map "\C-d" 'comint-delchar-or-maybe-eof)
  194.   (define-key comint-mode-map "\C-a" 'comint-bol)
  195.   (define-key comint-mode-map "\C-c\C-u" 'comint-kill-input)
  196.   (define-key comint-mode-map "\C-c\C-w" 'backward-kill-word)
  197.   (define-key comint-mode-map "\C-c\C-c" 'comint-interrupt-subjob)
  198.   (define-key comint-mode-map "\C-c\C-z" 'comint-stop-subjob)
  199.   (define-key comint-mode-map "\C-c\C-\\" 'comint-quit-subjob)
  200.   (define-key comint-mode-map "\C-c\C-o" 'comint-kill-output)
  201.   (define-key comint-mode-map "\C-cr"    'comint-previous-input-matching)
  202.   (define-key comint-mode-map "\C-c\C-r" 'comint-show-output)
  203.   ;;; Here's the prompt-search stuff I installed for RMS to try...
  204.   (define-key comint-mode-map "\eP" 'comint-msearch-input)
  205.   (define-key comint-mode-map "\eN" 'comint-psearch-input)
  206.   (define-key comint-mode-map "\C-cR" 'comint-msearch-input-matching))
  207.  
  208.  
  209. ;;; This function is used to make a full copy of the comint mode map,
  210. ;;; so that client modes won't interfere with each other. This function
  211. ;;; isn't necessary in emacs 18.5x, but we keep it around for 18.4x versions.
  212. (defun full-copy-sparse-keymap (km)
  213.   "Recursively copy the sparse keymap KM"
  214.   (cond ((consp km)
  215.      (cons (full-copy-sparse-keymap (car km))
  216.            (full-copy-sparse-keymap (cdr km))))
  217.     (t km)))
  218.  
  219. (defun comint-check-proc (buffer-name)
  220.   "True if there is a process associated w/buffer BUFFER-NAME, and
  221. it is alive (status RUN or STOP)."
  222.   (let ((proc (get-buffer-process buffer-name)))
  223.     (and proc (memq (process-status proc) '(run stop)))))
  224.  
  225. ;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
  226. ;;; for the second argument (program).
  227. (defun make-comint (name program &optional startfile &rest switches)
  228.   (let* ((buffer (get-buffer-create (concat "*" name "*")))
  229.      (proc (get-buffer-process buffer)))
  230.     ;; If no process, or nuked process, crank up a new one and put buffer in
  231.     ;; comint mode. Otherwise, leave buffer and existing process alone.
  232.     (cond ((or (not proc) (not (memq (process-status proc) '(run stop))))
  233.        (comint-exec buffer name program startfile switches)
  234.        (save-excursion
  235.          (set-buffer buffer)
  236.          (comint-mode)))) ; Install local vars, mode, keymap, ...
  237.     buffer))
  238.  
  239. (defun comint-exec (buffer name command startfile switches)
  240.   "Fires up a process in buffer for comint modes.
  241. Blasts any old process running in the buffer. Doesn't set the buffer mode.
  242. You can use this to cheaply run a series of processes in the same comint
  243. buffer."
  244.   (save-excursion
  245.     (set-buffer buffer)
  246.     (let ((proc (get-buffer-process buffer)))    ; Blast any old process.
  247.       (if proc (delete-process proc)))
  248.     ;; Crank up a new process
  249.     (let ((proc (apply 'start-process name buffer (concat exec-directory "env")
  250.                (format "TERMCAP=emacs:co#%d:tc=unknown:"
  251.                    (screen-width))
  252.                "TERM=emacs" "EMACS=t" "-" command switches)))
  253.       ;; Feed it the startfile.
  254.       (cond (startfile
  255.          ;;This is guaranteed to wait long enough
  256.          ;;but has bad results if the comint does not prompt at all
  257.          ;;         (while (= size (buffer-size))
  258.          ;;           (sleep-for 1))
  259.          ;;I hope 1 second is enough!
  260.          (sleep-for 1)
  261.          (goto-char (point-max))
  262.          (insert-file-contents startfile)
  263.          (setq startfile (buffer-substring (point) (point-max)))
  264.          (delete-region (point) (point-max))
  265.          (process-send-string proc startfile)))
  266.       ;; Jump to the end, and set the process mark.
  267.       (goto-char (point-max))
  268.       (set-marker (process-mark proc) (point)))
  269.     buffer))
  270.       
  271.  
  272.  
  273. ;;; Ring Code
  274. ;;;============================================================================
  275. ;;; This code defines a ring data structure. A ring is a 
  276. ;;;     (hd-index tl-index . vector) 
  277. ;;; list. You can insert to, remove from, and rotate a ring. When the ring
  278. ;;; fills up, insertions cause the oldest elts to be quietly dropped.
  279. ;;;
  280. ;;; HEAD = index of the newest item on the ring.
  281. ;;; TAIL = index of the oldest item on the ring.
  282. ;;;
  283. ;;; These functions are used by the input history mechanism, but they can
  284. ;;; be used for other purposes as well.
  285.  
  286. (defun ring-p (x) 
  287.   "T if X is a ring; NIL otherwise."
  288.   (and (consp x) (integerp (car x))
  289.        (consp (cdr x)) (integerp (car (cdr x)))
  290.        (vectorp (cdr (cdr x)))))
  291.  
  292. (defun make-ring (size)
  293.   "Make a ring that can contain SIZE elts"
  294.   (cons 1 (cons 0 (make-vector (+ size 1) nil))))
  295.  
  296. (defun ring-plus1 (index veclen)
  297.   "INDEX+1, with wraparound"
  298.   (let ((new-index (+ index 1)))
  299.     (if (= new-index veclen) 0 new-index)))
  300.  
  301. (defun ring-minus1 (index veclen)
  302.   "INDEX-1, with wraparound"
  303.   (- (if (= 0 index) veclen index) 1))
  304.  
  305. (defun ring-length (ring)
  306.   (let ((hd (car ring)) (tl (car (cdr ring)))  (siz (length (cdr (cdr ring)))))
  307.     (let ((len (if (<= hd tl) (+ 1 (- tl hd)) (+ 1 tl (- siz hd)))))
  308.       (if (= len siz) 0 len))))
  309.  
  310. (defun ring-empty-p (ring)
  311.   (= 0 (ring-length ring)))
  312.  
  313. (defun ring-insert (ring item)
  314.   "Insert a new item onto the ring. If the ring is full, dump the oldest
  315. item to make room."       
  316.   (let* ((vec (cdr (cdr ring)))  (len (length vec))
  317.      (new-hd (ring-minus1 (car ring) len)))
  318.       (setcar ring new-hd)
  319.       (aset vec new-hd item)
  320.       (if (ring-empty-p ring) ;overflow -- dump one off the tail.
  321.       (setcar (cdr ring) (ring-minus1 (car (cdr ring)) len)))))
  322.  
  323. (defun ring-remove (ring)
  324.   "Remove the oldest item retained on the ring."
  325.   (if (ring-empty-p ring) (error "Ring empty")
  326.       (let ((tl (car (cdr ring)))  (vec (cdr (cdr ring))))
  327.     (set-car (cdr ring) (ring-minus1 tl (length vec)))
  328.     (aref vec tl))))
  329.  
  330. ;;; This isn't actually used in this package. I just threw it in in case
  331. ;;; someone else wanted it. If you want rotating-ring behavior on your history
  332. ;;; retrieval (analagous to kill ring behavior), this function is what you
  333. ;;; need. I should write the yank-input and yank-pop-input-or-kill to go with
  334. ;;; this, and not bind it to a key by default, so it would be available to
  335. ;;; people who want to bind it to a key. But who would want it? Blech.
  336. (defun ring-rotate (ring n)
  337.   (if (not (= n 0))
  338.       (if (ring-empty-p ring) ;Is this the right error check?
  339.       (error "ring empty")
  340.       (let ((hd (car ring))  (tl (car (cdr ring)))  (vec (cdr (cdr ring))))
  341.         (let ((len (length vec)))
  342.           (while (> n 0)
  343.         (setq tl (ring-plus1 tl len))
  344.         (aset ring tl (aref ring hd))
  345.         (setq hd (ring-plus1 hd len))
  346.         (setq n (- n 1)))
  347.           (while (< n 0)
  348.         (setq hd (ring-minus1 hd len))
  349.         (aset vec hd (aref vec tl))
  350.         (setq tl (ring-minus1 tl len))
  351.         (setq n (- n 1))))
  352.         (set-car ring hd)
  353.         (set-car (cdr ring) tl)))))
  354.  
  355. (defun comint-mod (n m)
  356.   "Returns N mod M. M is positive. Answer is guaranteed to be non-negative, 
  357. and less than m."
  358.   (let ((n (% n m)))
  359.     (if (>= n 0) n
  360.     (+ n
  361.        (if (>= m 0) m (- m)))))) ; (abs m)
  362.  
  363. (defun ring-ref (ring index)
  364.   (let ((numelts (ring-length ring)))
  365.     (if (= numelts 0) (error "indexed empty ring")
  366.     (let* ((hd (car ring))  (tl (car (cdr ring)))  (vec (cdr (cdr ring)))
  367.            (index (comint-mod index numelts))
  368.            (vec-index (comint-mod (+ index hd) 
  369.                       (length vec))))
  370.       (aref vec vec-index)))))
  371.  
  372.  
  373. ;;; Input history retrieval commands
  374. ;;; M-p -- previous input    M-n -- next input
  375. ;;; C-c r -- previous input matching
  376. ;;; ===========================================================================
  377.  
  378. (defun comint-previous-input (arg)
  379.   "Cycle backwards through input history."
  380.   (interactive "*p")
  381.   (let ((len (ring-length input-ring)))
  382.     (cond ((<= len 0)
  383.        (message "Empty input ring")
  384.        (ding))
  385.       ((not (comint-after-pmark-p))
  386.        (message "Not after process mark")
  387.        (ding))
  388.       (t
  389.        (cond ((eq last-command 'comint-previous-input)
  390.           (delete-region (mark) (point))
  391.           (set-mark (point)))
  392.          (t                          
  393.           (setq input-ring-index
  394.             (if (> arg 0) -1
  395.                 (if (< arg 0) 1 0)))
  396.           (push-mark (point))))
  397.        (setq input-ring-index (comint-mod (+ input-ring-index arg) len))
  398.        (message "%d" (1+ input-ring-index))
  399.        (insert (ring-ref input-ring input-ring-index))
  400.        (setq this-command 'comint-previous-input))
  401.       (t (ding)))))
  402.      
  403. (defun comint-next-input (arg)
  404.   "Cycle forwards through input history."
  405.   (interactive "*p")
  406.   (comint-previous-input (- arg)))
  407.  
  408. (defvar comint-last-input-match ""
  409.   "Last string searched for by comint input history search, for defaulting.
  410. Buffer local variable.") 
  411.  
  412. (defun comint-previous-input-matching (str)
  413.   "Searches backwards through input history for substring match"
  414.   (interactive (let ((s (read-from-minibuffer 
  415.              (format "Command substring (default %s): "
  416.                  comint-last-input-match))))
  417.          (list (if (string= s "") comint-last-input-match s))))
  418. ; (interactive "sCommand substring: ")
  419.   (setq comint-last-input-match str) ; update default
  420.   (let ((str (regexp-quote str))
  421.         (len (ring-length input-ring))
  422.     (n 0))
  423.     (while (and (<= n len) (not (string-match str (ring-ref input-ring n))))
  424.       (setq n (+ n 1)))
  425.     (cond ((<= n len) (comint-previous-input (+ n 1)))
  426.       (t (error "Not found.")))))
  427.  
  428. ;;; These next three commands are alternatives to the input history commands --
  429. ;;; comint-next-input, comint-previous-input and 
  430. ;;; comint-previous-input-matching. They search through the process buffer
  431. ;;; text looking for occurrences of the prompt. RMS likes them better;
  432. ;;; I don't. Bound to M-P, M-N, and C-c R (uppercase P, N, and R) for
  433. ;;; now. Try'em out. Go with what you like...
  434.  
  435. ;;; comint-msearch-input-matching prompts for a string, not a regexp.
  436. ;;; This could be considered to be the wrong thing. I decided to keep it
  437. ;;; simple, and not make the user worry about regexps. This, of course,
  438. ;;; limits functionality.
  439.  
  440. (defun comint-psearch-input ()
  441.   "Search forwards for next occurrence of prompt and skip to end of line.
  442. \(prompt is anything matching regexp comint-prompt-regexp)"
  443.   (interactive)
  444.   (if (re-search-forward comint-prompt-regexp (point-max) t)
  445.       (end-of-line)
  446.       (error "No occurrence of prompt found")))
  447.  
  448. (defun comint-msearch-input ()
  449.   "Search backwards for previous occurrence of prompt and skip to end of line.
  450. Search starts from beginning of current line."
  451.   (interactive)
  452.   (let ((p (save-excursion
  453.          (beginning-of-line)
  454.          (cond ((re-search-backward comint-prompt-regexp (point-min) t)
  455.             (end-of-line)
  456.             (point))
  457.            (t nil)))))
  458.     (if p (goto-char p)
  459.     (error "No occurrence of prompt found"))))
  460.  
  461. (defun comint-msearch-input-matching (str)
  462.   "Search backwards for occurrence of prompt followed by STRING.
  463. STRING is prompted for, and is NOT a regular expression."
  464.   (interactive (let ((s (read-from-minibuffer 
  465.              (format "Command (default %s): "
  466.                  comint-last-input-match))))
  467.          (list (if (string= s "") comint-last-input-match s))))
  468. ; (interactive "sCommand: ")
  469.   (setq comint-last-input-match str) ; update default
  470.   (let* ((r (concat comint-prompt-regexp (regexp-quote str)))
  471.      (p (save-excursion
  472.           (beginning-of-line)
  473.           (cond ((re-search-backward r (point-min) t)
  474.              (end-of-line)
  475.              (point))
  476.             (t nil)))))
  477.     (if p (goto-char p)
  478.     (error "No match"))))
  479.  
  480. (defun comint-send-input () 
  481.   "Send input to process.  After the process output mark, sends all text
  482. from the process mark to point as input to the process.  Before the
  483. process output mark, calls value of variable comint-get-old-input to retrieve
  484. old input, copies it to the end of the buffer, and sends it.  A terminal
  485. newline is also inserted into the buffer and sent to the process.  In either
  486. case, value of variable comint-input-sentinel is called on the input before
  487. sending it.  The input is entered into the input history ring, if value of
  488. variable comint-input-filter returns T when called on the input.
  489.  
  490. comint-get-old-input, comint-input-sentinel, and comint-input-filter are chosen
  491. according to the command interpreter running in the buffer. E.g.,
  492. If the interpreter is the csh,
  493.     comint-get-old-input is the default: take the current line, discard any
  494.         initial string matching regexp comint-prompt-regexp.
  495.     comint-input-sentinel monitors input for \"cd\", \"pushd\", and \"popd\" 
  496.         commands. When it sees one, it cd's the buffer.
  497.     comint-input-filter is the default: returns T if the input isn't all white
  498.     space.
  499.  
  500. If the comint is Lucid Common Lisp, 
  501.     comint-get-old-input snarfs the sexp ending at point.
  502.     comint-input-sentinel does nothing.
  503.     comint-input-filter returns NIL if the input matches input-filter-regexp,
  504.         which matches (1) all whitespace (2) :a, :c, etc.
  505.  
  506. Similarly for Soar, Scheme, etc.."
  507.   (interactive)
  508.   ;; Note that the input string does not include its terminal newline.
  509.   (let ((proc (get-buffer-process (current-buffer))))
  510.     (if (not proc) (error "Current buffer has no process")
  511.     (let* ((pmark (process-mark proc))
  512.            (pmark-val (marker-position pmark))
  513.            (input (if (>= (point) pmark-val)
  514.               (buffer-substring pmark (point))
  515.               (let ((copy (funcall comint-get-old-input)))
  516.                 (goto-char pmark)
  517.                 (insert copy)
  518.                 copy))))
  519.       (insert ?\n)
  520.       (if (funcall comint-input-filter input) (ring-insert input-ring input))
  521.       (funcall comint-input-sentinel input)
  522.       (process-send-string proc input)
  523.       (process-send-string proc "\n")
  524.       (set-marker (process-mark proc) (point))
  525.       (set-marker comint-last-input-end (point))))))
  526.  
  527. (defun comint-get-old-input-default ()
  528.   "Default for comint-get-old-input: take the current line, and discard
  529. any initial text matching comint-prompt-regexp."
  530.   (save-excursion
  531.     (beginning-of-line)
  532.     (comint-skip-prompt)
  533.     (let ((beg (point)))
  534.       (end-of-line)
  535.       (buffer-substring beg (point)))))
  536.  
  537. (defun comint-skip-prompt ()
  538.   "Skip past the text matching regexp comint-prompt-regexp. 
  539. If this takes us past the end of the current line, don't skip at all."
  540.   (let ((eol (save-excursion (end-of-line) (point))))
  541.     (if (and (looking-at comint-prompt-regexp)
  542.          (<= (match-end 0) eol))
  543.     (goto-char (match-end 0)))))
  544.  
  545.  
  546. (defun comint-after-pmark-p ()
  547.   "Is point after the process output marker?"
  548.   ;; Since output could come into the buffer after we looked at the point
  549.   ;; but before we looked at the process marker's value, we explicitly 
  550.   ;; serialise. This is just because I don't know whether or not emacs
  551.   ;; services input during execution of lisp commands.
  552.   (let ((proc-pos (marker-position
  553.            (process-mark (get-buffer-process (current-buffer))))))
  554.     (<= proc-pos (point))))
  555.  
  556. (defun comint-bol (arg)
  557.   "Goes to the beginning of line, then skips past the prompt, if any.
  558. If a prefix argument is given (\\[universal-argument]), then no prompt skip 
  559. -- go straight to column 0.
  560.  
  561. The prompt skip is done by skipping text matching the regular expression
  562. comint-prompt-regexp, a buffer local variable.
  563.  
  564. If you don't like this command, reset c-a to beginning-of-line 
  565. in your hook, comint-mode-hook."
  566.   (interactive "P")
  567.   (beginning-of-line)
  568.   (if (null arg) (comint-skip-prompt)))
  569.  
  570. ;;; These two functions are for entering text you don't want echoed or
  571. ;;; saved -- typically passwords to ftp, telnet, or somesuch.
  572. ;;; Just enter m-x send-invisible and type in your line.
  573.  
  574. (defun comint-read-noecho (prompt)
  575.   "Prompt the user with argument PROMPT. Read a single line of text
  576. without echoing, and return it. Note that the keystrokes comprising
  577. the text can still be recovered (temporarily) with \\[view-lossage]. This
  578. may be a security bug for some applications."
  579.   (let ((echo-keystrokes 0)
  580.     (answ "")
  581.     tem)
  582.     (if (and (stringp prompt) (not (string= (message prompt) "")))
  583.     (message prompt))
  584.     (while (not(or  (= (setq tem (read-char)) ?\^m)
  585.             (= tem ?\n)))
  586.       (setq answ (concat answ (char-to-string tem))))
  587.     (message "")
  588.     answ))
  589.  
  590. (defun send-invisible (str)
  591.   "Read a string without echoing, and send it to the process running
  592. in the current buffer. A new-line is additionally sent. String is not 
  593. saved on comint input history list.
  594. Security bug: your string can still be temporarily recovered with
  595. \\[view-lossage]."
  596. ; (interactive (list (comint-read-noecho "Enter non-echoed text")))
  597.   (interactive "P") ; Defeat snooping via C-x esc
  598.   (let ((proc (get-buffer-process (current-buffer))))
  599.     (if (not proc) (error "Current buffer has no process")
  600.     (process-send-string proc
  601.                  (if (stringp str) str
  602.                  (comint-read-noecho "Enter non-echoed text")))
  603.     (process-send-string proc "\n"))))
  604.  
  605. ;;; Random input hackage
  606.  
  607. (defun comint-kill-output ()
  608.   "Kill all output from interpreter since last input."
  609.   (interactive)
  610.   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
  611.     (kill-region comint-last-input-end pmark)
  612.     (goto-char pmark)    
  613.     (insert "*** output flushed ***\n")
  614.     (set-marker pmark (point))))
  615.  
  616. (defun comint-show-output ()
  617.   "Display start of this batch of interpreter output at top of window.
  618. Also put cursor there."
  619.   (interactive)
  620.   (goto-char comint-last-input-end)
  621.   (backward-char)
  622.   (beginning-of-line)
  623.   (set-window-start (selected-window) (point))
  624.   (end-of-line))
  625.  
  626. (defun comint-interrupt-subjob ()
  627.   "Interrupt the current subjob."
  628.   (interactive)
  629.   (interrupt-process nil t))
  630.  
  631. (defun comint-kill-subjob ()
  632.   "Send kill signal to the current subjob."
  633.   (interactive)
  634.   (kill-process nil t))
  635.  
  636. (defun comint-quit-subjob ()
  637.   "Send quit signal to the current subjob."
  638.   (interactive)
  639.   (quit-process nil t))
  640.  
  641. (defun comint-stop-subjob ()
  642.   "Stop the current subjob.
  643. WARNING: if there is no current subjob, you can end up suspending
  644. the top-level process running in the buffer. If you accidentally do
  645. this, use \\[comint-continue-subjob] to resume the process. (This
  646. is not a problem with most shells, since they ignore this signal.)"
  647.   (interactive)
  648.   (stop-process nil t))
  649.  
  650. (defun comint-continue-subjob ()
  651.   "Send CONT signal to process buffer's process group.
  652. Useful if you accidentally suspend the top-level process."
  653.   (interactive)
  654.   (continue-process nil t))
  655.  
  656. (defun comint-kill-input ()
  657.   "Kill all text from last stuff output by interpreter to point."
  658.   (interactive)
  659.   (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
  660.      (p-pos (marker-position pmark)))
  661.     (if (> (point) p-pos)
  662.     (kill-region pmark (point)))))
  663.  
  664. (defun comint-delchar-or-maybe-eof (arg)
  665.   "Delete ARG characters forward, or send an EOF to lisp if at end of buffer."
  666.   (interactive "p")
  667.   (if (eobp)
  668.       (process-send-eof)
  669.       (delete-char arg)))
  670.  
  671.  
  672.  
  673.  
  674. ;;; Support for source-file processing commands.
  675. ;;;============================================================================
  676. ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
  677. ;;; commands that process files of source text (e.g. loading or compiling
  678. ;;; files). So the corresponding process-in-a-buffer modes have commands
  679. ;;; for doing this (e.g., lisp-load-file). The functions below are useful
  680. ;;; for defining these commands.
  681. ;;;
  682. ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
  683. ;;; and Soar, in that they don't know anything about file extensions.
  684. ;;; So the compile/load interface gets the wrong default occasionally.
  685. ;;; The load-file/compile-file default mechanism could be smarter -- it
  686. ;;; doesn't know about the relationship between filename extensions and
  687. ;;; whether the file is source or executable. If you compile foo.lisp
  688. ;;; with compile-file, then the next load-file should use foo.bin for
  689. ;;; the default, not foo.lisp. This is tricky to do right, particularly
  690. ;;; because the extension for executable files varies so much (.o, .bin,
  691. ;;; .lbin, .mo, .vo, .ao, ...).
  692.  
  693.  
  694. ;;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
  695. ;;; commands.
  696. ;;;
  697. ;;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
  698. ;;; want to save the buffer before issuing any process requests to the command
  699. ;;; interpreter.
  700. ;;;
  701. ;;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
  702. ;;; for the file to process.
  703.  
  704. ;;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
  705. ;;;============================================================================
  706. ;;; This function computes the defaults for the load-file and compile-file
  707. ;;; commands for tea, soar, cmulisp, and cmuscheme modes. 
  708. ;;; 
  709. ;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last 
  710. ;;; source-file processing command. NIL if there hasn't been one yet.
  711. ;;; - SOURCE-MODES is a list used to determine what buffers contain source
  712. ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
  713. ;;; Typically, (lisp-mode) or (scheme-mode).
  714. ;;; 
  715. ;;; If the command is given in a file buffer whose major modes is in
  716. ;;; SOURCE-MODES, then the the filename is the default file, and the
  717. ;;; file's directory is the default directory.
  718. ;;; 
  719. ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
  720. ;;; then the default directory & file are what was used in the last source-file
  721. ;;; processing command (i.e., PREVIOUS-DIR/FILE).  If this is the first time
  722. ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
  723. ;;; is the cwd, with no default file. (\"no default file\" = nil)
  724. ;;; 
  725. ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
  726. ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
  727. ;;; for Soar programs, etc.
  728. ;;; 
  729. ;;; The function returns a pair: (default-directory . default-file).
  730.  
  731. (defun comint-source-default (previous-dir/file source-modes)
  732.   (cond ((and buffer-file-name (memq major-mode source-modes))
  733.      (cons (file-name-directory    buffer-file-name)
  734.            (file-name-nondirectory buffer-file-name)))
  735.     (previous-dir/file)
  736.     (t
  737.      (cons default-directory nil))))
  738.  
  739.  
  740. ;;; (COMINT-CHECK-SOURCE fname)
  741. ;;;============================================================================
  742. ;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
  743. ;;; process-in-a-buffer modes), this function can be called on the filename.
  744. ;;; If the file is loaded into a buffer, and the buffer is modified, the user
  745. ;;; is queried to see if he wants to save the buffer before proceeding with
  746. ;;; the load or compile.
  747.  
  748. (defun comint-check-source (fname)
  749.   (let ((buff (get-file-buffer fname)))
  750.     (if (and buff
  751.          (buffer-modified-p buff)
  752.          (y-or-n-p (format "Save buffer %s first? "
  753.                    (buffer-name buff))))
  754.     ;; save BUFF.
  755.     (let ((old-buffer (current-buffer)))
  756.       (set-buffer buff)
  757.       (save-buffer)
  758.       (set-buffer old-buffer)))))
  759.  
  760.  
  761. ;;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
  762. ;;;============================================================================
  763. ;;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
  764. ;;; commands that process source files (like loading or compiling a file).
  765. ;;; It prompts for the filename, provides a default, if there is one,
  766. ;;; and returns the result filename.
  767. ;;; 
  768. ;;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
  769. ;;; 
  770. ;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
  771. ;;; from the last source processing command.  SOURCE-MODES is a list of major
  772. ;;; modes used to determine what file buffers contain source files.  (These
  773. ;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
  774. ;;; then the filename reader will only accept a file that exists.
  775. ;;; 
  776. ;;; A typical use:
  777. ;;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
  778. ;;;                                 "\\.lisp\\'" t))
  779.  
  780. (defun comint-get-source (prompt prev-dir/file source-regexp mustmatch-p)
  781.   (let* ((def (comint-source-default prev-dir/file source-regexp))
  782.      (defdir  (car def))
  783.      (deffile (cdr def))
  784.      (ans (read-file-name (if deffile (format "%s(default %s) "
  785.                           prompt    deffile)
  786.                   prompt)
  787.                   defdir
  788.                   (concat defdir deffile)
  789.                   mustmatch-p)))
  790.     (list (expand-file-name (substitute-in-file-name ans)))))
  791.  
  792.  
  793. ;;; Filename completion in a buffer
  794. ;;; ===========================================================================
  795. ;;; Useful completion functions, courtesy of the Ergo group.
  796. ;;; M-<Tab> will complete the filename at the cursor as much as possible
  797. ;;; M-? will display a list of completions in the help buffer.
  798.  
  799. ;;; Three commands:
  800. ;;; comint-dynamic-complete        Complete filename at point.
  801. ;;; comint-dynamic-list-completions    List completions in help buffer.
  802. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  803. ;;;                    replace with expanded/completed name.
  804.  
  805. ;;; These are not installed in the comint-mode keymap. But they are
  806. ;;; available for people who want them. Shell-mode installs them:
  807. ;;; (define-key cmushell-mode-map "\M-\t" 'comint-dynamic-complete)
  808. ;;; (define-key cmushell-mode-map "\M-?"  'comint-dynamic-list-completions)))
  809. ;;;
  810. ;;; Commands like this are fine things to put in load hooks if you
  811. ;;; want them present in specific modes. Example:
  812. ;;; (setq cmushell-load-hook
  813. ;;;       '((lambda () (define-key lisp-mode-map "\M-\t"
  814. ;;;                   'comint-replace-by-expanded-filename))))
  815. ;;;          
  816.  
  817.  
  818. (defun comint-match-partial-pathname ()
  819.   "Returns the string of an existing filename or causes and error."
  820.   (if (save-excursion (backward-char 1) (looking-at "\\s ")) ""
  821.       (save-excursion
  822.     (re-search-backward "[^~/A-Za-z0-9---_.$#,]+")
  823.     (re-search-forward "[~/A-Za-z0-9---_.$#,]+")
  824.     (substitute-in-file-name 
  825.       (buffer-substring (match-beginning 0) (match-end 0))))))
  826.  
  827. (defun comint-replace-by-expanded-filename ()
  828.   "Replace filename at point with expanded, completed name"
  829.   (interactive)
  830.   (let* ((pathname (comint-match-partial-pathname))
  831.      (pathdir (file-name-directory pathname))
  832.      (pathnondir (file-name-nondirectory pathname))
  833.      (completion (file-name-completion  pathnondir
  834.                        (or pathdir default-directory))))
  835.     (cond ((null completion)
  836.        (message "No completions of %s." pathname)
  837.        (ding))
  838.       ((eql completion t)
  839.        (message "Unique completion."))
  840.       (t                ; this means a string was returned.
  841.        (delete-region (match-beginning 0) (match-end 0))
  842.        (insert pathdir completion)))))
  843.  
  844. (defun comint-dynamic-complete ()
  845.   "Dynamically complete the filename at point."
  846.   (interactive)
  847.   (let* ((pathname (comint-match-partial-pathname))
  848.      (pathdir (file-name-directory pathname))
  849.      (pathnondir (file-name-nondirectory pathname))
  850.      (completion (file-name-completion  pathnondir
  851.                        (or pathdir default-directory))))
  852.     (cond ((null completion)
  853.        (message "No completions of %s." pathname)
  854.        (ding))
  855.       ((eql completion t)
  856.        (message "Unique completion."))
  857.       (t                ; this means a string was returned.
  858.        (insert (substring completion (length pathnondir)))))))
  859.  
  860. (defun comint-dynamic-list-completions ()
  861.   "List in help buffer all possible completions of the filename at point."
  862.   (interactive)
  863.   (let* ((pathname (comint-match-partial-pathname))
  864.      (pathdir (file-name-directory pathname))
  865.      (pathnondir (file-name-nondirectory pathname))
  866.      (completions
  867.       (file-name-all-completions pathnondir
  868.                      (or pathdir default-directory))))
  869.     (cond ((null completions)
  870.        (message "No completions of %s." pathname)
  871.        (ding))
  872.       (t (with-output-to-temp-buffer "*Help*"
  873.            (display-completion-list completions))))))
  874.  
  875. ; Ergo bindings
  876. ; (global-set-key "\M-\t" 'comint-replace-by-expanded-filename)
  877. ; (global-set-key "\M-?" 'comint-dynamic-list-completions)
  878. ; (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
  879.  
  880. ;;; Log the user, so I know who's using the package during the beta test 
  881. ;;; period. This just inserts the user's name and current time into a 
  882. ;;; central file.
  883. ;;(defun comint-log-user ()
  884. ;;  (interactive)
  885. ;;  (if (file-writable-p "/afs/cs/user/shivers/lib/emacs/logdir/comint.log")
  886. ;;      (let ((u (getenv "USER"))
  887. ;;        (old-buff (current-buffer)))
  888. ;;    (message "logging user in beta test database...")
  889. ;;    (find-file "/afs/cs/user/shivers/lib/emacs/logdir/comint.log")
  890. ;;    (cond ((search-forward u nil 'to-end)
  891. ;;           (search-forward "| ")
  892. ;;           (kill-line 1))
  893. ;;          (t (insert (format "%s\t%s\t| " u (current-time-string)))))
  894. ;;    (insert (format "%s\n" (current-time-string)))
  895. ;;    (let ((make-backup-files nil)) (save-buffer))
  896. ;;    (kill-buffer (current-buffer))
  897. ;;    (set-buffer old-buff))))
  898. ;;(comint-log-user)
  899.  
  900.  
  901. ;;; Converting process modes to use comint mode
  902. ;;; ===========================================================================
  903. ;;; Several gnu packages (tex-mode, background, dbx, gdb, kermit, prolog, 
  904. ;;; telnet are some) use the shell package as clients. Most of them would
  905. ;;; be better off using the comint package, but they predate it. 
  906. ;;;
  907. ;;; Altering these packages to use comint mode should greatly
  908. ;;; improve their functionality, and is fairly easy.
  909. ;;; 
  910. ;;; Renaming variables
  911. ;;; Most of the work is renaming variables and functions. These are the common
  912. ;;; ones:
  913. ;;; Local variables:
  914. ;;;     last-input-end        comint-last-input-end
  915. ;;;    last-input-start    <unnecessary>
  916. ;;;    shell-prompt-pattern    comint-prompt-regexp
  917. ;;;     shell-set-directory-error-hook <no equivalent>
  918. ;;; Miscellaneous:
  919. ;;;    shell-set-directory    <unnecessary>
  920. ;;;     shell-mode-map        comint-mode-map
  921. ;;; Commands:
  922. ;;;    shell-send-input    comint-send-input
  923. ;;;    shell-send-eof        comint-delchar-or-maybe-eof
  924. ;;;     kill-shell-input    comint-kill-input
  925. ;;;    interrupt-shell-subjob    comint-interrupt-subjob
  926. ;;;    stop-shell-subjob    comint-stop-subjob
  927. ;;;    quit-shell-subjob    comint-quit-subjob
  928. ;;;    kill-shell-subjob    comint-kill-subjob
  929. ;;;    kill-output-from-shell    comint-kill-output
  930. ;;;    show-output-from-shell    comint-show-output
  931. ;;;    copy-last-shell-input    Use comint-previous-input/comint-next-input
  932. ;;;
  933. ;;; LAST-INPUT-START is no longer necessary because inputs are stored on the
  934. ;;; input history ring. SHELL-SET-DIRECTORY is gone, its functionality taken
  935. ;;; over by SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-sentinel.
  936. ;;; Comint mode does not provide functionality equivalent to 
  937. ;;; shell-set-directory-error-hook; it is gone.
  938. ;;; 
  939. ;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
  940. ;;; *not* create the comint-mode local variables in your foo-mode function.
  941. ;;; This is not modular.  Instead, call comint-mode, and let *it* create the
  942. ;;; necessary comint-specific local variables. Then create the
  943. ;;; foo-mode-specific local variables in foo-mode.  Set the buffer's keymap to
  944. ;;; be foo-mode-map, and it's mode to be foo-mode.  Set the comint-mode hooks
  945. ;;; (comint-prompt-regexp, comint-input-filter, comint-input-sentinel,
  946. ;;; comint-get-old-input) that need to be different from the defaults.  Call
  947. ;;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
  948. ;;; comint-mode will take care of it. The following example, from cmushell.el,
  949. ;;; is typical:
  950. ;;; 
  951. ;;; (defun shell-mode ()
  952. ;;;   (interactive)
  953. ;;;   (comint-mode)
  954. ;;;   (setq comint-prompt-regexp shell-prompt-pattern)
  955. ;;;   (setq major-mode 'shell-mode)
  956. ;;;   (setq mode-name "Shell")
  957. ;;;   (cond ((not shell-mode-map)
  958. ;;;          (setq shell-mode-map (full-copy-sparse-keymap comint-mode-map))
  959. ;;;          (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
  960. ;;;          (define-key shell-mode-map "\M-?"
  961. ;;;                      'comint-dynamic-list-completions)))
  962. ;;;   (use-local-map shell-mode-map)
  963. ;;;   (make-local-variable 'shell-directory-stack)
  964. ;;;   (setq shell-directory-stack nil)
  965. ;;;   (setq comint-input-sentinel 'shell-directory-tracker)
  966. ;;;   (run-hooks 'shell-mode-hook))
  967. ;;;
  968. ;;;
  969. ;;; Note that make-comint is different from make-shell in that it
  970. ;;; doesn't have a default program argument. If you give make-shell
  971. ;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
  972. ;;; $ESHELL, $SHELL, or /bin/sh. If you give make-comint a program argument
  973. ;;; of NIL, it barfs. Adjust your code accordingly...
  974. ;;;
  975.  
  976. ;;; Do the user's customisation...
  977.  
  978. (defvar comint-load-hook nil
  979.   "This hook is run when comint is loaded in.
  980. This is a good place to put keybindings.")
  981.     
  982. (run-hooks 'comint-load-hook)
  983.