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