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