Initial Commit
[packages] / xemacs-packages / eterm / term.el
1 ;;; term.el --- general command interpreter in a window stuff
2
3 ;; Copyright (C) 1988-1995, 1997 Free Software Foundation, Inc.
4
5 ;; Author: Per Bothner <bothner@cygnus.com>
6 ;; Based on comint mode written by: Olin Shivers <shivers@cs.cmu.edu>
7 ;; Extended by Attila Fülöp <atf@loa.neuro.biologie.fu-berlin.de> 
8 ;;   <attilaf@zedat.fu-berlin.de> to support ANSI colors (c) 1998 ~~~
9 ;; Keyword: processes
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;; The changelog is at the end of this file.
31
32 ;; Please send me bug reports, bug fixes, and extensions, so that I can
33 ;; merge them into the master source.
34 ;;     - Per Bothner (bothner@cygnus.com)
35
36 ;; This file defines a general command-interpreter-in-a-buffer package
37 ;; (term mode). The idea is that you can build specific process-in-a-buffer
38 ;; modes on top of term mode -- e.g., lisp, shell, scheme, T, soar, ....
39 ;; This way, all these specific packages share a common base functionality, 
40 ;; and a common set of bindings, which makes them easier to use (and
41 ;; saves code, implementation time, etc., etc.).
42
43 ;; For hints on converting existing process modes (e.g., tex-mode,
44 ;; background, dbx, gdb, kermit, prolog, telnet) to use term-mode
45 ;; instead of shell-mode, see the notes at the end of this file.
46
47 \f
48 ;; Brief Command Documentation:
49 ;;============================================================================
50 ;; Term Mode Commands: (common to all derived modes, like cmushell & cmulisp
51 ;; mode)
52 ;;
53 ;; m-p      term-previous-input           Cycle backwards in input history
54 ;; m-n      term-next-input               Cycle forwards
55 ;; m-r     term-previous-matching-input  Previous input matching a regexp
56 ;; m-s     comint-next-matching-input      Next input that matches
57 ;; return  term-send-input
58 ;; c-c c-a term-bol                      Beginning of line; skip prompt.
59 ;; c-d      term-delchar-or-maybe-eof     Delete char unless at end of buff.
60 ;; c-c c-u term-kill-input                  ^u
61 ;; c-c c-w backward-kill-word               ^w
62 ;; c-c c-c term-interrupt-subjob            ^c
63 ;; c-c c-z term-stop-subjob                 ^z
64 ;; c-c c-\ term-quit-subjob                 ^\
65 ;; c-c c-o term-kill-output                 Delete last batch of process output
66 ;; c-c c-r term-show-output                 Show last batch of process output
67 ;; c-c c-h term-dynamic-list-input-ring  List input history
68 ;;
69 ;; Not bound by default in term-mode
70 ;; term-send-invisible                  Read a line w/o echo, and send to proc
71 ;; (These are bound in shell-mode)
72 ;; term-dynamic-complete                Complete filename at point.
73 ;; term-dynamic-list-completions        List completions in help buffer.
74 ;; term-replace-by-expanded-filename    Expand and complete filename at point;
75 ;;                                      replace with expanded/completed name.
76 ;; term-kill-subjob                     No mercy.
77 ;; term-show-maximum-output            Show as much output as possible.
78 ;; term-continue-subjob         Send CONT signal to buffer's process
79 ;;                                      group. Useful if you accidentally
80 ;;                                      suspend your process (with C-c C-z).
81
82 ;; term-mode-hook is the term mode hook. Basically for your keybindings.
83 ;; term-load-hook is run after loading in this package.
84
85 ;; Code:
86
87 ;; This is passed to the inferior in the EMACS environment variable,
88 ;; so it is important to increase it if there are protocol-relevant changes.
89 (defconst term-protocol-version "0.95")
90
91 (require 'ring)
92 (require 'ehelp)
93
94 (if (fboundp 'defgroup) nil
95   (defmacro defgroup (&rest forms) nil)
96   (defmacro defcustom (name init doc &rest forms)
97     (list 'defvar name init doc)))
98
99 (defgroup term nil
100   "General command interpreter in a window"
101   :group 'processes
102   :group 'unix)
103
104 \f
105 ;;; Buffer Local Variables:
106 ;;;============================================================================
107 ;;; Term mode buffer local variables:
108 ;;;     term-prompt-regexp    - string       term-bol uses to match prompt.
109 ;;;     term-delimiter-argument-list - list  For delimiters and arguments
110 ;;;     term-last-input-start - marker       Handy if inferior always echoes
111 ;;;     term-last-input-end   - marker       For term-kill-output command
112 ;; For the input history mechanism:
113 (defvar term-input-ring-size 32 "Size of input history ring.")
114 ;;;     term-input-ring-size  - integer
115 ;;;     term-input-ring       - ring
116 ;;;     term-input-ring-index - number           ...
117 ;;;     term-input-autoexpand - symbol           ...
118 ;;;     term-input-ignoredups - boolean          ...
119 ;;;     term-last-input-match - string           ...
120 ;;;     term-dynamic-complete-functions - hook   For the completion mechanism
121 ;;;     term-completion-fignore - list           ...
122 ;;;     term-get-old-input    - function     Hooks for specific 
123 ;;;     term-input-filter-functions - hook     process-in-a-buffer
124 ;;;     term-input-filter     - function         modes.
125 ;;;     term-input-send - function
126 ;;;     term-scroll-to-bottom-on-output - symbol ...
127 ;;;     term-scroll-show-maximum-output - boolean...
128 (defvar term-height) ;; Number of lines in window.
129 (defvar term-width) ;; Number of columns in window.
130 (defvar term-home-marker) ;; Marks the "home" position for cursor addressing.
131 (defvar term-saved-home-marker nil) ;; When using alternate sub-buffer,
132 ;;              contains saved term-home-marker from original sub-buffer .
133 (defvar term-start-line-column 0) ;; (current-column) at start of screen line,
134 ;;              or nil if unknown.
135 (defvar term-current-column 0) ;; If non-nil, is cache for (current-column).
136 (defvar term-current-row 0) ;; Current vertical row (relative to home-marker)
137 ;;              or nil if unknown.
138 (defvar term-insert-mode nil)
139 (defvar term-vertical-motion)
140 (defvar term-terminal-state 0) ;; State of the terminal emulator:
141 ;;              state 0: Normal state
142 ;;              state 1: Last character was a graphic in the last column.
143 ;;              If next char is graphic, first move one column right
144 ;;              (and line warp) before displaying it.
145 ;;              This emulates (more or less) the behavior of xterm.
146 ;;              state 2: seen ESC
147 ;;              state 3: seen ESC [ (or ESC [ ?)
148 ;;              state 4: term-terminal-parameter contains pending output.
149 (defvar term-kill-echo-list nil) ;; A queue of strings whose echo
150 ;;              we want suppressed.
151 (defvar term-terminal-parameter)
152 (defvar term-terminal-previous-parameter)
153 (defvar term-current-face 'term-default-face)
154 ;; need to keep track of atrributes and back/foreground colors for ansi color sup. ~~~
155 (defvar term-terminal-previous-previous-parameter)
156 (defvar term-current-fi 0)
157 (defvar term-current-fg 0)
158 (defvar term-current-bg 7)
159 (defvar term-fg)
160 (defvar term-bg)
161 (defvar term-attr)
162 (defvar term-fi)
163 (defvar term-tcf)
164 (defvar term-fnts)
165 (defvar tps)
166 (defvar ttp)
167 (defvar iii) 
168  ;; ~~~
169
170 (defvar term-scroll-start 0) ;; Top-most line (inclusive) of scrolling region.
171 (defvar term-scroll-end) ;; Number of line (zero-based) after scrolling region.
172 (defvar term-pager-count nil) ;; If nil, paging is disabled.
173 ;;              Otherwise, number of lines before we need to page.
174 (defvar term-saved-cursor nil)
175 (defvar term-command-hook)
176 (defvar term-log-buffer nil)
177 (defvar term-scroll-with-delete nil) ;; term-scroll-with-delete is t if
178 ;;              forward scrolling should be implemented by delete to
179 ;;              top-most line(s); and nil if scrolling should be implemented
180 ;;              by moving term-home-marker.  It is set to t iff there is a
181 ;;              (non-default) scroll-region OR the alternate buffer is used.
182 (defvar term-pending-delete-marker) ;; New user input in line mode needs to
183 ;;              be deleted, because it gets echoed by the inferior.
184 ;;              To reduce flicker, we defer the delete until the next output.
185 (defvar term-old-mode-map nil) ;; Saves the old keymap when in char mode.
186 (defvar term-old-mode-line-format) ;; Saves old mode-line-format while paging.
187 (defvar term-pager-old-local-map nil) ;; Saves old keymap while paging.
188 (defvar term-pager-old-filter) ;; Saved process-filter while paging.
189
190 (defcustom explicit-shell-file-name nil
191   "*If non-nil, is file name to use for explicitly requested inferior shell."
192   :type '(choice (const nil) file)
193   :group 'term)
194
195 (defvar term-prompt-regexp "^"
196   "Regexp to recognise prompts in the inferior process.
197 Defaults to \"^\", the null string at BOL.
198
199 Good choices:
200   Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
201   Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
202   franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
203   kcl: \"^>+ *\"
204   shell: \"^[^#$%>\\n]*[#$%>] *\"
205   T: \"^>+ *\"
206
207 This is a good thing to set in mode hooks.")
208
209 (defvar term-delimiter-argument-list ()
210   "List of characters to recognise as separate arguments in input.
211 Strings comprising a character in this list will separate the arguments
212 surrounding them, and also be regarded as arguments in their own right (unlike
213 whitespace).  See `term-arguments'.
214 Defaults to the empty list.
215
216 For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?;).
217
218 This is a good thing to set in mode hooks.")
219
220 (defcustom term-input-autoexpand nil
221   "*If non-nil, expand input command history references on completion.
222 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
223
224 If the value is `input', then the expansion is seen on input.
225 If the value is `history', then the expansion is only when inserting
226 into the buffer's input ring.  See also `term-magic-space' and
227 `term-dynamic-complete'.
228
229 This variable is buffer-local."
230   :type '(choice (const nil) (const t) (const input) (const history))
231   :group 'term)
232
233 (defcustom term-input-ignoredups nil
234   "*If non-nil, don't add input matching the last on the input ring.
235 This mirrors the optional behavior of bash.
236
237 This variable is buffer-local."
238   :type 'boolean
239   :group 'term)
240
241 (defcustom term-input-ring-file-name nil
242   "*If non-nil, name of the file to read/write input history.
243 See also `term-read-input-ring' and `term-write-input-ring'.
244
245 This variable is buffer-local, and is a good thing to set in mode hooks."
246   :type 'boolean
247   :group 'term)
248
249 (defcustom term-scroll-to-bottom-on-output nil
250   "*Controls whether interpreter output causes window to scroll.
251 If nil, then do not scroll.  If t or `all', scroll all windows showing buffer.
252 If `this', scroll only the selected window.
253 If `others', scroll only those that are not the selected window.
254
255 The default is nil.
256
257 See variable `term-scroll-show-maximum-output'. This variable is buffer-local."
258   :type '(choice (const :tag "off" nil)
259                  (const t)
260                  (const all)
261                  (const this)
262                  (const others))
263   :group 'term)
264
265 (defcustom term-scroll-show-maximum-output nil
266   "*Controls how interpreter output causes window to scroll.
267 If non-nil, then show the maximum output when the window is scrolled.
268
269 See variable `term-scroll-to-bottom-on-output'.
270 This variable is buffer-local."
271   :type 'boolean
272   :group 'term)
273
274 ;; Where gud-display-frame should put the debugging arrow.  This is
275 ;; set by the marker-filter, which scans the debugger's output for
276 ;; indications of the current pc.
277 (defvar term-pending-frame nil)
278
279 ;;; Here are the per-interpreter hooks.
280 (defvar term-get-old-input (function term-get-old-input-default)
281   "Function that submits old text in term mode.
282 This function is called when return is typed while the point is in old text.
283 It returns the text to be submitted as process input.  The default is
284 term-get-old-input-default, which grabs the current line, and strips off
285 leading text matching term-prompt-regexp")
286
287 (defvar term-dynamic-complete-functions
288   '(term-replace-by-expanded-history term-dynamic-complete-filename)
289   "List of functions called to perform completion.
290 Functions should return non-nil if completion was performed.
291 See also `term-dynamic-complete'.
292
293 This is a good thing to set in mode hooks.")
294
295 (defvar term-input-filter
296   (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
297   "Predicate for filtering additions to input history.
298 Only inputs answering true to this function are saved on the input
299 history list. Default is to save anything that isn't all whitespace")
300
301 (defvar term-input-filter-functions '()
302   "Functions to call before input is sent to the process.
303 These functions get one argument, a string containing the text to send.
304
305 This variable is buffer-local.")
306
307 (defvar term-input-sender (function term-simple-send)
308   "Function to actually send to PROCESS the STRING submitted by user.
309 Usually this is just 'term-simple-send, but if your mode needs to 
310 massage the input string, this is your hook. This is called from
311 the user command term-send-input. term-simple-send just sends
312 the string plus a newline.")
313
314 (defcustom term-eol-on-send t
315   "*Non-nil means go to the end of the line before sending input.
316 See `term-send-input'."
317   :type 'boolean
318   :group 'term)
319
320 (defcustom term-mode-hook '()
321   "Called upon entry into term-mode
322 This is run before the process is cranked up."
323   :type 'hook
324   :group 'term)
325
326 (defcustom term-exec-hook '()
327   "Called each time a process is exec'd by term-exec.
328 This is called after the process is cranked up.  It is useful for things that
329 must be done each time a process is executed in a term-mode buffer (e.g.,
330 \(process-kill-without-query)).  In contrast, the term-mode-hook is only
331 executed once when the buffer is created."
332   :type 'hook
333   :group 'term)
334
335 (defcustom term-delete-string "\C-?"
336   "String to send when Delete is pressed."
337   :type 'string
338   :group 'term)
339
340 (defcustom term-backspace-string "\C-H"
341   "String to send when BackSpace is pressed."
342   :type 'string
343   :group 'term)
344
345 (defvar term-mode-map nil)
346 (defvar term-raw-map nil
347   "Keyboard map for sending characters directly to the inferior process.")
348 (defvar term-escape-char nil
349   "Escape character for char-sub-mode of term mode.
350 Do not change it directly;  use term-set-escape-char instead.")
351 (defvar term-raw-escape-map nil)
352
353 (defvar term-pager-break-map nil)
354
355 (defvar term-ptyp t
356   "True if communications via pty; false if by pipe.  Buffer local.
357 This is to work around a bug in emacs process signaling.")
358
359 (defvar term-last-input-match ""
360   "Last string searched for by term input history search, for defaulting.
361 Buffer local variable.") 
362
363 (defvar term-input-ring nil)
364 (defvar term-last-input-start)
365 (defvar term-last-input-end)
366 (defvar term-input-ring-index nil
367   "Index of last matched history element.")
368 (defvar term-matching-input-from-input-string ""
369   "Input previously used to match input history.")
370 ; This argument to set-process-filter disables reading from the process,
371 ; assuming this is emacs-19.20 or newer.
372 (defvar term-pager-filter t)
373
374 (put 'term-replace-by-expanded-history 'menu-enable 'term-input-autoexpand)
375 (put 'term-input-ring 'permanent-local t)
376 (put 'term-input-ring-index 'permanent-local t)
377 (put 'term-input-autoexpand 'permanent-local t)
378 (put 'term-input-filter-functions 'permanent-local t)
379 (put 'term-scroll-to-bottom-on-output 'permanent-local t)
380 (put 'term-scroll-show-maximum-output 'permanent-local t)
381 (put 'term-ptyp 'permanent-local t)
382
383 ;; Do FORMS if running under Emacs-19.
384 (defmacro term-if-emacs19 (&rest forms)
385   (if (string-match "^19" emacs-version) (cons 'progn forms)))
386 ;; True if running under XEmacs (previously Lucid emacs).
387 (defmacro term-is-xemacs ()  '(string-match "XEmacs" emacs-version))
388 ;; Do FORM if running under XEmacs (previously Lucid emacs).
389 (defmacro term-if-xemacs (&rest forms)
390   (if (term-is-xemacs) (cons 'progn forms)))
391 ;; Do FORM if NOT running under XEmacs (previously Lucid emacs).
392 (defmacro term-ifnot-xemacs (&rest forms)
393   (if (not (term-is-xemacs)) (cons 'progn forms)))
394
395 (defmacro term-in-char-mode () '(eq (current-local-map) term-raw-map))
396 (defmacro term-in-line-mode () '(not (term-in-char-mode)))
397 ;; True if currently doing PAGER handling.
398 (defmacro term-pager-enabled () 'term-pager-count)
399 (defmacro term-handling-pager () 'term-pager-old-local-map)
400 (defmacro term-using-alternate-sub-buffer () 'term-saved-home-marker)
401
402 (defvar term-signals-menu)
403 (defvar term-terminal-menu)
404
405 (term-if-xemacs
406  (defvar term-terminal-menu
407    '("Terminal"
408      [ "Character mode" term-char-mode (term-in-line-mode)]
409      [ "Line mode" term-line-mode (term-in-char-mode)]
410      [ "Enable paging" term-pager-toggle (not term-pager-count)]
411      [ "Disable paging" term-pager-toggle term-pager-count])))
412
413 (defun term-mode ()
414   "Major mode for interacting with an inferior interpreter.
415 Interpreter name is same as buffer name, sans the asterisks.
416 In line sub-mode, return at end of buffer sends line as input,
417 while return not at end copies rest of line to end and sends it.
418 In char sub-mode, each character (except `term-escape-char`) is
419 set immediately.
420
421 This mode is typically customised to create inferior-lisp-mode,
422 shell-mode, etc.. This can be done by setting the hooks
423 term-input-filter-functions, term-input-filter, term-input-sender and
424 term-get-old-input to appropriate functions, and the variable
425 term-prompt-regexp to the appropriate regular expression.
426
427 An input history is maintained of size `term-input-ring-size', and
428 can be accessed with the commands \\[term-next-input], \\[term-previous-input], and \\[term-dynamic-list-input-ring].
429 Input ring history expansion can be achieved with the commands
430 \\[term-replace-by-expanded-history] or \\[term-magic-space].
431 Input ring expansion is controlled by the variable `term-input-autoexpand',
432 and addition is controlled by the variable `term-input-ignoredups'.
433
434 Input to, and output from, the subprocess can cause the window to scroll to
435 the end of the buffer.  See variables `term-scroll-to-bottom-on-input',
436 and `term-scroll-to-bottom-on-output'.
437
438 If you accidentally suspend your process, use \\[term-continue-subjob]
439 to continue it.
440
441 \\{term-mode-map}
442
443 Entry to this mode runs the hooks on term-mode-hook"
444   (interactive)
445     ;; Do not remove this.  All major modes must do this.
446     (kill-all-local-variables)
447     (setq major-mode 'term-mode)
448     (setq mode-name "Term")
449     (use-local-map term-mode-map)
450     (make-local-variable 'term-home-marker)
451     (setq term-home-marker (copy-marker 0))
452     (make-local-variable 'term-saved-home-marker)
453     (make-local-variable 'term-height)
454     (make-local-variable 'term-width)
455     (setq term-width (1- (window-width)))
456     (setq term-height (1- (window-displayed-height)))
457     (make-local-variable 'term-terminal-parameter)
458     (make-local-variable 'term-saved-cursor)
459     (make-local-variable 'term-last-input-start)
460     (setq term-last-input-start (make-marker))
461     (make-local-variable 'term-last-input-end)
462     (setq term-last-input-end (make-marker))
463     (make-local-variable 'term-last-input-match)
464     (setq term-last-input-match "")
465     (make-local-variable 'term-prompt-regexp)        ; Don't set; default
466     (make-local-variable 'term-input-ring-size)      ; ...to global val.
467     (make-local-variable 'term-input-ring)
468     (make-local-variable 'term-input-ring-file-name)
469     (or (and (boundp 'term-input-ring) term-input-ring)
470         (setq term-input-ring (make-ring term-input-ring-size)))
471     (make-local-variable 'term-input-ring-index)
472     (or (and (boundp 'term-input-ring-index) term-input-ring-index)
473         (setq term-input-ring-index nil))
474
475     (make-local-variable 'term-command-hook)
476     (setq term-command-hook (symbol-function 'term-command-hook))
477
478     (make-local-variable 'term-terminal-state)
479     (make-local-variable 'term-kill-echo-list)
480     (make-local-variable 'term-start-line-column)
481     (make-local-variable 'term-current-column)
482     (make-local-variable 'term-current-row)
483     (make-local-variable 'term-log-buffer)
484     (make-local-variable 'term-scroll-start)
485     (make-local-variable 'term-scroll-end)
486     (setq term-scroll-end term-height)
487     (make-local-variable 'term-scroll-with-delete)
488     (make-local-variable 'term-pager-count)
489     (make-local-variable 'term-pager-old-local-map)
490     (make-local-variable 'term-old-mode-map)
491     (make-local-variable 'term-insert-mode)
492     (make-local-variable 'term-dynamic-complete-functions)
493     (make-local-variable 'term-completion-fignore)
494     (make-local-variable 'term-get-old-input)
495     (make-local-variable 'term-matching-input-from-input-string)
496     (make-local-variable 'term-input-autoexpand)
497     (make-local-variable 'term-input-ignoredups)
498     (make-local-variable 'term-delimiter-argument-list)
499     (make-local-variable 'term-input-filter-functions)
500     (make-local-variable 'term-input-filter)  
501     (make-local-variable 'term-input-sender)
502     (make-local-variable 'term-eol-on-send)
503     (make-local-variable 'term-scroll-to-bottom-on-output)
504     (make-local-variable 'term-scroll-show-maximum-output)
505     (make-local-variable 'term-ptyp)
506     (make-local-variable 'term-exec-hook)
507     (make-local-variable 'term-vertical-motion)
508     (make-local-variable 'term-pending-delete-marker)
509     (setq term-pending-delete-marker (make-marker))
510     (make-local-variable 'term-current-face)
511     (make-local-variable 'term-current-bg) ;; ~~~
512     (make-local-variable 'term-current-fg) ;; ~~~
513     (make-local-variable 'term-current-fi) ;; ~~~
514     (make-local-variable 'term-tcf) ;; array of color faces ~~~
515     ;; (make-local-variable 'termfnts) -- nop global
516
517     (make-local-variable 'term-pending-frame)
518
519     (setq term-pending-frame nil)
520     (run-hooks 'term-mode-hook)
521     (term-if-xemacs
522      (if (fboundp 'add-submenu)
523          (progn
524            (set (make-local-variable 'current-menubar)
525                 (copy-sequence current-menubar))
526            (add-submenu nil term-terminal-menu))))
527     (or term-input-ring
528         (setq term-input-ring (make-ring term-input-ring-size)))
529     (term-update-mode-line))
530
531
532   ;; ~~~ ansi color stuff: we use a  font for each color and attr (normal bold ul inverted)
533   ;; since this makes up to 8*8*4 = 256 fonts we allocate the fonts uppon first request.
534   ;; see below for more comment
535
536   ;; make faces if they dont exis
537   (cond ((eq (find-face 'red) nil)
538          (make-face 'red)
539          (set-face-foreground 'red "red")))
540   (cond ((eq (find-face 'green) nil)
541          (make-face 'green)
542          (set-face-foreground 'green "green")))
543   (cond ((eq (find-face 'yellow) nil)
544          (make-face 'yellow)
545          (set-face-foreground 'yellow "yellow")))
546   (cond ((eq (find-face 'blue) nil)
547          (make-face 'blue)
548          (set-face-foreground 'blue "blue")))
549   (cond ((eq (find-face 'magenta) nil)
550          (make-face 'magenta )
551          (set-face-foreground 'magenta "magenta")))
552   (cond ((eq (find-face 'cyan) nil)
553          (make-face 'cyan)
554          (set-face-foreground 'cyan "cyan")))
555   (cond ((eq (find-face 'white) nil)
556          (make-face 'white )
557          (set-face-foreground 'white "white")))
558
559   ;; use this fonts to tweak the appearance of the ansi colors the term shows
560   ;; the names are quite intuitive
561   (setq term-tcf [default red green yellow blue magenta cyan white])
562   (setq term-fnts [ ;; normal
563         term-default-face term-red-face term-green-face term-yellow-face 
564         term-blue-face term-magenta-face term-cyan-face term-white-face
565         ;; bold
566         term-default-bold-face term-red-bold-face term-green-bold-face term-yellow-bold-face 
567         term-blue-bold-face term-magenta-bold-face term-cyan-bold-face term-white-bold-face
568         ;; underlined
569         term-default-ul-face term-red-ul-face term-green-ul-face term-yellow-ul-face 
570         term-blue-ul-face term-magenta-ul-face term-cyan-ul-face term-white-ul-face
571         ;; inverted
572         term-default-inv-face term-red-inv-face term-green-inv-face term-yellow-inv-face 
573         term-blue-inv-face term-magenta-inv-face term-cyan-inv-face term-white-inv-face
574         ])
575
576
577   ;; fixme how to set background pixmap/color, foreground of whole frame/window ?
578   (setq term-do-invert nil)
579   ;; (setq term-font "vga")
580
581   (setq fi 0)
582   (while (< fi 8)
583     (cond ((eq (find-face (aref term-fnts fi)) nil)
584            (copy-face (aref term-tcf fi) (aref term-fnts fi))))
585     (cond ((and (eq 0 fi) term-do-invert)
586            (invert-face 'term-default-face)
587            ))
588     (cond ((boundp 'term-font)
589            (set-face-font (aref term-fnts fi) term-font)
590            ))
591     (cond ((eq (find-face (aref term-fnts (+ fi 8))) nil)
592            (copy-face (aref term-fnts fi) (aref term-fnts (+ fi 8)))
593            (set-face-parent (aref term-fnts (+ fi 8)) (aref term-fnts fi)) 
594            (make-face-bold (aref term-fnts (+ fi 8)))
595            ))
596     (cond ((eq (find-face (aref term-fnts (+ fi 16))) nil)
597            (copy-face (aref term-fnts fi) (aref term-fnts (+ fi 16)))
598            (set-face-parent (aref term-fnts (+ fi 16)) (aref term-fnts fi)) 
599            (set-face-underline-p (aref term-fnts (+ fi 16)) t)
600            ))
601     (cond ((eq (find-face (aref term-fnts (+ fi 24))) nil)
602            (copy-face (aref term-fnts fi) (aref term-fnts (+ fi 24)))
603            ;; (set-face-parent (aref term-fnts (+ fi 24)) (aref term-fnts fi)) 
604            (invert-face (aref term-fnts (+ fi 24)))
605            ))
606     (setq fi (1+ fi))
607     )
608   (set-face-background 'term-white-inv-face (face-background 'term-default-face))
609   (set-face-background-pixmap 'term-white-inv-face (make-image-instance [nothing]))
610
611  (setq term-fnts-tmp-faces [
612         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
613         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
614         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
615         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
616         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
617         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
618         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
619         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
620         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
621         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
622         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
623         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
624         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
625         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
626         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
627         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
628         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
629         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
630         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
631         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
632         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
633         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
634         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
635         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
636         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
637         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil 
638         nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil
639         ])
640
641 ;; ~~~ end ansi color stuff 
642
643
644
645
646
647 (if term-mode-map
648     nil
649   (setq term-mode-map (make-sparse-keymap))
650   (define-key term-mode-map "\ep" 'term-previous-input)
651   (define-key term-mode-map "\en" 'term-next-input)
652   (define-key term-mode-map "\er" 'term-previous-matching-input)
653   (define-key term-mode-map "\es" 'term-next-matching-input)
654   (term-ifnot-xemacs
655    (define-key term-mode-map [?\A-\M-r] 'term-previous-matching-input-from-input)
656    (define-key term-mode-map [?\A-\M-s] 'term-next-matching-input-from-input))
657   (define-key term-mode-map "\e\C-l" 'term-show-output)
658   (define-key term-mode-map "\C-m" 'term-send-input)
659   (define-key term-mode-map "\C-d" 'term-delchar-or-maybe-eof)
660   (define-key term-mode-map "\C-c\C-a" 'term-bol)
661   (define-key term-mode-map "\C-c\C-u" 'term-kill-input)
662   (define-key term-mode-map "\C-c\C-w" 'backward-kill-word)
663   (define-key term-mode-map "\C-c\C-c" 'term-interrupt-subjob)
664   (define-key term-mode-map "\C-c\C-z" 'term-stop-subjob)
665   (define-key term-mode-map "\C-c\C-\\" 'term-quit-subjob)
666   (define-key term-mode-map "\C-c\C-m" 'term-copy-old-input)
667   (define-key term-mode-map "\C-c\C-o" 'term-kill-output)
668   (define-key term-mode-map "\C-c\C-r" 'term-show-output)
669   (define-key term-mode-map "\C-c\C-e" 'term-show-maximum-output)
670   (define-key term-mode-map "\C-c\C-l" 'term-dynamic-list-input-ring)
671   (define-key term-mode-map "\C-c\C-n" 'term-next-prompt)
672   (define-key term-mode-map "\C-c\C-p" 'term-previous-prompt)
673   (define-key term-mode-map "\C-c\C-d" 'term-send-eof)
674   (define-key term-mode-map "\C-c\C-k" 'term-char-mode)
675   (define-key term-mode-map "\C-c\C-j" 'term-line-mode)
676   (define-key term-mode-map "\C-c\C-q" 'term-pager-toggle)
677
678 ;  ;; completion:
679 ;  (define-key term-mode-map [menu-bar completion] 
680 ;    (cons "Complete" (make-sparse-keymap "Complete")))
681 ;  (define-key term-mode-map [menu-bar completion complete-expand]
682 ;    '("Expand File Name" . term-replace-by-expanded-filename))
683 ;  (define-key term-mode-map [menu-bar completion complete-listing]
684 ;    '("File Completion Listing" . term-dynamic-list-filename-completions))
685 ;  (define-key term-mode-map [menu-bar completion complete-file]
686 ;    '("Complete File Name" . term-dynamic-complete-filename))
687 ;  (define-key term-mode-map [menu-bar completion complete]
688 ;    '("Complete Before Point" . term-dynamic-complete))
689 ;  ;; Put them in the menu bar:
690 ;  (setq menu-bar-final-items (append '(terminal completion inout signals)
691 ;                                    menu-bar-final-items))
692   )
693
694 ;; Menu bars:
695 (term-ifnot-xemacs
696  (term-if-emacs19
697
698   ;; terminal:
699   (let (newmap)
700     (setq newmap (make-sparse-keymap "Terminal"))
701     (define-key newmap [terminal-pager-enable]
702       '("Enable paging" . term-fake-pager-enable))
703     (define-key newmap [terminal-pager-disable]
704       '("Disable paging" . term-fake-pager-disable))
705     (define-key newmap [terminal-char-mode]
706       '("Character mode" . term-char-mode))
707     (define-key newmap [terminal-line-mode]
708       '("Line mode" . term-line-mode))
709     (define-key newmap [menu-bar terminal] 
710       (setq term-terminal-menu (cons "Terminal" newmap)))
711
712     ;; completion:  (line mode only)
713     (defvar term-completion-menu (make-sparse-keymap "Complete"))
714     (define-key term-mode-map [menu-bar completion] 
715       (cons "Complete" term-completion-menu))
716     (define-key term-completion-menu [complete-expand]
717       '("Expand File Name" . term-replace-by-expanded-filename))
718     (define-key term-completion-menu [complete-listing]
719       '("File Completion Listing" . term-dynamic-list-filename-completions))
720     (define-key term-completion-menu [menu-bar completion complete-file]
721       '("Complete File Name" . term-dynamic-complete-filename))
722     (define-key term-completion-menu [menu-bar completion complete]
723       '("Complete Before Point" . term-dynamic-complete))
724
725     ;; Input history: (line mode only)
726     (defvar term-inout-menu (make-sparse-keymap "In/Out"))
727     (define-key term-mode-map [menu-bar inout] 
728       (cons "In/Out" term-inout-menu))
729     (define-key term-inout-menu [kill-output]
730       '("Kill Current Output Group" . term-kill-output))
731     (define-key term-inout-menu [next-prompt]
732       '("Forward Output Group" . term-next-prompt))
733     (define-key term-inout-menu [previous-prompt]
734       '("Backward Output Group" . term-previous-prompt))
735     (define-key term-inout-menu [show-maximum-output]
736       '("Show Maximum Output" . term-show-maximum-output))
737     (define-key term-inout-menu [show-output]
738       '("Show Current Output Group" . term-show-output))
739     (define-key term-inout-menu [kill-input]
740       '("Kill Current Input" . term-kill-input))
741     (define-key term-inout-menu [copy-input]
742       '("Copy Old Input" . term-copy-old-input))
743     (define-key term-inout-menu [forward-matching-history]
744       '("Forward Matching Input..." . term-forward-matching-input))
745     (define-key term-inout-menu [backward-matching-history]
746       '("Backward Matching Input..." . term-backward-matching-input))
747     (define-key term-inout-menu [next-matching-history]
748       '("Next Matching Input..." . term-next-matching-input))
749     (define-key term-inout-menu [previous-matching-history]
750       '("Previous Matching Input..." . term-previous-matching-input))
751     (define-key term-inout-menu [next-matching-history-from-input]
752       '("Next Matching Current Input" . term-next-matching-input-from-input))
753     (define-key term-inout-menu [previous-matching-history-from-input]
754       '("Previous Matching Current Input" . term-previous-matching-input-from-input))
755     (define-key term-inout-menu [next-history]
756       '("Next Input" . term-next-input))
757     (define-key term-inout-menu [previous-history]
758       '("Previous Input" . term-previous-input))
759     (define-key term-inout-menu [list-history]
760       '("List Input History" . term-dynamic-list-input-ring))
761     (define-key term-inout-menu [expand-history]
762       '("Expand History Before Point" . term-replace-by-expanded-history))
763
764     ;; Signals
765     (setq newmap (make-sparse-keymap "Signals"))
766     (define-key newmap [eof] '("EOF" . term-send-eof))
767     (define-key newmap [kill] '("KILL" . term-kill-subjob))
768     (define-key newmap [quit] '("QUIT" . term-quit-subjob))
769     (define-key newmap [cont] '("CONT" . term-continue-subjob))
770     (define-key newmap [stop] '("STOP" . term-stop-subjob))
771     (define-key newmap [] '("BREAK" . term-interrupt-subjob))
772     (define-key term-mode-map [menu-bar signals]
773       (setq term-signals-menu (cons "Signals" newmap)))
774     )))
775
776 (defun term-reset-size (height width)
777   (setq term-height height)
778   (setq term-width width)
779   (setq term-start-line-column nil)
780   (setq term-current-row nil)
781   (setq term-current-column nil)
782   (term-scroll-region 0 height))
783
784 ;; Recursive routine used to check if any string in term-kill-echo-list
785 ;; matches part of the buffer before point.
786 ;; If so, delete that matched part of the buffer - this suppresses echo.
787 ;; Also, remove that string from the term-kill-echo-list.
788 ;; We *also* remove any older string on the list, as a sanity measure,
789 ;; in case something gets out of sync.  (Except for type-ahead, there
790 ;; should only be one element in the list.)
791
792 (defun term-check-kill-echo-list ()
793   (let ((cur term-kill-echo-list) (found nil) (save-point (point)))
794     (unwind-protect
795         (progn
796           (end-of-line)
797           (while cur
798             (let* ((str (car cur)) (len (length str)) (start (- (point) len)))
799               (if (and (>= start (point-min))
800                        (string= str (buffer-substring start (point))))
801                   (progn (delete-backward-char len)
802                          (setq term-kill-echo-list (cdr cur))
803                          (setq term-current-column nil)
804                          (setq term-current-row nil)
805                          (setq term-start-line-column nil)
806                          (setq cur nil found t))
807                 (setq cur (cdr cur))))))
808       (if (not found)
809           (goto-char save-point)))
810     found))
811
812 (defun term-check-size (process)
813   (if (or (/= term-height (1- (window-displayed-height)))
814           (/= term-width (1- (window-width))))
815       (progn
816         (term-reset-size (1- (window-displayed-height)) (1- (window-width)))
817         (set-process-window-size process term-height term-width))))
818
819 (defun term-send-raw-string (chars)
820   (let ((proc (get-buffer-process (current-buffer))))
821     (if (not proc)
822         (error "Current buffer has no process")
823       ;; Note that (term-current-row) must be called *after*
824       ;; (point) has been updated to (process-mark proc).
825       (goto-char (process-mark proc))
826       (if (term-pager-enabled)
827           (setq term-pager-count (term-current-row)))
828       (process-send-string proc chars))))
829
830 (defun term-send-raw ()
831   "Send the last character typed through the terminal-emulator
832 without any interpretation." 
833   (interactive)
834
835   (term-if-xemacs
836    (if (key-press-event-p last-input-event)
837        (let ((mods (event-modifiers last-input-event))
838              (key (event-key last-input-event))
839              meta)
840          (if (memq 'meta mods)
841              (progn
842                (setq meta t)
843                (setq mods (delq 'meta mods))))
844          (let ((ascii (event-to-character (character-to-event
845                                            (append mods (list key)))
846                                           t ;; lenient
847                                           nil ;; no meta mucking
848                                           t ;; allow non-ASCII
849                                           )))
850            (cond (ascii
851                   (if meta
852                       (term-send-raw-string (format "\e%c" ascii))
853                     (term-send-raw-string (make-string 1 ascii))))
854                  (t (command-execute (key-binding last-input-event))))))
855      (let ((cmd (lookup-key (current-global-map) (this-command-keys))))
856        (and cmd (call-interactively cmd)))))
857
858   (term-ifnot-xemacs
859    ;; Convert `return' to C-m, etc.
860    (if (and (symbolp last-input-char)
861             (get last-input-char 'ascii-character))
862        (setq last-input-char 
863              (get last-input-char 'ascii-character))
864    (term-send-raw-string (make-string 1 last-input-char)))))
865
866 (defun term-mouse-paste (click arg)
867   "Insert the last stretch of killed text at the position clicked on."
868   (interactive "e\nP")
869   (term-if-xemacs
870    (term-send-raw-string (or (condition-case () (x-get-selection) (error ()))
871                              (x-get-cutbuffer)
872                              (error "No selection or cut buffer available"))))
873   (term-ifnot-xemacs
874    ;; Give temporary modes such as isearch a chance to turn off.
875    (run-hooks 'mouse-leave-buffer-hook)
876    (setq this-command 'yank)
877    (term-send-raw-string (current-kill (cond
878                                         ((listp arg) 0)
879                                         ((eq arg '-) -1)
880                                         (t (1- arg)))))))
881
882 ;; Which would be better:  "\e[A" or "\eOA"? readline accepts either.
883 ;; Both xterm and dtterm (CDE) send "\e[A", which argues for that choice.
884 ;; The xterm termcap claims ku=\EOA; the dtterm terminfo entry says ku=\E[A.
885 (defun term-send-up    () (interactive) (term-send-raw-string "\e[A"))
886 (defun term-send-down  () (interactive) (term-send-raw-string "\e[B"))
887 (defun term-send-right () (interactive) (term-send-raw-string "\e[C"))
888 (defun term-send-left  () (interactive) (term-send-raw-string "\e[D"))
889 (defun term-send-home  () (interactive) (term-send-raw-string "\e[H"))
890 (defun term-send-end   () (interactive) (term-send-raw-string "\eOw"))
891 (defun term-send-prior () (interactive) (term-send-raw-string "\e[5~"))
892 (defun term-send-next  () (interactive) (term-send-raw-string "\e[6~"))
893 (defun term-send-del   () (interactive) (term-send-raw-string term-delete-string))
894 (defun term-send-backspace  () (interactive) (term-send-raw-string term-backspace-string))
895
896 (defun term-set-escape-char (c)
897   "Change term-escape-char and keymaps that depend on it."
898   (if term-escape-char
899       (define-key term-raw-map term-escape-char 'term-send-raw))
900   (setq c (make-string 1 c))
901   (define-key term-raw-map c term-raw-escape-map)
902   ;; Define standard bindings in term-raw-escape-map
903   (define-key term-raw-escape-map "\C-x"
904     (lookup-key (current-global-map) "\C-x"))
905   (define-key term-raw-escape-map "\C-v"
906     (lookup-key (current-global-map) "\C-v"))
907   (define-key term-raw-escape-map "\C-u"
908     (lookup-key (current-global-map) "\C-u"))
909   (define-key term-raw-escape-map c 'term-send-raw)
910   (define-key term-raw-escape-map "\C-q" 'term-pager-toggle)
911   ;; The keybinding for term-char-mode is needed by the menubar code.
912   (define-key term-raw-escape-map "\C-k" 'term-char-mode)
913   (define-key term-raw-escape-map "\C-j" 'term-line-mode))
914     
915 (defun term-char-mode ()
916   "Switch to char (\"raw\") sub-mode of term mode.
917 Each character you type is sent directly to the inferior without
918 intervention from emacs, except for the escape character (usually C-c)."
919   (interactive)
920   (if (not term-raw-map)
921       ;; Initialize term-raw-map.
922       (let* ((map (make-keymap))
923              (save-meta-prefix-char meta-prefix-char)
924              (i 0))
925         ;; Temporarily disable meta-prefix-char while building keymaps.
926         (setq meta-prefix-char -1)
927         (term-if-xemacs
928          (set-keymap-default-binding map 'term-send-raw))
929         (term-ifnot-xemacs
930          (while (< i 128)
931            (define-key map (make-string 1 i) 'term-send-raw)
932            (setq i (1+ i))))
933         (setq term-raw-map map)
934         (setq term-raw-escape-map
935               (copy-keymap (lookup-key (current-global-map) "\C-x")))
936         (define-key term-raw-map [up] 'term-send-up)
937         (define-key term-raw-map [down] 'term-send-down)
938         (define-key term-raw-map [right] 'term-send-right)
939         (define-key term-raw-map [left] 'term-send-left)
940         (define-key term-raw-map [home] 'term-send-home)
941         (define-key term-raw-map [end] 'term-send-end)
942         (define-key term-raw-map [prior] 'term-send-prior)
943         (define-key term-raw-map [next] 'term-send-next)
944         (define-key term-raw-map [delete] 'term-send-del)
945         (define-key term-raw-map [backspace] 'term-send-backspace)
946         (term-if-xemacs
947          (define-key term-raw-map [button2] 'term-mouse-paste))
948         (term-ifnot-xemacs
949          (define-key term-raw-map [mouse-2] 'term-mouse-paste)
950          (define-key term-raw-map [menu-bar terminal] term-terminal-menu)
951          (define-key term-raw-map [menu-bar signals] term-signals-menu))
952         (setq meta-prefix-char save-meta-prefix-char)
953         (term-set-escape-char ?\C-c)))
954   ;; FIXME: Emit message? Cfr ilisp-raw-message
955   (if (term-in-line-mode)
956       (progn
957         (setq term-old-mode-map (current-local-map))
958         (use-local-map term-raw-map)
959
960         ;; Send existing partial line to inferior (without newline).
961         (let ((pmark (process-mark (get-buffer-process (current-buffer))))
962               (save-input-sender term-input-sender))
963           (if (> (point) pmark)
964               (unwind-protect
965                   (progn
966                     (setq term-input-sender
967                           (symbol-function 'term-send-string))
968                     (end-of-line)
969                     (term-send-input))
970                 (setq term-input-sender save-input-sender))))
971         (term-update-mode-line))))
972
973 (defun term-line-mode  ()
974   "Switch to line (\"cooked\") sub-mode of term mode.
975 This means that emacs editing commands work as normally, until
976 you type \\[term-send-input] which sends the current line to the inferior."
977   (interactive)
978   (if (term-in-char-mode)
979       (progn
980         (use-local-map term-old-mode-map)
981         (term-update-mode-line))))
982
983 (defun term-update-mode-line ()
984   (setq mode-line-process
985         (if (term-in-char-mode)
986             (if (term-pager-enabled) '(": char page %s") '(": char %s"))
987           (if (term-pager-enabled) '(": line page %s") '(": line %s"))))
988   (force-mode-line-update))
989
990 (defun term-check-proc (buffer)
991   "True if there is a process associated w/buffer BUFFER, and
992 it is alive (status RUN or STOP). BUFFER can be either a buffer or the
993 name of one"
994   (let ((proc (get-buffer-process buffer)))
995     (and proc (memq (process-status proc) '(run stop)))))
996
997 ;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
998 ;;; for the second argument (program).
999 ;;;###autoload
1000 (defun make-term (name program &optional startfile &rest switches)
1001   "Make a term process NAME in a buffer, running PROGRAM.
1002 The name of the buffer is made by surrounding NAME with `*'s.
1003 If there is already a running process in that buffer, it is not restarted.
1004 Optional third arg STARTFILE is the name of a file to send the contents of to 
1005 the process.  Any more args are arguments to PROGRAM."
1006   (let ((buffer (get-buffer-create (concat "*" name "*"))))
1007     ;; If no process, or nuked process, crank up a new one and put buffer in
1008     ;; term mode. Otherwise, leave buffer and existing process alone.
1009     (cond ((not (term-check-proc buffer))
1010            (save-excursion
1011              (set-buffer buffer)
1012              (term-mode)) ; Install local vars, mode, keymap, ...
1013            (term-exec buffer name program startfile switches)))
1014     buffer))
1015
1016 ;;;###autoload
1017 (defun term (program)
1018   "Start a terminal-emulator in a new buffer."
1019   (interactive (list (read-from-minibuffer "Run program: "
1020                                            (or explicit-shell-file-name
1021                                                (getenv "ESHELL")
1022                                                (getenv "SHELL")
1023                                                "/bin/sh"))))
1024   (set-buffer (make-term "terminal" program))
1025   (term-mode)
1026   (term-char-mode)
1027   (switch-to-buffer "*terminal*"))
1028
1029 (defun term-exec (buffer name command startfile switches)
1030   "Start up a process in buffer for term modes.
1031 Blasts any old process running in the buffer. Doesn't set the buffer mode.
1032 You can use this to cheaply run a series of processes in the same term
1033 buffer. The hook term-exec-hook is run after each exec."
1034   (save-excursion
1035     (set-buffer buffer)
1036     (let ((proc (get-buffer-process buffer)))   ; Blast any old process.
1037       (if proc (delete-process proc)))
1038     ;; Crank up a new process
1039     (let ((proc (term-exec-1 name buffer command switches)))
1040       (make-local-variable 'term-ptyp)
1041       (setq term-ptyp process-connection-type) ; T if pty, NIL if pipe.
1042       ;; Jump to the end, and set the process mark.
1043       (goto-char (point-max))
1044       (set-marker (process-mark proc) (point))
1045       (set-process-filter proc 'term-emulate-terminal)
1046       ;; Feed it the startfile.
1047       (cond (startfile
1048              ;;This is guaranteed to wait long enough
1049              ;;but has bad results if the term does not prompt at all
1050              ;;      (while (= size (buffer-size))
1051              ;;        (sleep-for 1))
1052              ;;I hope 1 second is enough!
1053              (sleep-for 1)
1054              (goto-char (point-max))
1055              (insert-file-contents startfile)
1056              (setq startfile (buffer-substring (point) (point-max)))
1057              (delete-region (point) (point-max))
1058              (term-send-string proc startfile)))
1059     (run-hooks 'term-exec-hook)
1060     buffer)))
1061
1062 ;;; Name to use for TERM.
1063 ;;; Using "emacs" loses, because bash disables editing if TERM == emacs.
1064 (defvar term-term-name "eterm")
1065 ; Format string, usage: (format term-termcap-string emacs-term-name "TERMCAP=" 24 80)
1066 (defvar term-termcap-format
1067   "%s%s:li#%d:co#%d:cl=\\E[H\\E[J:cd=\\E[J:bs:am:xn:cm=\\E[%%i%%d;%%dH\
1068 :nd=\\E[C:up=\\E[A:ce=\\E[K:ho=\\E[H:pt\
1069 :al=\\E[L:dl=\\E[M:DL=\\E[%%dM:AL=\\E[%%dL:cs=\\E[%%i%%d;%%dr:sf=\\n\
1070 :te=\\E[2J\\E[?47l\\E8:ti=\\E7\\E[?47h\
1071 :dc=\\E[P:DC=\\E[%%dP:IC=\\E[%%d@:im=\\E[4h:ei=\\E[4l:mi\
1072 :kd=\\E[B:kl=\\E[D:kr=\\E[C:ku=\\E[A\
1073 :so=\\E[7m:se=\\E[m:us=\\E[4m:ue=\\E[m:md=\\E[1m:mr=\\E[7m:me=\\E[m\
1074 :UP=\\E[%%dA:DO=\\E[%%dB:LE=\\E[%%dD:RI=\\E[%%dC"
1075 ;;; : -undefine ic
1076   "termcap capabilities supported")
1077
1078 ;;; This auxiliary function cranks up the process for term-exec in
1079 ;;; the appropriate environment.
1080
1081 (defun term-exec-1 (name buffer command switches)
1082   ;; We need to do an extra (fork-less) exec to run stty.
1083   ;; (This would not be needed if we had suitable emacs primitives.)
1084   ;; The 'if ...; then shift; fi' hack is because Bourne shell
1085   ;; loses one arg when called with -c, and newer shells (bash,  ksh) don't.
1086   ;; Thus we add an extra dummy argument "..", and then remove it.
1087   (let ((process-environment
1088          (nconc
1089           (list
1090            (format "TERM=%s" term-term-name)
1091            (if (and (boundp 'system-uses-terminfo) system-uses-terminfo)
1092                (format "TERMINFO=%s" (locate-data-directory "eterm"))
1093             (format term-termcap-format "TERMCAP="
1094                     term-term-name term-height term-width))
1095            (format "EMACS=%s (term:%s)" emacs-version term-protocol-version)
1096            (format "LINES=%d" term-height)
1097            (format "COLUMNS=%d" term-width))
1098           process-environment)))
1099     (if (eq system-type 'windows-nt)
1100         (apply 'start-process name buffer
1101                command switches)
1102       (apply 'start-process name buffer
1103              "/bin/sh" "-c"
1104              (format "stty -nl echo rows %d columns %d sane 2>/dev/null;\
1105 if [ $1 = .. ]; then shift; fi; exec \"$@\""
1106                      term-height term-width)
1107              ".."
1108              command switches))))
1109  
1110 ;;; This should be in emacs, but it isn't.
1111 (defun term-mem (item list &optional elt=)
1112   "Test to see if ITEM is equal to an item in LIST.
1113 Option comparison function ELT= defaults to equal."
1114   (let ((elt= (or elt= (function equal)))
1115         (done nil))
1116     (while (and list (not done))
1117       (if (funcall elt= item (car list))
1118           (setq done list)
1119           (setq list (cdr list))))
1120     done))
1121
1122 \f
1123 ;;; Input history processing in a buffer
1124 ;;; ===========================================================================
1125 ;;; Useful input history functions, courtesy of the Ergo group.
1126
1127 ;;; Eleven commands:
1128 ;;; term-dynamic-list-input-ring        List history in help buffer.
1129 ;;; term-previous-input         Previous input...
1130 ;;; term-previous-matching-input        ...matching a string.
1131 ;;; term-previous-matching-input-from-input ... matching the current input.
1132 ;;; term-next-input                     Next input...
1133 ;;; term-next-matching-input            ...matching a string.
1134 ;;; term-next-matching-input-from-input     ... matching the current input.
1135 ;;; term-backward-matching-input      Backwards input...
1136 ;;; term-forward-matching-input       ...matching a string.
1137 ;;; term-replace-by-expanded-history    Expand history at point;
1138 ;;;                                     replace with expanded history.
1139 ;;; term-magic-space                    Expand history and insert space.
1140 ;;;
1141 ;;; Three functions:
1142 ;;; term-read-input-ring              Read into term-input-ring...
1143 ;;; term-write-input-ring             Write to term-input-ring-file-name.
1144 ;;; term-replace-by-expanded-history-before-point Workhorse function.
1145
1146 (defun term-read-input-ring (&optional silent)
1147   "Sets the buffer's `term-input-ring' from a history file.
1148 The name of the file is given by the variable `term-input-ring-file-name'.
1149 The history ring is of size `term-input-ring-size', regardless of file size.
1150 If `term-input-ring-file-name' is nil this function does nothing.
1151
1152 If the optional argument SILENT is non-nil, we say nothing about a
1153 failure to read the history file.
1154
1155 This function is useful for major mode commands and mode hooks.
1156
1157 The structure of the history file should be one input command per line,
1158 with the most recent command last.
1159 See also `term-input-ignoredups' and `term-write-input-ring'."
1160   (cond ((or (null term-input-ring-file-name)
1161              (equal term-input-ring-file-name ""))
1162          nil)
1163         ((not (file-readable-p term-input-ring-file-name))
1164          (or silent
1165              (message "Cannot read history file %s"
1166                       term-input-ring-file-name)))
1167         (t
1168          (let ((history-buf (get-buffer-create " *temp*"))
1169                (file term-input-ring-file-name)
1170                (count 0)
1171                (ring (make-ring term-input-ring-size)))
1172            (unwind-protect
1173                (save-excursion
1174                  (set-buffer history-buf)
1175                  (widen)
1176                  (erase-buffer)
1177                  (insert-file-contents file)
1178                  ;; Save restriction in case file is already visited...
1179                  ;; Watch for those date stamps in history files!
1180                  (goto-char (point-max))
1181                  (while (and (< count term-input-ring-size)
1182                              (re-search-backward "^[ \t]*\\([^#\n].*\\)[ \t]*$"
1183                                                  nil t))
1184                    (let ((history (buffer-substring (match-beginning 1)
1185                                                     (match-end 1))))
1186                      (if (or (null term-input-ignoredups)
1187                              (ring-empty-p ring)
1188                              (not (string-equal (ring-ref ring 0) history)))
1189                          (ring-insert-at-beginning ring history)))
1190                    (setq count (1+ count))))
1191              (kill-buffer history-buf))
1192            (setq term-input-ring ring
1193                  term-input-ring-index nil)))))
1194
1195 (defun term-write-input-ring ()
1196   "Writes the buffer's `term-input-ring' to a history file.
1197 The name of the file is given by the variable `term-input-ring-file-name'.
1198 The original contents of the file are lost if `term-input-ring' is not empty.
1199 If `term-input-ring-file-name' is nil this function does nothing.
1200
1201 Useful within process sentinels.
1202
1203 See also `term-read-input-ring'."
1204   (cond ((or (null term-input-ring-file-name)
1205              (equal term-input-ring-file-name "")
1206              (null term-input-ring) (ring-empty-p term-input-ring))
1207          nil)
1208         ((not (file-writable-p term-input-ring-file-name))
1209          (message "Cannot write history file %s" term-input-ring-file-name))
1210         (t
1211          (let* ((history-buf (get-buffer-create " *Temp Input History*"))
1212                 (ring term-input-ring)
1213                 (file term-input-ring-file-name)
1214                 (index (ring-length ring)))
1215            ;; Write it all out into a buffer first.  Much faster, but messier,
1216            ;; than writing it one line at a time.
1217            (save-excursion
1218              (set-buffer history-buf)
1219              (erase-buffer)
1220              (while (> index 0)
1221                (setq index (1- index))
1222                (insert (ring-ref ring index) ?\n))
1223              (write-region (buffer-string) nil file nil 'no-message)
1224              (kill-buffer nil))))))
1225
1226
1227 (defun term-dynamic-list-input-ring ()
1228   "List in help buffer the buffer's input history."
1229   (interactive)
1230   (if (or (not (ring-p term-input-ring))
1231           (ring-empty-p term-input-ring))
1232       (message "No history")
1233     (let ((history nil)
1234           (history-buffer " *Input History*")
1235           (index (1- (ring-length term-input-ring)))
1236           (conf (current-window-configuration)))
1237       ;; We have to build up a list ourselves from the ring vector.
1238       (while (>= index 0)
1239         (setq history (cons (ring-ref term-input-ring index) history)
1240               index (1- index)))
1241       ;; Change "completion" to "history reference"
1242       ;; to make the display accurate.
1243       (with-output-to-temp-buffer history-buffer
1244         (display-completion-list history)
1245         (set-buffer history-buffer)
1246         (forward-line 3)
1247         (while (search-backward "completion" nil 'move)
1248           (replace-match "history reference")))
1249       (sit-for 0)
1250       (message "Hit space to flush")
1251       (let ((ch (read-event)))
1252         (if (eq ch ?\ )
1253             (set-window-configuration conf)
1254           (setq unread-command-events (list ch)))))))
1255
1256
1257 (defun term-regexp-arg (prompt)
1258   ;; Return list of regexp and prefix arg using PROMPT.
1259   (let* ((minibuffer-history-sexp-flag nil)
1260          ;; Don't clobber this.
1261          (last-command last-command)
1262          (regexp (read-from-minibuffer prompt nil nil nil
1263                                        'minibuffer-history-search-history)))
1264     (list (if (string-equal regexp "")
1265               (setcar minibuffer-history-search-history
1266                       (nth 1 minibuffer-history-search-history))
1267             regexp)
1268           (prefix-numeric-value current-prefix-arg))))
1269
1270 (defun term-search-arg (arg)
1271   ;; First make sure there is a ring and that we are after the process mark
1272   (cond ((not (term-after-pmark-p))
1273          (error "Not at command line"))
1274         ((or (null term-input-ring)
1275              (ring-empty-p term-input-ring))
1276          (error "Empty input ring"))
1277         ((zerop arg)
1278          ;; arg of zero resets search from beginning, and uses arg of 1
1279          (setq term-input-ring-index nil)
1280          1)
1281         (t
1282          arg)))
1283
1284 (defun term-search-start (arg)
1285   ;; Index to start a directional search, starting at term-input-ring-index
1286   (if term-input-ring-index
1287       ;; If a search is running, offset by 1 in direction of arg
1288       (mod (+ term-input-ring-index (if (> arg 0) 1 -1))
1289            (ring-length term-input-ring))
1290     ;; For a new search, start from beginning or end, as appropriate
1291     (if (>= arg 0)
1292         0                                      ; First elt for forward search
1293       (1- (ring-length term-input-ring)))))  ; Last elt for backward search
1294
1295 (defun term-previous-input-string (arg)
1296   "Return the string ARG places along the input ring.
1297 Moves relative to `term-input-ring-index'."
1298   (ring-ref term-input-ring (if term-input-ring-index
1299                                   (mod (+ arg term-input-ring-index) 
1300                                        (ring-length term-input-ring))
1301                                 arg)))
1302
1303 (defun term-previous-input (arg)
1304   "Cycle backwards through input history."
1305   (interactive "*p")
1306   (term-previous-matching-input "." arg))
1307
1308 (defun term-next-input (arg)
1309   "Cycle forwards through input history."
1310   (interactive "*p")
1311   (term-previous-input (- arg)))
1312
1313 (defun term-previous-matching-input-string (regexp arg)
1314   "Return the string matching REGEXP ARG places along the input ring.
1315 Moves relative to `term-input-ring-index'."
1316   (let* ((pos (term-previous-matching-input-string-position regexp arg)))
1317     (if pos (ring-ref term-input-ring pos))))
1318
1319 (defun term-previous-matching-input-string-position (regexp arg &optional start)
1320   "Return the index matching REGEXP ARG places along the input ring.
1321 Moves relative to START, or `term-input-ring-index'."
1322   (if (or (not (ring-p term-input-ring))
1323           (ring-empty-p term-input-ring))
1324       (error "No history"))
1325   (let* ((len (ring-length term-input-ring))
1326          (motion (if (> arg 0) 1 -1))
1327          (n (mod (- (or start (term-search-start arg)) motion) len))
1328          (tried-each-ring-item nil)
1329          (prev nil))
1330     ;; Do the whole search as many times as the argument says.
1331     (while (and (/= arg 0) (not tried-each-ring-item))
1332       ;; Step once.
1333       (setq prev n
1334             n (mod (+ n motion) len))
1335       ;; If we haven't reached a match, step some more.
1336       (while (and (< n len) (not tried-each-ring-item)
1337                   (not (string-match regexp (ring-ref term-input-ring n))))
1338         (setq n (mod (+ n motion) len)
1339               ;; If we have gone all the way around in this search.
1340               tried-each-ring-item (= n prev)))
1341       (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1342     ;; Now that we know which ring element to use, if we found it, return that.
1343     (if (string-match regexp (ring-ref term-input-ring n))
1344         n)))
1345
1346 (defun term-previous-matching-input (regexp arg)
1347   "Search backwards through input history for match for REGEXP.
1348 \(Previous history elements are earlier commands.)
1349 With prefix argument N, search for Nth previous match.
1350 If N is negative, find the next or Nth next match."
1351   (interactive (term-regexp-arg "Previous input matching (regexp): "))
1352   (setq arg (term-search-arg arg))
1353   (let ((pos (term-previous-matching-input-string-position regexp arg)))
1354     ;; Has a match been found?
1355     (if (null pos)
1356         (error "Not found")
1357       (setq term-input-ring-index pos)
1358       (message "History item: %d" (1+ pos))
1359       (delete-region 
1360        ;; Can't use kill-region as it sets this-command
1361        (process-mark (get-buffer-process (current-buffer))) (point))
1362       (insert (ring-ref term-input-ring pos)))))
1363
1364 (defun term-next-matching-input (regexp arg)
1365   "Search forwards through input history for match for REGEXP.
1366 \(Later history elements are more recent commands.)
1367 With prefix argument N, search for Nth following match.
1368 If N is negative, find the previous or Nth previous match."
1369   (interactive (term-regexp-arg "Next input matching (regexp): "))
1370   (term-previous-matching-input regexp (- arg)))
1371
1372 (defun term-previous-matching-input-from-input (arg)
1373   "Search backwards through input history for match for current input.
1374 \(Previous history elements are earlier commands.)
1375 With prefix argument N, search for Nth previous match.
1376 If N is negative, search forwards for the -Nth following match."
1377   (interactive "p")
1378   (if (not (memq last-command '(term-previous-matching-input-from-input
1379                                 term-next-matching-input-from-input)))
1380       ;; Starting a new search
1381       (setq term-matching-input-from-input-string
1382             (buffer-substring 
1383              (process-mark (get-buffer-process (current-buffer))) 
1384              (point))
1385             term-input-ring-index nil))
1386   (term-previous-matching-input
1387    (concat "^" (regexp-quote term-matching-input-from-input-string))
1388    arg))
1389
1390 (defun term-next-matching-input-from-input (arg)
1391   "Search forwards through input history for match for current input.
1392 \(Following history elements are more recent commands.)
1393 With prefix argument N, search for Nth following match.
1394 If N is negative, search backwards for the -Nth previous match."
1395   (interactive "p")
1396   (term-previous-matching-input-from-input (- arg)))
1397
1398
1399 (defun term-replace-by-expanded-history (&optional silent)
1400   "Expand input command history references before point.
1401 Expansion is dependent on the value of `term-input-autoexpand'.
1402
1403 This function depends on the buffer's idea of the input history, which may not
1404 match the command interpreter's idea, assuming it has one.
1405
1406 Assumes history syntax is like typical Un*x shells'.  However, since emacs
1407 cannot know the interpreter's idea of input line numbers, assuming it has one,
1408 it cannot expand absolute input line number references.
1409
1410 If the optional argument SILENT is non-nil, never complain
1411 even if history reference seems erroneous.
1412
1413 See `term-magic-space' and `term-replace-by-expanded-history-before-point'.
1414
1415 Returns t if successful."
1416   (interactive)
1417   (if (and term-input-autoexpand
1418            (string-match "[!^]" (funcall term-get-old-input))
1419            (save-excursion (beginning-of-line)
1420                            (looking-at term-prompt-regexp)))
1421       ;; Looks like there might be history references in the command.
1422       (let ((previous-modified-tick (buffer-modified-tick)))
1423         (message "Expanding history references...")
1424         (term-replace-by-expanded-history-before-point silent)
1425         (/= previous-modified-tick (buffer-modified-tick)))))
1426
1427
1428 (defun term-replace-by-expanded-history-before-point (silent)
1429   "Expand directory stack reference before point.
1430 See `term-replace-by-expanded-history'.  Returns t if successful."
1431   (save-excursion
1432     (let ((toend (- (save-excursion (end-of-line nil) (point)) (point)))
1433           (start (progn (term-bol nil) (point))))
1434       (while (progn
1435                (skip-chars-forward "^!^"
1436                                    (save-excursion
1437                                      (end-of-line nil) (- (point) toend)))
1438                (< (point)
1439                   (save-excursion
1440                     (end-of-line nil) (- (point) toend))))
1441         ;; This seems a bit complex.  We look for references such as !!, !-num,
1442         ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
1443         ;; If that wasn't enough, the plings can be suffixed with argument
1444         ;; range specifiers.
1445         ;; Argument ranges are complex too, so we hive off the input line,
1446         ;; referenced with plings, with the range string to `term-args'.
1447         (setq term-input-ring-index nil)
1448         (cond ((or (= (preceding-char) ?\\)
1449                    (term-within-quotes start (point)))
1450                ;; The history is quoted, or we're in quotes.
1451                (goto-char (1+ (point))))
1452               ((looking-at "![0-9]+\\($\\|[^-]\\)")
1453                ;; We cannot know the interpreter's idea of input line numbers.
1454                (goto-char (match-end 0))
1455                (message "Absolute reference cannot be expanded"))
1456               ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
1457                ;; Just a number of args from `number' lines backward.
1458                (let ((number (1- (string-to-number
1459                                   (buffer-substring (match-beginning 1)
1460                                                     (match-end 1))))))
1461                  (if (<= number (ring-length term-input-ring))
1462                      (progn
1463                        (replace-match
1464                         (term-args (term-previous-input-string number)
1465                                      (match-beginning 2) (match-end 2))
1466                         t t)
1467                        (setq term-input-ring-index number)
1468                        (message "History item: %d" (1+ number)))
1469                    (goto-char (match-end 0))
1470                    (message "Relative reference exceeds input history size"))))
1471               ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
1472                ;; Just a number of args from the previous input line.
1473                (replace-match
1474                 (term-args (term-previous-input-string 0)
1475                              (match-beginning 1) (match-end 1))
1476                 t t)
1477                (message "History item: previous"))
1478               ((looking-at
1479                 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
1480                ;; Most recent input starting with or containing (possibly
1481                ;; protected) string, maybe just a number of args.  Phew.
1482                (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
1483                       (mb2 (match-beginning 2)) (me2 (match-end 2))
1484                       (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
1485                       (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
1486                       (pos (save-match-data
1487                              (term-previous-matching-input-string-position
1488                               (concat pref (regexp-quote exp)) 1))))
1489                  (if (null pos)
1490                      (progn
1491                        (goto-char (match-end 0))
1492                        (or silent
1493                            (progn (message "Not found")
1494                                   (ding))))
1495                    (setq term-input-ring-index pos)
1496                    (replace-match
1497                     (term-args (ring-ref term-input-ring pos)
1498                                  (match-beginning 4) (match-end 4))
1499                     t t)
1500                    (message "History item: %d" (1+ pos)))))
1501               ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
1502                ;; Quick substitution on the previous input line.
1503                (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
1504                      (new (buffer-substring (match-beginning 2) (match-end 2)))
1505                      (pos nil))
1506                  (replace-match (term-previous-input-string 0) t t)
1507                  (setq pos (point))
1508                  (goto-char (match-beginning 0))
1509                  (if (not (search-forward old pos t))
1510                      (or silent
1511                          (error "Not found"))
1512                    (replace-match new t t)
1513                    (message "History item: substituted"))))
1514               (t
1515                (goto-char (match-end 0))))))))
1516
1517
1518 (defun term-magic-space (arg)
1519   "Expand input history references before point and insert ARG spaces.
1520 A useful command to bind to SPC.  See `term-replace-by-expanded-history'."
1521   (interactive "p")
1522   (term-replace-by-expanded-history)
1523   (self-insert-command arg))
1524 \f
1525 (defun term-within-quotes (beg end)
1526   "Return t if the number of quotes between BEG and END is odd.
1527 Quotes are single and double."
1528   (let ((countsq (term-how-many-region "\\(^\\|[^\\\\]\\)\'" beg end))
1529         (countdq (term-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
1530     (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
1531
1532 (defun term-how-many-region (regexp beg end)
1533   "Return number of matches for REGEXP from BEG to END."
1534   (let ((count 0))
1535     (save-excursion
1536       (save-match-data
1537         (goto-char beg)
1538         (while (re-search-forward regexp end t)
1539           (setq count (1+ count)))))
1540     count))
1541
1542 (defun term-args (string begin end)
1543   ;; From STRING, return the args depending on the range specified in the text
1544   ;; from BEGIN to END.  If BEGIN is nil, assume all args.  Ignore leading `:'.
1545   ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
1546   (save-match-data
1547     (if (null begin)
1548         (term-arguments string 0 nil)
1549       (let* ((range (buffer-substring
1550                      (if (eq (char-after begin) ?:) (1+ begin) begin) end))
1551              (nth (cond ((string-match "^[*^]" range) 1)
1552                         ((string-match "^-" range) 0)
1553                         ((string-equal range "$") nil)
1554                         (t (string-to-number range))))
1555              (mth (cond ((string-match "[-*$]$" range) nil)
1556                         ((string-match "-" range)
1557                          (string-to-number (substring range (match-end 0))))
1558                         (t nth))))
1559         (term-arguments string nth mth)))))
1560
1561 ;; Return a list of arguments from ARG.  Break it up at the
1562 ;; delimiters in term-delimiter-argument-list.  Returned list is backwards.
1563 (defun term-delim-arg (arg)
1564   (if (null term-delimiter-argument-list)
1565       (list arg)
1566     (let ((args nil)
1567           (pos 0)
1568           (len (length arg)))
1569       (while (< pos len)
1570         (let ((char (aref arg pos))
1571               (start pos))
1572           (if (memq char term-delimiter-argument-list)
1573               (while (and (< pos len) (eq (aref arg pos) char))
1574                 (setq pos (1+ pos)))
1575             (while (and (< pos len)
1576                         (not (memq (aref arg pos)
1577                                    term-delimiter-argument-list)))
1578               (setq pos (1+ pos))))
1579           (setq args (cons (substring arg start pos) args))))
1580       args)))
1581
1582 (defun term-arguments (string nth mth)
1583   "Return from STRING the NTH to MTH arguments.
1584 NTH and/or MTH can be nil, which means the last argument.
1585 Returned arguments are separated by single spaces.
1586 We assume whitespace separates arguments, except within quotes.
1587 Also, a run of one or more of a single character
1588 in `term-delimiter-argument-list' is a separate argument.
1589 Argument 0 is the command name."
1590   (let ((argpart "[^ \n\t\"'`]+\\|\\(\"[^\"]*\"\\|'[^']*'\\|`[^`]*`\\)")
1591         (args ()) (pos 0)
1592         (count 0)
1593         beg str quotes)
1594     ;; Build a list of all the args until we have as many as we want.
1595     (while (and (or (null mth) (<= count mth))
1596                 (string-match argpart string pos))
1597       (if (and beg (= pos (match-beginning 0)))
1598           ;; It's contiguous, part of the same arg.
1599           (setq pos (match-end 0)
1600                 quotes (or quotes (match-beginning 1)))
1601         ;; It's a new separate arg.
1602         (if beg
1603             ;; Put the previous arg, if there was one, onto ARGS.
1604             (setq str (substring string beg pos)
1605                   args (if quotes (cons str args)
1606                          (nconc (term-delim-arg str) args))
1607                   count (1+ count)))
1608         (setq quotes (match-beginning 1))
1609         (setq beg (match-beginning 0))
1610         (setq pos (match-end 0))))
1611     (if beg
1612         (setq str (substring string beg pos)
1613               args (if quotes (cons str args)
1614                      (nconc (term-delim-arg str) args))
1615               count (1+ count)))
1616     (let ((n (or nth (1- count)))
1617           (m (if mth (1- (- count mth)) 0)))
1618       (mapconcat
1619        (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
1620 \f
1621 ;;;
1622 ;;; Input processing stuff [line mode]
1623 ;;;
1624
1625 (defun term-send-input () 
1626   "Send input to process.
1627 After the process output mark, sends all text from the process mark to
1628 point as input to the process.  Before the process output mark, calls value
1629 of variable term-get-old-input to retrieve old input, copies it to the
1630 process mark, and sends it.  A terminal newline is also inserted into the
1631 buffer and sent to the process.  The list of function names contained in the
1632 value of `term-input-filter-functions' is called on the input before sending
1633 it.  The input is entered into the input history ring, if the value of variable
1634 term-input-filter returns non-nil when called on the input.
1635
1636 Any history reference may be expanded depending on the value of the variable
1637 `term-input-autoexpand'.  The list of function names contained in the value
1638 of `term-input-filter-functions' is called on the input before sending it.
1639 The input is entered into the input history ring, if the value of variable
1640 `term-input-filter' returns non-nil when called on the input.
1641
1642 If variable `term-eol-on-send' is non-nil, then point is moved to the
1643 end of line before sending the input.
1644
1645 The values of `term-get-old-input', `term-input-filter-functions', and
1646 `term-input-filter' are chosen according to the command interpreter running
1647 in the buffer.  E.g.,
1648
1649 If the interpreter is the csh,
1650     term-get-old-input is the default: take the current line, discard any
1651         initial string matching regexp term-prompt-regexp.
1652     term-input-filter-functions monitors input for \"cd\", \"pushd\", and
1653         \"popd\" commands. When it sees one, it cd's the buffer.
1654     term-input-filter is the default: returns T if the input isn't all white
1655         space.
1656
1657 If the term is Lucid Common Lisp, 
1658     term-get-old-input snarfs the sexp ending at point.
1659     term-input-filter-functions does nothing.
1660     term-input-filter returns NIL if the input matches input-filter-regexp,
1661         which matches (1) all whitespace (2) :a, :c, etc.
1662
1663 Similarly for Soar, Scheme, etc."
1664   (interactive)
1665   ;; Note that the input string does not include its terminal newline.
1666   (let ((proc (get-buffer-process (current-buffer))))
1667     (if (not proc) (error "Current buffer has no process")
1668       (let* ((pmark (process-mark proc))
1669              (pmark-val (marker-position pmark))
1670              (input-is-new (>= (point) pmark-val))
1671              (intxt (if input-is-new
1672                         (progn (if term-eol-on-send (end-of-line))
1673                                (buffer-substring pmark (point)))
1674                       (funcall term-get-old-input)))
1675              (input (if (not (eq term-input-autoexpand 'input))
1676                         ;; Just whatever's already there
1677                         intxt
1678                       ;; Expand and leave it visible in buffer
1679                       (term-replace-by-expanded-history t)
1680                       (buffer-substring pmark (point))))
1681              (history (if (not (eq term-input-autoexpand 'history))
1682                           input
1683                         ;; This is messy 'cos ultimately the original
1684                         ;; functions used do insertion, rather than return
1685                         ;; strings.  We have to expand, then insert back.
1686                         (term-replace-by-expanded-history t)
1687                         (let ((copy (buffer-substring pmark (point))))
1688                           (delete-region pmark (point))
1689                           (insert input)
1690                           copy))))
1691         (if (term-pager-enabled)
1692             (save-excursion
1693               (goto-char (process-mark proc))
1694               (setq term-pager-count (term-current-row))))
1695         (if (and (funcall term-input-filter history)
1696                  (or (null term-input-ignoredups)
1697                      (not (ring-p term-input-ring))
1698                      (ring-empty-p term-input-ring)
1699                      (not (string-equal (ring-ref term-input-ring 0)
1700                                         history))))
1701             (ring-insert term-input-ring history))
1702         (let ((functions term-input-filter-functions))
1703           (while functions
1704             (funcall (car functions) (concat input "\n"))
1705             (setq functions (cdr functions))))
1706         (setq term-input-ring-index nil)
1707
1708         ;; Update the markers before we send the input
1709         ;; in case we get output amidst sending the input.
1710         (set-marker term-last-input-start pmark)
1711         (set-marker term-last-input-end (point))
1712         (if input-is-new
1713             (progn
1714               ;; Set up to delete, because inferior should echo.
1715               (if (marker-buffer term-pending-delete-marker)
1716                   (delete-region term-pending-delete-marker pmark))
1717               (set-marker term-pending-delete-marker pmark-val)
1718               (set-marker (process-mark proc) (point))))
1719         (goto-char pmark)
1720         (funcall term-input-sender proc input)))))
1721
1722 (defun term-get-old-input-default ()
1723   "Default for term-get-old-input.
1724 Take the current line, and discard any initial text matching
1725 term-prompt-regexp."
1726   (save-excursion
1727     (beginning-of-line)
1728     (term-skip-prompt)
1729     (let ((beg (point)))
1730       (end-of-line)
1731       (buffer-substring beg (point)))))
1732
1733 (defun term-copy-old-input ()
1734   "Insert after prompt old input at point as new input to be edited.
1735 Calls `term-get-old-input' to get old input."
1736   (interactive)
1737   (let ((input (funcall term-get-old-input))
1738         (process (get-buffer-process (current-buffer))))
1739     (if (not process)
1740         (error "Current buffer has no process")
1741       (goto-char (process-mark process))
1742       (insert input))))
1743
1744 (defun term-skip-prompt ()
1745   "Skip past the text matching regexp term-prompt-regexp. 
1746 If this takes us past the end of the current line, don't skip at all."
1747   (let ((eol (save-excursion (end-of-line) (point))))
1748     (if (and (looking-at term-prompt-regexp)
1749              (<= (match-end 0) eol))
1750         (goto-char (match-end 0)))))
1751
1752
1753 (defun term-after-pmark-p ()
1754   "Is point after the process output marker?"
1755   ;; Since output could come into the buffer after we looked at the point
1756   ;; but before we looked at the process marker's value, we explicitly 
1757   ;; serialise. This is just because I don't know whether or not emacs
1758   ;; services input during execution of lisp commands.
1759   (let ((proc-pos (marker-position
1760                    (process-mark (get-buffer-process (current-buffer))))))
1761     (<= proc-pos (point))))
1762
1763 (defun term-simple-send (proc string)
1764   "Default function for sending to PROC input STRING.
1765 This just sends STRING plus a newline. To override this,
1766 set the hook TERM-INPUT-SENDER."
1767   (term-send-string proc string)
1768   (term-send-string proc "\n"))
1769
1770 (defun term-bol (arg)
1771   "Goes to the beginning of line, then skips past the prompt, if any.
1772 If a prefix argument is given (\\[universal-argument]), then no prompt skip 
1773 -- go straight to column 0.
1774
1775 The prompt skip is done by skipping text matching the regular expression
1776 term-prompt-regexp, a buffer local variable."
1777   (interactive "P")
1778   (beginning-of-line)
1779   (if (null arg) (term-skip-prompt)))
1780
1781 ;;; These two functions are for entering text you don't want echoed or
1782 ;;; saved -- typically passwords to ftp, telnet, or somesuch.
1783 ;;; Just enter m-x term-send-invisible and type in your line.
1784
1785 (defun term-read-noecho (prompt &optional stars)
1786   "Read a single line of text from user without echoing, and return it. 
1787 Prompt with argument PROMPT, a string.  Optional argument STARS causes
1788 input to be echoed with '*' characters on the prompt line.  Input ends with
1789 RET, LFD, or ESC.  DEL or C-h rubs out.  C-u kills line.  C-g aborts (if
1790 `inhibit-quit' is set because e.g. this function was called from a process
1791 filter and C-g is pressed, this function returns nil rather than a string).
1792
1793 Note that the keystrokes comprising the text can still be recovered
1794 \(temporarily) with \\[view-lossage].  This may be a security bug for some
1795 applications."
1796   (let ((ans "")
1797         (c 0)
1798         (echo-keystrokes 0)
1799         (cursor-in-echo-area t)
1800         (done nil))
1801     (while (not done)
1802       (if stars
1803           (message "%s%s" prompt (make-string (length ans) ?*))
1804         (message "%s" prompt))
1805       (setq c (read-char))
1806       (cond ((= c ?\C-g)
1807              ;; This function may get called from a process filter, where
1808              ;; inhibit-quit is set.  In later versions of emacs read-char
1809              ;; may clear quit-flag itself and return C-g.  That would make
1810              ;; it impossible to quit this loop in a simple way, so
1811              ;; re-enable it here (for backward-compatibility the check for
1812              ;; quit-flag below would still be necessary, so this seems
1813              ;; like the simplest way to do things).
1814              (setq quit-flag t
1815                    done t))
1816             ((or (= c ?\r) (= c ?\n) (= c ?\e))
1817              (setq done t))
1818             ((= c ?\C-u)
1819              (setq ans ""))
1820             ((and (/= c ?\b) (/= c ?\177))
1821              (setq ans (concat ans (char-to-string c))))
1822             ((> (length ans) 0)
1823              (setq ans (substring ans 0 -1)))))
1824     (if quit-flag
1825         ;; Emulate a true quit, except that we have to return a value.
1826         (prog1
1827             (setq quit-flag nil)
1828           (message "Quit")
1829           (beep t))
1830       (message "")
1831       ans)))
1832
1833 (defun term-send-invisible (str &optional proc)
1834   "Read a string without echoing.
1835 Then send it to the process running in the current buffer. A new-line
1836 is additionally sent. String is not saved on term input history list.
1837 Security bug: your string can still be temporarily recovered with
1838 \\[view-lossage]."
1839   (interactive "P") ; Defeat snooping via C-x esc
1840   (if (not (stringp str))
1841       (setq str (term-read-noecho "Non-echoed text: " t)))
1842   (if (not proc)
1843       (setq proc (get-buffer-process (current-buffer))))
1844   (if (not proc) (error "Current buffer has no process")
1845     (setq term-kill-echo-list (nconc term-kill-echo-list
1846                                      (cons str nil)))
1847     (term-send-string proc str)
1848     (term-send-string proc "\n")))
1849
1850 \f
1851 ;;; Low-level process communication
1852
1853 (defvar term-input-chunk-size 512
1854   "*Long inputs send to term processes are broken up into chunks of this size.
1855 If your process is choking on big inputs, try lowering the value.")
1856
1857 (defun term-send-string (proc str)
1858   "Send PROCESS the contents of STRING as input.
1859 This is equivalent to process-send-string, except that long input strings
1860 are broken up into chunks of size term-input-chunk-size. Processes
1861 are given a chance to output between chunks. This can help prevent processes
1862 from hanging when you send them long inputs on some OS's."
1863   (let* ((len (length str))
1864          (i (min len term-input-chunk-size)))
1865     (process-send-string proc (substring str 0 i))
1866     (while (< i len)
1867       (let ((next-i (+ i term-input-chunk-size)))
1868         (accept-process-output)
1869         (process-send-string proc (substring str i (min len next-i)))
1870         (setq i next-i)))))
1871
1872 (defun term-send-region (proc start end)
1873   "Sends to PROC the region delimited by START and END.
1874 This is a replacement for process-send-region that tries to keep
1875 your process from hanging on long inputs. See term-send-string."
1876   (term-send-string proc (buffer-substring start end)))
1877
1878 \f
1879 ;;; Random input hackage
1880
1881 (defun term-kill-output ()
1882   "Kill all output from interpreter since last input."
1883   (interactive)
1884   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
1885     (kill-region term-last-input-end pmark)
1886     (goto-char pmark)    
1887     (insert "*** output flushed ***\n")
1888     (set-marker pmark (point))))
1889
1890 (defun term-show-output ()
1891   "Display start of this batch of interpreter output at top of window.
1892 Sets mark to the value of point when this command is run."
1893   (interactive)
1894   (goto-char term-last-input-end)
1895   (backward-char)
1896   (beginning-of-line)
1897   (set-window-start (selected-window) (point))
1898   (end-of-line))
1899
1900 (defun term-interrupt-subjob ()
1901   "Interrupt the current subjob."
1902   (interactive)
1903   (interrupt-process nil term-ptyp))
1904
1905 (defun term-kill-subjob ()
1906   "Send kill signal to the current subjob."
1907   (interactive)
1908   (kill-process nil term-ptyp))
1909
1910 (defun term-quit-subjob ()
1911   "Send quit signal to the current subjob."
1912   (interactive)
1913   (quit-process nil term-ptyp))
1914
1915 (defun term-stop-subjob ()
1916   "Stop the current subjob.
1917 WARNING: if there is no current subjob, you can end up suspending
1918 the top-level process running in the buffer. If you accidentally do
1919 this, use \\[term-continue-subjob] to resume the process. (This
1920 is not a problem with most shells, since they ignore this signal.)"
1921   (interactive)
1922   (stop-process nil term-ptyp))
1923
1924 (defun term-continue-subjob ()
1925   "Send CONT signal to process buffer's process group.
1926 Useful if you accidentally suspend the top-level process."
1927   (interactive)
1928   (continue-process nil term-ptyp))
1929
1930 (defun term-kill-input ()
1931   "Kill all text from last stuff output by interpreter to point."
1932   (interactive)
1933   (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
1934          (p-pos (marker-position pmark)))
1935     (if (> (point) p-pos)
1936         (kill-region pmark (point)))))
1937
1938 (defun term-delchar-or-maybe-eof (arg)
1939   "Delete ARG characters forward, or send an EOF to process if at end of buffer."
1940   (interactive "p")
1941   (if (eobp)
1942       (process-send-eof)
1943       (delete-char arg)))
1944
1945 (defun term-send-eof ()
1946   "Send an EOF to the current buffer's process."
1947   (interactive)
1948   (process-send-eof))
1949
1950 (defun term-backward-matching-input (regexp arg)
1951   "Search backward through buffer for match for REGEXP.
1952 Matches are searched for on lines that match `term-prompt-regexp'.
1953 With prefix argument N, search for Nth previous match.
1954 If N is negative, find the next or Nth next match."
1955   (interactive (term-regexp-arg "Backward input matching (regexp): "))
1956   (let* ((re (concat term-prompt-regexp ".*" regexp))
1957          (pos (save-excursion (end-of-line (if (> arg 0) 0 1))
1958                               (if (re-search-backward re nil t arg)
1959                                   (point)))))
1960     (if (null pos)
1961         (progn (message "Not found")
1962                (ding))
1963       (goto-char pos)
1964       (term-bol nil))))
1965
1966 (defun term-forward-matching-input (regexp arg)
1967   "Search forward through buffer for match for REGEXP.
1968 Matches are searched for on lines that match `term-prompt-regexp'.
1969 With prefix argument N, search for Nth following match.
1970 If N is negative, find the previous or Nth previous match."
1971   (interactive (term-regexp-arg "Forward input matching (regexp): "))
1972   (term-backward-matching-input regexp (- arg)))
1973
1974
1975 (defun term-next-prompt (n)
1976   "Move to end of Nth next prompt in the buffer.
1977 See `term-prompt-regexp'."
1978   (interactive "p")
1979   (let ((paragraph-start term-prompt-regexp))
1980     (end-of-line (if (> n 0) 1 0))
1981     (forward-paragraph n)
1982     (term-skip-prompt)))
1983
1984 (defun term-previous-prompt (n)
1985   "Move to end of Nth previous prompt in the buffer.
1986 See `term-prompt-regexp'."
1987   (interactive "p")
1988   (term-next-prompt (- n)))
1989 \f
1990 ;;; Support for source-file processing commands.
1991 ;;;============================================================================
1992 ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
1993 ;;; commands that process files of source text (e.g. loading or compiling
1994 ;;; files). So the corresponding process-in-a-buffer modes have commands
1995 ;;; for doing this (e.g., lisp-load-file). The functions below are useful
1996 ;;; for defining these commands.
1997 ;;;
1998 ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
1999 ;;; and Soar, in that they don't know anything about file extensions.
2000 ;;; So the compile/load interface gets the wrong default occasionally.
2001 ;;; The load-file/compile-file default mechanism could be smarter -- it
2002 ;;; doesn't know about the relationship between filename extensions and
2003 ;;; whether the file is source or executable. If you compile foo.lisp
2004 ;;; with compile-file, then the next load-file should use foo.bin for
2005 ;;; the default, not foo.lisp. This is tricky to do right, particularly
2006 ;;; because the extension for executable files varies so much (.o, .bin,
2007 ;;; .lbin, .mo, .vo, .ao, ...).
2008
2009
2010 ;;; TERM-SOURCE-DEFAULT -- determines defaults for source-file processing
2011 ;;; commands.
2012 ;;;
2013 ;;; TERM-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
2014 ;;; want to save the buffer before issuing any process requests to the command
2015 ;;; interpreter.
2016 ;;;
2017 ;;; TERM-GET-SOURCE -- used by the source-file processing commands to prompt
2018 ;;; for the file to process.
2019
2020 ;;; (TERM-SOURCE-DEFAULT previous-dir/file source-modes)
2021 ;;;============================================================================
2022 ;;; This function computes the defaults for the load-file and compile-file
2023 ;;; commands for tea, soar, cmulisp, and cmuscheme modes. 
2024 ;;; 
2025 ;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last 
2026 ;;; source-file processing command. NIL if there hasn't been one yet.
2027 ;;; - SOURCE-MODES is a list used to determine what buffers contain source
2028 ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
2029 ;;; Typically, (lisp-mode) or (scheme-mode).
2030 ;;; 
2031 ;;; If the command is given while the cursor is inside a string, *and*
2032 ;;; the string is an existing filename, *and* the filename is not a directory,
2033 ;;; then the string is taken as default. This allows you to just position
2034 ;;; your cursor over a string that's a filename and have it taken as default.
2035 ;;;
2036 ;;; If the command is given in a file buffer whose major mode is in
2037 ;;; SOURCE-MODES, then the filename is the default file, and the
2038 ;;; file's directory is the default directory.
2039 ;;; 
2040 ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
2041 ;;; then the default directory & file are what was used in the last source-file
2042 ;;; processing command (i.e., PREVIOUS-DIR/FILE).  If this is the first time
2043 ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
2044 ;;; is the cwd, with no default file. (\"no default file\" = nil)
2045 ;;; 
2046 ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
2047 ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
2048 ;;; for Soar programs, etc.
2049 ;;; 
2050 ;;; The function returns a pair: (default-directory . default-file).
2051
2052 (defun term-source-default (previous-dir/file source-modes)
2053   (cond ((and buffer-file-name (memq major-mode source-modes))
2054          (cons (file-name-directory    buffer-file-name)
2055                (file-name-nondirectory buffer-file-name)))
2056         (previous-dir/file)
2057         (t
2058          (cons default-directory nil))))
2059
2060
2061 ;;; (TERM-CHECK-SOURCE fname)
2062 ;;;============================================================================
2063 ;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
2064 ;;; process-in-a-buffer modes), this function can be called on the filename.
2065 ;;; If the file is loaded into a buffer, and the buffer is modified, the user
2066 ;;; is queried to see if he wants to save the buffer before proceeding with
2067 ;;; the load or compile.
2068
2069 (defun term-check-source (fname)
2070   (let ((buff (get-file-buffer fname)))
2071     (if (and buff
2072              (buffer-modified-p buff)
2073              (y-or-n-p (format "Save buffer %s first? "
2074                                (buffer-name buff))))
2075         ;; save BUFF.
2076         (let ((old-buffer (current-buffer)))
2077           (set-buffer buff)
2078           (save-buffer)
2079           (set-buffer old-buffer)))))
2080
2081
2082 ;;; (TERM-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
2083 ;;;============================================================================
2084 ;;; TERM-GET-SOURCE is used to prompt for filenames in command-interpreter
2085 ;;; commands that process source files (like loading or compiling a file).
2086 ;;; It prompts for the filename, provides a default, if there is one,
2087 ;;; and returns the result filename.
2088 ;;; 
2089 ;;; See TERM-SOURCE-DEFAULT for more on determining defaults.
2090 ;;; 
2091 ;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
2092 ;;; from the last source processing command.  SOURCE-MODES is a list of major
2093 ;;; modes used to determine what file buffers contain source files.  (These
2094 ;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
2095 ;;; then the filename reader will only accept a file that exists.
2096 ;;; 
2097 ;;; A typical use:
2098 ;;; (interactive (term-get-source "Compile file: " prev-lisp-dir/file
2099 ;;;                                 '(lisp-mode) t))
2100
2101 ;;; This is pretty stupid about strings. It decides we're in a string
2102 ;;; if there's a quote on both sides of point on the current line.
2103 (defun term-extract-string ()
2104   "Returns string around POINT that starts the current line or nil." 
2105   (save-excursion
2106     (let* ((point (point))
2107            (bol (progn (beginning-of-line) (point)))
2108            (eol (progn (end-of-line) (point)))
2109            (start (progn (goto-char point) 
2110                          (and (search-backward "\"" bol t) 
2111                               (1+ (point)))))
2112            (end (progn (goto-char point)
2113                        (and (search-forward "\"" eol t)
2114                             (1- (point))))))
2115       (and start end
2116            (buffer-substring start end)))))
2117
2118 (defun term-get-source (prompt prev-dir/file source-modes mustmatch-p)
2119   (let* ((def (term-source-default prev-dir/file source-modes))
2120          (stringfile (term-extract-string))
2121          (sfile-p (and stringfile
2122                        (condition-case ()
2123                            (file-exists-p stringfile)
2124                          (error nil))
2125                        (not (file-directory-p stringfile))))
2126          (defdir  (if sfile-p (file-name-directory stringfile)
2127                       (car def)))
2128          (deffile (if sfile-p (file-name-nondirectory stringfile)
2129                       (cdr def)))
2130          (ans (read-file-name (if deffile (format "%s(default %s) "
2131                                                   prompt    deffile)
2132                                   prompt)
2133                               defdir
2134                               (concat defdir deffile)
2135                               mustmatch-p)))
2136     (list (expand-file-name (substitute-in-file-name ans)))))
2137
2138 ;;; I am somewhat divided on this string-default feature. It seems
2139 ;;; to violate the principle-of-least-astonishment, in that it makes
2140 ;;; the default harder to predict, so you actually have to look and see
2141 ;;; what the default really is before choosing it. This can trip you up.
2142 ;;; On the other hand, it can be useful, I guess. I would appreciate feedback
2143 ;;; on this.
2144 ;;;     -Olin
2145
2146 \f
2147 ;;; Simple process query facility.
2148 ;;; ===========================================================================
2149 ;;; This function is for commands that want to send a query to the process
2150 ;;; and show the response to the user. For example, a command to get the
2151 ;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
2152 ;;; to an inferior Common Lisp process.
2153 ;;; 
2154 ;;; This simple facility just sends strings to the inferior process and pops
2155 ;;; up a window for the process buffer so you can see what the process
2156 ;;; responds with.  We don't do anything fancy like try to intercept what the
2157 ;;; process responds with and put it in a pop-up window or on the message
2158 ;;; line. We just display the buffer. Low tech. Simple. Works good.
2159
2160 ;;; Send to the inferior process PROC the string STR. Pop-up but do not select
2161 ;;; a window for the inferior process so that its response can be seen.
2162 (defun term-proc-query (proc str)
2163   (let* ((proc-buf (process-buffer proc))
2164          (proc-mark (process-mark proc)))
2165     (display-buffer proc-buf)
2166     (set-buffer proc-buf) ; but it's not the selected *window*
2167     (let ((proc-win (get-buffer-window proc-buf))
2168           (proc-pt (marker-position proc-mark)))
2169       (term-send-string proc str) ; send the query
2170       (accept-process-output proc)  ; wait for some output
2171       ;; Try to position the proc window so you can see the answer.
2172       ;; This is bogus code. If you delete the (sit-for 0), it breaks.
2173       ;; I don't know why. Wizards invited to improve it.
2174       (if (not (pos-visible-in-window-p proc-pt proc-win))
2175           (let ((opoint (window-point proc-win)))
2176             (set-window-point proc-win proc-mark) (sit-for 0)
2177             (if (not (pos-visible-in-window-p opoint proc-win))
2178                 (push-mark opoint)
2179                 (set-window-point proc-win opoint)))))))
2180 \f
2181 ;;; Returns the current column in the current screen line.
2182 ;;; Note: (current-column) yields column in buffer line.
2183
2184 (defun term-horizontal-column ()
2185   (- (term-current-column) (term-start-line-column)))
2186
2187 ;; Calls either vertical-motion or buffer-vertical-motion
2188 (defmacro term-vertical-motion (count)
2189   (list 'funcall 'term-vertical-motion count))
2190
2191 ;; An emulation of vertical-motion that is independent of having a window.
2192 ;; Instead, it uses the term-width variable as the logical window width.
2193
2194 (defun buffer-vertical-motion (count)
2195   (cond ((= count 0)
2196          (move-to-column (* term-width (/ (current-column) term-width)))
2197          0)
2198         ((> count 0)
2199          (let ((H)
2200                (todo (+ count (/ (current-column) term-width))))
2201            (end-of-line)
2202            ;; The loop iterates over buffer lines;
2203            ;; H is the number of screen lines in the current line, i.e.
2204            ;; the ceiling of dividing the buffer line width by term-width.
2205            (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2206                                            term-width)
2207                                         1))
2208                            todo)
2209                        (not (eobp)))
2210              (setq todo (- todo H))
2211              (forward-char) ;; Move past the ?\n
2212              (end-of-line)) ;; and on to the end of the next line.
2213            (if (and (>= todo H) (> todo 0))
2214                (+ (- count todo) H -1) ;; Hit end of buffer.
2215              (move-to-column (* todo term-width))
2216              count)))
2217         (t ;; (< count 0) ;; Similar algorithm, but for upward motion.
2218          (let ((H)
2219                (todo (- count)))
2220            (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2221                                            term-width)
2222                                         1))
2223                            todo)
2224                        (progn (beginning-of-line)
2225                               (not (bobp))))
2226              (setq todo (- todo H))
2227              (backward-char)) ;; Move to end of previous line.
2228            (if (and (>= todo H) (> todo 0))
2229                (+ count todo (- 1 H)) ;; Hit beginning of buffer.
2230              (move-to-column (* (- H todo 1) term-width))
2231              count)))))
2232
2233 ;;; The term-start-line-column variable is used as a cache.
2234 (defun term-start-line-column ()
2235   (cond (term-start-line-column)
2236         ((let ((save-pos (point)))
2237            (term-vertical-motion 0)
2238            (setq term-start-line-column (current-column))
2239            (goto-char save-pos)
2240            term-start-line-column))))
2241
2242 ;;; Same as (current-column), but uses term-current-column as a cache.
2243 (defun term-current-column ()
2244   (cond (term-current-column)
2245         ((setq term-current-column (current-column)))))
2246
2247 ;;; Move DELTA column right (or left if delta < 0).
2248
2249 (defun term-move-columns (delta)
2250   (setq term-current-column (+ (term-current-column) delta))
2251   (move-to-column term-current-column t))
2252
2253 ;; Insert COUNT copies of CHAR in the default face.
2254 (defun term-insert-char (char count)
2255   (let ((old-point (point)))
2256     (insert-char char count)
2257     (put-text-property old-point (point) 'face 'default)))
2258
2259 (defun term-current-row ()
2260   (cond (term-current-row)
2261         ((setq term-current-row
2262                (save-restriction
2263                  (save-excursion
2264                    (narrow-to-region term-home-marker (point-max))
2265                    (- (term-vertical-motion -9999))))))))
2266
2267 (defun term-adjust-current-row-cache (delta)
2268   (if term-current-row
2269       (setq term-current-row (+ term-current-row delta))))
2270
2271 (defun term-terminal-pos ()
2272   (save-excursion ;    save-restriction
2273     (let ((save-col (term-current-column))
2274           x y)
2275       (term-vertical-motion 0)
2276       (setq x (- save-col (current-column)))
2277       (setq y (term-vertical-motion term-height))
2278       (cons x y))))
2279
2280 ;;; Terminal emulation
2281 ;;; This is the standard process filter for term buffers.
2282 ;;; It emulates (most of the features of) a VT100/ANSI-style terminal.
2283
2284 (defun term-emulate-terminal (proc str)
2285   (let* ((previous-buffer (current-buffer))
2286          (i 0) char funny count save-point save-marker old-point temp win
2287          (selected (selected-window))
2288          (str-length (length str)))
2289     (unwind-protect
2290         (progn
2291           (set-buffer (process-buffer proc))
2292
2293           (if (marker-buffer term-pending-delete-marker)
2294               (progn
2295                 ;; Delete text following term-pending-delete-marker.
2296                 (delete-region term-pending-delete-marker (process-mark proc))
2297                 (set-marker term-pending-delete-marker nil)))
2298
2299           (if (eq (window-buffer) (current-buffer))
2300               (progn
2301                 (setq term-vertical-motion (symbol-function 'vertical-motion))
2302                 (term-check-size proc))
2303             (setq term-vertical-motion
2304                   (symbol-function 'buffer-vertical-motion)))
2305
2306           (setq save-marker (copy-marker (process-mark proc)))
2307
2308           (if (/= (point) (process-mark proc))
2309               (progn (setq save-point (point-marker))
2310                      (goto-char (process-mark proc))))
2311
2312           (save-restriction
2313             ;; If the buffer is in line mode, and there is a partial
2314             ;; input line, save the line (by narrowing to leave it
2315             ;; outside the restriction ) until we're done with output.
2316             (if (and (> (point-max) (process-mark proc))
2317                      (term-in-line-mode))
2318                 (narrow-to-region (point-min) (process-mark proc)))
2319             
2320             (if term-log-buffer
2321                 (princ str term-log-buffer))
2322             (cond ((eq term-terminal-state 4) ;; Have saved pending output.
2323                    (setq str (concat term-terminal-parameter str))
2324                    (setq term-terminal-parameter nil)
2325                    (setq str-length (length str))
2326                    (setq term-terminal-state 0)))
2327             
2328             (while (< i str-length)
2329               (setq char (aref str i))
2330               (cond ((< term-terminal-state 2)
2331                      ;; Look for prefix of regular chars
2332                      (setq funny
2333                            (string-match "[\r\n\000\007\033\t\b\032\016\017]"
2334                                          str i))
2335                      (if (not funny) (setq funny str-length))
2336                      (cond ((> funny i)
2337                             (cond ((eq term-terminal-state 1)
2338                                    (term-move-columns 1)
2339                                    (setq term-terminal-state 0)))
2340                             (setq count (- funny i))
2341                             (setq temp (- (+ (term-horizontal-column) count)
2342                                           term-width))
2343                             (cond ((<= temp 0)) ;; All count chars fit in line.
2344                                   ((> count temp) ;; Some chars fit.
2345                                    ;; This iteration, handle only what fits.
2346                                    (setq count (- count temp))
2347                                    (setq funny (+ count i)))
2348                                   ((or (not (or term-pager-count
2349                                                 term-scroll-with-delete))
2350                                        (>  (term-handle-scroll 1) 0))
2351                                    (term-adjust-current-row-cache 1)
2352                                    (setq count (min count term-width))
2353                                    (setq funny (+ count i))
2354                                    (setq term-start-line-column
2355                                          term-current-column))
2356                                   (t ;; Doing PAGER processing.
2357                                    (setq count 0 funny i)
2358                                    (setq term-current-column nil)
2359                                    (setq term-start-line-column nil)))
2360                             (setq old-point (point))
2361                             ;; In the common case that we're at the end of
2362                             ;; the buffer, we can save a little work.
2363                             (cond ((/= (point) (point-max))
2364                                    (if term-insert-mode
2365                                        ;; Inserting spaces, then deleting them,
2366                                        ;; then inserting the actual text is
2367                                        ;; inefficient, but it is simple, and
2368                                        ;; the actual overhead is miniscule.
2369                                        (term-insert-spaces count))
2370                                    (term-move-columns count)
2371                                    (delete-region old-point (point)))
2372         (t (setq term-current-column (+ (term-current-column) count))))
2373                             (insert (substring str i funny))
2374                             (put-text-property old-point (point)
2375                                                'face term-current-face)
2376                             ;; If the last char was written in last column,
2377                             ;; back up one column, but remember we did so.
2378                             ;; Thus we emulate xterm/vt100-style line-wrapping.
2379                             (cond ((eq temp 0)
2380                                    (term-move-columns -1)
2381                                    (setq term-terminal-state 1)))
2382                             (setq i (1- funny)))
2383                            ((and (setq term-terminal-state 0)
2384                             (eq char ?\^I)) ; TAB
2385                             ;; FIXME:  Does not handle line wrap!
2386                             (setq count (term-current-column))
2387                             (setq count (+ count 8 (- (mod count 8))))
2388                             (if (< (move-to-column count nil) count)
2389                                 (term-insert-char char 1))
2390                             (setq term-current-column count))
2391                            ((eq char ?\r)
2392                             ;; Optimize CRLF at end of buffer:
2393                             (cond ((and (< (setq temp (1+ i)) str-length)
2394                                         (eq (aref str temp) ?\n)
2395                                         (= (point) (point-max))
2396                                         (not (or term-pager-count
2397                                                  term-kill-echo-list
2398                                                  term-scroll-with-delete)))
2399                                    (insert ?\n)
2400                                    (term-adjust-current-row-cache 1)
2401                                    (setq term-start-line-column 0)
2402                                    (setq term-current-column 0)
2403                                    (setq i temp))
2404                                   (t ;; Not followed by LF or can't optimize:
2405                                    (term-vertical-motion 0)
2406                                    (setq term-current-column term-start-line-column))))
2407                            ((eq char ?\n)
2408                             (if (not (and term-kill-echo-list
2409                                           (term-check-kill-echo-list)))
2410                                 (term-down 1 t)))
2411                            ((eq char ?\b)
2412                             (term-move-columns -1))
2413                            ((eq char ?\033) ; Escape
2414                             (setq term-terminal-state 2))
2415                            ((eq char ?\0)) ; NUL: Do nothing
2416                            ((eq char ?\016)) ; Shift Out - ignored
2417                            ((eq char ?\017)) ; Shift In - ignored
2418                            ((eq char ?\^G)
2419                             (beep t)) ; Bell
2420                            ((eq char ?\032)
2421                             (let ((end (string-match "\n" str i)))
2422                               (if end
2423                                   (progn (funcall term-command-hook
2424                                                   (substring str (1+ i) (1- end)))
2425                                          (setq i end))
2426                                 (setq term-terminal-parameter
2427                                       (substring str i))
2428                                 (setq term-terminal-state 4)
2429                                 (setq i str-length))))
2430                            (t ; insert char FIXME: Should never happen
2431                             (term-move-columns 1)
2432                             (backward-delete-char 1)
2433                             (insert char))))
2434                     ((eq term-terminal-state 2) ; Seen Esc
2435                      (cond ((eq char ?\133) ;; ?\133 = ?[
2436                             (make-local-variable 'term-terminal-parameter)
2437                             (make-local-variable 'term-terminal-previous-parameter)
2438                             (make-local-variable 'term-terminal-previous-previous-parameter)   ;; ~~~
2439                             (setq term-terminal-parameter 0)
2440                             (setq term-terminal-previous-parameter -1)
2441                             (setq term-terminal-previous-previous-parameter -1)  ;; ~~~
2442                             (setq term-terminal-state 3))
2443                            ((eq char ?D) ;; scroll forward
2444                             (term-handle-deferred-scroll)
2445                             (term-down 1 t)
2446                             (setq term-terminal-state 0))
2447                            ((eq char ?M) ;; scroll reversed
2448                             (term-insert-lines 1)
2449                             (setq term-terminal-state 0))
2450                            ((eq char ?7) ;; Save cursor
2451                             (term-handle-deferred-scroll)
2452                             (setq term-saved-cursor
2453                                   (cons (term-current-row)
2454                                         (term-horizontal-column)))
2455                             (setq term-terminal-state 0))
2456                            ((eq char ?8) ;; Restore cursor
2457                             (if term-saved-cursor
2458                                 (term-goto (car term-saved-cursor)
2459                                            (cdr term-saved-cursor)))
2460                             (setq term-terminal-state 0))
2461                            ((setq term-terminal-state 0))))
2462                     ((eq term-terminal-state 3) ; Seen Esc [
2463                      (cond ((and (>= char ?0) (<= char ?9))
2464                             (setq term-terminal-parameter
2465                                   (+ (* 10 term-terminal-parameter) (- char ?0))))
2466                            ((eq char ?\073 ) ; ?;
2467                             ;; ~~~ we need three params for ANSI colors
2468                             (setq term-terminal-previous-previous-parameter
2469                                          term-terminal-previous-parameter) ;; ~~~
2470                             (setq term-terminal-previous-parameter
2471                                   term-terminal-parameter)
2472                             (setq term-terminal-parameter 0))
2473                            ((eq char ??)) ; Ignore ? 
2474                            (t
2475                             (term-handle-ansi-escape proc char)
2476                             (setq term-terminal-state 0)))))
2477               (if (term-handling-pager)
2478                   ;; Finish stuff to get ready to handle PAGER.
2479                   (progn
2480                     (if (> (% (current-column) term-width) 0)
2481                         (setq term-terminal-parameter
2482                               (substring str i))
2483                       ;; We're at column 0.  Goto end of buffer; to compensate,
2484                       ;; prepend a ?\r for later.  This looks more consistent.
2485                       (if (zerop i)
2486                           (setq term-terminal-parameter
2487                                 (concat "\r" (substring str i)))
2488                         (setq term-terminal-parameter (substring str (1- i)))
2489                         (aset term-terminal-parameter 0 ?\r))
2490                       (goto-char (point-max)))
2491                     (setq term-terminal-state 4)
2492                     (make-local-variable 'term-pager-old-filter)
2493                     (setq term-pager-old-filter (process-filter proc))
2494                     (set-process-filter proc term-pager-filter)
2495                     (setq i str-length)))
2496               (setq i (1+ i))))
2497
2498           (if (>= (term-current-row) term-height)
2499               (term-handle-deferred-scroll))
2500
2501           (set-marker (process-mark proc) (point))
2502           (if save-point
2503               (progn (goto-char save-point)
2504                      (set-marker save-point nil)))
2505
2506           ;; Check for a pending filename-and-line number to display.
2507           ;; We do this before scrolling, because we might create a new window.
2508           (if (and term-pending-frame
2509                    (eq (window-buffer selected) (current-buffer)))
2510               (progn (term-display-line (car term-pending-frame)
2511                                         (cdr term-pending-frame))
2512                      (setq term-pending-frame nil)
2513                  ;; We have created a new window, so check the window size.
2514                      (term-check-size proc)))
2515
2516           ;; Scroll each window displaying the buffer but (by default)
2517           ;; only if the point matches the process-mark we started with.
2518           (setq win selected)
2519           (while (progn
2520                    (setq win (next-window win nil t))
2521                    (if (eq (window-buffer win) (process-buffer proc))
2522                        (let ((scroll term-scroll-to-bottom-on-output))
2523                          (select-window win)
2524                          (if (or (= (point) save-marker)
2525                                  (eq scroll t) (eq scroll 'all)
2526                                  ;; Maybe user wants point to jump to the end.
2527                                  (and (eq selected win)
2528                                       (or (eq scroll 'this) (not save-point)))
2529                                  (and (eq scroll 'others)
2530                                       (not (eq selected win))))
2531                              (progn
2532                                (goto-char term-home-marker)
2533                                (recenter 0)
2534                                (goto-char (process-mark proc))
2535                                (if (not (pos-visible-in-window-p (point) win))
2536                                    (recenter -1))))
2537                          ;; Optionally scroll so that the text
2538                          ;; ends at the bottom of the window.
2539                          (if (and term-scroll-show-maximum-output
2540                                   (>= (point) (process-mark proc)))
2541                              (save-excursion
2542                                (goto-char (point-max))
2543                                (recenter -1)))))
2544                    (not (eq win selected))))
2545
2546           (set-marker save-marker nil))
2547       ;; unwind-protect cleanup-forms follow:
2548       (set-buffer previous-buffer)
2549       (select-window selected))))
2550
2551 (defun term-handle-deferred-scroll ()
2552   (let ((count (- (term-current-row) term-height)))
2553     (if (>= count 0)
2554         (save-excursion
2555           (goto-char term-home-marker)
2556           (term-vertical-motion (1+ count))
2557           (set-marker term-home-marker (point))
2558           (setq term-current-row (1- term-height))))))
2559
2560 ;;; Handle a character assuming (eq terminal-state 2) -
2561 ;;; i.e. we have previously seen Escape followed by ?[.
2562
2563 (defun term-handle-ansi-escape (proc char)
2564   (cond
2565    ((eq char ?H) ; cursor motion
2566     (if (<= term-terminal-parameter 0)
2567         (setq term-terminal-parameter 1))
2568     (if (<= term-terminal-previous-parameter 0)
2569         (setq term-terminal-previous-parameter 1))
2570     (if (> term-terminal-previous-parameter term-height)
2571         (setq term-terminal-previous-parameter term-height))
2572     (if (> term-terminal-parameter term-width)
2573         (setq term-terminal-parameter term-width))
2574     (term-goto
2575      (1- term-terminal-previous-parameter)
2576      (1- term-terminal-parameter)))
2577    ;; \E[A - cursor up
2578    ((eq char ?A)
2579     (term-handle-deferred-scroll)
2580     (term-down (- (max 1 term-terminal-parameter)) t))
2581    ;; \E[B - cursor down
2582    ((eq char ?B)
2583     (term-down (max 1 term-terminal-parameter) t))
2584    ;; \E[C - cursor right
2585    ((eq char ?C)
2586     (term-move-columns (max 1 term-terminal-parameter)))
2587    ;; \E[D - cursor left
2588    ((eq char ?D)
2589     (term-move-columns (- (max 1 term-terminal-parameter))))
2590    ;; \E[J - clear to end of screen
2591    ((eq char ?J)
2592     (term-erase-in-display term-terminal-parameter))
2593    ;; \E[K - clear to end of line
2594    ((eq char ?K)
2595     (term-erase-in-line term-terminal-parameter))
2596    ;; \E[L - insert lines
2597    ((eq char ?L)
2598     (term-insert-lines (max 1 term-terminal-parameter)))
2599    ;; \E[M - delete lines
2600    ((eq char ?M)
2601     (term-delete-lines (max 1 term-terminal-parameter)))
2602    ;; \E[P - delete chars
2603    ((eq char ?P)
2604     (term-delete-chars (max 1 term-terminal-parameter)))
2605    ;; \E[@ - insert spaces
2606    ((eq char ?@)
2607     (term-insert-spaces (max 1 term-terminal-parameter)))
2608    ;; \E[?h - DEC Private Mode Set
2609    ((eq char ?h)
2610     (cond ((eq term-terminal-parameter 4)
2611            (setq term-insert-mode t))
2612           ((eq term-terminal-parameter 47)
2613            (term-switch-to-alternate-sub-buffer t))))
2614    ;; \E[?l - DEC Private Mode Reset
2615    ((eq char ?l)
2616     (cond ((eq term-terminal-parameter 4)
2617            (setq term-insert-mode nil))
2618           ((eq term-terminal-parameter 47)
2619            (term-switch-to-alternate-sub-buffer nil))))
2620
2621    ;; \E[m - Set/reset standard mode
2622    ;; ~~~ and handle ansi colours; added isb isb@loa.neuro.biologie.fu-berlin.de ~~~
2623    ;; we can have up to 3 params: attributes 0-8; fg color 30 - 37; bg color 40 - 47; 
2624    ;; since this makes up to 8*8*4 = 256 faces we allocate the faces upon first request.
2625    ;; (this may be ugly lisp code but as an 'everything but a lisp' hacker i am just happy to get things going)
2626    ;; The face stuff seems to be quite slow. If you use a lot of faces (eg start BitchX) things slow down
2627    ;; On a pentium 133 this code is at 3s - 5s per redraw. On 5 - 10 times faster machine it may be usable 
2628    ;; Tools like color-ls and similar, which dont use backgrounds colors excessively, on the other
2629    ;; hand are usable on a p133
2630
2631    ((eq char ?m)
2632     (make-local-variable 'term-fg)
2633     (make-local-variable 'term-bg)
2634     (make-local-variable 'term-attr)
2635     (make-local-variable 'term-fi)
2636     (make-local-variable 'tps)
2637     (make-local-variable 'ttp)
2638     (make-local-variable 'iii)
2639
2640     (setq term-fg term-current-fg)
2641     (setq term-bg term-current-bg)
2642     (setq term-fi term-current-fi)
2643     (setq term-attr -1)
2644     (setq ttp 0)
2645     (setq iii 0)
2646     (setq term-f-change nil)
2647
2648     (setq tps [ term-terminal-parameter term-terminal-previous-parameter
2649                                         term-terminal-previous-previous-parameter ])
2650     (while (< iii 3)
2651       (setq ttp (eval (aref tps iii)))
2652       (cond ((and (>= ttp 0) (<= ttp 8))
2653              ;; ~~~ attr found 
2654              (setq term-attr ttp)
2655              )
2656             ((and (>= ttp 30) (<= ttp 37))
2657              ;; found fg. color
2658              (setq term-fg (- ttp 30 ))
2659              )
2660             ((and (>= ttp 40) (<= ttp 47))
2661              ;; found bg. color
2662              (setq term-bg (- ttp 40 ))
2663              ))
2664       (setq iii (+ iii 1))
2665       )
2666
2667     ;; process attr. We support bold, underlined, and inversed. Not sup: blink, concealed 
2668     (cond ((eq term-attr 0) ;; ^[[x;0m resets only font attribute whereas  ^[[0m or ^[[m resets everything
2669            (setq term-fi 0)    ;; Is this right? Just a guess
2670            (cond ((and (eq term-terminal-previous-parameter -1) (eq term-terminal-previous-previous-parameter -1))
2671                   (setq term-fg 0)
2672                   (setq term-bg 7)
2673                   (setq term-f-change t)
2674                   ; (message "%s %d %d %d" "0m found" term-attr term-terminal-previous-parameter 
2675                   ;        term-terminal-previous-previous-parameter)
2676                   ;  ))
2677            )))
2678           ((eq term-attr 1) ;; bold -> take bold font
2679            (setq term-fi 1)
2680            )
2681           ((eq term-attr 4) ;; underscore
2682            (setq term-fi 2)
2683            )
2684           ((eq term-attr 5) ;; blink
2685            )
2686           ((eq term-attr 7) ;; reverse
2687            (setq term-fi 3)
2688            )
2689           ((eq term-attr 8) ;; concealed ??
2690            )
2691           )
2692     (cond ((or term-f-change
2693                (not (eq term-current-fi term-fi)) 
2694                (not (eq term-current-bg term-bg)) 
2695                (not (eq term-current-fg term-fg))
2696                )
2697            ;; found font change, test if if we already created this font
2698            (cond ((eq (aref term-fnts-tmp-faces (+ (* term-fi 8 8)  (* term-bg 8) term-fg)) nil)
2699                   ;; new face, create it
2700                   (setq bxt-tmp-face (make-symbol (concat "zzterm-" (int-to-string term-fi) "-" 
2701                                                 (int-to-string term-fg) "-"     (int-to-string term-bg) "-face")))
2702
2703                   ;; (message "%s %s %d %d %d  -- %d" "Setting current faces" (symbol-name bxt-tmp-face) 
2704                   ;;        term-fi term-fg term-bg
2705                   ;;        (+ (* term-fi 8 8)  (* term-bg 8) term-fg) bxt-tmp-face)
2706
2707                   (make-empty-face bxt-tmp-face 
2708                                    "Do not mess with this, use term-color-spec-face instead" nil)  ;;t)
2709                   (copy-face (aref term-fnts (+ term-fg (* term-fi 8))) bxt-tmp-face)
2710                   (set-face-parent bxt-tmp-face (aref term-fnts (+ term-fg (* term-fi 8)))) 
2711                   (set-face-background bxt-tmp-face (face-background (aref term-fnts (+ term-bg (* 3 8)))))
2712                   ;; clobber background pixmap, unless we're setting background color to "default"
2713                   (if (not (= term-bg 7))
2714                       (set-face-background-pixmap bxt-tmp-face (make-image-instance [nothing])))
2715
2716                   ;; (set-face-doc-string bxt-tmp-face "Do not mess with this.")
2717                   (aset term-fnts-tmp-faces  (+ (* term-fi 8 8)  (* term-bg 8) term-fg) bxt-tmp-face)
2718
2719                   ))
2720            (setq term-current-face (aref term-fnts-tmp-faces (+ (* term-fi 8 8)  (* term-bg 8) term-fg))) 
2721            ))
2722     (setq term-current-fi term-fi)
2723     (setq term-current-fg term-fg)
2724     (setq term-current-bg term-bg)
2725     ;; (message " ")
2726
2727     )
2728 ;; ~~~ ansi colors done
2729
2730 ;   ((eq char ?m)
2731 ;    (cond ((eq term-terminal-parameter 7) 
2732 ;          (setq term-current-face 'highlight))
2733 ;         ((eq term-terminal-parameter 4)
2734 ;          (setq term-current-face 'term-underline-face))
2735 ;         ((eq term-terminal-parameter 1)
2736 ;          (setq term-current-face 'bold))
2737 ;         (t (setq term-current-face 'default)))))
2738
2739    ;; \E[6n - Report cursor position
2740    ((eq char ?n)
2741     (term-handle-deferred-scroll)
2742     (process-send-string proc
2743                          (format "\e[%s;%sR"
2744                                  (1+ (term-current-row))
2745                                  (1+ (term-horizontal-column)))))
2746    ;; \E[r - Set scrolling region
2747    ((eq char ?r)
2748     (term-scroll-region
2749      (1- term-terminal-previous-parameter)
2750      term-terminal-parameter))
2751    (t)))
2752
2753 (defun term-scroll-region (top bottom)
2754   "Set scrolling region.
2755 TOP is the top-most line (inclusive) of the new scrolling region,
2756 while BOTTOM is the line following the new scrolling region (e.g. exclusive).
2757 The top-most line is line 0."
2758   (setq term-scroll-start
2759         (if (or (< top 0) (>= top term-height))
2760             0
2761           top))
2762   (setq term-scroll-end
2763         (if (or (<= bottom term-scroll-start) (> bottom term-height))
2764             term-height
2765           bottom))
2766   (setq term-scroll-with-delete
2767         (or (term-using-alternate-sub-buffer)
2768             (not (and (= term-scroll-start 0)
2769                       (= term-scroll-end term-height))))))
2770
2771 (defun term-switch-to-alternate-sub-buffer (set)
2772   ;; If asked to switch to (from) the alternate sub-buffer, and already (not)
2773   ;; using it, do nothing.  This test is needed for some programs (including
2774   ;; emacs) that emit the ti termcap string twice, for unknown reason.
2775   (term-handle-deferred-scroll)
2776   (if (eq set (not (term-using-alternate-sub-buffer)))
2777       (let ((row (term-current-row))
2778             (col (term-horizontal-column)))
2779         (cond (set
2780                (goto-char (point-max))
2781                (if (not (eq (preceding-char) ?\n))
2782                    (term-insert-char ?\n 1))
2783                (setq term-scroll-with-delete t)
2784                (setq term-saved-home-marker (copy-marker term-home-marker))
2785                (set-marker term-home-marker (point)))
2786               (t
2787                (setq term-scroll-with-delete
2788                      (not (and (= term-scroll-start 0)
2789                                (= term-scroll-end term-height))))
2790                (set-marker term-home-marker term-saved-home-marker)
2791                (set-marker term-saved-home-marker nil)
2792                (setq term-saved-home-marker nil)
2793                (goto-char term-home-marker)))
2794         (setq term-current-column nil)
2795         (setq term-current-row 0)
2796         (term-goto row col))))
2797
2798 ;; Default value for the symbol term-command-hook.
2799
2800 (defun term-command-hook (string)
2801   (cond ((= (aref string 0) ?\032)
2802          ;; gdb (when invoked with -fullname) prints:
2803          ;; \032\032FULLFILENAME:LINENUMBER:CHARPOS:BEG_OR_MIDDLE:PC\n
2804          (let* ((first-colon (string-match ":" string 1))
2805                 (second-colon
2806                  (string-match ":" string (1+ first-colon)))
2807                 (filename (substring string 1 first-colon))
2808                 (fileline (string-to-int
2809                            (substring string (1+ first-colon) second-colon))))
2810            (setq term-pending-frame (cons filename fileline))))
2811         ((= (aref string 0) ?/)
2812          ;; FIXME: If cd fails, should ignore, and not raise error.
2813          (cd (substring string 1)))
2814         ;; Allowing the inferior to call functions in emacs is
2815         ;; probably too big a security hole.
2816         ;; ((= (aref string 0) ?!)
2817         ;; (eval (car (read-from-string string 1))))
2818         (t)));; Otherwise ignore it
2819
2820 ;; Make sure the file named TRUE-FILE is in a buffer that appears on the screen
2821 ;; and that its line LINE is visible.
2822 ;; Put the overlay-arrow on the line LINE in that buffer.
2823 ;; This is mainly used by gdb.
2824
2825 (defun term-display-line (true-file line)
2826   (term-display-buffer-line (find-file-noselect true-file) line))
2827
2828 (defun term-display-buffer-line (buffer line)
2829   (let* ((window (display-buffer buffer t))
2830          (pos))
2831     (save-excursion
2832       (set-buffer buffer)
2833       (save-restriction
2834         (widen)
2835         (goto-line line)
2836         (setq pos (point))
2837         (setq overlay-arrow-string "=>")
2838         (or overlay-arrow-position
2839             (setq overlay-arrow-position (make-marker)))
2840         (set-marker overlay-arrow-position (point) (current-buffer)))
2841       (cond ((or (< pos (point-min)) (> pos (point-max)))
2842              (widen)
2843              (goto-char pos))))
2844     (set-window-point window overlay-arrow-position)))
2845
2846 ;;; The buffer-local marker term-home-marker defines the "home position"
2847 ;;; (in terms of cursor motion).  However, we move the term-home-marker
2848 ;;; "down" as needed so that is no more that a window-full above (point-max).
2849
2850 (defun term-goto-home ()
2851   (term-handle-deferred-scroll)
2852   (goto-char term-home-marker)
2853   (setq term-current-row 0)
2854   (setq term-current-column (current-column))
2855   (setq term-start-line-column term-current-column))
2856
2857 (defun term-goto (row col)
2858   (term-handle-deferred-scroll)
2859   (cond ((and term-current-row (>= row term-current-row))
2860          ;; I assume this is a worthwhile optimization.
2861          (term-vertical-motion 0)
2862          (setq term-current-column term-start-line-column)
2863          (setq row (- row term-current-row)))
2864         (t
2865          (term-goto-home)))
2866   (term-down row)
2867   (term-move-columns col))
2868
2869 ; The page is full, so enter "pager" mode, and wait for input.
2870
2871 (defun term-process-pager ()
2872   (if (not term-pager-break-map)
2873       (let* ((map (make-keymap))
2874              (i 0) tmp)
2875 ;       (while (< i 128)
2876 ;         (define-key map (make-string 1 i) 'term-send-raw)
2877 ;         (setq i (1+ i)))
2878         (define-key map "\e"
2879           (lookup-key (current-global-map) "\e"))
2880         (define-key map "\C-x"
2881           (lookup-key (current-global-map) "\C-x"))
2882         (define-key map "\C-u"
2883           (lookup-key (current-global-map) "\C-u"))
2884         (define-key map " " 'term-pager-page)
2885         (define-key map "\r" 'term-pager-line)
2886         (define-key map "?" 'term-pager-help)
2887         (define-key map "h" 'term-pager-help)
2888         (define-key map "b" 'term-pager-back-page)
2889         (define-key map "\177" 'term-pager-back-line)
2890         (define-key map "q" 'term-pager-discard)
2891         (define-key map "D" 'term-pager-disable)
2892         (define-key map "<" 'term-pager-bob)
2893         (define-key map ">" 'term-pager-eob)
2894
2895         ;; Add menu bar.
2896         (term-if-emacs19
2897          (term-ifnot-xemacs
2898           (define-key map [menu-bar terminal] term-terminal-menu)
2899           (define-key map [menu-bar signals] term-signals-menu)
2900           (setq tmp (make-sparse-keymap "More pages?"))
2901           (define-key tmp [help] '("Help" . term-pager-help))
2902           (define-key tmp [disable]
2903             '("Disable paging" . term-fake-pager-disable))
2904           (define-key tmp [discard]
2905             '("Discard remaining output" . term-pager-discard))
2906           (define-key tmp [eob] '("Goto to end" . term-pager-eob))
2907           (define-key tmp [bob] '("Goto to beginning" . term-pager-bob))
2908           (define-key tmp [line] '("1 line forwards" . term-pager-line))
2909           (define-key tmp [bline] '("1 line backwards" . term-pager-back-line))
2910           (define-key tmp [back] '("1 page backwards" . term-pager-back-page))
2911           (define-key tmp [page] '("1 page forwards" . term-pager-page))
2912           (define-key map [menu-bar page] (cons "More pages?" tmp))
2913           ))
2914
2915         (setq term-pager-break-map map)))
2916 ;  (let ((process (get-buffer-process (current-buffer))))
2917 ;    (stop-process process))  
2918   (setq term-pager-old-local-map (current-local-map))
2919   (use-local-map term-pager-break-map)
2920   (make-local-variable 'term-old-mode-line-format)
2921   (setq term-old-mode-line-format mode-line-format)
2922   (setq mode-line-format
2923         (list "--  **MORE**  "
2924               mode-line-buffer-identification
2925               " [Type ? for help] "
2926               "%-"))
2927   (force-mode-line-update))
2928
2929 (defun term-pager-line (lines)
2930   (interactive "p")
2931   (let* ((moved (vertical-motion (1+ lines)))
2932          (deficit (- lines moved)))
2933     (if (> moved lines)
2934         (backward-char))
2935     (cond ((<= deficit 0) ;; OK, had enough in the buffer for request.
2936            (recenter (1- term-height)))
2937           ((term-pager-continue deficit)))))
2938
2939 (defun term-pager-page (arg)
2940   "Proceed past the **MORE** break, allowing the next page of output to appear"
2941   (interactive "p")
2942   (term-pager-line (* arg term-height)))
2943
2944 ; Pager mode command to go to beginning of buffer
2945 (defun term-pager-bob ()
2946   (interactive)
2947   (goto-char (point-min))
2948   (if (= (vertical-motion term-height) term-height)
2949       (backward-char))
2950   (recenter (1- term-height)))
2951
2952 ; pager mode command to go to end of buffer
2953 (defun term-pager-eob ()
2954   (interactive)
2955   (goto-char term-home-marker)
2956   (recenter 0)
2957   (goto-char (process-mark (get-buffer-process (current-buffer)))))
2958
2959 (defun term-pager-back-line (lines)
2960   (interactive "p")
2961   (vertical-motion (- 1 lines))
2962   (if (not (bobp))
2963       (backward-char)
2964     (beep)
2965     ;; Move cursor to end of window.
2966     (vertical-motion term-height)
2967     (backward-char))
2968   (recenter (1- term-height)))
2969
2970 (defun term-pager-back-page (arg)
2971   (interactive "p")
2972   (term-pager-back-line (* arg term-height)))
2973
2974 (defun term-pager-discard ()
2975   (interactive)
2976   (setq term-terminal-parameter "")
2977   (interrupt-process nil t)
2978   (term-pager-continue term-height))
2979
2980 ; Disable pager processing.
2981 ; Only callable while in pager mode.  (Contrast term-disable-pager.)
2982 (defun term-pager-disable ()
2983   (interactive)
2984   (if (term-handling-pager)
2985       (term-pager-continue nil)
2986     (setq term-pager-count nil))
2987   (term-update-mode-line))
2988     
2989 ; Enable pager processing.
2990 (defun term-pager-enable ()
2991   (interactive)
2992   (or (term-pager-enabled)
2993       (setq term-pager-count 0)) ;; Or maybe set to (term-current-row) ??
2994   (term-update-mode-line))
2995
2996 (defun term-pager-toggle ()
2997   (interactive)
2998   (if (term-pager-enabled) (term-pager-disable) (term-pager-enable)))
2999
3000 (term-ifnot-xemacs
3001  (defalias 'term-fake-pager-enable 'term-pager-toggle)
3002  (defalias 'term-fake-pager-disable 'term-pager-toggle)
3003  (put 'term-char-mode 'menu-enable '(term-in-line-mode))
3004  (put 'term-line-mode 'menu-enable '(term-in-char-mode))
3005  (put 'term-fake-pager-enable 'menu-enable '(not term-pager-count))
3006  (put 'term-fake-pager-disable 'menu-enable 'term-pager-count))
3007
3008 (defun term-pager-help ()
3009   "Provide help on commands available in a terminal-emulator **MORE** break"
3010   (interactive)
3011   (message "Terminal-emulator pager break help...")
3012   (sit-for 0)
3013   (with-electric-help
3014     (function (lambda ()
3015                 (princ (substitute-command-keys
3016 "\\<term-pager-break-map>\
3017 Terminal-emulator MORE break.\n\
3018 Type one of the following keys:\n\n\
3019 \\[term-pager-page]\t\tMove forward one page.\n\
3020 \\[term-pager-line]\t\tMove forward one line.\n\
3021 \\[universal-argument] N \\[term-pager-page]\tMove N pages forward.\n\
3022 \\[universal-argument] N \\[term-pager-line]\tMove N lines forward.\n\
3023 \\[universal-argument] N \\[term-pager-back-line]\tMove N lines back.\n\
3024 \\[universal-argument] N \\[term-pager-back-page]\t\tMove N pages back.\n\
3025 \\[term-pager-bob]\t\tMove to the beginning of the buffer.\n\
3026 \\[term-pager-eob]\t\tMove to the end of the buffer.\n\
3027 \\[term-pager-discard]\t\tKill pending output and kill process.\n\
3028 \\[term-pager-disable]\t\tDisable PAGER handling.\n\n\
3029 \\{term-pager-break-map}\n\
3030 Any other key is passed through to the program
3031 running under the terminal emulator and disables pager processing until
3032 all pending output has been dealt with."))
3033                 nil))))
3034
3035 (defun term-pager-continue (new-count)
3036   (let ((process (get-buffer-process (current-buffer))))
3037     (use-local-map term-pager-old-local-map)
3038     (setq term-pager-old-local-map nil)
3039     (setq mode-line-format term-old-mode-line-format)
3040     (force-mode-line-update)
3041     (setq term-pager-count new-count)
3042     (set-process-filter process term-pager-old-filter)
3043     (funcall term-pager-old-filter process "")
3044     (continue-process process)))
3045
3046 ;; Make sure there are DOWN blank lines below the current one.
3047 ;; Return 0 if we're unable (because of PAGER handling), else return DOWN.
3048
3049 (defun term-handle-scroll (down)
3050   (let ((scroll-needed
3051          (- (+ (term-current-row) down 1) term-scroll-end)))
3052     (if (> scroll-needed 0)
3053         (let ((save-point (copy-marker (point))) (save-top))
3054           (goto-char term-home-marker)
3055           (cond (term-scroll-with-delete
3056                  ;; delete scroll-needed lines at term-scroll-start
3057                  (term-vertical-motion term-scroll-start)
3058                  (setq save-top (point))
3059                  (term-vertical-motion scroll-needed)
3060                  (delete-region save-top (point))
3061                  (goto-char save-point)
3062                  (term-vertical-motion down)
3063                  (term-adjust-current-row-cache (- scroll-needed))
3064                  (setq term-current-column nil)
3065                  (term-insert-char ?\n scroll-needed))
3066                 ((and (numberp term-pager-count)
3067                       (< (setq term-pager-count (- term-pager-count down))
3068                          0))
3069                  (setq down 0)
3070                  (term-process-pager))
3071                 (t
3072                  (term-adjust-current-row-cache (- scroll-needed))
3073                  (term-vertical-motion scroll-needed)
3074                  (set-marker term-home-marker (point))))
3075           (goto-char save-point)
3076           (set-marker save-point nil))))
3077   down)
3078
3079 (defun term-down (down &optional check-for-scroll)
3080   "Move down DOWN screen lines vertically."
3081   (let ((start-column (term-horizontal-column)))
3082     (if (and check-for-scroll (or term-scroll-with-delete term-pager-count))
3083         (setq down (term-handle-scroll down)))
3084     (term-adjust-current-row-cache down)
3085     (if (/= (point) (point-max))
3086         (setq down (- down (term-vertical-motion down))))
3087     ;; Extend buffer with extra blank lines if needed.
3088     (cond ((> down 0)
3089            (term-insert-char ?\n down)
3090            (setq term-current-column 0)
3091            (setq term-start-line-column 0))
3092           (t
3093            (setq term-current-column nil)
3094            (setq term-start-line-column (current-column))))
3095     (if start-column
3096         (term-move-columns start-column))))
3097
3098 ;; Assuming point is at the beginning of a screen line,
3099 ;; if the line above point wraps around, add a ?\n to undo the wrapping.
3100 ;; FIXME:  Probably should be called more than it is.
3101 (defun term-unwrap-line ()
3102   (if (not (bolp)) (insert-before-markers ?\n)))
3103
3104 (defun term-erase-in-line (kind)
3105   (if (> kind 1) ;; erase left of point
3106       (let ((cols (term-horizontal-column)) (saved-point (point)))
3107         (term-vertical-motion 0)
3108         (delete-region (point) saved-point)
3109         (term-insert-char ?\n cols)))
3110   (if (not (eq kind 1)) ;; erase right of point
3111       (let ((saved-point (point))
3112             (wrapped (and (zerop (term-horizontal-column))
3113                           (not (zerop (term-current-column))))))
3114         (term-vertical-motion 1)
3115         (delete-region saved-point (point))
3116         ;; wrapped is true if we're at the beginning of screen line,
3117         ;; but not a buffer line.  If we delete the current screen line
3118         ;; that will make the previous line no longer wrap, and (because
3119         ;; of the way emacs display works) point will be at the end of
3120         ;; the previous screen line rather then the beginning of the
3121         ;; current one. To avoid that, we make sure that current line
3122         ;; contain a space, to force the previous line to continue to wrap.
3123         ;; We could do this always, but it seems preferable to not add the
3124         ;; extra space when wrapped is false.
3125         (if wrapped
3126             (insert ? ))
3127         (insert ?\n)
3128         (put-text-property saved-point (point) 'face 'default)
3129         (goto-char saved-point))))
3130
3131 (defun term-erase-in-display (kind)
3132   "Erases (that is blanks out) part of the window.
3133 If KIND is 0, erase from (point) to (point-max);
3134 if KIND is 1, erase from home to point; else erase from home to point-max.
3135 Should only be called when point is at the start of a screen line."
3136   (term-handle-deferred-scroll)
3137   (cond ((eq term-terminal-parameter 0)
3138          (delete-region (point) (point-max))
3139          (term-unwrap-line))
3140         ((let ((row (term-current-row))
3141               (col (term-horizontal-column))
3142               (start-region term-home-marker)
3143               (end-region (if (eq kind 1) (point) (point-max))))
3144            (delete-region start-region end-region)
3145            (term-unwrap-line)
3146            (if (eq kind 1)
3147                (term-insert-char ?\n row))
3148            (setq term-current-column nil)
3149            (setq term-current-row nil)
3150            (term-goto row col)))))
3151
3152 (defun term-delete-chars (count)
3153   (let ((save-point (point)))
3154     (term-vertical-motion 1)
3155     (term-unwrap-line)
3156     (goto-char save-point)
3157     (move-to-column (+ (term-current-column) count) t)
3158     (delete-region save-point (point))))
3159
3160 ;;; Insert COUNT spaces after point, but do not change any of
3161 ;;; following screen lines.  Hence we may have to delete characters
3162 ;;; at the end of this screen line to make room.
3163
3164 (defun term-insert-spaces (count)
3165   (let ((save-point (point)) (save-eol))
3166     (term-vertical-motion 1)
3167     (if (bolp)
3168         (backward-char))
3169     (setq save-eol (point))
3170     (move-to-column (+ (term-start-line-column) (- term-width count)) t)
3171     (if (> save-eol (point))
3172         (delete-region (point) save-eol))
3173     (goto-char save-point)
3174     (term-insert-char ?  count)
3175     (goto-char save-point)))
3176
3177 (defun term-delete-lines (lines)
3178   (let ((start (point))
3179         (save-current-column term-current-column)
3180         (save-start-line-column term-start-line-column)
3181         (save-current-row (term-current-row)))
3182     (term-down lines)
3183     (delete-region start (point))
3184     (term-down (- term-scroll-end save-current-row lines))
3185     (term-insert-char ?\n lines)
3186     (setq term-current-column save-current-column)
3187     (setq term-start-line-column save-start-line-column)
3188     (setq term-current-row save-current-row)
3189     (goto-char start)))
3190
3191 (defun term-insert-lines (lines)
3192   (let ((start (point))
3193         (start-deleted)
3194         (save-current-column term-current-column)
3195         (save-start-line-column term-start-line-column)
3196         (save-current-row (term-current-row)))
3197     (term-down (- term-scroll-end save-current-row lines))
3198     (setq start-deleted (point))
3199     (term-down lines)
3200     (delete-region start-deleted (point))
3201     (goto-char start)
3202     (setq term-current-column save-current-column)
3203     (setq term-start-line-column save-start-line-column)
3204     (setq term-current-row save-current-row)
3205     (term-insert-char ?\n lines)
3206     (goto-char start)))
3207 \f
3208 (defun term-set-output-log (name)
3209   "Record raw inferior process output in a buffer."
3210   (interactive (list (if term-log-buffer
3211                          nil
3212                        (read-buffer "Record output in buffer: "
3213                                     (format "%s output-log"
3214                                             (buffer-name (current-buffer)))
3215                                     nil))))
3216   (if (or (null name) (equal name ""))
3217       (progn (setq term-log-buffer nil)
3218              (message "Output logging off."))
3219     (if (get-buffer name)
3220         nil
3221       (save-excursion
3222         (set-buffer (get-buffer-create name))
3223         (fundamental-mode)
3224         (buffer-disable-undo (current-buffer))
3225         (erase-buffer)))
3226     (setq term-log-buffer (get-buffer name))
3227     (message "Recording terminal emulator output into buffer \"%s\""
3228              (buffer-name term-log-buffer))))
3229
3230 (defun term-stop-photo ()
3231   "Discontinue raw inferior process logging."
3232   (interactive)
3233   (term-set-output-log nil))
3234
3235 (defun term-show-maximum-output ()
3236   "Put the end of the buffer at the bottom of the window."
3237   (interactive)
3238   (goto-char (point-max))
3239   (recenter -1))
3240 \f
3241 ;;; Do the user's customisation...
3242
3243 (defvar term-load-hook nil
3244   "This hook is run when term is loaded in.
3245 This is a good place to put keybindings.")
3246         
3247 (run-hooks 'term-load-hook)
3248
3249 \f
3250 ;;; Filename/command/history completion in a buffer
3251 ;;; ===========================================================================
3252 ;;; Useful completion functions, courtesy of the Ergo group.
3253
3254 ;;; Six commands:
3255 ;;; term-dynamic-complete               Complete or expand command, filename,
3256 ;;;                                     history at point.
3257 ;;; term-dynamic-complete-filename      Complete filename at point.
3258 ;;; term-dynamic-list-filename-completions List completions in help buffer.
3259 ;;; term-replace-by-expanded-filename   Expand and complete filename at point;
3260 ;;;                                     replace with expanded/completed name.
3261 ;;; term-dynamic-simple-complete        Complete stub given candidates.
3262
3263 ;;; These are not installed in the term-mode keymap. But they are
3264 ;;; available for people who want them. Shell-mode installs them:
3265 ;;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
3266 ;;; (define-key shell-mode-map "\M-?"
3267 ;;;             'term-dynamic-list-filename-completions)))
3268 ;;;
3269 ;;; Commands like this are fine things to put in load hooks if you
3270 ;;; want them present in specific modes.
3271
3272 (defvar term-completion-autolist nil
3273   "*If non-nil, automatically list possibilities on partial completion.
3274 This mirrors the optional behavior of tcsh.")
3275
3276 (defvar term-completion-addsuffix t
3277   "*If non-nil, add a `/' to completed directories, ` ' to file names.
3278 If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
3279 DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact
3280 completion.  This mirrors the optional behavior of tcsh.")
3281
3282 (defvar term-completion-recexact nil
3283   "*If non-nil, use shortest completion if characters cannot be added.
3284 This mirrors the optional behavior of tcsh.
3285
3286 A non-nil value is useful if `term-completion-autolist' is non-nil too.")
3287
3288 (defvar term-completion-fignore nil
3289   "*List of suffixes to be disregarded during file completion.
3290 This mirrors the optional behavior of bash and tcsh.
3291
3292 Note that this applies to `term-dynamic-complete-filename' only.")
3293
3294 (defvar term-file-name-prefix ""
3295   "Prefix prepended to absolute file names taken from process input.
3296 This is used by term's and shell's completion functions, and by shell's
3297 directory tracking functions.")
3298
3299
3300 (defun term-directory (directory)
3301   ;; Return expanded DIRECTORY, with `term-file-name-prefix' if absolute.
3302   (expand-file-name (if (file-name-absolute-p directory)
3303                         (concat term-file-name-prefix directory)
3304                       directory)))
3305
3306
3307 (defun term-word (word-chars)
3308   "Return the word of WORD-CHARS at point, or nil if non is found.
3309 Word constituents are considered to be those in WORD-CHARS, which is like the
3310 inside of a \"[...]\" (see `skip-chars-forward')."
3311   (save-excursion
3312     (let ((limit (point))
3313           (word (concat "[" word-chars "]"))
3314           (non-word (concat "[^" word-chars "]")))
3315       (if (re-search-backward non-word nil 'move)
3316           (forward-char 1))
3317       ;; Anchor the search forwards.
3318       (if (or (eolp) (looking-at non-word))
3319           nil
3320         (re-search-forward (concat word "+") limit)
3321         (buffer-substring (match-beginning 0) (match-end 0))))))
3322
3323
3324 (defun term-match-partial-filename ()
3325   "Return the filename at point, or nil if non is found.
3326 Environment variables are substituted.  See `term-word'."
3327   (let ((filename (term-word "~/A-Za-z0-9+@:_.$#,={}-")))
3328     (and filename (substitute-in-file-name filename))))
3329
3330
3331 (defun term-dynamic-complete ()
3332   "Dynamically perform completion at point.
3333 Calls the functions in `term-dynamic-complete-functions' to perform
3334 completion until a function returns non-nil, at which point completion is
3335 assumed to have occurred."
3336   (interactive)
3337   (let ((functions term-dynamic-complete-functions))
3338     (while (and functions (null (funcall (car functions))))
3339       (setq functions (cdr functions)))))
3340
3341
3342 (defun term-dynamic-complete-filename ()
3343   "Dynamically complete the filename at point.
3344 Completes if after a filename.  See `term-match-partial-filename' and
3345 `term-dynamic-complete-as-filename'.
3346 This function is similar to `term-replace-by-expanded-filename', except that
3347 it won't change parts of the filename already entered in the buffer; it just
3348 adds completion characters to the end of the filename.  A completions listing
3349 may be shown in a help buffer if completion is ambiguous.
3350
3351 Completion is dependent on the value of `term-completion-addsuffix',
3352 `term-completion-recexact' and `term-completion-fignore', and the timing of
3353 completions listing is dependent on the value of `term-completion-autolist'.
3354
3355 Returns t if successful."
3356   (interactive)
3357   (if (term-match-partial-filename)
3358       (prog2 (or (eq (selected-window) (minibuffer-window))
3359                  (message "Completing file name..."))
3360           (term-dynamic-complete-as-filename))))
3361
3362 (defun term-dynamic-complete-as-filename ()
3363   "Dynamically complete at point as a filename.
3364 See `term-dynamic-complete-filename'.  Returns t if successful."
3365   (let* ((completion-ignore-case nil)
3366          (completion-ignored-extensions term-completion-fignore)
3367          (success t)
3368          (dirsuffix (cond ((not term-completion-addsuffix) "")
3369                           ((not (consp term-completion-addsuffix)) "/")
3370                           (t (car term-completion-addsuffix))))
3371          (filesuffix (cond ((not term-completion-addsuffix) "")
3372                            ((not (consp term-completion-addsuffix)) " ")
3373                            (t (cdr term-completion-addsuffix))))         
3374          (filename (or (term-match-partial-filename) ""))
3375          (pathdir (file-name-directory filename))
3376          (pathnondir (file-name-nondirectory filename))
3377          (directory (if pathdir (term-directory pathdir) default-directory))
3378          (completion (file-name-completion pathnondir directory))
3379          (mini-flag (eq (selected-window) (minibuffer-window))))
3380     (cond ((null completion)
3381            (message "No completions of %s" filename)
3382            (setq success nil))
3383           ((eq completion t)            ; Means already completed "file".
3384            (if term-completion-addsuffix (insert " "))
3385            (or mini-flag (message "Sole completion")))
3386           ((string-equal completion "") ; Means completion on "directory/".
3387            (term-dynamic-list-filename-completions))
3388           (t                            ; Completion string returned.
3389            (let ((file (concat (file-name-as-directory directory) completion)))
3390              (insert (substring (directory-file-name completion)
3391                                 (length pathnondir)))
3392              (cond ((symbolp (file-name-completion completion directory))
3393                     ;; We inserted a unique completion.
3394                     (insert (if (file-directory-p file) dirsuffix filesuffix))
3395                     (or mini-flag (message "Completed")))
3396                    ((and term-completion-recexact term-completion-addsuffix
3397                          (string-equal pathnondir completion)
3398                          (file-exists-p file))
3399                     ;; It's not unique, but user wants shortest match.
3400                     (insert (if (file-directory-p file) dirsuffix filesuffix))
3401                     (or mini-flag (message "Completed shortest")))
3402                    ((or term-completion-autolist
3403                         (string-equal pathnondir completion))
3404                     ;; It's not unique, list possible completions.
3405                     (term-dynamic-list-filename-completions))
3406                    (t
3407                     (or mini-flag (message "Partially completed")))))))
3408     success))
3409
3410
3411 (defun term-replace-by-expanded-filename ()
3412   "Dynamically expand and complete the filename at point.
3413 Replace the filename with an expanded, canonicalised and completed replacement.
3414 \"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
3415 with the corresponding directories.  \"Canonicalised\" means `..'  and `.' are
3416 removed, and the filename is made absolute instead of relative.  For expansion
3417 see `expand-file-name' and `substitute-in-file-name'.  For completion see
3418 `term-dynamic-complete-filename'."
3419   (interactive)
3420   (replace-match (expand-file-name (term-match-partial-filename)) t t)
3421   (term-dynamic-complete-filename))
3422
3423
3424 (defun term-dynamic-simple-complete (stub candidates)
3425   "Dynamically complete STUB from CANDIDATES list.
3426 This function inserts completion characters at point by completing STUB from
3427 the strings in CANDIDATES.  A completions listing may be shown in a help buffer
3428 if completion is ambiguous.
3429
3430 Returns nil if no completion was inserted.
3431 Returns `sole' if completed with the only completion match.
3432 Returns `shortest' if completed with the shortest of the completion matches.
3433 Returns `partial' if completed as far as possible with the completion matches.
3434 Returns `listed' if a completion listing was shown.
3435
3436 See also `term-dynamic-complete-filename'."
3437   (let* ((completion-ignore-case nil)
3438          (candidates (mapcar (function (lambda (x) (list x))) candidates))
3439          (completions (all-completions stub candidates)))
3440     (cond ((null completions)
3441            (message "No completions of %s" stub)
3442            nil)
3443           ((= 1 (length completions))   ; Gotcha!
3444            (let ((completion (car completions)))
3445              (if (string-equal completion stub)
3446                  (message "Sole completion")
3447                (insert (substring completion (length stub)))
3448                (message "Completed"))
3449              (if term-completion-addsuffix (insert " "))
3450              'sole))
3451           (t                            ; There's no unique completion.
3452            (let ((completion (try-completion stub candidates)))
3453              ;; Insert the longest substring.
3454              (insert (substring completion (length stub)))
3455              (cond ((and term-completion-recexact term-completion-addsuffix
3456                          (string-equal stub completion)
3457                          (member completion completions))
3458                     ;; It's not unique, but user wants shortest match.
3459                     (insert " ")
3460                     (message "Completed shortest")
3461                     'shortest)
3462                    ((or term-completion-autolist
3463                         (string-equal stub completion))
3464                     ;; It's not unique, list possible completions.
3465                     (term-dynamic-list-completions completions)
3466                     'listed)
3467                    (t
3468                     (message "Partially completed")
3469                     'partial)))))))
3470
3471
3472 (defun term-dynamic-list-filename-completions ()
3473   "List in help buffer possible completions of the filename at point."
3474   (interactive)
3475   (let* ((completion-ignore-case nil)
3476          (filename (or (term-match-partial-filename) ""))
3477          (pathdir (file-name-directory filename))
3478          (pathnondir (file-name-nondirectory filename))
3479          (directory (if pathdir (term-directory pathdir) default-directory))
3480          (completions (file-name-all-completions pathnondir directory)))
3481     (if completions
3482         (term-dynamic-list-completions completions)
3483       (message "No completions of %s" filename))))
3484
3485
3486 (defun term-dynamic-list-completions (completions)
3487   "List in help buffer sorted COMPLETIONS.
3488 Typing SPC flushes the help buffer."
3489   (let ((conf (current-window-configuration)))
3490     (with-output-to-temp-buffer "*Completions*"
3491       (display-completion-list (sort completions 'string-lessp)))
3492     (message "Hit space to flush")
3493     (let (key first)
3494       (if (save-excursion
3495             (set-buffer (get-buffer "*Completions*"))
3496             (setq key (read-key-sequence nil)
3497                   first (aref key 0))
3498             (and (consp first)
3499                  (eq (window-buffer (posn-window (event-start first)))
3500                      (get-buffer "*Completions*"))
3501                  (eq (key-binding key) 'mouse-choose-completion)))
3502           ;; If the user does mouse-choose-completion with the mouse,
3503           ;; execute the command, then delete the completion window.
3504           (progn
3505             (mouse-choose-completion first)
3506             (set-window-configuration conf))
3507         (if (eq first ?\ )
3508             (set-window-configuration conf)
3509           (term-ifnot-xemacs
3510            (setq unread-command-events (listify-key-sequence key)))
3511           (term-if-xemacs
3512            (setq unread-command-events (append key nil))))))))
3513 \f
3514 ;;; Converting process modes to use term mode
3515 ;;; ===========================================================================
3516 ;;; Renaming variables
3517 ;;; Most of the work is renaming variables and functions. These are the common
3518 ;;; ones:
3519 ;;; Local variables:
3520 ;;;     last-input-start        term-last-input-start
3521 ;;;     last-input-end          term-last-input-end
3522 ;;;     shell-prompt-pattern    term-prompt-regexp
3523 ;;;     shell-set-directory-error-hook <no equivalent>
3524 ;;; Miscellaneous:
3525 ;;;     shell-set-directory     <unnecessary>
3526 ;;;     shell-mode-map          term-mode-map
3527 ;;; Commands:
3528 ;;;     shell-send-input        term-send-input
3529 ;;;     shell-send-eof          term-delchar-or-maybe-eof
3530 ;;;     kill-shell-input        term-kill-input
3531 ;;;     interrupt-shell-subjob  term-interrupt-subjob
3532 ;;;     stop-shell-subjob       term-stop-subjob
3533 ;;;     quit-shell-subjob       term-quit-subjob
3534 ;;;     kill-shell-subjob       term-kill-subjob
3535 ;;;     kill-output-from-shell  term-kill-output
3536 ;;;     show-output-from-shell  term-show-output
3537 ;;;     copy-last-shell-input   Use term-previous-input/term-next-input
3538 ;;;
3539 ;;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
3540 ;;; SHELL-DIRECTORY-TRACKER, the shell mode's term-input-filter-functions.
3541 ;;; Term mode does not provide functionality equivalent to
3542 ;;; shell-set-directory-error-hook; it is gone.
3543 ;;;
3544 ;;; term-last-input-start is provided for modes which want to munge
3545 ;;; the buffer after input is sent, perhaps because the inferior
3546 ;;; insists on echoing the input.  The LAST-INPUT-START variable in
3547 ;;; the old shell package was used to implement a history mechanism,
3548 ;;; but you should think twice before using term-last-input-start
3549 ;;; for this; the input history ring often does the job better.
3550 ;;; 
3551 ;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
3552 ;;; *not* create the term-mode local variables in your foo-mode function.
3553 ;;; This is not modular.  Instead, call term-mode, and let *it* create the
3554 ;;; necessary term-specific local variables. Then create the
3555 ;;; foo-mode-specific local variables in foo-mode.  Set the buffer's keymap to
3556 ;;; be foo-mode-map, and its mode to be foo-mode.  Set the term-mode hooks
3557 ;;; (term-{prompt-regexp, input-filter, input-filter-functions,
3558 ;;; get-old-input) that need to be different from the defaults.  Call
3559 ;;; foo-mode-hook, and you're done. Don't run the term-mode hook yourself;
3560 ;;; term-mode will take care of it. The following example, from shell.el,
3561 ;;; is typical:
3562 ;;; 
3563 ;;; (defvar shell-mode-map '())
3564 ;;; (cond ((not shell-mode-map)
3565 ;;;        (setq shell-mode-map (copy-keymap term-mode-map))
3566 ;;;        (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
3567 ;;;        (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
3568 ;;;        (define-key shell-mode-map "\t" 'term-dynamic-complete)
3569 ;;;        (define-key shell-mode-map "\M-?"
3570 ;;;          'term-dynamic-list-filename-completions)))
3571 ;;;
3572 ;;; (defun shell-mode ()
3573 ;;;   (interactive)
3574 ;;;   (term-mode)
3575 ;;;   (setq term-prompt-regexp shell-prompt-pattern)
3576 ;;;   (setq major-mode 'shell-mode)
3577 ;;;   (setq mode-name "Shell")
3578 ;;;   (use-local-map shell-mode-map)
3579 ;;;   (make-local-variable 'shell-directory-stack)
3580 ;;;   (setq shell-directory-stack nil)
3581 ;;;   (add-hook 'term-input-filter-functions 'shell-directory-tracker)
3582 ;;;   (run-hooks 'shell-mode-hook))
3583 ;;;
3584 ;;;
3585 ;;; Note that make-term is different from make-shell in that it
3586 ;;; doesn't have a default program argument. If you give make-shell
3587 ;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
3588 ;;; $ESHELL, $SHELL, or /bin/sh. If you give make-term a program argument
3589 ;;; of NIL, it barfs. Adjust your code accordingly...
3590 ;;;
3591 ;;; Completion for term-mode users
3592 ;;; 
3593 ;;; For modes that use term-mode, term-dynamic-complete-functions is the
3594 ;;; hook to add completion functions to.  Functions on this list should return
3595 ;;; non-nil if completion occurs (i.e., further completion should not occur).
3596 ;;; You could use term-dynamic-simple-complete to do the bulk of the
3597 ;;; completion job.
3598 \f
3599 (provide 'term)
3600
3601 ;;; term.el ends here