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