comparison lisp/eterm/term.el @ 0:376386a54a3c r19-14

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