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