Switch to recommended form of GPLv3 permissions notice.
[bpt/emacs.git] / lisp / term.el
1 ;;; term.el --- general command interpreter in a window stuff
2
3 ;; Copyright (C) 1988, 1990, 1992, 1994, 1995, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Per Bothner <per@bothner.com>
7 ;; Maintainer: Dan Nicolaescu <dann@ics.uci.edu>, Per Bothner <per@bothner.com>
8 ;; Based on comint mode written by: Olin Shivers <shivers@cs.cmu.edu>
9 ;; Keywords: processes
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Marck 13 2001
27 ;;; Fixes for CJK support by Yong Lu <lyongu@yahoo.com>.
28
29 ;;; Dir/Hostname tracking and ANSI colorization by
30 ;;; Marco Melgazzi <marco@techie.com>.
31
32 ;;; To see what I've modified and where it came from search for '-mm'
33
34 ;;; Commentary:
35
36 ;;; Speed considerations and a few caveats
37 ;;; --------------------------------------
38 ;;;
39 ;;; While the message passing and the colorization surely introduce some
40 ;;; overhead this has became so small that IMHO is surely outweighted by
41 ;;; the benefits you get but, as usual, YMMV
42 ;;;
43 ;;; Important caveat, when deciding the cursor/'grey keys' keycodes I had to
44 ;;; make a choice: on my Linux box this choice allows me to run all the
45 ;;; ncurses applications without problems but make these keys
46 ;;; uncomprehensible to all the cursesX programs. Your mileage may vary so
47 ;;; you may consider changing the default 'emulation'. Just search for this
48 ;;; piece of code and modify it as you like:
49 ;;;
50 ;;; ;; Which would be better: "\e[A" or "\eOA"? readline accepts either.
51 ;;; ;; For my configuration it's definitely better \eOA but YMMV. -mm
52 ;;; ;; For example: vi works with \eOA while elm wants \e[A ...
53 ;;; (defun term-send-up () (interactive) (term-send-raw-string "\eOA"))
54 ;;; (defun term-send-down () (interactive) (term-send-raw-string "\eOB"))
55 ;;; (defun term-send-right () (interactive) (term-send-raw-string "\eOC"))
56 ;;; (defun term-send-left () (interactive) (term-send-raw-string "\eOD"))
57 ;;;
58 ;;;
59 ;;; IMPORTANT: additions & changes
60 ;;; ------------------------------
61 ;;;
62 ;;; With this enhanced ansi-term.el you will get a reliable mechanism of
63 ;;; directory/username/host tracking: the only drawback is that you will
64 ;;; have to modify your shell start-up script. It's worth it, believe me :).
65 ;;;
66 ;;; When you rlogin/su/telnet and the account you access has a modified
67 ;;; startup script, you will be able to access the remote files as usual
68 ;;; with C-x C-f, if it's needed you will have to enter a password,
69 ;;; otherwise the file should get loaded straight away.
70 ;;;
71 ;;; This is useful even if you work only on one host: it often happens that,
72 ;;; for maintenance reasons, you have to edit files 'as root': before
73 ;;; patching term.el, I su-ed in a term.el buffer and used vi :), now I
74 ;;; simply do a C-x C-f and, via ange-ftp, the file is automatically loaded
75 ;;; 'as-root'. ( If you don't want to enter the root password every time you
76 ;;; can put it in your .netrc: note that this is -not- advisable if you're
77 ;;; connected to the internet or if somebody else works on your workstation!)
78 ;;;
79 ;;; If you use wu-ftpd you can use some of its features to avoid root ftp
80 ;;; access to the rest of the world: just put in /etc/ftphosts something like
81 ;;;
82 ;;; # Local access
83 ;;; allow root 127.0.0.1
84 ;;;
85 ;;; # By default nobody can't do anything
86 ;;; deny root *
87 ;;;
88 ;;;
89 ;;; ----------------------------------------
90 ;;;
91 ;;; If, instead of 'term', you call 'ansi-term', you get multiple term
92 ;;; buffers, after every new call ansi-term opens a new *ansi-term*<xx> window,
93 ;;; where <xx> is, as usual, a number...
94 ;;;
95 ;;; ----------------------------------------
96 ;;;
97 ;;; With the term-buffer-maximum-size you can finally decide how many
98 ;;; scrollback lines to keep: its default is 2048 but you can change it as
99 ;;; usual.
100 ;;;
101 ;;; ----------------------------------------
102 ;;;
103 ;;;
104 ;;; ANSI colorization should work well, I've decided to limit the interpreter
105 ;;; to five outstanding commands (like ESC [ 01;04;32;41;07m.
106 ;;; You shouldn't need more, if you do, tell me and I'll increase it. It's
107 ;;; so easy you could do it yourself...
108 ;;;
109 ;;; Blink, is not supported. Currently it's mapped as bold.
110 ;;;
111 ;;; Important caveat:
112 ;;; -----------------
113 ;;; if you want custom colors in term.el redefine term-default-fg-color
114 ;;; and term-default-bg-color BEFORE loading it.
115 ;;;
116 ;;; ----------------------------------------
117 ;;;
118 ;;; If you'd like to check out my complete configuration, you can download
119 ;;; it from http://www.polito.it/~s64912/things.html, it's ~500k in size and
120 ;;; contains my .cshrc, .emacs and my whole site-lisp subdirectory. (notice
121 ;;; that this term.el may be newer/older than the one in there, please
122 ;;; check!)
123 ;;;
124 ;;; This complete configuration contains, among other things, a complete
125 ;;; rectangular marking solution (based on rect-mark.el and
126 ;;; pc-bindings.el) and should be a good example of how extensively Emacs
127 ;;; can be configured on a ppp-connected ws.
128 ;;;
129 ;;; ----------------------------------------
130 ;;;
131 ;;; TODO:
132 ;;;
133 ;;; - Add hooks to allow raw-mode keys to be configurable
134 ;;; - Which keys are better ? \eOA or \e[A ?
135 ;;;
136 ;;;
137 ;;; Changes:
138 ;;;
139 ;;; V4.0 January 1997
140 ;;;
141 ;;; - Huge reworking of the faces code: now we only have roughly 20-30
142 ;;; faces for everything so we're even faster than the old md-term.el !
143 ;;; - Finished removing all the J-Shell code.
144 ;;;
145 ;;; V3.0 January 1997
146 ;;;
147 ;;; - Now all the supportable ANSI commands work well.
148 ;;; - Reworked a little the code: much less jsh-inspired stuff
149 ;;;
150 ;;; V2.3 November
151 ;;;
152 ;;; - Now all the faces are accessed through an array: much cleaner code.
153 ;;;
154 ;;; V2.2 November 4 1996
155 ;;;
156 ;;; - Implemented ANSI output colorization ( a bit rough but enough for
157 ;;; color_ls )
158 ;;;
159 ;;; - Implemented a maximum limit for the scroll buffer (stolen from
160 ;;; comint.el)
161 ;;;
162 ;;; v2.1 October 28 1996, first public release
163 ;;;
164 ;;; - Some new keybindings for term-char mode ( notably home/end/...)
165 ;;; - Directory, hostname and username tracking via ange-ftp
166 ;;; - Multi-term capability via the ansi-term call
167 ;;;
168 ;;; ----------------------------------------------------------------
169 ;;; You should/could have something like this in your .emacs to take
170 ;;; full advantage of this package
171 ;;;
172 ;;; (add-hook 'term-mode-hook
173 ;;; (function
174 ;;; (lambda ()
175 ;;; (setq term-prompt-regexp "^[^#$%>\n]*[#$%>] *")
176 ;;; (make-local-variable 'mouse-yank-at-point)
177 ;;; (make-local-variable 'transient-mark-mode)
178 ;;; (setq mouse-yank-at-point t)
179 ;;; (setq transient-mark-mode nil)
180 ;;; (auto-fill-mode -1)
181 ;;; (setq tab-width 8 ))))
182 ;;;
183 ;;;
184 ;;; ----------------------------------------
185 ;;;
186 ;;; If you want to use color ls the best setup is to have a different file
187 ;;; when you use eterm ( see above, mine is named .emacs_dircolors ). This
188 ;;; is necessary because some terminals, rxvt for example, need non-ansi
189 ;;; hacks to work ( for example on my rxvt white is wired to fg, and to
190 ;;; obtain normal white I have to do bold-white :)
191 ;;;
192 ;;; ----------------------------------------
193 ;;;
194 ;;;
195 ;;; # Configuration file for the color ls utility
196 ;;; # This file goes in the /etc directory, and must be world readable.
197 ;;; # You can copy this file to .dir_colors in your $HOME directory to
198 ;;; # override the system defaults.
199 ;;;
200 ;;; # COLOR needs one of these arguments: 'tty' colorizes output to ttys, but
201 ;;; # not pipes. 'all' adds color characters to all output. 'none' shuts
202 ;;; # colorization off.
203 ;;; COLOR tty
204 ;;; OPTIONS -F
205 ;;;
206 ;;; # Below, there should be one TERM entry for each termtype that is
207 ;;; # colorizable
208 ;;; TERM eterm
209 ;;;
210 ;;; # EIGHTBIT, followed by '1' for on, '0' for off. (8-bit output)
211 ;;; EIGHTBIT 1
212 ;;;
213 ;;; # Below are the color init strings for the basic file types. A color init
214 ;;; # string consists of one or more of the following numeric codes:
215 ;;; # Attribute codes:
216 ;;; # 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
217 ;;; # Text color codes:
218 ;;; # 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
219 ;;; # Background color codes:
220 ;;; # 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
221 ;;; NORMAL 00 # global default, although everything should be something.
222 ;;; FILE 00 # normal file
223 ;;; DIR 00;37 # directory
224 ;;; LINK 00;36 # symbolic link
225 ;;; FIFO 00;37 # pipe
226 ;;; SOCK 40;35 # socket
227 ;;; BLK 33;01 # block device driver
228 ;;; CHR 33;01 # character device driver
229 ;;;
230 ;;; # This is for files with execute permission:
231 ;;; EXEC 00;32
232 ;;;
233 ;;; # List any file extensions like '.gz' or '.tar' that you would like ls
234 ;;; # to colorize below. Put the extension, a space, and the color init
235 ;;; # string. (and any comments you want to add after a '#')
236 ;;; .tar 01;33 # archives or compressed
237 ;;; .tgz 01;33
238 ;;; .arj 01;33
239 ;;; .taz 01;33
240 ;;; .lzh 01;33
241 ;;; .zip 01;33
242 ;;; .z 01;33
243 ;;; .Z 01;33
244 ;;; .gz 01;33
245 ;;; .jpg 01;35 # image formats
246 ;;; .gif 01;35
247 ;;; .bmp 01;35
248 ;;; .xbm 01;35
249 ;;; .xpm 01;35
250 ;;;
251 ;;;
252 ;;; ----------------------------------------
253 ;;;
254 ;;; Notice: for directory/host/user tracking you need to have something
255 ;;; like this in your shell startup script ( this is for tcsh but should
256 ;;; be quite easy to port to other shells )
257 ;;;
258 ;;; ----------------------------------------
259 ;;;
260 ;;;
261 ;;; set os = `uname`
262 ;;; set host = `hostname`
263 ;;; set date = `date`
264 ;;;
265 ;;; # su does not change this but I'd like it to
266 ;;;
267 ;;; set user = `whoami`
268 ;;;
269 ;;; # ...
270 ;;;
271 ;;; if ( eterm =~ $TERM ) then
272 ;;;
273 ;;; echo --------------------------------------------------------------
274 ;;; echo Hello $user
275 ;;; echo Today is $date
276 ;;; echo We are on $host running $os under Emacs term mode
277 ;;; echo --------------------------------------------------------------
278 ;;;
279 ;;; setenv EDITOR emacsclient
280 ;;;
281 ;;; # Notice: $host and $user have been set before to 'hostname' and 'whoami'
282 ;;; # this is necessary because, f.e., certain versions of 'su' do not change
283 ;;; # $user, YMMV: if you don't want to fiddle with them define a couple
284 ;;; # of new variables and use these instead.
285 ;;; # NOTICE that there is a space between "AnSiT?" and $whatever NOTICE
286 ;;;
287 ;;; # These are because we want the real cwd in the messages, not the login
288 ;;; # time one !
289 ;;;
290 ;;; set cwd_hack='$cwd'
291 ;;; set host_hack='$host'
292 ;;; set user_hack='$user'
293 ;;;
294 ;;; # Notice that the ^[ character is an ESC, not two chars. You can
295 ;;; # get it in various ways, for example by typing
296 ;;; # echo -e '\033' > escape.file
297 ;;; # or by using your favourite editor
298 ;;;
299 ;;; foreach temp (cd pushd)
300 ;;; alias $temp "$temp \!* ; echo '\eAnSiTc' $cwd_hack"
301 ;;; end
302 ;;; alias popd 'popd ;echo "\eAnSiTc" $cwd'
303 ;;;
304 ;;; # Every command that can modify the user/host/directory should be aliased
305 ;;; # as follows for the tracking mechanism to work.
306 ;;;
307 ;;; foreach temp ( rlogin telnet rsh sh ksh csh tcsh zsh bash tcl su )
308 ;;; alias $temp "$temp \!* ; echo '\eAnSiTh' $host_hack ; \
309 ;;; echo '\eAnSiTu' $user_hack ;echo '\eAnSiTc' $cwd_hack"
310 ;;; end
311 ;;;
312 ;;; # Start up & use color ls
313 ;;;
314 ;;; echo "\eAnSiTh" $host
315 ;;; echo "\eAnSiTu" $user
316 ;;; echo "\eAnSiTc" $cwd
317 ;;;
318 ;;; # some housekeeping
319 ;;;
320 ;;; unset cwd_hack
321 ;;; unset host_hack
322 ;;; unset user_hack
323 ;;; unset temp
324 ;;;
325 ;;; eval `/bin/dircolors /home/marco/.emacs_dircolors`
326 ;;; endif
327 ;;;
328 ;;; # ...
329 ;;;
330 ;;; # Let's not clutter user space
331 ;;;
332 ;;; unset os
333 ;;; unset date
334 ;;;
335 ;;;
336
337 ;;; Original Commentary:
338 ;;; --------------------
339
340 ;; The changelog is at the end of this file.
341
342 ;; Please send me bug reports, bug fixes, and extensions, so that I can
343 ;; merge them into the master source.
344 ;; - Per Bothner (bothner@cygnus.com)
345
346 ;; This file defines a general command-interpreter-in-a-buffer package
347 ;; (term mode). The idea is that you can build specific process-in-a-buffer
348 ;; modes on top of term mode -- e.g., lisp, shell, scheme, T, soar, ....
349 ;; This way, all these specific packages share a common base functionality,
350 ;; and a common set of bindings, which makes them easier to use (and
351 ;; saves code, implementation time, etc., etc.).
352
353 ;; For hints on converting existing process modes (e.g., tex-mode,
354 ;; background, dbx, gdb, kermit, prolog, telnet) to use term-mode
355 ;; instead of shell-mode, see the notes at the end of this file.
356
357 \f
358 ;; Brief Command Documentation:
359 ;;============================================================================
360 ;; Term Mode Commands: (common to all derived modes, like cmushell & cmulisp
361 ;; mode)
362 ;;
363 ;; m-p term-previous-input Cycle backwards in input history
364 ;; m-n term-next-input Cycle forwards
365 ;; m-r term-previous-matching-input Previous input matching a regexp
366 ;; m-s comint-next-matching-input Next input that matches
367 ;; return term-send-input
368 ;; c-c c-a term-bol Beginning of line; skip prompt.
369 ;; c-d term-delchar-or-maybe-eof Delete char unless at end of buff.
370 ;; c-c c-u term-kill-input ^u
371 ;; c-c c-w backward-kill-word ^w
372 ;; c-c c-c term-interrupt-subjob ^c
373 ;; c-c c-z term-stop-subjob ^z
374 ;; c-c c-\ term-quit-subjob ^\
375 ;; c-c c-o term-kill-output Delete last batch of process output
376 ;; c-c c-r term-show-output Show last batch of process output
377 ;; c-c c-h term-dynamic-list-input-ring List input history
378 ;;
379 ;; Not bound by default in term-mode
380 ;; term-send-invisible Read a line w/o echo, and send to proc
381 ;; (These are bound in shell-mode)
382 ;; term-dynamic-complete Complete filename at point.
383 ;; term-dynamic-list-completions List completions in help buffer.
384 ;; term-replace-by-expanded-filename Expand and complete filename at point;
385 ;; replace with expanded/completed name.
386 ;; term-kill-subjob No mercy.
387 ;; term-show-maximum-output Show as much output as possible.
388 ;; term-continue-subjob Send CONT signal to buffer's process
389 ;; group. Useful if you accidentally
390 ;; suspend your process (with C-c C-z).
391
392 ;; term-mode-hook is the term mode hook. Basically for your keybindings.
393 ;; term-load-hook is run after loading in this package.
394
395 ;;; Code:
396
397 ;; This is passed to the inferior in the EMACS environment variable,
398 ;; so it is important to increase it if there are protocol-relevant changes.
399 (defconst term-protocol-version "0.96")
400
401 (eval-when-compile
402 (require 'ange-ftp))
403 (require 'ring)
404 (require 'ehelp)
405
406 (defgroup term nil
407 "General command interpreter in a window."
408 :group 'processes)
409
410 \f
411 ;;; Buffer Local Variables:
412 ;;;============================================================================
413 ;;; Term mode buffer local variables:
414 ;;; term-prompt-regexp - string term-bol uses to match prompt.
415 ;;; term-delimiter-argument-list - list For delimiters and arguments
416 ;;; term-last-input-start - marker Handy if inferior always echoes
417 ;;; term-last-input-end - marker For term-kill-output command
418 ;; For the input history mechanism:
419 (defvar term-input-ring-size 32 "Size of input history ring.")
420 ;;; term-input-ring-size - integer
421 ;;; term-input-ring - ring
422 ;;; term-input-ring-index - number ...
423 ;;; term-input-autoexpand - symbol ...
424 ;;; term-input-ignoredups - boolean ...
425 ;;; term-last-input-match - string ...
426 ;;; term-dynamic-complete-functions - hook For the completion mechanism
427 ;;; term-completion-fignore - list ...
428 ;;; term-get-old-input - function Hooks for specific
429 ;;; term-input-filter-functions - hook process-in-a-buffer
430 ;;; term-input-filter - function modes.
431 ;;; term-input-send - function
432 ;;; term-scroll-to-bottom-on-output - symbol ...
433 ;;; term-scroll-show-maximum-output - boolean...
434 (defvar term-height) ;; Number of lines in window.
435 (defvar term-width) ;; Number of columns in window.
436 (defvar term-home-marker) ;; Marks the "home" position for cursor addressing.
437 (defvar term-saved-home-marker nil) ;; When using alternate sub-buffer,
438 ;; contains saved term-home-marker from original sub-buffer .
439 (defvar term-start-line-column 0) ;; (current-column) at start of screen line,
440 ;; or nil if unknown.
441 (defvar term-current-column 0) ;; If non-nil, is cache for (current-column).
442 (defvar term-current-row 0) ;; Current vertical row (relative to home-marker)
443 ;; or nil if unknown.
444 (defvar term-insert-mode nil)
445 (defvar term-vertical-motion)
446 (defvar term-terminal-state 0) ;; State of the terminal emulator:
447 ;; state 0: Normal state
448 ;; state 1: Last character was a graphic in the last column.
449 ;; If next char is graphic, first move one column right
450 ;; (and line warp) before displaying it.
451 ;; This emulates (more or less) the behavior of xterm.
452 ;; state 2: seen ESC
453 ;; state 3: seen ESC [ (or ESC [ ?)
454 ;; state 4: term-terminal-parameter contains pending output.
455 (defvar term-kill-echo-list nil) ;; A queue of strings whose echo
456 ;; we want suppressed.
457 (defvar term-terminal-parameter)
458 (defvar term-terminal-previous-parameter)
459 (defvar term-current-face 'default)
460 (defvar term-scroll-start 0) ;; Top-most line (inclusive) of scrolling region.
461 (defvar term-scroll-end) ;; Number of line (zero-based) after scrolling region.
462 (defvar term-pager-count nil) ;; If nil, paging is disabled.
463 ;; Otherwise, number of lines before we need to page.
464 (defvar term-saved-cursor nil)
465 (defvar term-command-hook)
466 (defvar term-log-buffer nil)
467 (defvar term-scroll-with-delete nil) ;; term-scroll-with-delete is t if
468 ;; forward scrolling should be implemented by delete to
469 ;; top-most line(s); and nil if scrolling should be implemented
470 ;; by moving term-home-marker. It is set to t if there is a
471 ;; (non-default) scroll-region OR the alternate buffer is used.
472 (defvar term-pending-delete-marker) ;; New user input in line mode needs to
473 ;; be deleted, because it gets echoed by the inferior.
474 ;; To reduce flicker, we defer the delete until the next output.
475 (defvar term-old-mode-map nil) ;; Saves the old keymap when in char mode.
476 (defvar term-old-mode-line-format) ;; Saves old mode-line-format while paging.
477 (defvar term-pager-old-local-map nil) ;; Saves old keymap while paging.
478 (defvar term-pager-old-filter) ;; Saved process-filter while paging.
479
480 (defcustom explicit-shell-file-name nil
481 "*If non-nil, is file name to use for explicitly requested inferior shell."
482 :type '(choice (const nil) file)
483 :group 'term)
484
485 (defvar term-prompt-regexp "^"
486 "Regexp to recognize prompts in the inferior process.
487 Defaults to \"^\", the null string at BOL.
488
489 Good choices:
490 Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
491 Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
492 franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
493 kcl: \"^>+ *\"
494 shell: \"^[^#$%>\\n]*[#$%>] *\"
495 T: \"^>+ *\"
496
497 This is a good thing to set in mode hooks.")
498
499 (defvar term-delimiter-argument-list ()
500 "List of characters to recognize as separate arguments in input.
501 Strings comprising a character in this list will separate the arguments
502 surrounding them, and also be regarded as arguments in their own right (unlike
503 whitespace). See `term-arguments'.
504 Defaults to the empty list.
505
506 For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
507
508 This is a good thing to set in mode hooks.")
509
510 (defcustom term-input-autoexpand nil
511 "*If non-nil, expand input command history references on completion.
512 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
513
514 If the value is `input', then the expansion is seen on input.
515 If the value is `history', then the expansion is only when inserting
516 into the buffer's input ring. See also `term-magic-space' and
517 `term-dynamic-complete'.
518
519 This variable is buffer-local."
520 :type '(choice (const nil) (const t) (const input) (const history))
521 :group 'term)
522
523 (defcustom term-input-ignoredups nil
524 "*If non-nil, don't add input matching the last on the input ring.
525 This mirrors the optional behavior of bash.
526
527 This variable is buffer-local."
528 :type 'boolean
529 :group 'term)
530
531 (defcustom term-input-ring-file-name nil
532 "*If non-nil, name of the file to read/write input history.
533 See also `term-read-input-ring' and `term-write-input-ring'.
534
535 This variable is buffer-local, and is a good thing to set in mode hooks."
536 :type 'boolean
537 :group 'term)
538
539 (defcustom term-scroll-to-bottom-on-output nil
540 "*Controls whether interpreter output causes window to scroll.
541 If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
542 If `this', scroll only the selected window.
543 If `others', scroll only those that are not the selected window.
544
545 The default is nil.
546
547 See variable `term-scroll-show-maximum-output'.
548 This variable is buffer-local."
549 :type 'boolean
550 :group 'term)
551
552 (defcustom term-scroll-show-maximum-output nil
553 "*Controls how interpreter output causes window to scroll.
554 If non-nil, then show the maximum output when the window is scrolled.
555
556 See variable `term-scroll-to-bottom-on-output'.
557 This variable is buffer-local."
558 :type 'boolean
559 :group 'term)
560
561 ;; Where gud-display-frame should put the debugging arrow. This is
562 ;; set by the marker-filter, which scans the debugger's output for
563 ;; indications of the current pc.
564 (defvar term-pending-frame nil)
565
566 ;;; Here are the per-interpreter hooks.
567 (defvar term-get-old-input (function term-get-old-input-default)
568 "Function that submits old text in term mode.
569 This function is called when return is typed while the point is in old text.
570 It returns the text to be submitted as process input. The default is
571 `term-get-old-input-default', which grabs the current line, and strips off
572 leading text matching `term-prompt-regexp'.")
573
574 (defvar term-dynamic-complete-functions
575 '(term-replace-by-expanded-history term-dynamic-complete-filename)
576 "List of functions called to perform completion.
577 Functions should return non-nil if completion was performed.
578 See also `term-dynamic-complete'.
579
580 This is a good thing to set in mode hooks.")
581
582 (defvar term-input-filter
583 (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
584 "Predicate for filtering additions to input history.
585 Only inputs answering true to this function are saved on the input
586 history list. Default is to save anything that isn't all whitespace.")
587
588 (defvar term-input-filter-functions '()
589 "Functions to call before input is sent to the process.
590 These functions get one argument, a string containing the text to send.
591
592 This variable is buffer-local.")
593
594 (defvar term-input-sender (function term-simple-send)
595 "Function to actually send to PROCESS the STRING submitted by user.
596 Usually this is just `term-simple-send', but if your mode needs to
597 massage the input string, this is your hook. This is called from
598 the user command `term-send-input'. `term-simple-send' just sends
599 the string plus a newline.")
600
601 (defcustom term-eol-on-send t
602 "*Non-nil means go to the end of the line before sending input.
603 See `term-send-input'."
604 :type 'boolean
605 :group 'term)
606
607 (defcustom term-mode-hook '()
608 "Called upon entry into term mode.
609 This is run before the process is cranked up."
610 :type 'hook
611 :group 'term)
612
613 (defcustom term-exec-hook '()
614 "Called each time a process is exec'd by `term-exec'.
615 This is called after the process is cranked up. It is useful for things that
616 must be done each time a process is executed in a term mode buffer (e.g.,
617 `process-kill-without-query'). In contrast, `term-mode-hook' is only
618 executed once when the buffer is created."
619 :type 'hook
620 :group 'term)
621
622 (defvar term-mode-map
623 (let ((map (make-sparse-keymap)))
624 (define-key map "\ep" 'term-previous-input)
625 (define-key map "\en" 'term-next-input)
626 (define-key map "\er" 'term-previous-matching-input)
627 (define-key map "\es" 'term-next-matching-input)
628 (unless (featurep 'xemacs)
629 (define-key map [?\A-\M-r]
630 'term-previous-matching-input-from-input)
631 (define-key map [?\A-\M-s] 'term-next-matching-input-from-input))
632 (define-key map "\e\C-l" 'term-show-output)
633 (define-key map "\C-m" 'term-send-input)
634 (define-key map "\C-d" 'term-delchar-or-maybe-eof)
635 (define-key map "\C-c\C-a" 'term-bol)
636 (define-key map "\C-c\C-u" 'term-kill-input)
637 (define-key map "\C-c\C-w" 'backward-kill-word)
638 (define-key map "\C-c\C-c" 'term-interrupt-subjob)
639 (define-key map "\C-c\C-z" 'term-stop-subjob)
640 (define-key map "\C-c\C-\\" 'term-quit-subjob)
641 (define-key map "\C-c\C-m" 'term-copy-old-input)
642 (define-key map "\C-c\C-o" 'term-kill-output)
643 (define-key map "\C-c\C-r" 'term-show-output)
644 (define-key map "\C-c\C-e" 'term-show-maximum-output)
645 (define-key map "\C-c\C-l" 'term-dynamic-list-input-ring)
646 (define-key map "\C-c\C-n" 'term-next-prompt)
647 (define-key map "\C-c\C-p" 'term-previous-prompt)
648 (define-key map "\C-c\C-d" 'term-send-eof)
649 (define-key map "\C-c\C-k" 'term-char-mode)
650 (define-key map "\C-c\C-j" 'term-line-mode)
651 (define-key map "\C-c\C-q" 'term-pager-toggle)
652
653 ;; ;; completion:
654 ;; (define-key map [menu-bar completion]
655 ;; (cons "Complete" (make-sparse-keymap "Complete")))
656 ;; (define-key map [menu-bar completion complete-expand]
657 ;; '("Expand File Name" . term-replace-by-expanded-filename))
658 ;; (define-key map [menu-bar completion complete-listing]
659 ;; '("File Completion Listing" . term-dynamic-list-filename-completions))
660 ;; (define-key map [menu-bar completion complete-file]
661 ;; '("Complete File Name" . term-dynamic-complete-filename))
662 ;; (define-key map [menu-bar completion complete]
663 ;; '("Complete Before Point" . term-dynamic-complete))
664 ;; ;; Put them in the menu bar:
665 ;; (setq menu-bar-final-items (append '(terminal completion inout signals)
666 ;; menu-bar-final-items))
667 map))
668
669 (defvar term-raw-map nil
670 "Keyboard map for sending characters directly to the inferior process.")
671 (defvar term-escape-char nil
672 "Escape character for char sub-mode of term mode.
673 Do not change it directly; use `term-set-escape-char' instead.")
674 (defvar term-raw-escape-map nil)
675
676 (defvar term-pager-break-map nil)
677
678 (defvar term-ptyp t
679 "True if communications via pty; false if by pipe. Buffer local.
680 This is to work around a bug in Emacs process signaling.")
681
682 (defvar term-last-input-match ""
683 "Last string searched for by term input history search, for defaulting.
684 Buffer local variable.")
685
686 (defvar term-input-ring nil)
687 (defvar term-last-input-start)
688 (defvar term-last-input-end)
689 (defvar term-input-ring-index nil
690 "Index of last matched history element.")
691 (defvar term-matching-input-from-input-string ""
692 "Input previously used to match input history.")
693 ; This argument to set-process-filter disables reading from the process,
694 ; assuming this is Emacs 19.20 or newer.
695 (defvar term-pager-filter t)
696
697 (put 'term-replace-by-expanded-history 'menu-enable 'term-input-autoexpand)
698 (put 'term-input-ring 'permanent-local t)
699 (put 'term-input-ring-index 'permanent-local t)
700 (put 'term-input-autoexpand 'permanent-local t)
701 (put 'term-input-filter-functions 'permanent-local t)
702 (put 'term-scroll-to-bottom-on-output 'permanent-local t)
703 (put 'term-scroll-show-maximum-output 'permanent-local t)
704 (put 'term-ptyp 'permanent-local t)
705
706 (defmacro term-in-char-mode () '(eq (current-local-map) term-raw-map))
707 (defmacro term-in-line-mode () '(not (term-in-char-mode)))
708 ;; True if currently doing PAGER handling.
709 (defmacro term-pager-enabled () 'term-pager-count)
710 (defmacro term-handling-pager () 'term-pager-old-local-map)
711 (defmacro term-using-alternate-sub-buffer () 'term-saved-home-marker)
712
713 (defvar term-signals-menu)
714 (defvar term-terminal-menu)
715
716 ;;; Let's silence the byte-compiler -mm
717 (defvar term-ansi-at-host nil)
718 (defvar term-ansi-at-dir nil)
719 (defvar term-ansi-at-user nil)
720 (defvar term-ansi-at-message nil)
721 (defvar term-ansi-at-save-user nil)
722 (defvar term-ansi-at-save-pwd nil)
723 (defvar term-ansi-at-save-anon nil)
724 (defvar term-ansi-current-bold nil)
725 (defvar term-ansi-current-color 0)
726 (defvar term-ansi-face-already-done nil)
727 (defvar term-ansi-current-bg-color 0)
728 (defvar term-ansi-current-underline nil)
729 (defvar term-ansi-current-reverse nil)
730 (defvar term-ansi-current-invisible nil)
731
732 ;;; Four should be enough, if you want more, just add. -mm
733 (defvar term-terminal-more-parameters 0)
734 (defvar term-terminal-previous-parameter-2 -1)
735 (defvar term-terminal-previous-parameter-3 -1)
736 (defvar term-terminal-previous-parameter-4 -1)
737 ;;;
738
739 ;;; faces -mm
740
741 (defcustom term-default-fg-color (face-foreground term-current-face)
742 "Default color for foreground in `term'."
743 :group 'term
744 :type 'string)
745
746 (defcustom term-default-bg-color (face-background term-current-face)
747 "Default color for background in `term'."
748 :group 'term
749 :type 'string)
750
751 ;;; Use the same colors that xterm uses, see `xterm-standard-colors'.
752 (defvar ansi-term-color-vector
753 [unspecified "black" "red3" "green3" "yellow3" "blue2"
754 "magenta3" "cyan3" "white"])
755
756 ;;; Inspiration came from comint.el -mm
757 (defvar term-buffer-maximum-size 2048
758 "*The maximum size in lines for term buffers.
759 Term buffers are truncated from the top to be no greater than this number.
760 Notice that a setting of 0 means \"don't truncate anything\". This variable
761 is buffer-local.")
762 ;;;
763 \f
764 (when (featurep 'xemacs)
765 (defvar term-terminal-menu
766 '("Terminal"
767 [ "Character mode" term-char-mode (term-in-line-mode)]
768 [ "Line mode" term-line-mode (term-in-char-mode)]
769 [ "Enable paging" term-pager-toggle (not term-pager-count)]
770 [ "Disable paging" term-pager-toggle term-pager-count])))
771
772 ;; Menu bars:
773 (unless (featurep 'xemacs)
774 ;; terminal:
775 (let (newmap)
776 (setq newmap (make-sparse-keymap "Terminal"))
777 (define-key newmap [terminal-pager-enable]
778 '(menu-item "Enable paging" term-fake-pager-enable
779 :help "Enable paging feature"))
780 (define-key newmap [terminal-pager-disable]
781 '(menu-item "Disable paging" term-fake-pager-disable
782 :help "Disable paging feature"))
783 (define-key newmap [terminal-char-mode]
784 '(menu-item "Character mode" term-char-mode
785 :help "Switch to char (raw) sub-mode of term mode"))
786 (define-key newmap [terminal-line-mode]
787 '(menu-item "Line mode" term-line-mode
788 :help "Switch to line (cooked) sub-mode of term mode"))
789 (setq term-terminal-menu (cons "Terminal" newmap))
790
791 ;; completion: (line mode only)
792 (defvar term-completion-menu (make-sparse-keymap "Complete"))
793 (define-key term-mode-map [menu-bar completion]
794 (cons "Complete" term-completion-menu))
795 (define-key term-completion-menu [complete-expand]
796 '("Expand File Name" . term-replace-by-expanded-filename))
797 (define-key term-completion-menu [complete-listing]
798 '("File Completion Listing" . term-dynamic-list-filename-completions))
799 (define-key term-completion-menu [menu-bar completion complete-file]
800 '("Complete File Name" . term-dynamic-complete-filename))
801 (define-key term-completion-menu [menu-bar completion complete]
802 '("Complete Before Point" . term-dynamic-complete))
803
804 ;; Input history: (line mode only)
805 (defvar term-inout-menu (make-sparse-keymap "In/Out"))
806 (define-key term-mode-map [menu-bar inout]
807 (cons "In/Out" term-inout-menu))
808 (define-key term-inout-menu [kill-output]
809 '("Kill Current Output Group" . term-kill-output))
810 (define-key term-inout-menu [next-prompt]
811 '("Forward Output Group" . term-next-prompt))
812 (define-key term-inout-menu [previous-prompt]
813 '("Backward Output Group" . term-previous-prompt))
814 (define-key term-inout-menu [show-maximum-output]
815 '("Show Maximum Output" . term-show-maximum-output))
816 (define-key term-inout-menu [show-output]
817 '("Show Current Output Group" . term-show-output))
818 (define-key term-inout-menu [kill-input]
819 '("Kill Current Input" . term-kill-input))
820 (define-key term-inout-menu [copy-input]
821 '("Copy Old Input" . term-copy-old-input))
822 (define-key term-inout-menu [forward-matching-history]
823 '("Forward Matching Input..." . term-forward-matching-input))
824 (define-key term-inout-menu [backward-matching-history]
825 '("Backward Matching Input..." . term-backward-matching-input))
826 (define-key term-inout-menu [next-matching-history]
827 '("Next Matching Input..." . term-next-matching-input))
828 (define-key term-inout-menu [previous-matching-history]
829 '("Previous Matching Input..." . term-previous-matching-input))
830 (define-key term-inout-menu [next-matching-history-from-input]
831 '("Next Matching Current Input" . term-next-matching-input-from-input))
832 (define-key term-inout-menu [previous-matching-history-from-input]
833 '("Previous Matching Current Input" .
834 term-previous-matching-input-from-input))
835 (define-key term-inout-menu [next-history]
836 '("Next Input" . term-next-input))
837 (define-key term-inout-menu [previous-history]
838 '("Previous Input" . term-previous-input))
839 (define-key term-inout-menu [list-history]
840 '("List Input History" . term-dynamic-list-input-ring))
841 (define-key term-inout-menu [expand-history]
842 '("Expand History Before Point" . term-replace-by-expanded-history))
843
844 ;; Signals
845 (setq newmap (make-sparse-keymap "Signals"))
846 (define-key term-mode-map [menu-bar signals]
847 (setq term-signals-menu (cons "Signals" newmap)))
848 (define-key newmap [eof]
849 '(menu-item "EOF" term-send-eof
850 :help "Send an EOF to the current buffer's process"))
851 (define-key newmap [kill]
852 '(menu-item "KILL" term-kill-subjob
853 :help "Send kill signal to the current subjob"))
854 (define-key newmap [quit]
855 '(menu-item "QUIT" term-quit-subjob
856 :help "Send quit signal to the current subjob."))
857 (define-key newmap [cont]
858 '(menu-item "CONT" term-continue-subjob
859 :help "Send CONT signal to process buffer's process group"))
860 (define-key newmap [stop]
861 '(menu-item "STOP" term-stop-subjob
862 :help "Stop the current subjob"))
863 (define-key newmap [brk]
864 '(menu-item "BREAK" term-interrupt-subjob
865 :help "Interrupt the current subjob"))
866 ))
867 \f
868 ;; Set up term-raw-map, etc.
869
870 (defun term-set-escape-char (c)
871 "Change `term-escape-char' and keymaps that depend on it."
872 (when term-escape-char
873 (define-key term-raw-map term-escape-char 'term-send-raw))
874 (setq c (make-string 1 c))
875 (define-key term-raw-map c term-raw-escape-map)
876 ;; Define standard bindings in term-raw-escape-map
877 (define-key term-raw-escape-map "\C-v"
878 (lookup-key (current-global-map) "\C-v"))
879 (define-key term-raw-escape-map "\C-u"
880 (lookup-key (current-global-map) "\C-u"))
881 (define-key term-raw-escape-map c 'term-send-raw)
882 (define-key term-raw-escape-map "\C-q" 'term-pager-toggle)
883 ;; The keybinding for term-char-mode is needed by the menubar code.
884 (define-key term-raw-escape-map "\C-k" 'term-char-mode)
885 (define-key term-raw-escape-map "\C-j" 'term-line-mode)
886 ;; It's convenient to have execute-extended-command here.
887 (define-key term-raw-escape-map [?\M-x] 'execute-extended-command))
888
889 (let* ((map (make-keymap))
890 (esc-map (make-keymap))
891 (i 0))
892 (while (< i 128)
893 (define-key map (make-string 1 i) 'term-send-raw)
894 ;; Avoid O and [. They are used in escape sequences for various keys.
895 (unless (or (eq i ?O) (eq i 91))
896 (define-key esc-map (make-string 1 i) 'term-send-raw-meta))
897 (setq i (1+ i)))
898 (define-key map "\e" esc-map)
899 (setq term-raw-map map)
900 (setq term-raw-escape-map
901 (copy-keymap (lookup-key (current-global-map) "\C-x")))
902
903 ;;; Added nearly all the 'grey keys' -mm
904
905 (if (featurep 'xemacs)
906 (define-key term-raw-map [button2] 'term-mouse-paste)
907 (define-key term-raw-map [mouse-2] 'term-mouse-paste)
908 (define-key term-raw-map [menu-bar terminal] term-terminal-menu)
909 (define-key term-raw-map [menu-bar signals] term-signals-menu))
910 (define-key term-raw-map [up] 'term-send-up)
911 (define-key term-raw-map [down] 'term-send-down)
912 (define-key term-raw-map [right] 'term-send-right)
913 (define-key term-raw-map [left] 'term-send-left)
914 (define-key term-raw-map [delete] 'term-send-del)
915 (define-key term-raw-map [deletechar] 'term-send-del)
916 (define-key term-raw-map [backspace] 'term-send-backspace)
917 (define-key term-raw-map [home] 'term-send-home)
918 (define-key term-raw-map [end] 'term-send-end)
919 (define-key term-raw-map [insert] 'term-send-insert)
920 (define-key term-raw-map [S-prior] 'scroll-down)
921 (define-key term-raw-map [S-next] 'scroll-up)
922 (define-key term-raw-map [S-insert] 'term-paste)
923 (define-key term-raw-map [prior] 'term-send-prior)
924 (define-key term-raw-map [next] 'term-send-next))
925
926 (term-set-escape-char ?\C-c)
927
928 (defun term-window-width ()
929 (if (featurep 'xemacs)
930 (1- (window-width))
931 (if (and window-system overflow-newline-into-fringe)
932 (window-width)
933 (1- (window-width)))))
934
935 \f
936 (put 'term-mode 'mode-class 'special)
937
938
939 ;;; Use this variable as a display table for `term-mode'.
940 (defvar term-display-table
941 (let ((dt (or (copy-sequence standard-display-table)
942 (make-display-table)))
943 i)
944 ;; avoid changing the display table for ^J
945 (setq i 0)
946 (while (< i 10)
947 (aset dt i (vector i))
948 (setq i (1+ i)))
949 (setq i 11)
950 (while (< i 32)
951 (aset dt i (vector i))
952 (setq i (1+ i)))
953 (setq i 128)
954 (while (< i 256)
955 (aset dt i (vector i))
956 (setq i (1+ i)))
957 dt))
958
959 (defun term-mode ()
960 "Major mode for interacting with an inferior interpreter.
961 The interpreter name is same as buffer name, sans the asterisks.
962
963 There are two submodes: line mode and char mode. By default, you are
964 in char mode. In char sub-mode, each character (except
965 `term-escape-char') is sent immediately to the subprocess.
966 The escape character is equivalent to the usual meaning of C-x.
967
968 In line mode, you send a line of input at a time; use
969 \\[term-send-input] to send.
970
971 In line mode, this maintains an input history of size
972 `term-input-ring-size', and you can access it with the commands
973 \\[term-next-input], \\[term-previous-input], and
974 \\[term-dynamic-list-input-ring]. Input ring history expansion can be
975 achieved with the commands \\[term-replace-by-expanded-history] or
976 \\[term-magic-space]. Input ring expansion is controlled by the
977 variable `term-input-autoexpand', and addition is controlled by the
978 variable `term-input-ignoredups'.
979
980 Input to, and output from, the subprocess can cause the window to scroll to
981 the end of the buffer. See variables `term-scroll-to-bottom-on-input',
982 and `term-scroll-to-bottom-on-output'.
983
984 If you accidentally suspend your process, use \\[term-continue-subjob]
985 to continue it.
986
987 This mode can be customized to create specific modes for running
988 particular subprocesses. This can be done by setting the hooks
989 `term-input-filter-functions', `term-input-filter',
990 `term-input-sender' and `term-get-old-input' to appropriate functions,
991 and the variable `term-prompt-regexp' to the appropriate regular
992 expression.
993
994 Commands in raw mode:
995
996 \\{term-raw-map}
997
998 Commands in line mode:
999
1000 \\{term-mode-map}
1001
1002 Entry to this mode runs the hooks on `term-mode-hook'."
1003 (interactive)
1004 ;; Do not remove this. All major modes must do this.
1005 (kill-all-local-variables)
1006 (setq major-mode 'term-mode)
1007 (setq mode-name "Term")
1008 (use-local-map term-mode-map)
1009 ;; we do not want indent to sneak in any tabs
1010 (setq indent-tabs-mode nil)
1011 (setq buffer-display-table term-display-table)
1012 (make-local-variable 'term-home-marker)
1013 (setq term-home-marker (copy-marker 0))
1014 (make-local-variable 'term-saved-home-marker)
1015 (make-local-variable 'term-height)
1016 (make-local-variable 'term-width)
1017 (setq term-width (term-window-width))
1018 (setq term-height (1- (window-height)))
1019 (make-local-variable 'term-terminal-parameter)
1020 (make-local-variable 'term-saved-cursor)
1021 (make-local-variable 'term-last-input-start)
1022 (setq term-last-input-start (make-marker))
1023 (make-local-variable 'term-last-input-end)
1024 (setq term-last-input-end (make-marker))
1025 (make-local-variable 'term-last-input-match)
1026 (setq term-last-input-match "")
1027 (make-local-variable 'term-prompt-regexp) ; Don't set; default
1028 (make-local-variable 'term-input-ring-size) ; ...to global val.
1029 (make-local-variable 'term-input-ring)
1030 (make-local-variable 'term-input-ring-file-name)
1031 (or (and (boundp 'term-input-ring) term-input-ring)
1032 (setq term-input-ring (make-ring term-input-ring-size)))
1033 (make-local-variable 'term-input-ring-index)
1034 (or (and (boundp 'term-input-ring-index) term-input-ring-index)
1035 (setq term-input-ring-index nil))
1036
1037 (make-local-variable 'term-command-hook)
1038 (setq term-command-hook (symbol-function 'term-command-hook))
1039
1040 ;;; I'm not sure these saves are necessary but, since I
1041 ;;; haven't tested the whole thing on a net connected machine with
1042 ;;; a properly configured ange-ftp, I've decided to be conservative
1043 ;;; and put them in. -mm
1044
1045 (make-local-variable 'term-ansi-at-host)
1046 (setq term-ansi-at-host (system-name))
1047
1048 (make-local-variable 'term-ansi-at-dir)
1049 (setq term-ansi-at-dir default-directory)
1050
1051 (make-local-variable 'term-ansi-at-message)
1052 (setq term-ansi-at-message nil)
1053
1054 ;;; For user tracking purposes -mm
1055 (make-local-variable 'ange-ftp-default-user)
1056 (make-local-variable 'ange-ftp-default-password)
1057 (make-local-variable 'ange-ftp-generate-anonymous-password)
1058
1059 ;;; You may want to have different scroll-back sizes -mm
1060 (make-local-variable 'term-buffer-maximum-size)
1061
1062 ;;; Of course these have to be buffer-local -mm
1063 (make-local-variable 'term-ansi-current-bold)
1064 (make-local-variable 'term-ansi-current-color)
1065 (make-local-variable 'term-ansi-face-already-done)
1066 (make-local-variable 'term-ansi-current-bg-color)
1067 (make-local-variable 'term-ansi-current-underline)
1068 (make-local-variable 'term-ansi-current-reverse)
1069 (make-local-variable 'term-ansi-current-invisible)
1070
1071 (make-local-variable 'term-terminal-parameter)
1072 (make-local-variable 'term-terminal-previous-parameter)
1073 (make-local-variable 'term-terminal-previous-parameter-2)
1074 (make-local-variable 'term-terminal-previous-parameter-3)
1075 (make-local-variable 'term-terminal-previous-parameter-4)
1076 (make-local-variable 'term-terminal-more-parameters)
1077
1078 (make-local-variable 'term-terminal-state)
1079 (make-local-variable 'term-kill-echo-list)
1080 (make-local-variable 'term-start-line-column)
1081 (make-local-variable 'term-current-column)
1082 (make-local-variable 'term-current-row)
1083 (make-local-variable 'term-log-buffer)
1084 (make-local-variable 'term-scroll-start)
1085 (make-local-variable 'term-scroll-end)
1086 (setq term-scroll-end term-height)
1087 (make-local-variable 'term-scroll-with-delete)
1088 (make-local-variable 'term-pager-count)
1089 (make-local-variable 'term-pager-old-local-map)
1090 (make-local-variable 'term-old-mode-map)
1091 (make-local-variable 'term-insert-mode)
1092 (make-local-variable 'term-dynamic-complete-functions)
1093 (make-local-variable 'term-completion-fignore)
1094 (make-local-variable 'term-get-old-input)
1095 (make-local-variable 'term-matching-input-from-input-string)
1096 (make-local-variable 'term-input-autoexpand)
1097 (make-local-variable 'term-input-ignoredups)
1098 (make-local-variable 'term-delimiter-argument-list)
1099 (make-local-variable 'term-input-filter-functions)
1100 (make-local-variable 'term-input-filter)
1101 (make-local-variable 'term-input-sender)
1102 (make-local-variable 'term-eol-on-send)
1103 (make-local-variable 'term-scroll-to-bottom-on-output)
1104 (make-local-variable 'term-scroll-show-maximum-output)
1105 (make-local-variable 'term-ptyp)
1106 (make-local-variable 'term-exec-hook)
1107 (make-local-variable 'term-vertical-motion)
1108 (make-local-variable 'term-pending-delete-marker)
1109 (setq term-pending-delete-marker (make-marker))
1110 (make-local-variable 'term-current-face)
1111 (setq term-current-face (list :background term-default-bg-color
1112 :foreground term-default-fg-color))
1113 (make-local-variable 'term-pending-frame)
1114 (setq term-pending-frame nil)
1115 ;; Cua-mode's keybindings interfere with the term keybindings, disable it.
1116 (set (make-local-variable 'cua-mode) nil)
1117 (run-mode-hooks 'term-mode-hook)
1118 (when (featurep 'xemacs)
1119 (set-buffer-menubar
1120 (append current-menubar (list term-terminal-menu))))
1121 (or term-input-ring
1122 (setq term-input-ring (make-ring term-input-ring-size)))
1123 (term-update-mode-line))
1124 \f
1125 (defun term-reset-size (height width)
1126 (setq term-height height)
1127 (setq term-width width)
1128 (setq term-start-line-column nil)
1129 (setq term-current-row nil)
1130 (setq term-current-column nil)
1131 (term-set-scroll-region 0 height))
1132
1133 ;; Recursive routine used to check if any string in term-kill-echo-list
1134 ;; matches part of the buffer before point.
1135 ;; If so, delete that matched part of the buffer - this suppresses echo.
1136 ;; Also, remove that string from the term-kill-echo-list.
1137 ;; We *also* remove any older string on the list, as a sanity measure,
1138 ;; in case something gets out of sync. (Except for type-ahead, there
1139 ;; should only be one element in the list.)
1140
1141 (defun term-check-kill-echo-list ()
1142 (let ((cur term-kill-echo-list) (found nil) (save-point (point)))
1143 (unwind-protect
1144 (progn
1145 (end-of-line)
1146 (while cur
1147 (let* ((str (car cur)) (len (length str)) (start (- (point) len)))
1148 (if (and (>= start (point-min))
1149 (string= str (buffer-substring start (point))))
1150 (progn (delete-backward-char len)
1151 (setq term-kill-echo-list (cdr cur))
1152 (setq term-current-column nil)
1153 (setq term-current-row nil)
1154 (setq term-start-line-column nil)
1155 (setq cur nil found t))
1156 (setq cur (cdr cur))))))
1157 (when (not found)
1158 (goto-char save-point)))
1159 found))
1160
1161 (defun term-check-size (process)
1162 (when (or (/= term-height (1- (window-height)))
1163 (/= term-width (term-window-width)))
1164 (term-reset-size (1- (window-height)) (term-window-width))
1165 (set-process-window-size process term-height term-width)))
1166
1167 (defun term-send-raw-string (chars)
1168 (let ((proc (get-buffer-process (current-buffer))))
1169 (if (not proc)
1170 (error "Current buffer has no process")
1171 ;; Note that (term-current-row) must be called *after*
1172 ;; (point) has been updated to (process-mark proc).
1173 (goto-char (process-mark proc))
1174 (when (term-pager-enabled)
1175 (setq term-pager-count (term-current-row)))
1176 (process-send-string proc chars))))
1177
1178 (defun term-send-raw ()
1179 "Send the last character typed through the terminal-emulator
1180 without any interpretation."
1181 (interactive)
1182 ;; Convert `return' to C-m, etc.
1183 (when (and (symbolp last-input-char)
1184 (get last-input-char 'ascii-character))
1185 (setq last-input-char (get last-input-char 'ascii-character)))
1186 (term-send-raw-string (make-string 1 last-input-char)))
1187
1188 (defun term-send-raw-meta ()
1189 (interactive)
1190 (let ((char last-input-char))
1191 (when (symbolp last-input-char)
1192 ;; Convert `return' to C-m, etc.
1193 (let ((tmp (get char 'event-symbol-elements)))
1194 (when tmp
1195 (setq char (car tmp)))
1196 (when (symbolp char)
1197 (setq tmp (get char 'ascii-character))
1198 (when tmp
1199 (setq char tmp)))))
1200 (setq char (event-basic-type char))
1201 (term-send-raw-string (if (and (numberp char)
1202 (> char 127)
1203 (< char 256))
1204 (make-string 1 char)
1205 (format "\e%c" char)))))
1206
1207 (defun term-mouse-paste (click arg)
1208 "Insert the last stretch of killed text at the position clicked on."
1209 (interactive "e\nP")
1210 (if (featurep 'xemacs)
1211 (term-send-raw-string
1212 (or (condition-case () (x-get-selection) (error ()))
1213 (x-get-cutbuffer)
1214 (error "No selection or cut buffer available")))
1215 ;; Give temporary modes such as isearch a chance to turn off.
1216 (run-hooks 'mouse-leave-buffer-hook)
1217 (setq this-command 'yank)
1218 (mouse-set-point click)
1219 (term-send-raw-string (current-kill (cond
1220 ((listp arg) 0)
1221 ((eq arg '-) -1)
1222 (t (1- arg)))))))
1223
1224 (defun term-paste ()
1225 "Insert the last stretch of killed text at point."
1226 (interactive)
1227 (term-send-raw-string (current-kill 0)))
1228
1229 ;; Which would be better: "\e[A" or "\eOA"? readline accepts either.
1230 ;; For my configuration it's definitely better \eOA but YMMV. -mm
1231 ;; For example: vi works with \eOA while elm wants \e[A ...
1232 ;;; (terminfo: kcuu1, kcud1, kcuf1, kcub1, khome, kend, kpp, knp, kdch1, kbs)
1233 (defun term-send-up () (interactive) (term-send-raw-string "\eOA"))
1234 (defun term-send-down () (interactive) (term-send-raw-string "\eOB"))
1235 (defun term-send-right () (interactive) (term-send-raw-string "\eOC"))
1236 (defun term-send-left () (interactive) (term-send-raw-string "\eOD"))
1237 (defun term-send-home () (interactive) (term-send-raw-string "\e[1~"))
1238 (defun term-send-insert() (interactive) (term-send-raw-string "\e[2~"))
1239 (defun term-send-end () (interactive) (term-send-raw-string "\e[4~"))
1240 (defun term-send-prior () (interactive) (term-send-raw-string "\e[5~"))
1241 (defun term-send-next () (interactive) (term-send-raw-string "\e[6~"))
1242 (defun term-send-del () (interactive) (term-send-raw-string "\e[3~"))
1243 (defun term-send-backspace () (interactive) (term-send-raw-string "\C-?"))
1244 \f
1245 (defun term-char-mode ()
1246 "Switch to char (\"raw\") sub-mode of term mode.
1247 Each character you type is sent directly to the inferior without
1248 intervention from Emacs, except for the escape character (usually C-c)."
1249 (interactive)
1250 ;; FIXME: Emit message? Cfr ilisp-raw-message
1251 (when (term-in-line-mode)
1252 (setq term-old-mode-map (current-local-map))
1253 (use-local-map term-raw-map)
1254
1255 ;; Send existing partial line to inferior (without newline).
1256 (let ((pmark (process-mark (get-buffer-process (current-buffer))))
1257 (save-input-sender term-input-sender))
1258 (when (> (point) pmark)
1259 (unwind-protect
1260 (progn
1261 (setq term-input-sender
1262 (symbol-function 'term-send-string))
1263 (end-of-line)
1264 (term-send-input))
1265 (setq term-input-sender save-input-sender))))
1266 (term-update-mode-line)))
1267
1268 (defun term-line-mode ()
1269 "Switch to line (\"cooked\") sub-mode of term mode.
1270 This means that Emacs editing commands work as normally, until
1271 you type \\[term-send-input] which sends the current line to the inferior."
1272 (interactive)
1273 (when (term-in-char-mode)
1274 (use-local-map term-old-mode-map)
1275 (term-update-mode-line)))
1276
1277 (defun term-update-mode-line ()
1278 (setq mode-line-process
1279 (if (term-in-char-mode)
1280 (if (term-pager-enabled) '(": char page %s") '(": char %s"))
1281 (if (term-pager-enabled) '(": line page %s") '(": line %s"))))
1282 (force-mode-line-update))
1283
1284 (defun term-check-proc (buffer)
1285 "True if there is a process associated w/buffer BUFFER, and
1286 it is alive (status RUN or STOP). BUFFER can be either a buffer or the
1287 name of one."
1288 (let ((proc (get-buffer-process buffer)))
1289 (and proc (memq (process-status proc) '(run stop)))))
1290
1291 ;;;###autoload
1292 (defun make-term (name program &optional startfile &rest switches)
1293 "Make a term process NAME in a buffer, running PROGRAM.
1294 The name of the buffer is made by surrounding NAME with `*'s.
1295 If there is already a running process in that buffer, it is not restarted.
1296 Optional third arg STARTFILE is the name of a file to send the contents of to
1297 the process. Any more args are arguments to PROGRAM."
1298 (let ((buffer (get-buffer-create (concat "*" name "*"))))
1299 ;; If no process, or nuked process, crank up a new one and put buffer in
1300 ;; term mode. Otherwise, leave buffer and existing process alone.
1301 (cond ((not (term-check-proc buffer))
1302 (save-excursion
1303 (set-buffer buffer)
1304 (term-mode)) ; Install local vars, mode, keymap, ...
1305 (term-exec buffer name program startfile switches)))
1306 buffer))
1307
1308 ;;;###autoload
1309 (defun term (program)
1310 "Start a terminal-emulator in a new buffer.
1311 The buffer is in Term mode; see `term-mode' for the
1312 commands to use in that buffer.
1313
1314 \\<term-raw-map>Type \\[switch-to-buffer] to switch to another buffer."
1315 (interactive (list (read-from-minibuffer "Run program: "
1316 (or explicit-shell-file-name
1317 (getenv "ESHELL")
1318 (getenv "SHELL")
1319 "/bin/sh"))))
1320 (set-buffer (make-term "terminal" program))
1321 (term-mode)
1322 (term-char-mode)
1323 (switch-to-buffer "*terminal*"))
1324
1325 (defun term-exec (buffer name command startfile switches)
1326 "Start up a process in buffer for term modes.
1327 Blasts any old process running in the buffer. Doesn't set the buffer mode.
1328 You can use this to cheaply run a series of processes in the same term
1329 buffer. The hook `term-exec-hook' is run after each exec."
1330 (save-excursion
1331 (set-buffer buffer)
1332 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
1333 (when proc (delete-process proc)))
1334 ;; Crank up a new process
1335 (let ((proc (term-exec-1 name buffer command switches)))
1336 (make-local-variable 'term-ptyp)
1337 (setq term-ptyp process-connection-type) ; t if pty, nil if pipe.
1338 ;; Jump to the end, and set the process mark.
1339 (goto-char (point-max))
1340 (set-marker (process-mark proc) (point))
1341 (set-process-filter proc 'term-emulate-terminal)
1342 (set-process-sentinel proc 'term-sentinel)
1343 ;; Feed it the startfile.
1344 (cond (startfile
1345 ;;This is guaranteed to wait long enough
1346 ;;but has bad results if the term does not prompt at all
1347 ;; (while (= size (buffer-size))
1348 ;; (sleep-for 1))
1349 ;;I hope 1 second is enough!
1350 (sleep-for 1)
1351 (goto-char (point-max))
1352 (insert-file-contents startfile)
1353 (setq startfile (buffer-substring (point) (point-max)))
1354 (delete-region (point) (point-max))
1355 (term-send-string proc startfile)))
1356 (run-hooks 'term-exec-hook)
1357 buffer)))
1358
1359 (defun term-sentinel (proc msg)
1360 "Sentinel for term buffers.
1361 The main purpose is to get rid of the local keymap."
1362 (let ((buffer (process-buffer proc)))
1363 (when (memq (process-status proc) '(signal exit))
1364 (if (null (buffer-name buffer))
1365 ;; buffer killed
1366 (set-process-buffer proc nil)
1367 (let ((obuf (current-buffer)))
1368 ;; save-excursion isn't the right thing if
1369 ;; process-buffer is current-buffer
1370 (unwind-protect
1371 (progn
1372 ;; Write something in the compilation buffer
1373 ;; and hack its mode line.
1374 (set-buffer buffer)
1375 ;; Get rid of local keymap.
1376 (use-local-map nil)
1377 (term-handle-exit (process-name proc)
1378 msg)
1379 ;; Since the buffer and mode line will show that the
1380 ;; process is dead, we can delete it now. Otherwise it
1381 ;; will stay around until M-x list-processes.
1382 (delete-process proc))
1383 (set-buffer obuf)))
1384 ))))
1385
1386 (defun term-handle-exit (process-name msg)
1387 "Write process exit (or other change) message MSG in the current buffer."
1388 (let ((buffer-read-only nil)
1389 (omax (point-max))
1390 (opoint (point)))
1391 ;; Record where we put the message, so we can ignore it
1392 ;; later on.
1393 (goto-char omax)
1394 (insert ?\n "Process " process-name " " msg)
1395 ;; Force mode line redisplay soon.
1396 (force-mode-line-update)
1397 (when (and opoint (< opoint omax))
1398 (goto-char opoint))))
1399
1400
1401 ;;; Name to use for TERM.
1402 ;;; Using "emacs" loses, because bash disables editing if TERM == emacs.
1403 (defvar term-term-name "eterm-color")
1404 ; Format string, usage:
1405 ; (format term-termcap-string emacs-term-name "TERMCAP=" 24 80)
1406 (defvar term-termcap-format
1407 "%s%s:li#%d:co#%d:cl=\\E[H\\E[J:cd=\\E[J:bs:am:xn:cm=\\E[%%i%%d;%%dH\
1408 :nd=\\E[C:up=\\E[A:ce=\\E[K:ho=\\E[H:pt\
1409 :al=\\E[L:dl=\\E[M:DL=\\E[%%dM:AL=\\E[%%dL:cs=\\E[%%i%%d;%%dr:sf=^J\
1410 :dc=\\E[P:DC=\\E[%%dP:IC=\\E[%%d@:im=\\E[4h:ei=\\E[4l:mi:\
1411 :so=\\E[7m:se=\\E[m:us=\\E[4m:ue=\\E[m:md=\\E[1m:mr=\\E[7m:me=\\E[m\
1412 :UP=\\E[%%dA:DO=\\E[%%dB:LE=\\E[%%dD:RI=\\E[%%dC\
1413 :kl=\\EOD:kd=\\EOB:kr=\\EOC:ku=\\EOA:kN=\\E[6~:kP=\\E[5~:@7=\\E[4~:kh=\\E[1~\
1414 :mk=\\E[8m:cb=\\E[1K:op=\\E[39;49m:Co#8:pa#64:AB=\\E[4%%dm:AF=\\E[3%%dm:cr=^M\
1415 :bl=^G:do=^J:le=^H:ta=^I:se=\\E[27m:ue=\\E24m\
1416 :kb=^?:kD=^[[3~:sc=\\E7:rc=\\E8:r1=\\Ec:"
1417 ;;; : -undefine ic
1418 ;;; don't define :te=\\E[2J\\E[?47l\\E8:ti=\\E7\\E[?47h\
1419 "Termcap capabilities supported.")
1420
1421 ;;; This auxiliary function cranks up the process for term-exec in
1422 ;;; the appropriate environment.
1423
1424 (defun term-exec-1 (name buffer command switches)
1425 ;; We need to do an extra (fork-less) exec to run stty.
1426 ;; (This would not be needed if we had suitable Emacs primitives.)
1427 ;; The 'if ...; then shift; fi' hack is because Bourne shell
1428 ;; loses one arg when called with -c, and newer shells (bash, ksh) don't.
1429 ;; Thus we add an extra dummy argument "..", and then remove it.
1430 (let ((process-environment
1431 (nconc
1432 (list
1433 (format "TERM=%s" term-term-name)
1434 (format "TERMINFO=%s" data-directory)
1435 (format term-termcap-format "TERMCAP="
1436 term-term-name term-height term-width)
1437 ;; We are going to get rid of the binding for EMACS,
1438 ;; probably in Emacs 23, because it breaks
1439 ;; `./configure' of some packages that expect it to
1440 ;; say where to find EMACS.
1441 (format "EMACS=%s (term:%s)" emacs-version term-protocol-version)
1442 (format "INSIDE_EMACS=%s,term:%s" emacs-version term-protocol-version)
1443 (format "LINES=%d" term-height)
1444 (format "COLUMNS=%d" term-width))
1445 process-environment))
1446 (process-connection-type t)
1447 ;; We should suppress conversion of end-of-line format.
1448 (inhibit-eol-conversion t)
1449 ;; The process's output contains not just chars but also binary
1450 ;; escape codes, so we need to see the raw output. We will have to
1451 ;; do the decoding by hand on the parts that are made of chars.
1452 (coding-system-for-read 'binary))
1453 (apply 'start-process name buffer
1454 "/bin/sh" "-c"
1455 (format "stty -nl echo rows %d columns %d sane 2>/dev/null;\
1456 if [ $1 = .. ]; then shift; fi; exec \"$@\""
1457 term-height term-width)
1458 ".."
1459 command switches)))
1460
1461 \f
1462 ;;; Input history processing in a buffer
1463 ;;; ===========================================================================
1464 ;;; Useful input history functions, courtesy of the Ergo group.
1465
1466 ;;; Eleven commands:
1467 ;;; term-dynamic-list-input-ring List history in help buffer.
1468 ;;; term-previous-input Previous input...
1469 ;;; term-previous-matching-input ...matching a string.
1470 ;;; term-previous-matching-input-from-input ... matching the current input.
1471 ;;; term-next-input Next input...
1472 ;;; term-next-matching-input ...matching a string.
1473 ;;; term-next-matching-input-from-input ... matching the current input.
1474 ;;; term-backward-matching-input Backwards input...
1475 ;;; term-forward-matching-input ...matching a string.
1476 ;;; term-replace-by-expanded-history Expand history at point;
1477 ;;; replace with expanded history.
1478 ;;; term-magic-space Expand history and insert space.
1479 ;;;
1480 ;;; Three functions:
1481 ;;; term-read-input-ring Read into term-input-ring...
1482 ;;; term-write-input-ring Write to term-input-ring-file-name.
1483 ;;; term-replace-by-expanded-history-before-point Workhorse function.
1484
1485 (defun term-read-input-ring (&optional silent)
1486 "Sets the buffer's `term-input-ring' from a history file.
1487 The name of the file is given by the variable `term-input-ring-file-name'.
1488 The history ring is of size `term-input-ring-size', regardless of file size.
1489 If `term-input-ring-file-name' is nil this function does nothing.
1490
1491 If the optional argument SILENT is non-nil, we say nothing about a
1492 failure to read the history file.
1493
1494 This function is useful for major mode commands and mode hooks.
1495
1496 The structure of the history file should be one input command per line,
1497 with the most recent command last.
1498 See also `term-input-ignoredups' and `term-write-input-ring'."
1499 (cond ((or (null term-input-ring-file-name)
1500 (equal term-input-ring-file-name ""))
1501 nil)
1502 ((not (file-readable-p term-input-ring-file-name))
1503 (or silent
1504 (message "Cannot read history file %s"
1505 term-input-ring-file-name)))
1506 (t
1507 (let ((history-buf (get-buffer-create " *temp*"))
1508 (file term-input-ring-file-name)
1509 (count 0)
1510 (ring (make-ring term-input-ring-size)))
1511 (unwind-protect
1512 (save-excursion
1513 (set-buffer history-buf)
1514 (widen)
1515 (erase-buffer)
1516 (insert-file-contents file)
1517 ;; Save restriction in case file is already visited...
1518 ;; Watch for those date stamps in history files!
1519 (goto-char (point-max))
1520 (while (and (< count term-input-ring-size)
1521 (re-search-backward "^[ \t]*\\([^#\n].*\\)[ \t]*$"
1522 nil t))
1523 (let ((history (buffer-substring (match-beginning 1)
1524 (match-end 1))))
1525 (when (or (null term-input-ignoredups)
1526 (ring-empty-p ring)
1527 (not (string-equal (ring-ref ring 0) history)))
1528 (ring-insert-at-beginning ring history)))
1529 (setq count (1+ count))))
1530 (kill-buffer history-buf))
1531 (setq term-input-ring ring
1532 term-input-ring-index nil)))))
1533
1534 (defun term-write-input-ring ()
1535 "Writes the buffer's `term-input-ring' to a history file.
1536 The name of the file is given by the variable `term-input-ring-file-name'.
1537 The original contents of the file are lost if `term-input-ring' is not empty.
1538 If `term-input-ring-file-name' is nil this function does nothing.
1539
1540 Useful within process sentinels.
1541
1542 See also `term-read-input-ring'."
1543 (cond ((or (null term-input-ring-file-name)
1544 (equal term-input-ring-file-name "")
1545 (null term-input-ring) (ring-empty-p term-input-ring))
1546 nil)
1547 ((not (file-writable-p term-input-ring-file-name))
1548 (message "Cannot write history file %s" term-input-ring-file-name))
1549 (t
1550 (let* ((history-buf (get-buffer-create " *Temp Input History*"))
1551 (ring term-input-ring)
1552 (file term-input-ring-file-name)
1553 (index (ring-length ring)))
1554 ;; Write it all out into a buffer first. Much faster, but messier,
1555 ;; than writing it one line at a time.
1556 (save-excursion
1557 (set-buffer history-buf)
1558 (erase-buffer)
1559 (while (> index 0)
1560 (setq index (1- index))
1561 (insert (ring-ref ring index) ?\n))
1562 (write-region (buffer-string) nil file nil 'no-message)
1563 (kill-buffer nil))))))
1564
1565
1566 (defun term-dynamic-list-input-ring ()
1567 "List in help buffer the buffer's input history."
1568 (interactive)
1569 (if (or (not (ring-p term-input-ring))
1570 (ring-empty-p term-input-ring))
1571 (message "No history")
1572 (let ((history nil)
1573 (history-buffer " *Input History*")
1574 (index (1- (ring-length term-input-ring)))
1575 (conf (current-window-configuration)))
1576 ;; We have to build up a list ourselves from the ring vector.
1577 (while (>= index 0)
1578 (setq history (cons (ring-ref term-input-ring index) history)
1579 index (1- index)))
1580 ;; Change "completion" to "history reference"
1581 ;; to make the display accurate.
1582 (with-output-to-temp-buffer history-buffer
1583 (display-completion-list history)
1584 (set-buffer history-buffer)
1585 (forward-line 3)
1586 (while (search-backward "completion" nil 'move)
1587 (replace-match "history reference")))
1588 (sit-for 0)
1589 (message "Hit space to flush")
1590 (let ((ch (read-event)))
1591 (if (eq ch ?\s)
1592 (set-window-configuration conf)
1593 (setq unread-command-events (list ch)))))))
1594
1595
1596 (defun term-regexp-arg (prompt)
1597 ;; Return list of regexp and prefix arg using PROMPT.
1598 (let* (;; Don't clobber this.
1599 (last-command last-command)
1600 (regexp (read-from-minibuffer prompt nil nil nil
1601 'minibuffer-history-search-history)))
1602 (list (if (string-equal regexp "")
1603 (setcar minibuffer-history-search-history
1604 (nth 1 minibuffer-history-search-history))
1605 regexp)
1606 (prefix-numeric-value current-prefix-arg))))
1607
1608 (defun term-search-arg (arg)
1609 ;; First make sure there is a ring and that we are after the process mark
1610 (cond ((not (term-after-pmark-p))
1611 (error "Not at command line"))
1612 ((or (null term-input-ring)
1613 (ring-empty-p term-input-ring))
1614 (error "Empty input ring"))
1615 ((zerop arg)
1616 ;; arg of zero resets search from beginning, and uses arg of 1
1617 (setq term-input-ring-index nil)
1618 1)
1619 (t
1620 arg)))
1621
1622 (defun term-search-start (arg)
1623 ;; Index to start a directional search, starting at term-input-ring-index
1624 (if term-input-ring-index
1625 ;; If a search is running, offset by 1 in direction of arg
1626 (mod (+ term-input-ring-index (if (> arg 0) 1 -1))
1627 (ring-length term-input-ring))
1628 ;; For a new search, start from beginning or end, as appropriate
1629 (if (>= arg 0)
1630 0 ; First elt for forward search
1631 (1- (ring-length term-input-ring))))) ; Last elt for backward search
1632
1633 (defun term-previous-input-string (arg)
1634 "Return the string ARG places along the input ring.
1635 Moves relative to `term-input-ring-index'."
1636 (ring-ref term-input-ring (if term-input-ring-index
1637 (mod (+ arg term-input-ring-index)
1638 (ring-length term-input-ring))
1639 arg)))
1640
1641 (defun term-previous-input (arg)
1642 "Cycle backwards through input history."
1643 (interactive "*p")
1644 (term-previous-matching-input "." arg))
1645
1646 (defun term-next-input (arg)
1647 "Cycle forwards through input history."
1648 (interactive "*p")
1649 (term-previous-input (- arg)))
1650
1651 (defun term-previous-matching-input-string (regexp arg)
1652 "Return the string matching REGEXP ARG places along the input ring.
1653 Moves relative to `term-input-ring-index'."
1654 (let* ((pos (term-previous-matching-input-string-position regexp arg)))
1655 (when pos (ring-ref term-input-ring pos))))
1656
1657 (defun term-previous-matching-input-string-position
1658 (regexp arg &optional start)
1659 "Return the index matching REGEXP ARG places along the input ring.
1660 Moves relative to START, or `term-input-ring-index'."
1661 (when (or (not (ring-p term-input-ring))
1662 (ring-empty-p term-input-ring))
1663 (error "No history"))
1664 (let* ((len (ring-length term-input-ring))
1665 (motion (if (> arg 0) 1 -1))
1666 (n (mod (- (or start (term-search-start arg)) motion) len))
1667 (tried-each-ring-item nil)
1668 (prev nil))
1669 ;; Do the whole search as many times as the argument says.
1670 (while (and (/= arg 0) (not tried-each-ring-item))
1671 ;; Step once.
1672 (setq prev n
1673 n (mod (+ n motion) len))
1674 ;; If we haven't reached a match, step some more.
1675 (while (and (< n len) (not tried-each-ring-item)
1676 (not (string-match regexp (ring-ref term-input-ring n))))
1677 (setq n (mod (+ n motion) len)
1678 ;; If we have gone all the way around in this search.
1679 tried-each-ring-item (= n prev)))
1680 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1681 ;; Now that we know which ring element to use, if we found it, return that.
1682 (when (string-match regexp (ring-ref term-input-ring n))
1683 n)))
1684
1685 (defun term-previous-matching-input (regexp arg)
1686 "Search backwards through input history for match for REGEXP.
1687 \(Previous history elements are earlier commands.)
1688 With prefix argument N, search for Nth previous match.
1689 If N is negative, find the next or Nth next match."
1690 (interactive (term-regexp-arg "Previous input matching (regexp): "))
1691 (setq arg (term-search-arg arg))
1692 (let ((pos (term-previous-matching-input-string-position regexp arg)))
1693 ;; Has a match been found?
1694 (if (null pos)
1695 (error "Not found")
1696 (setq term-input-ring-index pos)
1697 (message "History item: %d" (1+ pos))
1698 (delete-region
1699 ;; Can't use kill-region as it sets this-command
1700 (process-mark (get-buffer-process (current-buffer))) (point))
1701 (insert (ring-ref term-input-ring pos)))))
1702
1703 (defun term-next-matching-input (regexp arg)
1704 "Search forwards through input history for match for REGEXP.
1705 \(Later history elements are more recent commands.)
1706 With prefix argument N, search for Nth following match.
1707 If N is negative, find the previous or Nth previous match."
1708 (interactive (term-regexp-arg "Next input matching (regexp): "))
1709 (term-previous-matching-input regexp (- arg)))
1710
1711 (defun term-previous-matching-input-from-input (arg)
1712 "Search backwards through input history for match for current input.
1713 \(Previous history elements are earlier commands.)
1714 With prefix argument N, search for Nth previous match.
1715 If N is negative, search forwards for the -Nth following match."
1716 (interactive "p")
1717 (when (not (memq last-command '(term-previous-matching-input-from-input
1718 term-next-matching-input-from-input)))
1719 ;; Starting a new search
1720 (setq term-matching-input-from-input-string
1721 (buffer-substring
1722 (process-mark (get-buffer-process (current-buffer)))
1723 (point))
1724 term-input-ring-index nil))
1725 (term-previous-matching-input
1726 (concat "^" (regexp-quote term-matching-input-from-input-string))
1727 arg))
1728
1729 (defun term-next-matching-input-from-input (arg)
1730 "Search forwards through input history for match for current input.
1731 \(Following history elements are more recent commands.)
1732 With prefix argument N, search for Nth following match.
1733 If N is negative, search backwards for the -Nth previous match."
1734 (interactive "p")
1735 (term-previous-matching-input-from-input (- arg)))
1736
1737
1738 (defun term-replace-by-expanded-history (&optional silent)
1739 "Expand input command history references before point.
1740 Expansion is dependent on the value of `term-input-autoexpand'.
1741
1742 This function depends on the buffer's idea of the input history, which may not
1743 match the command interpreter's idea, assuming it has one.
1744
1745 Assumes history syntax is like typical Un*x shells'. However, since Emacs
1746 cannot know the interpreter's idea of input line numbers, assuming it has one,
1747 it cannot expand absolute input line number references.
1748
1749 If the optional argument SILENT is non-nil, never complain
1750 even if history reference seems erroneous.
1751
1752 See `term-magic-space' and `term-replace-by-expanded-history-before-point'.
1753
1754 Returns t if successful."
1755 (interactive)
1756 (when (and term-input-autoexpand
1757 (string-match "[!^]" (funcall term-get-old-input))
1758 (save-excursion (beginning-of-line)
1759 (looking-at term-prompt-regexp)))
1760 ;; Looks like there might be history references in the command.
1761 (let ((previous-modified-tick (buffer-modified-tick)))
1762 (message "Expanding history references...")
1763 (term-replace-by-expanded-history-before-point silent)
1764 (/= previous-modified-tick (buffer-modified-tick)))))
1765
1766
1767 (defun term-replace-by-expanded-history-before-point (silent)
1768 "Expand directory stack reference before point.
1769 See `term-replace-by-expanded-history'. Returns t if successful."
1770 (save-excursion
1771 (let ((toend (- (save-excursion (end-of-line nil) (point)) (point)))
1772 (start (progn (term-bol nil) (point))))
1773 (while (progn
1774 (skip-chars-forward "^!^"
1775 (save-excursion
1776 (end-of-line nil) (- (point) toend)))
1777 (< (point)
1778 (save-excursion
1779 (end-of-line nil) (- (point) toend))))
1780 ;; This seems a bit complex. We look for references such as !!, !-num,
1781 ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
1782 ;; If that wasn't enough, the plings can be suffixed with argument
1783 ;; range specifiers.
1784 ;; Argument ranges are complex too, so we hive off the input line,
1785 ;; referenced with plings, with the range string to `term-args'.
1786 (setq term-input-ring-index nil)
1787 (cond ((or (= (preceding-char) ?\\)
1788 (term-within-quotes start (point)))
1789 ;; The history is quoted, or we're in quotes.
1790 (goto-char (1+ (point))))
1791 ((looking-at "![0-9]+\\($\\|[^-]\\)")
1792 ;; We cannot know the interpreter's idea of input line numbers.
1793 (goto-char (match-end 0))
1794 (message "Absolute reference cannot be expanded"))
1795 ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
1796 ;; Just a number of args from `number' lines backward.
1797 (let ((number (1- (string-to-number
1798 (buffer-substring (match-beginning 1)
1799 (match-end 1))))))
1800 (if (<= number (ring-length term-input-ring))
1801 (progn
1802 (replace-match
1803 (term-args (term-previous-input-string number)
1804 (match-beginning 2) (match-end 2))
1805 t t)
1806 (setq term-input-ring-index number)
1807 (message "History item: %d" (1+ number)))
1808 (goto-char (match-end 0))
1809 (message "Relative reference exceeds input history size"))))
1810 ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
1811 ;; Just a number of args from the previous input line.
1812 (replace-match
1813 (term-args (term-previous-input-string 0)
1814 (match-beginning 1) (match-end 1))
1815 t t)
1816 (message "History item: previous"))
1817 ((looking-at
1818 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
1819 ;; Most recent input starting with or containing (possibly
1820 ;; protected) string, maybe just a number of args. Phew.
1821 (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
1822 (mb2 (match-beginning 2)) (me2 (match-end 2))
1823 (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
1824 (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
1825 (pos (save-match-data
1826 (term-previous-matching-input-string-position
1827 (concat pref (regexp-quote exp)) 1))))
1828 (if (null pos)
1829 (progn
1830 (goto-char (match-end 0))
1831 (or silent
1832 (progn (message "Not found")
1833 (ding))))
1834 (setq term-input-ring-index pos)
1835 (replace-match
1836 (term-args (ring-ref term-input-ring pos)
1837 (match-beginning 4) (match-end 4))
1838 t t)
1839 (message "History item: %d" (1+ pos)))))
1840 ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
1841 ;; Quick substitution on the previous input line.
1842 (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
1843 (new (buffer-substring (match-beginning 2) (match-end 2)))
1844 (pos nil))
1845 (replace-match (term-previous-input-string 0) t t)
1846 (setq pos (point))
1847 (goto-char (match-beginning 0))
1848 (if (not (search-forward old pos t))
1849 (or silent
1850 (error "Not found"))
1851 (replace-match new t t)
1852 (message "History item: substituted"))))
1853 (t
1854 (goto-char (match-end 0))))))))
1855
1856
1857 (defun term-magic-space (arg)
1858 "Expand input history references before point and insert ARG spaces.
1859 A useful command to bind to SPC. See `term-replace-by-expanded-history'."
1860 (interactive "p")
1861 (term-replace-by-expanded-history)
1862 (self-insert-command arg))
1863 \f
1864 (defun term-within-quotes (beg end)
1865 "Return t if the number of quotes between BEG and END is odd.
1866 Quotes are single and double."
1867 (let ((countsq (term-how-many-region "\\(^\\|[^\\\\]\\)\'" beg end))
1868 (countdq (term-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
1869 (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
1870
1871 (defun term-how-many-region (regexp beg end)
1872 "Return number of matches for REGEXP from BEG to END."
1873 (let ((count 0))
1874 (save-excursion
1875 (save-match-data
1876 (goto-char beg)
1877 (while (re-search-forward regexp end t)
1878 (setq count (1+ count)))))
1879 count))
1880
1881 (defun term-args (string begin end)
1882 ;; From STRING, return the args depending on the range specified in the text
1883 ;; from BEGIN to END. If BEGIN is nil, assume all args. Ignore leading `:'.
1884 ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
1885 (save-match-data
1886 (if (null begin)
1887 (term-arguments string 0 nil)
1888 (let* ((range (buffer-substring
1889 (if (eq (char-after begin) ?:) (1+ begin) begin) end))
1890 (nth (cond ((string-match "^[*^]" range) 1)
1891 ((string-match "^-" range) 0)
1892 ((string-equal range "$") nil)
1893 (t (string-to-number range))))
1894 (mth (cond ((string-match "[-*$]$" range) nil)
1895 ((string-match "-" range)
1896 (string-to-number (substring range (match-end 0))))
1897 (t nth))))
1898 (term-arguments string nth mth)))))
1899
1900 ;; Return a list of arguments from ARG. Break it up at the
1901 ;; delimiters in term-delimiter-argument-list. Returned list is backwards.
1902 (defun term-delim-arg (arg)
1903 (if (null term-delimiter-argument-list)
1904 (list arg)
1905 (let ((args nil)
1906 (pos 0)
1907 (len (length arg)))
1908 (while (< pos len)
1909 (let ((char (aref arg pos))
1910 (start pos))
1911 (if (memq char term-delimiter-argument-list)
1912 (while (and (< pos len) (eq (aref arg pos) char))
1913 (setq pos (1+ pos)))
1914 (while (and (< pos len)
1915 (not (memq (aref arg pos)
1916 term-delimiter-argument-list)))
1917 (setq pos (1+ pos))))
1918 (setq args (cons (substring arg start pos) args))))
1919 args)))
1920
1921 (defun term-arguments (string nth mth)
1922 "Return from STRING the NTH to MTH arguments.
1923 NTH and/or MTH can be nil, which means the last argument.
1924 Returned arguments are separated by single spaces.
1925 We assume whitespace separates arguments, except within quotes.
1926 Also, a run of one or more of a single character
1927 in `term-delimiter-argument-list' is a separate argument.
1928 Argument 0 is the command name."
1929 (let ((argpart "[^ \n\t\"'`]+\\|\\(\"[^\"]*\"\\|'[^']*'\\|`[^`]*`\\)")
1930 (args ()) (pos 0)
1931 (count 0)
1932 beg str quotes)
1933 ;; Build a list of all the args until we have as many as we want.
1934 (while (and (or (null mth) (<= count mth))
1935 (string-match argpart string pos))
1936 (if (and beg (= pos (match-beginning 0)))
1937 ;; It's contiguous, part of the same arg.
1938 (setq pos (match-end 0)
1939 quotes (or quotes (match-beginning 1)))
1940 ;; It's a new separate arg.
1941 (if beg
1942 ;; Put the previous arg, if there was one, onto ARGS.
1943 (setq str (substring string beg pos)
1944 args (if quotes (cons str args)
1945 (nconc (term-delim-arg str) args))
1946 count (1+ count)))
1947 (setq quotes (match-beginning 1))
1948 (setq beg (match-beginning 0))
1949 (setq pos (match-end 0))))
1950 (if beg
1951 (setq str (substring string beg pos)
1952 args (if quotes (cons str args)
1953 (nconc (term-delim-arg str) args))
1954 count (1+ count)))
1955 (let ((n (or nth (1- count)))
1956 (m (if mth (1- (- count mth)) 0)))
1957 (mapconcat
1958 (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
1959 \f
1960 ;;;
1961 ;;; Input processing stuff [line mode]
1962 ;;;
1963
1964 (defun term-send-input ()
1965 "Send input to process.
1966 After the process output mark, sends all text from the process mark to
1967 point as input to the process. Before the process output mark, calls value
1968 of variable term-get-old-input to retrieve old input, copies it to the
1969 process mark, and sends it. A terminal newline is also inserted into the
1970 buffer and sent to the process. The list of function names contained in the
1971 value of `term-input-filter-functions' is called on the input before sending
1972 it. The input is entered into the input history ring, if the value of variable
1973 term-input-filter returns non-nil when called on the input.
1974
1975 Any history reference may be expanded depending on the value of the variable
1976 `term-input-autoexpand'. The list of function names contained in the value
1977 of `term-input-filter-functions' is called on the input before sending it.
1978 The input is entered into the input history ring, if the value of variable
1979 `term-input-filter' returns non-nil when called on the input.
1980
1981 If variable `term-eol-on-send' is non-nil, then point is moved to the
1982 end of line before sending the input.
1983
1984 The values of `term-get-old-input', `term-input-filter-functions', and
1985 `term-input-filter' are chosen according to the command interpreter running
1986 in the buffer. E.g.,
1987
1988 If the interpreter is the csh,
1989 term-get-old-input is the default: take the current line, discard any
1990 initial string matching regexp term-prompt-regexp.
1991 term-input-filter-functions monitors input for \"cd\", \"pushd\", and
1992 \"popd\" commands. When it sees one, it cd's the buffer.
1993 term-input-filter is the default: returns t if the input isn't all white
1994 space.
1995
1996 If the term is Lucid Common Lisp,
1997 term-get-old-input snarfs the sexp ending at point.
1998 term-input-filter-functions does nothing.
1999 term-input-filter returns nil if the input matches input-filter-regexp,
2000 which matches (1) all whitespace (2) :a, :c, etc.
2001
2002 Similarly for Soar, Scheme, etc."
2003 (interactive)
2004 ;; Note that the input string does not include its terminal newline.
2005 (let ((proc (get-buffer-process (current-buffer))))
2006 (if (not proc) (error "Current buffer has no process")
2007 (let* ((pmark (process-mark proc))
2008 (pmark-val (marker-position pmark))
2009 (input-is-new (>= (point) pmark-val))
2010 (intxt (if input-is-new
2011 (progn (if term-eol-on-send (end-of-line))
2012 (buffer-substring pmark (point)))
2013 (funcall term-get-old-input)))
2014 (input (if (not (eq term-input-autoexpand 'input))
2015 ;; Just whatever's already there
2016 intxt
2017 ;; Expand and leave it visible in buffer
2018 (term-replace-by-expanded-history t)
2019 (buffer-substring pmark (point))))
2020 (history (if (not (eq term-input-autoexpand 'history))
2021 input
2022 ;; This is messy 'cos ultimately the original
2023 ;; functions used do insertion, rather than return
2024 ;; strings. We have to expand, then insert back.
2025 (term-replace-by-expanded-history t)
2026 (let ((copy (buffer-substring pmark (point))))
2027 (delete-region pmark (point))
2028 (insert input)
2029 copy))))
2030 (when (term-pager-enabled)
2031 (save-excursion
2032 (goto-char (process-mark proc))
2033 (setq term-pager-count (term-current-row))))
2034 (when (and (funcall term-input-filter history)
2035 (or (null term-input-ignoredups)
2036 (not (ring-p term-input-ring))
2037 (ring-empty-p term-input-ring)
2038 (not (string-equal (ring-ref term-input-ring 0)
2039 history))))
2040 (ring-insert term-input-ring history))
2041 (let ((functions term-input-filter-functions))
2042 (while functions
2043 (funcall (car functions) (concat input "\n"))
2044 (setq functions (cdr functions))))
2045 (setq term-input-ring-index nil)
2046
2047 ;; Update the markers before we send the input
2048 ;; in case we get output amidst sending the input.
2049 (set-marker term-last-input-start pmark)
2050 (set-marker term-last-input-end (point))
2051 (when input-is-new
2052 ;; Set up to delete, because inferior should echo.
2053 (when (marker-buffer term-pending-delete-marker)
2054 (delete-region term-pending-delete-marker pmark))
2055 (set-marker term-pending-delete-marker pmark-val)
2056 (set-marker (process-mark proc) (point)))
2057 (goto-char pmark)
2058 (funcall term-input-sender proc input)))))
2059
2060 (defun term-get-old-input-default ()
2061 "Default for `term-get-old-input'.
2062 Take the current line, and discard any initial text matching
2063 `term-prompt-regexp'."
2064 (save-excursion
2065 (beginning-of-line)
2066 (term-skip-prompt)
2067 (let ((beg (point)))
2068 (end-of-line)
2069 (buffer-substring beg (point)))))
2070
2071 (defun term-copy-old-input ()
2072 "Insert after prompt old input at point as new input to be edited.
2073 Calls `term-get-old-input' to get old input."
2074 (interactive)
2075 (let ((input (funcall term-get-old-input))
2076 (process (get-buffer-process (current-buffer))))
2077 (if (not process)
2078 (error "Current buffer has no process")
2079 (goto-char (process-mark process))
2080 (insert input))))
2081
2082 (defun term-skip-prompt ()
2083 "Skip past the text matching regexp `term-prompt-regexp'.
2084 If this takes us past the end of the current line, don't skip at all."
2085 (let ((eol (save-excursion (end-of-line) (point))))
2086 (when (and (looking-at term-prompt-regexp)
2087 (<= (match-end 0) eol))
2088 (goto-char (match-end 0)))))
2089
2090
2091 (defun term-after-pmark-p ()
2092 "Is point after the process output marker?"
2093 ;; Since output could come into the buffer after we looked at the point
2094 ;; but before we looked at the process marker's value, we explicitly
2095 ;; serialise. This is just because I don't know whether or not Emacs
2096 ;; services input during execution of lisp commands.
2097 (let ((proc-pos (marker-position
2098 (process-mark (get-buffer-process (current-buffer))))))
2099 (<= proc-pos (point))))
2100
2101 (defun term-simple-send (proc string)
2102 "Default function for sending to PROC input STRING.
2103 This just sends STRING plus a newline. To override this,
2104 set the hook `term-input-sender'."
2105 (term-send-string proc string)
2106 (term-send-string proc "\n"))
2107
2108 (defun term-bol (arg)
2109 "Goes to the beginning of line, then skips past the prompt, if any.
2110 If a prefix argument is given (\\[universal-argument]), then no prompt skip
2111 -- go straight to column 0.
2112
2113 The prompt skip is done by skipping text matching the regular expression
2114 `term-prompt-regexp', a buffer local variable."
2115 (interactive "P")
2116 (beginning-of-line)
2117 (when (null arg) (term-skip-prompt)))
2118
2119 ;;; These two functions are for entering text you don't want echoed or
2120 ;;; saved -- typically passwords to ftp, telnet, or somesuch.
2121 ;;; Just enter m-x term-send-invisible and type in your line.
2122
2123 (defun term-read-noecho (prompt &optional stars)
2124 "Read a single line of text from user without echoing, and return it.
2125 Prompt with argument PROMPT, a string. Optional argument STARS causes
2126 input to be echoed with '*' characters on the prompt line. Input ends with
2127 RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line. C-g aborts (if
2128 `inhibit-quit' is set because e.g. this function was called from a process
2129 filter and C-g is pressed, this function returns nil rather than a string).
2130
2131 Note that the keystrokes comprising the text can still be recovered
2132 \(temporarily) with \\[view-lossage]. This may be a security bug for some
2133 applications."
2134 (let ((ans "")
2135 (c 0)
2136 (echo-keystrokes 0)
2137 (cursor-in-echo-area t)
2138 (done nil))
2139 (while (not done)
2140 (if stars
2141 (message "%s%s" prompt (make-string (length ans) ?*))
2142 (message "%s" prompt))
2143 (setq c (read-char))
2144 (cond ((= c ?\C-g)
2145 ;; This function may get called from a process filter, where
2146 ;; inhibit-quit is set. In later versions of Emacs read-char
2147 ;; may clear quit-flag itself and return C-g. That would make
2148 ;; it impossible to quit this loop in a simple way, so
2149 ;; re-enable it here (for backward-compatibility the check for
2150 ;; quit-flag below would still be necessary, so this seems
2151 ;; like the simplest way to do things).
2152 (setq quit-flag t
2153 done t))
2154 ((or (= c ?\r) (= c ?\n) (= c ?\e))
2155 (setq done t))
2156 ((= c ?\C-u)
2157 (setq ans ""))
2158 ((and (/= c ?\b) (/= c ?\177))
2159 (setq ans (concat ans (char-to-string c))))
2160 ((> (length ans) 0)
2161 (setq ans (substring ans 0 -1)))))
2162 (if quit-flag
2163 ;; Emulate a true quit, except that we have to return a value.
2164 (prog1
2165 (setq quit-flag nil)
2166 (message "Quit")
2167 (beep t))
2168 (message "")
2169 ans)))
2170
2171 (defun term-send-invisible (str &optional proc)
2172 "Read a string without echoing.
2173 Then send it to the process running in the current buffer. A new-line
2174 is additionally sent. String is not saved on term input history list.
2175 Security bug: your string can still be temporarily recovered with
2176 \\[view-lossage]."
2177 (interactive "P") ; Defeat snooping via C-x esc
2178 (when (not (stringp str))
2179 (setq str (term-read-noecho "Non-echoed text: " t)))
2180 (when (not proc)
2181 (setq proc (get-buffer-process (current-buffer))))
2182 (if (not proc) (error "Current buffer has no process")
2183 (setq term-kill-echo-list (nconc term-kill-echo-list
2184 (cons str nil)))
2185 (term-send-string proc str)
2186 (term-send-string proc "\n")))
2187
2188 \f
2189 ;;; Low-level process communication
2190
2191 (defvar term-input-chunk-size 512
2192 "*Long inputs send to term processes are broken up into chunks of this size.
2193 If your process is choking on big inputs, try lowering the value.")
2194
2195 (defun term-send-string (proc str)
2196 "Send to PROC the contents of STR as input.
2197 This is equivalent to `process-send-string', except that long input strings
2198 are broken up into chunks of size `term-input-chunk-size'. Processes
2199 are given a chance to output between chunks. This can help prevent processes
2200 from hanging when you send them long inputs on some OS's."
2201 (let* ((len (length str))
2202 (i (min len term-input-chunk-size)))
2203 (process-send-string proc (substring str 0 i))
2204 (while (< i len)
2205 (let ((next-i (+ i term-input-chunk-size)))
2206 (accept-process-output)
2207 (process-send-string proc (substring str i (min len next-i)))
2208 (setq i next-i)))))
2209
2210 (defun term-send-region (proc start end)
2211 "Send to PROC the region delimited by START and END.
2212 This is a replacement for `process-send-region' that tries to keep
2213 your process from hanging on long inputs. See `term-send-string'."
2214 (term-send-string proc (buffer-substring start end)))
2215
2216 \f
2217 ;;; Random input hackage
2218
2219 (defun term-kill-output ()
2220 "Kill all output from interpreter since last input."
2221 (interactive)
2222 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2223 (kill-region term-last-input-end pmark)
2224 (goto-char pmark)
2225 (insert "*** output flushed ***\n")
2226 (set-marker pmark (point))))
2227
2228 (defun term-show-output ()
2229 "Display start of this batch of interpreter output at top of window.
2230 Sets mark to the value of point when this command is run."
2231 (interactive)
2232 (goto-char term-last-input-end)
2233 (backward-char)
2234 (beginning-of-line)
2235 (set-window-start (selected-window) (point))
2236 (end-of-line))
2237
2238 (defun term-interrupt-subjob ()
2239 "Interrupt the current subjob."
2240 (interactive)
2241 (interrupt-process nil term-ptyp))
2242
2243 (defun term-kill-subjob ()
2244 "Send kill signal to the current subjob."
2245 (interactive)
2246 (kill-process nil term-ptyp))
2247
2248 (defun term-quit-subjob ()
2249 "Send quit signal to the current subjob."
2250 (interactive)
2251 (quit-process nil term-ptyp))
2252
2253 (defun term-stop-subjob ()
2254 "Stop the current subjob.
2255 WARNING: if there is no current subjob, you can end up suspending
2256 the top-level process running in the buffer. If you accidentally do
2257 this, use \\[term-continue-subjob] to resume the process. (This
2258 is not a problem with most shells, since they ignore this signal.)"
2259 (interactive)
2260 (stop-process nil term-ptyp))
2261
2262 (defun term-continue-subjob ()
2263 "Send CONT signal to process buffer's process group.
2264 Useful if you accidentally suspend the top-level process."
2265 (interactive)
2266 (continue-process nil term-ptyp))
2267
2268 (defun term-kill-input ()
2269 "Kill all text from last stuff output by interpreter to point."
2270 (interactive)
2271 (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
2272 (p-pos (marker-position pmark)))
2273 (when (> (point) p-pos)
2274 (kill-region pmark (point)))))
2275
2276 (defun term-delchar-or-maybe-eof (arg)
2277 "Delete ARG characters forward, or send an EOF to process if at end of
2278 buffer."
2279 (interactive "p")
2280 (if (eobp)
2281 (process-send-eof)
2282 (delete-char arg)))
2283
2284 (defun term-send-eof ()
2285 "Send an EOF to the current buffer's process."
2286 (interactive)
2287 (process-send-eof))
2288
2289 (defun term-backward-matching-input (regexp arg)
2290 "Search backward through buffer for match for REGEXP.
2291 Matches are searched for on lines that match `term-prompt-regexp'.
2292 With prefix argument N, search for Nth previous match.
2293 If N is negative, find the next or Nth next match."
2294 (interactive (term-regexp-arg "Backward input matching (regexp): "))
2295 (let* ((re (concat term-prompt-regexp ".*" regexp))
2296 (pos (save-excursion (end-of-line (if (> arg 0) 0 1))
2297 (when (re-search-backward re nil t arg)
2298 (point)))))
2299 (if (null pos)
2300 (progn (message "Not found")
2301 (ding))
2302 (goto-char pos)
2303 (term-bol nil))))
2304
2305 (defun term-forward-matching-input (regexp arg)
2306 "Search forward through buffer for match for REGEXP.
2307 Matches are searched for on lines that match `term-prompt-regexp'.
2308 With prefix argument N, search for Nth following match.
2309 If N is negative, find the previous or Nth previous match."
2310 (interactive (term-regexp-arg "Forward input matching (regexp): "))
2311 (term-backward-matching-input regexp (- arg)))
2312
2313
2314 (defun term-next-prompt (n)
2315 "Move to end of Nth next prompt in the buffer.
2316 See `term-prompt-regexp'."
2317 (interactive "p")
2318 (let ((paragraph-start term-prompt-regexp))
2319 (end-of-line (if (> n 0) 1 0))
2320 (forward-paragraph n)
2321 (term-skip-prompt)))
2322
2323 (defun term-previous-prompt (n)
2324 "Move to end of Nth previous prompt in the buffer.
2325 See `term-prompt-regexp'."
2326 (interactive "p")
2327 (term-next-prompt (- n)))
2328 \f
2329 ;;; Support for source-file processing commands.
2330 ;;;============================================================================
2331 ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
2332 ;;; commands that process files of source text (e.g. loading or compiling
2333 ;;; files). So the corresponding process-in-a-buffer modes have commands
2334 ;;; for doing this (e.g., lisp-load-file). The functions below are useful
2335 ;;; for defining these commands.
2336 ;;;
2337 ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
2338 ;;; and Soar, in that they don't know anything about file extensions.
2339 ;;; So the compile/load interface gets the wrong default occasionally.
2340 ;;; The load-file/compile-file default mechanism could be smarter -- it
2341 ;;; doesn't know about the relationship between filename extensions and
2342 ;;; whether the file is source or executable. If you compile foo.lisp
2343 ;;; with compile-file, then the next load-file should use foo.bin for
2344 ;;; the default, not foo.lisp. This is tricky to do right, particularly
2345 ;;; because the extension for executable files varies so much (.o, .bin,
2346 ;;; .lbin, .mo, .vo, .ao, ...).
2347
2348
2349 ;;; TERM-SOURCE-DEFAULT -- determines defaults for source-file processing
2350 ;;; commands.
2351 ;;;
2352 ;;; TERM-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
2353 ;;; want to save the buffer before issuing any process requests to the command
2354 ;;; interpreter.
2355 ;;;
2356 ;;; TERM-GET-SOURCE -- used by the source-file processing commands to prompt
2357 ;;; for the file to process.
2358
2359 ;;; (TERM-SOURCE-DEFAULT previous-dir/file source-modes)
2360 ;;;============================================================================
2361 ;;; This function computes the defaults for the load-file and compile-file
2362 ;;; commands for tea, soar, cmulisp, and cmuscheme modes.
2363 ;;;
2364 ;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
2365 ;;; source-file processing command, or nil if there hasn't been one yet.
2366 ;;; - SOURCE-MODES is a list used to determine what buffers contain source
2367 ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
2368 ;;; Typically, (lisp-mode) or (scheme-mode).
2369 ;;;
2370 ;;; If the command is given while the cursor is inside a string, *and*
2371 ;;; the string is an existing filename, *and* the filename is not a directory,
2372 ;;; then the string is taken as default. This allows you to just position
2373 ;;; your cursor over a string that's a filename and have it taken as default.
2374 ;;;
2375 ;;; If the command is given in a file buffer whose major mode is in
2376 ;;; SOURCE-MODES, then the filename is the default file, and the
2377 ;;; file's directory is the default directory.
2378 ;;;
2379 ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
2380 ;;; then the default directory & file are what was used in the last source-file
2381 ;;; processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
2382 ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
2383 ;;; is the cwd, with no default file. (\"no default file\" = nil)
2384 ;;;
2385 ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
2386 ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
2387 ;;; for Soar programs, etc.
2388 ;;;
2389 ;;; The function returns a pair: (default-directory . default-file).
2390
2391 (defun term-source-default (previous-dir/file source-modes)
2392 (cond ((and buffer-file-name (memq major-mode source-modes))
2393 (cons (file-name-directory buffer-file-name)
2394 (file-name-nondirectory buffer-file-name)))
2395 (previous-dir/file)
2396 (t
2397 (cons default-directory nil))))
2398
2399
2400 ;;; (TERM-CHECK-SOURCE fname)
2401 ;;;============================================================================
2402 ;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
2403 ;;; process-in-a-buffer modes), this function can be called on the filename.
2404 ;;; If the file is loaded into a buffer, and the buffer is modified, the user
2405 ;;; is queried to see if he wants to save the buffer before proceeding with
2406 ;;; the load or compile.
2407
2408 (defun term-check-source (fname)
2409 (let ((buff (get-file-buffer fname)))
2410 (when (and buff
2411 (buffer-modified-p buff)
2412 (y-or-n-p (format "Save buffer %s first? "
2413 (buffer-name buff))))
2414 ;; save BUFF.
2415 (let ((old-buffer (current-buffer)))
2416 (set-buffer buff)
2417 (save-buffer)
2418 (set-buffer old-buffer)))))
2419
2420
2421 ;;; (TERM-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
2422 ;;;============================================================================
2423 ;;; TERM-GET-SOURCE is used to prompt for filenames in command-interpreter
2424 ;;; commands that process source files (like loading or compiling a file).
2425 ;;; It prompts for the filename, provides a default, if there is one,
2426 ;;; and returns the result filename.
2427 ;;;
2428 ;;; See TERM-SOURCE-DEFAULT for more on determining defaults.
2429 ;;;
2430 ;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
2431 ;;; from the last source processing command. SOURCE-MODES is a list of major
2432 ;;; modes used to determine what file buffers contain source files. (These
2433 ;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
2434 ;;; then the filename reader will only accept a file that exists.
2435 ;;;
2436 ;;; A typical use:
2437 ;;; (interactive (term-get-source "Compile file: " prev-lisp-dir/file
2438 ;;; '(lisp-mode) t))
2439
2440 ;;; This is pretty stupid about strings. It decides we're in a string
2441 ;;; if there's a quote on both sides of point on the current line.
2442 (defun term-extract-string ()
2443 "Return string around `point' that starts the current line or nil."
2444 (save-excursion
2445 (let* ((point (point))
2446 (bol (progn (beginning-of-line) (point)))
2447 (eol (progn (end-of-line) (point)))
2448 (start (progn (goto-char point)
2449 (and (search-backward "\"" bol t)
2450 (1+ (point)))))
2451 (end (progn (goto-char point)
2452 (and (search-forward "\"" eol t)
2453 (1- (point))))))
2454 (and start end
2455 (buffer-substring start end)))))
2456
2457 (defun term-get-source (prompt prev-dir/file source-modes mustmatch-p)
2458 (let* ((def (term-source-default prev-dir/file source-modes))
2459 (stringfile (term-extract-string))
2460 (sfile-p (and stringfile
2461 (condition-case ()
2462 (file-exists-p stringfile)
2463 (error nil))
2464 (not (file-directory-p stringfile))))
2465 (defdir (if sfile-p (file-name-directory stringfile)
2466 (car def)))
2467 (deffile (if sfile-p (file-name-nondirectory stringfile)
2468 (cdr def)))
2469 (ans (read-file-name (if deffile (format "%s(default %s) "
2470 prompt deffile)
2471 prompt)
2472 defdir
2473 (concat defdir deffile)
2474 mustmatch-p)))
2475 (list (expand-file-name (substitute-in-file-name ans)))))
2476
2477 ;;; I am somewhat divided on this string-default feature. It seems
2478 ;;; to violate the principle-of-least-astonishment, in that it makes
2479 ;;; the default harder to predict, so you actually have to look and see
2480 ;;; what the default really is before choosing it. This can trip you up.
2481 ;;; On the other hand, it can be useful, I guess. I would appreciate feedback
2482 ;;; on this.
2483 ;;; -Olin
2484
2485 \f
2486 ;;; Simple process query facility.
2487 ;;; ===========================================================================
2488 ;;; This function is for commands that want to send a query to the process
2489 ;;; and show the response to the user. For example, a command to get the
2490 ;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
2491 ;;; to an inferior Common Lisp process.
2492 ;;;
2493 ;;; This simple facility just sends strings to the inferior process and pops
2494 ;;; up a window for the process buffer so you can see what the process
2495 ;;; responds with. We don't do anything fancy like try to intercept what the
2496 ;;; process responds with and put it in a pop-up window or on the message
2497 ;;; line. We just display the buffer. Low tech. Simple. Works good.
2498
2499 ;;; Send to the inferior process PROC the string STR. Pop-up but do not select
2500 ;;; a window for the inferior process so that its response can be seen.
2501 (defun term-proc-query (proc str)
2502 (let* ((proc-buf (process-buffer proc))
2503 (proc-mark (process-mark proc)))
2504 (display-buffer proc-buf)
2505 (set-buffer proc-buf) ; but it's not the selected *window*
2506 (let ((proc-win (get-buffer-window proc-buf))
2507 (proc-pt (marker-position proc-mark)))
2508 (term-send-string proc str) ; send the query
2509 (accept-process-output proc) ; wait for some output
2510 ;; Try to position the proc window so you can see the answer.
2511 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
2512 ;; I don't know why. Wizards invited to improve it.
2513 (when (not (pos-visible-in-window-p proc-pt proc-win))
2514 (let ((opoint (window-point proc-win)))
2515 (set-window-point proc-win proc-mark) (sit-for 0)
2516 (if (not (pos-visible-in-window-p opoint proc-win))
2517 (push-mark opoint)
2518 (set-window-point proc-win opoint)))))))
2519 \f
2520 ;;; Returns the current column in the current screen line.
2521 ;;; Note: (current-column) yields column in buffer line.
2522
2523 (defun term-horizontal-column ()
2524 (- (term-current-column) (term-start-line-column)))
2525
2526 ;; Calls either vertical-motion or term-buffer-vertical-motion
2527 (defmacro term-vertical-motion (count)
2528 (list 'funcall 'term-vertical-motion count))
2529
2530 ;; An emulation of vertical-motion that is independent of having a window.
2531 ;; Instead, it uses the term-width variable as the logical window width.
2532
2533 (defun term-buffer-vertical-motion (count)
2534 (cond ((= count 0)
2535 (move-to-column (* term-width (/ (current-column) term-width)))
2536 0)
2537 ((> count 0)
2538 (let ((H)
2539 (todo (+ count (/ (current-column) term-width))))
2540 (end-of-line)
2541 ;; The loop iterates over buffer lines;
2542 ;; H is the number of screen lines in the current line, i.e.
2543 ;; the ceiling of dividing the buffer line width by term-width.
2544 (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2545 term-width)
2546 1))
2547 todo)
2548 (not (eobp)))
2549 (setq todo (- todo H))
2550 (forward-char) ;; Move past the ?\n
2551 (end-of-line)) ;; and on to the end of the next line.
2552 (if (and (>= todo H) (> todo 0))
2553 (+ (- count todo) H -1) ;; Hit end of buffer.
2554 (move-to-column (* todo term-width))
2555 count)))
2556 (t ;; (< count 0) ;; Similar algorithm, but for upward motion.
2557 (let ((H)
2558 (todo (- count)))
2559 (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2560 term-width)
2561 1))
2562 todo)
2563 (progn (beginning-of-line)
2564 (not (bobp))))
2565 (setq todo (- todo H))
2566 (backward-char)) ;; Move to end of previous line.
2567 (if (and (>= todo H) (> todo 0))
2568 (+ count todo (- 1 H)) ;; Hit beginning of buffer.
2569 (move-to-column (* (- H todo 1) term-width))
2570 count)))))
2571
2572 ;;; The term-start-line-column variable is used as a cache.
2573 (defun term-start-line-column ()
2574 (cond (term-start-line-column)
2575 ((let ((save-pos (point)))
2576 (term-vertical-motion 0)
2577 (setq term-start-line-column (current-column))
2578 (goto-char save-pos)
2579 term-start-line-column))))
2580
2581 ;;; Same as (current-column), but uses term-current-column as a cache.
2582 (defun term-current-column ()
2583 (cond (term-current-column)
2584 ((setq term-current-column (current-column)))))
2585
2586 ;;; Move DELTA column right (or left if delta < 0 limiting at column 0).
2587
2588 (defun term-move-columns (delta)
2589 (setq term-current-column (max 0 (+ (term-current-column) delta)))
2590 (let (point-at-eol)
2591 (save-excursion
2592 (end-of-line)
2593 (setq point-at-eol (point)))
2594 (move-to-column term-current-column t)
2595 ;; If move-to-column extends the current line it will use the face
2596 ;; from the last character on the line, set the face for the chars
2597 ;; to default.
2598 (when (> (point) point-at-eol)
2599 (put-text-property point-at-eol (point) 'face 'default))))
2600
2601 ;; Insert COUNT copies of CHAR in the default face.
2602 (defun term-insert-char (char count)
2603 (let ((old-point (point)))
2604 (insert-char char count)
2605 (put-text-property old-point (point) 'face 'default)))
2606
2607 (defun term-current-row ()
2608 (cond (term-current-row)
2609 ((setq term-current-row
2610 (save-restriction
2611 (save-excursion
2612 (narrow-to-region term-home-marker (point-max))
2613 (- (term-vertical-motion -9999))))))))
2614
2615 (defun term-adjust-current-row-cache (delta)
2616 (when term-current-row
2617 (setq term-current-row
2618 (max 0 (+ term-current-row delta)))))
2619
2620 (defun term-terminal-pos ()
2621 (save-excursion ; save-restriction
2622 (let ((save-col (term-current-column))
2623 x y)
2624 (term-vertical-motion 0)
2625 (setq x (- save-col (current-column)))
2626 (setq y (term-vertical-motion term-height))
2627 (cons x y))))
2628
2629 ;;;Function that handles term messages: code by rms ( and you can see the
2630 ;;;difference ;-) -mm
2631
2632 (defun term-handle-ansi-terminal-messages (message)
2633 ;; Is there a command here?
2634 (while (string-match "\eAnSiT.+\n" message)
2635 ;; Extract the command code and the argument.
2636 (let* ((start (match-beginning 0))
2637 (end (match-end 0))
2638 (command-code (aref message (+ start 6)))
2639 (argument
2640 (save-match-data
2641 (substring message
2642 (+ start 8)
2643 (string-match "\r?\n" message
2644 (+ start 8)))))
2645 ignore)
2646 ;; Delete this command from MESSAGE.
2647 (setq message (replace-match "" t t message))
2648
2649 ;; If we recognize the type of command, set the appropriate variable.
2650 (cond ((= command-code ?c)
2651 (setq term-ansi-at-dir argument))
2652 ((= command-code ?h)
2653 (setq term-ansi-at-host argument))
2654 ((= command-code ?u)
2655 (setq term-ansi-at-user argument))
2656 ;; Otherwise ignore this one.
2657 (t
2658 (setq ignore t)))
2659
2660 ;; Update default-directory based on the changes this command made.
2661 (if ignore
2662 nil
2663 (setq default-directory
2664 (file-name-as-directory
2665 (if (and (string= term-ansi-at-host (system-name))
2666 (string= term-ansi-at-user (user-real-login-name)))
2667 (expand-file-name term-ansi-at-dir)
2668 (if (string= term-ansi-at-user (user-real-login-name))
2669 (concat "/" term-ansi-at-host ":" term-ansi-at-dir)
2670 (concat "/" term-ansi-at-user "@" term-ansi-at-host ":"
2671 term-ansi-at-dir)))))
2672
2673 ;; I'm not sure this is necessary,
2674 ;; but it's best to be on the safe side.
2675 (if (string= term-ansi-at-host (system-name))
2676 (progn
2677 (setq ange-ftp-default-user term-ansi-at-save-user)
2678 (setq ange-ftp-default-password term-ansi-at-save-pwd)
2679 (setq ange-ftp-generate-anonymous-password term-ansi-at-save-anon))
2680 (setq term-ansi-at-save-user ange-ftp-default-user)
2681 (setq term-ansi-at-save-pwd ange-ftp-default-password)
2682 (setq term-ansi-at-save-anon ange-ftp-generate-anonymous-password)
2683 (setq ange-ftp-default-user nil)
2684 (setq ange-ftp-default-password nil)
2685 (setq ange-ftp-generate-anonymous-password nil)))))
2686 message)
2687
2688
2689 ;;; Terminal emulation
2690 ;;; This is the standard process filter for term buffers.
2691 ;;; It emulates (most of the features of) a VT100/ANSI-style terminal.
2692
2693 (defun term-emulate-terminal (proc str)
2694 (with-current-buffer (process-buffer proc)
2695 (let* ((i 0) char funny count save-point save-marker old-point temp win
2696 (buffer-undo-list t)
2697 (selected (selected-window))
2698 last-win
2699 handled-ansi-message
2700 (str-length (length str)))
2701 (save-selected-window
2702
2703 ;; Let's handle the messages. -mm
2704
2705 (let* ((newstr (term-handle-ansi-terminal-messages str)))
2706 (when (not (eq str newstr))
2707 (setq handled-ansi-message t
2708 str newstr)))
2709 (setq str-length (length str))
2710
2711 (when (marker-buffer term-pending-delete-marker)
2712 ;; Delete text following term-pending-delete-marker.
2713 (delete-region term-pending-delete-marker (process-mark proc))
2714 (set-marker term-pending-delete-marker nil))
2715
2716 (if (eq (window-buffer) (current-buffer))
2717 (progn
2718 (setq term-vertical-motion (symbol-function 'vertical-motion))
2719 (term-check-size proc))
2720 (setq term-vertical-motion
2721 (symbol-function 'term-buffer-vertical-motion)))
2722
2723 (setq save-marker (copy-marker (process-mark proc)))
2724
2725 (when (/= (point) (process-mark proc))
2726 (setq save-point (point-marker))
2727 (goto-char (process-mark proc)))
2728
2729 (save-restriction
2730 ;; If the buffer is in line mode, and there is a partial
2731 ;; input line, save the line (by narrowing to leave it
2732 ;; outside the restriction ) until we're done with output.
2733 (when (and (> (point-max) (process-mark proc))
2734 (term-in-line-mode))
2735 (narrow-to-region (point-min) (process-mark proc)))
2736
2737 (when term-log-buffer
2738 (princ str term-log-buffer))
2739 (cond ((eq term-terminal-state 4) ;; Have saved pending output.
2740 (setq str (concat term-terminal-parameter str))
2741 (setq term-terminal-parameter nil)
2742 (setq str-length (length str))
2743 (setq term-terminal-state 0)))
2744
2745 (while (< i str-length)
2746 (setq char (aref str i))
2747 (cond ((< term-terminal-state 2)
2748 ;; Look for prefix of regular chars
2749 (setq funny
2750 (string-match "[\r\n\000\007\033\t\b\032\016\017]"
2751 str i))
2752 (when (not funny) (setq funny str-length))
2753 (cond ((> funny i)
2754 (cond ((eq term-terminal-state 1)
2755 ;; We are in state 1, we need to wrap
2756 ;; around. Go to the beginning of
2757 ;; the next line and switch to state
2758 ;; 0.
2759 (term-down 1 t)
2760 (term-move-columns (- (term-current-column)))
2761 (setq term-terminal-state 0)))
2762 (setq count (- funny i))
2763 (setq temp (- (+ (term-horizontal-column) count)
2764 term-width))
2765 (cond ((<= temp 0)) ;; All count chars fit in line.
2766 ((> count temp) ;; Some chars fit.
2767 ;; This iteration, handle only what fits.
2768 (setq count (- count temp))
2769 (setq temp 0)
2770 (setq funny (+ count i)))
2771 ((or (not (or term-pager-count
2772 term-scroll-with-delete))
2773 (> (term-handle-scroll 1) 0))
2774 (term-adjust-current-row-cache 1)
2775 (setq count (min count term-width))
2776 (setq funny (+ count i))
2777 (setq term-start-line-column
2778 term-current-column))
2779 (t ;; Doing PAGER processing.
2780 (setq count 0 funny i)
2781 (setq term-current-column nil)
2782 (setq term-start-line-column nil)))
2783 (setq old-point (point))
2784
2785 ;; Insert a string, check how many columns
2786 ;; we moved, then delete that many columns
2787 ;; following point if not eob nor insert-mode.
2788 (let ((old-column (current-column))
2789 columns pos)
2790 (insert (decode-coding-string (substring str i funny) locale-coding-system))
2791 (setq term-current-column (current-column)
2792 columns (- term-current-column old-column))
2793 (when (not (or (eobp) term-insert-mode))
2794 (setq pos (point))
2795 (term-move-columns columns)
2796 (delete-region pos (point)))
2797 ;; In insert mode if the current line
2798 ;; has become too long it needs to be
2799 ;; chopped off.
2800 (when term-insert-mode
2801 (setq pos (point))
2802 (end-of-line)
2803 (when (> (current-column) term-width)
2804 (delete-region (- (point) (- (current-column) term-width))
2805 (point)))
2806 (goto-char pos)))
2807 (setq term-current-column nil)
2808
2809 (put-text-property old-point (point)
2810 'face term-current-face)
2811 ;; If the last char was written in last column,
2812 ;; back up one column, but remember we did so.
2813 ;; Thus we emulate xterm/vt100-style line-wrapping.
2814 (cond ((eq temp 0)
2815 (term-move-columns -1)
2816 (setq term-terminal-state 1)))
2817 (setq i (1- funny)))
2818 ((and (setq term-terminal-state 0)
2819 (eq char ?\^I)) ; TAB (terminfo: ht)
2820 (setq count (term-current-column))
2821 ;; The line cannot exceed term-width. TAB at
2822 ;; the end of a line should not cause wrapping.
2823 (setq count (min term-width
2824 (+ count 8 (- (mod count 8)))))
2825 (if (> term-width count)
2826 (progn
2827 (term-move-columns
2828 (- count (term-current-column)))
2829 (setq term-current-column count))
2830 (when (> term-width (term-current-column))
2831 (term-move-columns
2832 (1- (- term-width (term-current-column)))))
2833 (when (= term-width (term-current-column))
2834 (term-move-columns -1))))
2835 ((eq char ?\r) ;; (terminfo: cr)
2836 (term-vertical-motion 0)
2837 (setq term-current-column term-start-line-column))
2838 ((eq char ?\n) ;; (terminfo: cud1, ind)
2839 (unless (and term-kill-echo-list
2840 (term-check-kill-echo-list))
2841 (term-down 1 t)))
2842 ((eq char ?\b) ;; (terminfo: cub1)
2843 (term-move-columns -1))
2844 ((eq char ?\033) ; Escape
2845 (setq term-terminal-state 2))
2846 ((eq char 0)) ; NUL: Do nothing
2847 ((eq char ?\016)) ; Shift Out - ignored
2848 ((eq char ?\017)) ; Shift In - ignored
2849 ((eq char ?\^G) ;; (terminfo: bel)
2850 (beep t))
2851 ((and (eq char ?\032)
2852 (not handled-ansi-message))
2853 (let ((end (string-match "\r?$" str i)))
2854 (if end
2855 (funcall term-command-hook
2856 (prog1 (substring str (1+ i) end)
2857 (setq i (match-end 0))))
2858 (setq term-terminal-parameter (substring str i))
2859 (setq term-terminal-state 4)
2860 (setq i str-length))))
2861 (t ; insert char FIXME: Should never happen
2862 (term-move-columns 1)
2863 (backward-delete-char 1)
2864 (insert char))))
2865 ((eq term-terminal-state 2) ; Seen Esc
2866 (cond ((eq char ?\133) ;; ?\133 = ?[
2867
2868 ;;; Some modifications to cope with multiple settings like ^[[01;32;43m -mm
2869 ;;; Note that now the init value of term-terminal-previous-parameter has
2870 ;;; been changed to -1
2871
2872 (setq term-terminal-parameter 0)
2873 (setq term-terminal-previous-parameter -1)
2874 (setq term-terminal-previous-parameter-2 -1)
2875 (setq term-terminal-previous-parameter-3 -1)
2876 (setq term-terminal-previous-parameter-4 -1)
2877 (setq term-terminal-more-parameters 0)
2878 (setq term-terminal-state 3))
2879 ((eq char ?D) ;; scroll forward
2880 (term-handle-deferred-scroll)
2881 (term-down 1 t)
2882 (setq term-terminal-state 0))
2883 ;; ((eq char ?E) ;; (terminfo: nw), not used for
2884 ;; ;; now, but this is a working
2885 ;; ;; implementation
2886 ;; (term-down 1)
2887 ;; (term-goto term-current-row 0)
2888 ;; (setq term-terminal-state 0))
2889 ((eq char ?M) ;; scroll reversed (terminfo: ri)
2890 (if (or (< (term-current-row) term-scroll-start)
2891 (>= (1- (term-current-row))
2892 term-scroll-start))
2893 ;; Scrolling up will not move outside
2894 ;; the scroll region.
2895 (term-down -1)
2896 ;; Scrolling the scroll region is needed.
2897 (term-down -1 t))
2898 (setq term-terminal-state 0))
2899 ((eq char ?7) ;; Save cursor (terminfo: sc)
2900 (term-handle-deferred-scroll)
2901 (setq term-saved-cursor
2902 (list (term-current-row)
2903 (term-horizontal-column)
2904 term-ansi-current-bg-color
2905 term-ansi-current-bold
2906 term-ansi-current-color
2907 term-ansi-current-invisible
2908 term-ansi-current-reverse
2909 term-ansi-current-underline
2910 term-current-face)
2911 )
2912 (setq term-terminal-state 0))
2913 ((eq char ?8) ;; Restore cursor (terminfo: rc)
2914 (when term-saved-cursor
2915 (term-goto (nth 0 term-saved-cursor)
2916 (nth 1 term-saved-cursor))
2917 (setq term-ansi-current-bg-color
2918 (nth 2 term-saved-cursor)
2919 term-ansi-current-bold
2920 (nth 3 term-saved-cursor)
2921 term-ansi-current-color
2922 (nth 4 term-saved-cursor)
2923 term-ansi-current-invisible
2924 (nth 5 term-saved-cursor)
2925 term-ansi-current-reverse
2926 (nth 6 term-saved-cursor)
2927 term-ansi-current-underline
2928 (nth 7 term-saved-cursor)
2929 term-current-face
2930 (nth 8 term-saved-cursor)))
2931 (setq term-terminal-state 0))
2932 ((eq char ?c) ;; \Ec - Reset (terminfo: rs1)
2933 ;; This is used by the "clear" program.
2934 (setq term-terminal-state 0)
2935 (term-reset-terminal))
2936 ;; The \E#8 reset sequence for xterm. We
2937 ;; probably don't need to handle it, but this
2938 ;; is the code to parse it.
2939 ;; ((eq char ?#)
2940 ;; (when (eq (aref str (1+ i)) ?8)
2941 ;; (setq i (1+ i))
2942 ;; (setq term-scroll-start 0)
2943 ;; (setq term-scroll-end term-height)
2944 ;; (setq term-terminal-state 0)))
2945 ((setq term-terminal-state 0))))
2946 ((eq term-terminal-state 3) ; Seen Esc [
2947 (cond ((and (>= char ?0) (<= char ?9))
2948 (setq term-terminal-parameter
2949 (+ (* 10 term-terminal-parameter) (- char ?0))))
2950 ((eq char ?\;)
2951 ;;; Some modifications to cope with multiple settings like ^[[01;32;43m -mm
2952 (setq term-terminal-more-parameters 1)
2953 (setq term-terminal-previous-parameter-4
2954 term-terminal-previous-parameter-3)
2955 (setq term-terminal-previous-parameter-3
2956 term-terminal-previous-parameter-2)
2957 (setq term-terminal-previous-parameter-2
2958 term-terminal-previous-parameter)
2959 (setq term-terminal-previous-parameter
2960 term-terminal-parameter)
2961 (setq term-terminal-parameter 0))
2962 ((eq char ??)) ; Ignore ?
2963 (t
2964 (term-handle-ansi-escape proc char)
2965 (setq term-terminal-more-parameters 0)
2966 (setq term-terminal-previous-parameter-4 -1)
2967 (setq term-terminal-previous-parameter-3 -1)
2968 (setq term-terminal-previous-parameter-2 -1)
2969 (setq term-terminal-previous-parameter -1)
2970 (setq term-terminal-state 0)))))
2971 (when (term-handling-pager)
2972 ;; Finish stuff to get ready to handle PAGER.
2973 (if (> (% (current-column) term-width) 0)
2974 (setq term-terminal-parameter
2975 (substring str i))
2976 ;; We're at column 0. Goto end of buffer; to compensate,
2977 ;; prepend a ?\r for later. This looks more consistent.
2978 (if (zerop i)
2979 (setq term-terminal-parameter
2980 (concat "\r" (substring str i)))
2981 (setq term-terminal-parameter (substring str (1- i)))
2982 (aset term-terminal-parameter 0 ?\r))
2983 (goto-char (point-max)))
2984 (setq term-terminal-state 4)
2985 (make-local-variable 'term-pager-old-filter)
2986 (setq term-pager-old-filter (process-filter proc))
2987 (set-process-filter proc term-pager-filter)
2988 (setq i str-length))
2989 (setq i (1+ i))))
2990
2991 (when (>= (term-current-row) term-height)
2992 (term-handle-deferred-scroll))
2993
2994 (set-marker (process-mark proc) (point))
2995 (when save-point
2996 (goto-char save-point)
2997 (set-marker save-point nil))
2998
2999 ;; Check for a pending filename-and-line number to display.
3000 ;; We do this before scrolling, because we might create a new window.
3001 (when (and term-pending-frame
3002 (eq (window-buffer selected) (current-buffer)))
3003 (term-display-line (car term-pending-frame)
3004 (cdr term-pending-frame))
3005 (setq term-pending-frame nil)
3006 ;; We have created a new window, so check the window size.
3007 (term-check-size proc))
3008
3009 ;; Scroll each window displaying the buffer but (by default)
3010 ;; only if the point matches the process-mark we started with.
3011 (setq win selected)
3012 ;; Avoid infinite loop in strange case where minibuffer window
3013 ;; is selected but not active.
3014 (while (window-minibuffer-p win)
3015 (setq win (next-window win nil t)))
3016 (setq last-win win)
3017 (while (progn
3018 (setq win (next-window win nil t))
3019 (when (eq (window-buffer win) (process-buffer proc))
3020 (let ((scroll term-scroll-to-bottom-on-output))
3021 (select-window win)
3022 (when (or (= (point) save-marker)
3023 (eq scroll t) (eq scroll 'all)
3024 ;; Maybe user wants point to jump to the end.
3025 (and (eq selected win)
3026 (or (eq scroll 'this) (not save-point)))
3027 (and (eq scroll 'others)
3028 (not (eq selected win))))
3029 (goto-char term-home-marker)
3030 (recenter 0)
3031 (goto-char (process-mark proc))
3032 (if (not (pos-visible-in-window-p (point) win))
3033 (recenter -1)))
3034 ;; Optionally scroll so that the text
3035 ;; ends at the bottom of the window.
3036 (when (and term-scroll-show-maximum-output
3037 (>= (point) (process-mark proc)))
3038 (save-excursion
3039 (goto-char (point-max))
3040 (recenter -1)))))
3041 (not (eq win last-win))))
3042
3043 ;;; Stolen from comint.el and adapted -mm
3044 (when (> term-buffer-maximum-size 0)
3045 (save-excursion
3046 (goto-char (process-mark (get-buffer-process (current-buffer))))
3047 (forward-line (- term-buffer-maximum-size))
3048 (beginning-of-line)
3049 (delete-region (point-min) (point))))
3050 (set-marker save-marker nil)))
3051 ;; This might be expensive, but we need it to handle something
3052 ;; like `sleep 5 | less -c' in more-or-less real time.
3053 (when (get-buffer-window (current-buffer))
3054 (redisplay))))
3055
3056 (defun term-handle-deferred-scroll ()
3057 (let ((count (- (term-current-row) term-height)))
3058 (when (>= count 0)
3059 (save-excursion
3060 (goto-char term-home-marker)
3061 (term-vertical-motion (1+ count))
3062 (set-marker term-home-marker (point))
3063 (setq term-current-row (1- term-height))))))
3064
3065 ;;; Reset the terminal, delete all the content and set the face to the
3066 ;;; default one.
3067 (defun term-reset-terminal ()
3068 (erase-buffer)
3069 (setq term-current-row 0)
3070 (setq term-current-column 1)
3071 (setq term-scroll-start 0)
3072 (setq term-scroll-end term-height)
3073 (setq term-insert-mode nil)
3074 (setq term-current-face (list :background term-default-bg-color
3075 :foreground term-default-fg-color))
3076 (setq term-ansi-current-underline nil)
3077 (setq term-ansi-current-bold nil)
3078 (setq term-ansi-current-reverse nil)
3079 (setq term-ansi-current-color 0)
3080 (setq term-ansi-current-invisible nil)
3081 (setq term-ansi-face-already-done nil)
3082 (setq term-ansi-current-bg-color 0))
3083
3084 ;;; New function to deal with ansi colorized output, as you can see you can
3085 ;;; have any bold/underline/fg/bg/reverse combination. -mm
3086
3087 (defun term-handle-colors-array (parameter)
3088 (cond
3089
3090 ;;; Bold (terminfo: bold)
3091 ((eq parameter 1)
3092 (setq term-ansi-current-bold t))
3093
3094 ;;; Underline
3095 ((eq parameter 4)
3096 (setq term-ansi-current-underline t))
3097
3098 ;;; Blink (unsupported by Emacs), will be translated to bold.
3099 ;;; This may change in the future though.
3100 ((eq parameter 5)
3101 (setq term-ansi-current-bold t))
3102
3103 ;;; Reverse (terminfo: smso)
3104 ((eq parameter 7)
3105 (setq term-ansi-current-reverse t))
3106
3107 ;;; Invisible
3108 ((eq parameter 8)
3109 (setq term-ansi-current-invisible t))
3110
3111 ;;; Reset underline (terminfo: rmul)
3112 ((eq parameter 24)
3113 (setq term-ansi-current-underline nil))
3114
3115 ;;; Reset reverse (terminfo: rmso)
3116 ((eq parameter 27)
3117 (setq term-ansi-current-reverse nil))
3118
3119 ;;; Foreground
3120 ((and (>= parameter 30) (<= parameter 37))
3121 (setq term-ansi-current-color (- parameter 29)))
3122
3123 ;;; Reset foreground
3124 ((eq parameter 39)
3125 (setq term-ansi-current-color 0))
3126
3127 ;;; Background
3128 ((and (>= parameter 40) (<= parameter 47))
3129 (setq term-ansi-current-bg-color (- parameter 39)))
3130
3131 ;;; Reset background
3132 ((eq parameter 49)
3133 (setq term-ansi-current-bg-color 0))
3134
3135 ;;; 0 (Reset) or unknown (reset anyway)
3136 (t
3137 (setq term-current-face (list :background term-default-bg-color
3138 :foreground term-default-fg-color))
3139 (setq term-ansi-current-underline nil)
3140 (setq term-ansi-current-bold nil)
3141 (setq term-ansi-current-reverse nil)
3142 (setq term-ansi-current-color 0)
3143 (setq term-ansi-current-invisible nil)
3144 (setq term-ansi-face-already-done t)
3145 (setq term-ansi-current-bg-color 0)))
3146
3147 ; (message "Debug: U-%d R-%d B-%d I-%d D-%d F-%d B-%d"
3148 ; term-ansi-current-underline
3149 ; term-ansi-current-reverse
3150 ; term-ansi-current-bold
3151 ; term-ansi-current-invisible
3152 ; term-ansi-face-already-done
3153 ; term-ansi-current-color
3154 ; term-ansi-current-bg-color)
3155
3156
3157 (unless term-ansi-face-already-done
3158 (if term-ansi-current-reverse
3159 (if term-ansi-current-invisible
3160 (setq term-current-face
3161 (if (= term-ansi-current-color 0)
3162 (list :background
3163 term-default-fg-color
3164 :foreground
3165 term-default-fg-color)
3166 (list :background
3167 (elt ansi-term-color-vector term-ansi-current-color)
3168 :foreground
3169 (elt ansi-term-color-vector term-ansi-current-color)))
3170 ;; No need to bother with anything else if it's invisible
3171 )
3172 (setq term-current-face
3173 (list :background
3174 (if (= term-ansi-current-color 0)
3175 term-default-fg-color
3176 (elt ansi-term-color-vector term-ansi-current-color))
3177 :foreground
3178 (if (= term-ansi-current-bg-color 0)
3179 term-default-bg-color
3180 (elt ansi-term-color-vector term-ansi-current-bg-color))))
3181 (when term-ansi-current-bold
3182 (setq term-current-face
3183 (append '(:weight bold) term-current-face)))
3184 (when term-ansi-current-underline
3185 (setq term-current-face
3186 (append '(:underline t) term-current-face))))
3187 (if term-ansi-current-invisible
3188 (setq term-current-face
3189 (if (= term-ansi-current-bg-color 0)
3190 (list :background
3191 term-default-bg-color
3192 :foreground
3193 term-default-bg-color)
3194 (list :foreground
3195 (elt ansi-term-color-vector term-ansi-current-bg-color)
3196 :background
3197 (elt ansi-term-color-vector term-ansi-current-bg-color)))
3198 ;; No need to bother with anything else if it's invisible
3199 )
3200 (setq term-current-face
3201 (list :foreground
3202 (if (= term-ansi-current-color 0)
3203 term-default-fg-color
3204 (elt ansi-term-color-vector term-ansi-current-color))
3205 :background
3206 (if (= term-ansi-current-bg-color 0)
3207 term-default-bg-color
3208 (elt ansi-term-color-vector term-ansi-current-bg-color))))
3209 (when term-ansi-current-bold
3210 (setq term-current-face
3211 (append '(:weight bold) term-current-face)))
3212 (when term-ansi-current-underline
3213 (setq term-current-face
3214 (append '(:underline t) term-current-face))))))
3215
3216 ;;; (message "Debug %S" term-current-face)
3217 (setq term-ansi-face-already-done nil))
3218
3219
3220 ;;; Handle a character assuming (eq terminal-state 2) -
3221 ;;; i.e. we have previously seen Escape followed by ?[.
3222
3223 (defun term-handle-ansi-escape (proc char)
3224 (cond
3225 ((or (eq char ?H) ;; cursor motion (terminfo: cup,home)
3226 ;; (eq char ?f) ;; xterm seems to handle this sequence too, not
3227 ;; needed for now
3228 )
3229 (when (<= term-terminal-parameter 0)
3230 (setq term-terminal-parameter 1))
3231 (when (<= term-terminal-previous-parameter 0)
3232 (setq term-terminal-previous-parameter 1))
3233 (when (> term-terminal-previous-parameter term-height)
3234 (setq term-terminal-previous-parameter term-height))
3235 (when (> term-terminal-parameter term-width)
3236 (setq term-terminal-parameter term-width))
3237 (term-goto
3238 (1- term-terminal-previous-parameter)
3239 (1- term-terminal-parameter)))
3240 ;; \E[A - cursor up (terminfo: cuu, cuu1)
3241 ((eq char ?A)
3242 (term-handle-deferred-scroll)
3243 (let ((tcr (term-current-row)))
3244 (term-down
3245 (if (< (- tcr term-terminal-parameter) term-scroll-start)
3246 ;; If the amount to move is before scroll start, move
3247 ;; to scroll start.
3248 (- term-scroll-start tcr)
3249 (if (>= term-terminal-parameter tcr)
3250 (- tcr)
3251 (- (max 1 term-terminal-parameter)))) t)))
3252 ;; \E[B - cursor down (terminfo: cud)
3253 ((eq char ?B)
3254 (let ((tcr (term-current-row)))
3255 (unless (= tcr (1- term-scroll-end))
3256 (term-down
3257 (if (> (+ tcr term-terminal-parameter) term-scroll-end)
3258 (- term-scroll-end 1 tcr)
3259 (max 1 term-terminal-parameter)) t))))
3260 ;; \E[C - cursor right (terminfo: cuf, cuf1)
3261 ((eq char ?C)
3262 (term-move-columns
3263 (max 1
3264 (if (>= (+ term-terminal-parameter (term-current-column)) term-width)
3265 (- term-width (term-current-column) 1)
3266 term-terminal-parameter))))
3267 ;; \E[D - cursor left (terminfo: cub)
3268 ((eq char ?D)
3269 (term-move-columns (- (max 1 term-terminal-parameter))))
3270 ;; \E[J - clear to end of screen (terminfo: ed, clear)
3271 ((eq char ?J)
3272 (term-erase-in-display term-terminal-parameter))
3273 ;; \E[K - clear to end of line (terminfo: el, el1)
3274 ((eq char ?K)
3275 (term-erase-in-line term-terminal-parameter))
3276 ;; \E[L - insert lines (terminfo: il, il1)
3277 ((eq char ?L)
3278 (term-insert-lines (max 1 term-terminal-parameter)))
3279 ;; \E[M - delete lines (terminfo: dl, dl1)
3280 ((eq char ?M)
3281 (term-delete-lines (max 1 term-terminal-parameter)))
3282 ;; \E[P - delete chars (terminfo: dch, dch1)
3283 ((eq char ?P)
3284 (term-delete-chars (max 1 term-terminal-parameter)))
3285 ;; \E[@ - insert spaces (terminfo: ich)
3286 ((eq char ?@)
3287 (term-insert-spaces (max 1 term-terminal-parameter)))
3288 ;; \E[?h - DEC Private Mode Set
3289 ((eq char ?h)
3290 (cond ((eq term-terminal-parameter 4) ;; (terminfo: smir)
3291 (setq term-insert-mode t))
3292 ;; ((eq term-terminal-parameter 47) ;; (terminfo: smcup)
3293 ;; (term-switch-to-alternate-sub-buffer t))
3294 ))
3295 ;; \E[?l - DEC Private Mode Reset
3296 ((eq char ?l)
3297 (cond ((eq term-terminal-parameter 4) ;; (terminfo: rmir)
3298 (setq term-insert-mode nil))
3299 ;; ((eq term-terminal-parameter 47) ;; (terminfo: rmcup)
3300 ;; (term-switch-to-alternate-sub-buffer nil))
3301 ))
3302
3303 ;;; Modified to allow ansi coloring -mm
3304 ;; \E[m - Set/reset modes, set bg/fg
3305 ;;(terminfo: smso,rmso,smul,rmul,rev,bold,sgr0,invis,op,setab,setaf)
3306 ((eq char ?m)
3307 (when (= term-terminal-more-parameters 1)
3308 (when (>= term-terminal-previous-parameter-4 0)
3309 (term-handle-colors-array term-terminal-previous-parameter-4))
3310 (when (>= term-terminal-previous-parameter-3 0)
3311 (term-handle-colors-array term-terminal-previous-parameter-3))
3312 (when (>= term-terminal-previous-parameter-2 0)
3313 (term-handle-colors-array term-terminal-previous-parameter-2))
3314 (term-handle-colors-array term-terminal-previous-parameter))
3315 (term-handle-colors-array term-terminal-parameter))
3316
3317 ;; \E[6n - Report cursor position
3318 ((eq char ?n)
3319 (term-handle-deferred-scroll)
3320 (process-send-string proc
3321 (format "\e[%s;%sR"
3322 (1+ (term-current-row))
3323 (1+ (term-horizontal-column)))))
3324 ;; \E[r - Set scrolling region (terminfo: csr)
3325 ((eq char ?r)
3326 (term-set-scroll-region
3327 (1- term-terminal-previous-parameter)
3328 (1- term-terminal-parameter)))
3329 (t)))
3330
3331 (defun term-set-scroll-region (top bottom)
3332 "Set scrolling region.
3333 TOP is the top-most line (inclusive) of the new scrolling region,
3334 while BOTTOM is the line following the new scrolling region (e.g. exclusive).
3335 The top-most line is line 0."
3336 (setq term-scroll-start
3337 (if (or (< top 0) (>= top term-height))
3338 0
3339 top))
3340 (setq term-scroll-end
3341 (if (or (<= bottom term-scroll-start) (> bottom term-height))
3342 term-height
3343 bottom))
3344 (setq term-scroll-with-delete
3345 (or (term-using-alternate-sub-buffer)
3346 (not (and (= term-scroll-start 0)
3347 (= term-scroll-end term-height)))))
3348 (term-move-columns (- (term-current-column)))
3349 (term-goto 0 0))
3350
3351 ;; (defun term-switch-to-alternate-sub-buffer (set)
3352 ;; ;; If asked to switch to (from) the alternate sub-buffer, and already (not)
3353 ;; ;; using it, do nothing. This test is needed for some programs (including
3354 ;; ;; Emacs) that emit the ti termcap string twice, for unknown reason.
3355 ;; (term-handle-deferred-scroll)
3356 ;; (if (eq set (not (term-using-alternate-sub-buffer)))
3357 ;; (let ((row (term-current-row))
3358 ;; (col (term-horizontal-column)))
3359 ;; (cond (set
3360 ;; (goto-char (point-max))
3361 ;; (if (not (eq (preceding-char) ?\n))
3362 ;; (term-insert-char ?\n 1))
3363 ;; (setq term-scroll-with-delete t)
3364 ;; (setq term-saved-home-marker (copy-marker term-home-marker))
3365 ;; (set-marker term-home-marker (point)))
3366 ;; (t
3367 ;; (setq term-scroll-with-delete
3368 ;; (not (and (= term-scroll-start 0)
3369 ;; (= term-scroll-end term-height))))
3370 ;; (set-marker term-home-marker term-saved-home-marker)
3371 ;; (set-marker term-saved-home-marker nil)
3372 ;; (setq term-saved-home-marker nil)
3373 ;; (goto-char term-home-marker)))
3374 ;; (setq term-current-column nil)
3375 ;; (setq term-current-row 0)
3376 ;; (term-goto row col))))
3377
3378 ;; Default value for the symbol term-command-hook.
3379
3380 (defun term-command-hook (string)
3381 (cond ((equal string "")
3382 t)
3383 ((= (aref string 0) ?\032)
3384 ;; gdb (when invoked with -fullname) prints:
3385 ;; \032\032FULLFILENAME:LINENUMBER:CHARPOS:BEG_OR_MIDDLE:PC\n
3386 (let* ((first-colon (string-match ":" string 1))
3387 (second-colon
3388 (string-match ":" string (1+ first-colon)))
3389 (filename (substring string 1 first-colon))
3390 (fileline (string-to-number
3391 (substring string (1+ first-colon) second-colon))))
3392 (setq term-pending-frame (cons filename fileline))))
3393 ((= (aref string 0) ?/)
3394 (cd (substring string 1)))
3395 ;; Allowing the inferior to call functions in Emacs is
3396 ;; probably too big a security hole.
3397 ;; ((= (aref string 0) ?!)
3398 ;; (eval (car (read-from-string string 1))))
3399 (t)));; Otherwise ignore it
3400
3401 ;; Make sure the file named TRUE-FILE is in a buffer that appears on the screen
3402 ;; and that its line LINE is visible.
3403 ;; Put the overlay-arrow on the line LINE in that buffer.
3404 ;; This is mainly used by gdb.
3405
3406 (defun term-display-line (true-file line)
3407 (term-display-buffer-line (find-file-noselect true-file) line))
3408
3409 (defun term-display-buffer-line (buffer line)
3410 (let* ((window (display-buffer buffer t))
3411 (pos))
3412 (save-excursion
3413 (set-buffer buffer)
3414 (save-restriction
3415 (widen)
3416 (goto-line line)
3417 (setq pos (point))
3418 (setq overlay-arrow-string "=>")
3419 (or overlay-arrow-position
3420 (setq overlay-arrow-position (make-marker)))
3421 (set-marker overlay-arrow-position (point) (current-buffer)))
3422 (cond ((or (< pos (point-min)) (> pos (point-max)))
3423 (widen)
3424 (goto-char pos))))
3425 (set-window-point window overlay-arrow-position)))
3426
3427 ;;; The buffer-local marker term-home-marker defines the "home position"
3428 ;;; (in terms of cursor motion). However, we move the term-home-marker
3429 ;;; "down" as needed so that is no more that a window-full above (point-max).
3430
3431 (defun term-goto-home ()
3432 (term-handle-deferred-scroll)
3433 (goto-char term-home-marker)
3434 (setq term-current-row 0)
3435 (setq term-current-column (current-column))
3436 (setq term-start-line-column term-current-column))
3437
3438 (defun term-goto (row col)
3439 (term-handle-deferred-scroll)
3440 (cond ((and term-current-row (>= row term-current-row))
3441 ;; I assume this is a worthwhile optimization.
3442 (term-vertical-motion 0)
3443 (setq term-current-column term-start-line-column)
3444 (setq row (- row term-current-row)))
3445 (t
3446 (term-goto-home)))
3447 (term-down row)
3448 (term-move-columns col))
3449
3450 ; The page is full, so enter "pager" mode, and wait for input.
3451
3452 (defun term-process-pager ()
3453 (when (not term-pager-break-map)
3454 (let* ((map (make-keymap))
3455 (i 0) tmp)
3456 ; (while (< i 128)
3457 ; (define-key map (make-string 1 i) 'term-send-raw)
3458 ; (setq i (1+ i)))
3459 (define-key map "\e"
3460 (lookup-key (current-global-map) "\e"))
3461 (define-key map "\C-x"
3462 (lookup-key (current-global-map) "\C-x"))
3463 (define-key map "\C-u"
3464 (lookup-key (current-global-map) "\C-u"))
3465 (define-key map " " 'term-pager-page)
3466 (define-key map "\r" 'term-pager-line)
3467 (define-key map "?" 'term-pager-help)
3468 (define-key map "h" 'term-pager-help)
3469 (define-key map "b" 'term-pager-back-page)
3470 (define-key map "\177" 'term-pager-back-line)
3471 (define-key map "q" 'term-pager-discard)
3472 (define-key map "D" 'term-pager-disable)
3473 (define-key map "<" 'term-pager-bob)
3474 (define-key map ">" 'term-pager-eob)
3475
3476 ;; Add menu bar.
3477 (unless (featurep 'xemacs)
3478 (define-key map [menu-bar terminal] term-terminal-menu)
3479 (define-key map [menu-bar signals] term-signals-menu)
3480 (setq tmp (make-sparse-keymap "More pages?"))
3481 (define-key tmp [help] '("Help" . term-pager-help))
3482 (define-key tmp [disable]
3483 '("Disable paging" . term-fake-pager-disable))
3484 (define-key tmp [discard]
3485 '("Discard remaining output" . term-pager-discard))
3486 (define-key tmp [eob] '("Goto to end" . term-pager-eob))
3487 (define-key tmp [bob] '("Goto to beginning" . term-pager-bob))
3488 (define-key tmp [line] '("1 line forwards" . term-pager-line))
3489 (define-key tmp [bline] '("1 line backwards" . term-pager-back-line))
3490 (define-key tmp [back] '("1 page backwards" . term-pager-back-page))
3491 (define-key tmp [page] '("1 page forwards" . term-pager-page))
3492 (define-key map [menu-bar page] (cons "More pages?" tmp))
3493 )
3494
3495 (setq term-pager-break-map map)))
3496 ; (let ((process (get-buffer-process (current-buffer))))
3497 ; (stop-process process))
3498 (setq term-pager-old-local-map (current-local-map))
3499 (use-local-map term-pager-break-map)
3500 (make-local-variable 'term-old-mode-line-format)
3501 (setq term-old-mode-line-format mode-line-format)
3502 (setq mode-line-format
3503 (list "-- **MORE** "
3504 mode-line-buffer-identification
3505 " [Type ? for help] "
3506 "%-"))
3507 (force-mode-line-update))
3508
3509 (defun term-pager-line (lines)
3510 (interactive "p")
3511 (let* ((moved (vertical-motion (1+ lines)))
3512 (deficit (- lines moved)))
3513 (when (> moved lines)
3514 (backward-char))
3515 (cond ((<= deficit 0) ;; OK, had enough in the buffer for request.
3516 (recenter (1- term-height)))
3517 ((term-pager-continue deficit)))))
3518
3519 (defun term-pager-page (arg)
3520 "Proceed past the **MORE** break, allowing the next page of output to appear."
3521 (interactive "p")
3522 (term-pager-line (* arg term-height)))
3523
3524 ; Pager mode command to go to beginning of buffer
3525 (defun term-pager-bob ()
3526 (interactive)
3527 (goto-char (point-min))
3528 (when (= (vertical-motion term-height) term-height)
3529 (backward-char))
3530 (recenter (1- term-height)))
3531
3532 ; pager mode command to go to end of buffer
3533 (defun term-pager-eob ()
3534 (interactive)
3535 (goto-char term-home-marker)
3536 (recenter 0)
3537 (goto-char (process-mark (get-buffer-process (current-buffer)))))
3538
3539 (defun term-pager-back-line (lines)
3540 (interactive "p")
3541 (vertical-motion (- 1 lines))
3542 (if (not (bobp))
3543 (backward-char)
3544 (beep)
3545 ;; Move cursor to end of window.
3546 (vertical-motion term-height)
3547 (backward-char))
3548 (recenter (1- term-height)))
3549
3550 (defun term-pager-back-page (arg)
3551 (interactive "p")
3552 (term-pager-back-line (* arg term-height)))
3553
3554 (defun term-pager-discard ()
3555 (interactive)
3556 (setq term-terminal-parameter "")
3557 (interrupt-process nil t)
3558 (term-pager-continue term-height))
3559
3560 ; Disable pager processing.
3561 ; Only callable while in pager mode. (Contrast term-disable-pager.)
3562 (defun term-pager-disable ()
3563 (interactive)
3564 (if (term-handling-pager)
3565 (term-pager-continue nil)
3566 (setq term-pager-count nil))
3567 (term-update-mode-line))
3568
3569 ; Enable pager processing.
3570 (defun term-pager-enable ()
3571 (interactive)
3572 (or (term-pager-enabled)
3573 (setq term-pager-count 0)) ;; Or maybe set to (term-current-row) ??
3574 (term-update-mode-line))
3575
3576 (defun term-pager-toggle ()
3577 (interactive)
3578 (if (term-pager-enabled) (term-pager-disable) (term-pager-enable)))
3579
3580 (unless (featurep 'xemacs)
3581 (defalias 'term-fake-pager-enable 'term-pager-toggle)
3582 (defalias 'term-fake-pager-disable 'term-pager-toggle)
3583 (put 'term-char-mode 'menu-enable '(term-in-line-mode))
3584 (put 'term-line-mode 'menu-enable '(term-in-char-mode))
3585 (put 'term-fake-pager-enable 'menu-enable '(not term-pager-count))
3586 (put 'term-fake-pager-disable 'menu-enable 'term-pager-count))
3587
3588 (defun term-pager-help ()
3589 "Provide help on commands available in a terminal-emulator **MORE** break."
3590 (interactive)
3591 (message "Terminal-emulator pager break help...")
3592 (sit-for 0)
3593 (with-electric-help
3594 (function (lambda ()
3595 (princ (substitute-command-keys
3596 "\\<term-pager-break-map>\
3597 Terminal-emulator MORE break.\n\
3598 Type one of the following keys:\n\n\
3599 \\[term-pager-page]\t\tMove forward one page.\n\
3600 \\[term-pager-line]\t\tMove forward one line.\n\
3601 \\[universal-argument] N \\[term-pager-page]\tMove N pages forward.\n\
3602 \\[universal-argument] N \\[term-pager-line]\tMove N lines forward.\n\
3603 \\[universal-argument] N \\[term-pager-back-line]\tMove N lines back.\n\
3604 \\[universal-argument] N \\[term-pager-back-page]\t\tMove N pages back.\n\
3605 \\[term-pager-bob]\t\tMove to the beginning of the buffer.\n\
3606 \\[term-pager-eob]\t\tMove to the end of the buffer.\n\
3607 \\[term-pager-discard]\t\tKill pending output and kill process.\n\
3608 \\[term-pager-disable]\t\tDisable PAGER handling.\n\n\
3609 \\{term-pager-break-map}\n\
3610 Any other key is passed through to the program
3611 running under the terminal emulator and disables pager processing until
3612 all pending output has been dealt with."))
3613 nil))))
3614
3615 (defun term-pager-continue (new-count)
3616 (let ((process (get-buffer-process (current-buffer))))
3617 (use-local-map term-pager-old-local-map)
3618 (setq term-pager-old-local-map nil)
3619 (setq mode-line-format term-old-mode-line-format)
3620 (force-mode-line-update)
3621 (setq term-pager-count new-count)
3622 (set-process-filter process term-pager-old-filter)
3623 (funcall term-pager-old-filter process "")
3624 (continue-process process)))
3625
3626 ;; Make sure there are DOWN blank lines below the current one.
3627 ;; Return 0 if we're unable (because of PAGER handling), else return DOWN.
3628
3629 (defun term-handle-scroll (down)
3630 (let ((scroll-needed
3631 (- (+ (term-current-row) down)
3632 (if (< down 0) term-scroll-start term-scroll-end))))
3633 (when (or (and (< down 0) (< scroll-needed 0))
3634 (and (> down 0) (> scroll-needed 0)))
3635 (let ((save-point (copy-marker (point))) (save-top))
3636 (goto-char term-home-marker)
3637 (cond (term-scroll-with-delete
3638 (if (< down 0)
3639 (progn
3640 ;; Delete scroll-needed lines at term-scroll-end,
3641 ;; then insert scroll-needed lines.
3642 (term-vertical-motion term-scroll-end)
3643 (end-of-line)
3644 (setq save-top (point))
3645 (term-vertical-motion scroll-needed)
3646 (end-of-line)
3647 (delete-region save-top (point))
3648 (goto-char save-point)
3649 (setq down (- scroll-needed down))
3650 (term-vertical-motion down))
3651 ;; Delete scroll-needed lines at term-scroll-start.
3652 (term-vertical-motion term-scroll-start)
3653 (setq save-top (point))
3654 (term-vertical-motion scroll-needed)
3655 (delete-region save-top (point))
3656 (goto-char save-point)
3657 (term-vertical-motion down)
3658 (term-adjust-current-row-cache (- scroll-needed)))
3659 (setq term-current-column nil)
3660 (term-insert-char ?\n (abs scroll-needed)))
3661 ((and (numberp term-pager-count)
3662 (< (setq term-pager-count (- term-pager-count down))
3663 0))
3664 (setq down 0)
3665 (term-process-pager))
3666 (t
3667 (term-adjust-current-row-cache (- scroll-needed))
3668 (term-vertical-motion scroll-needed)
3669 (set-marker term-home-marker (point))))
3670 (goto-char save-point)
3671 (set-marker save-point nil))))
3672 down)
3673
3674 (defun term-down (down &optional check-for-scroll)
3675 "Move down DOWN screen lines vertically."
3676 (let ((start-column (term-horizontal-column)))
3677 (when (and check-for-scroll (or term-scroll-with-delete term-pager-count))
3678 (setq down (term-handle-scroll down)))
3679 (unless (and (= term-current-row 0) (< down 0))
3680 (term-adjust-current-row-cache down)
3681 (when (or (/= (point) (point-max)) (< down 0))
3682 (setq down (- down (term-vertical-motion down)))))
3683 (cond ((>= down 0)
3684 ;; Extend buffer with extra blank lines if needed.
3685 (term-insert-char ?\n down)
3686 (setq term-current-column 0)
3687 (setq term-start-line-column 0))
3688 (t
3689 (when (= term-current-row 0)
3690 ;; Insert lines if at the beginning.
3691 (save-excursion (term-insert-char ?\n (- down)))
3692 (save-excursion
3693 (let (p)
3694 ;; Delete lines from the end.
3695 (forward-line term-height)
3696 (setq p (point))
3697 (forward-line (- down))
3698 (delete-region p (point)))))
3699 (setq term-current-column 0)
3700 (setq term-start-line-column (current-column))))
3701 (when start-column
3702 (term-move-columns start-column))))
3703
3704 ;; Assuming point is at the beginning of a screen line,
3705 ;; if the line above point wraps around, add a ?\n to undo the wrapping.
3706 ;; FIXME: Probably should be called more than it is.
3707 (defun term-unwrap-line ()
3708 (when (not (bolp)) (insert-before-markers ?\n)))
3709
3710 (defun term-erase-in-line (kind)
3711 (when (= kind 1) ;; erase left of point
3712 (let ((cols (term-horizontal-column)) (saved-point (point)))
3713 (term-vertical-motion 0)
3714 (delete-region (point) saved-point)
3715 (term-insert-char ? cols)))
3716 (when (not (eq kind 1)) ;; erase right of point
3717 (let ((saved-point (point))
3718 (wrapped (and (zerop (term-horizontal-column))
3719 (not (zerop (term-current-column))))))
3720 (term-vertical-motion 1)
3721 (delete-region saved-point (point))
3722 ;; wrapped is true if we're at the beginning of screen line,
3723 ;; but not a buffer line. If we delete the current screen line
3724 ;; that will make the previous line no longer wrap, and (because
3725 ;; of the way Emacs display works) point will be at the end of
3726 ;; the previous screen line rather then the beginning of the
3727 ;; current one. To avoid that, we make sure that current line
3728 ;; contain a space, to force the previous line to continue to wrap.
3729 ;; We could do this always, but it seems preferable to not add the
3730 ;; extra space when wrapped is false.
3731 (when wrapped
3732 (insert ? ))
3733 (insert ?\n)
3734 (put-text-property saved-point (point) 'face 'default)
3735 (goto-char saved-point))))
3736
3737 (defun term-erase-in-display (kind)
3738 "Erases (that is blanks out) part of the window.
3739 If KIND is 0, erase from (point) to (point-max);
3740 if KIND is 1, erase from home to point; else erase from home to point-max."
3741 (term-handle-deferred-scroll)
3742 (cond ((eq term-terminal-parameter 0)
3743 (let ((need-unwrap (bolp)))
3744 (delete-region (point) (point-max))
3745 (when need-unwrap (term-unwrap-line))))
3746 ((let ((row (term-current-row))
3747 (col (term-horizontal-column))
3748 (start-region term-home-marker)
3749 (end-region (if (eq kind 1) (point) (point-max))))
3750 (delete-region start-region end-region)
3751 (term-unwrap-line)
3752 (when (eq kind 1)
3753 (term-insert-char ?\n row))
3754 (setq term-current-column nil)
3755 (setq term-current-row nil)
3756 (term-goto row col)))))
3757
3758 (defun term-delete-chars (count)
3759 (let ((save-point (point)))
3760 (term-vertical-motion 1)
3761 (term-unwrap-line)
3762 (goto-char save-point)
3763 (move-to-column (+ (term-current-column) count) t)
3764 (delete-region save-point (point))))
3765
3766 ;;; Insert COUNT spaces after point, but do not change any of
3767 ;;; following screen lines. Hence we may have to delete characters
3768 ;;; at the end of this screen line to make room.
3769
3770 (defun term-insert-spaces (count)
3771 (let ((save-point (point)) (save-eol) (pnt-at-eol))
3772 (term-vertical-motion 1)
3773 (when (bolp)
3774 (backward-char))
3775 (setq save-eol (point))
3776 (save-excursion
3777 (end-of-line)
3778 (setq pnt-at-eol (point)))
3779 (move-to-column (+ (term-start-line-column) (- term-width count)) t)
3780 ;; If move-to-column extends the current line it will use the face
3781 ;; from the last character on the line, set the face for the chars
3782 ;; to default.
3783 (when (>= (point) pnt-at-eol)
3784 (put-text-property pnt-at-eol (point) 'face 'default))
3785 (when (> save-eol (point))
3786 (delete-region (point) save-eol))
3787 (goto-char save-point)
3788 (term-insert-char ? count)
3789 (goto-char save-point)))
3790
3791 (defun term-delete-lines (lines)
3792 (let ((start (point))
3793 (save-current-column term-current-column)
3794 (save-start-line-column term-start-line-column)
3795 (save-current-row (term-current-row)))
3796 ;; The number of inserted lines shouldn't exceed the scroll region end.
3797 ;; The `term-scroll-end' line is part of the scrolling region, so
3798 ;; we need to go one line past it in order to ensure correct
3799 ;; scrolling.
3800 (when (> (+ save-current-row lines) (1+ term-scroll-end))
3801 (setq lines (- lines (- (+ save-current-row lines) (1+ term-scroll-end)))))
3802 (term-down lines)
3803 (delete-region start (point))
3804 (term-down (- (1+ term-scroll-end) save-current-row lines))
3805 (term-insert-char ?\n lines)
3806 (setq term-current-column save-current-column)
3807 (setq term-start-line-column save-start-line-column)
3808 (setq term-current-row save-current-row)
3809 (goto-char start)))
3810
3811 (defun term-insert-lines (lines)
3812 (let ((start (point))
3813 (start-deleted)
3814 (save-current-column term-current-column)
3815 (save-start-line-column term-start-line-column)
3816 (save-current-row (term-current-row)))
3817 ;; Inserting lines should take into account the scroll region.
3818 ;; The `term-scroll-end' line is part of the scrolling region, so
3819 ;; we need to go one line past it in order to ensure correct
3820 ;; scrolling.
3821 (if (< save-current-row term-scroll-start)
3822 ;; If point is before scroll start,
3823 (progn
3824 (setq lines (- lines (- term-scroll-start save-current-row)))
3825 (term-down (- term-scroll-start save-current-row))
3826 (setq start (point)))
3827 ;; The number of inserted lines shouldn't exceed the scroll region end.
3828 (when (> (+ save-current-row lines) (1+ term-scroll-end))
3829 (setq lines (- lines (- (+ save-current-row lines)(1+ term-scroll-end)))))
3830 (term-down (- (1+ term-scroll-end) save-current-row lines)))
3831 (setq start-deleted (point))
3832 (term-down lines)
3833 (delete-region start-deleted (point))
3834 (goto-char start)
3835 (setq term-current-column save-current-column)
3836 (setq term-start-line-column save-start-line-column)
3837 (setq term-current-row save-current-row)
3838 (term-insert-char ?\n lines)
3839 (goto-char start)))
3840 \f
3841 (defun term-start-output-log (name)
3842 "Record raw inferior process output in a buffer."
3843 (interactive (list (if term-log-buffer
3844 nil
3845 (read-buffer "Record output in buffer: "
3846 (format "%s output-log"
3847 (buffer-name (current-buffer)))
3848 nil))))
3849 (if (or (null name) (equal name ""))
3850 (progn (setq term-log-buffer nil)
3851 (message "Output logging off."))
3852 (if (get-buffer name)
3853 nil
3854 (save-excursion
3855 (set-buffer (get-buffer-create name))
3856 (fundamental-mode)
3857 (buffer-disable-undo (current-buffer))
3858 (erase-buffer)))
3859 (setq term-log-buffer (get-buffer name))
3860 (message "Recording terminal emulator output into buffer \"%s\""
3861 (buffer-name term-log-buffer))))
3862
3863 (defun term-stop-output-log ()
3864 "Discontinue raw inferior process logging."
3865 (interactive)
3866 (term-start-output-log nil))
3867
3868 (defun term-show-maximum-output ()
3869 "Put the end of the buffer at the bottom of the window."
3870 (interactive)
3871 (goto-char (point-max))
3872 (recenter -1))
3873 \f
3874 ;;; Do the user's customisation...
3875
3876 (defvar term-load-hook nil
3877 "This hook is run when term is loaded in.
3878 This is a good place to put keybindings.")
3879
3880 (run-hooks 'term-load-hook)
3881
3882 \f
3883 ;;; Filename/command/history completion in a buffer
3884 ;;; ===========================================================================
3885 ;;; Useful completion functions, courtesy of the Ergo group.
3886
3887 ;;; Six commands:
3888 ;;; term-dynamic-complete Complete or expand command, filename,
3889 ;;; history at point.
3890 ;;; term-dynamic-complete-filename Complete filename at point.
3891 ;;; term-dynamic-list-filename-completions List completions in help buffer.
3892 ;;; term-replace-by-expanded-filename Expand and complete filename at point;
3893 ;;; replace with expanded/completed name.
3894 ;;; term-dynamic-simple-complete Complete stub given candidates.
3895
3896 ;;; These are not installed in the term-mode keymap. But they are
3897 ;;; available for people who want them. Shell-mode installs them:
3898 ;;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
3899 ;;; (define-key shell-mode-map "\M-?"
3900 ;;; 'term-dynamic-list-filename-completions)))
3901 ;;;
3902 ;;; Commands like this are fine things to put in load hooks if you
3903 ;;; want them present in specific modes.
3904
3905 (defvar term-completion-autolist nil
3906 "*If non-nil, automatically list possibilities on partial completion.
3907 This mirrors the optional behavior of tcsh.")
3908
3909 (defvar term-completion-addsuffix t
3910 "*If non-nil, add a `/' to completed directories, ` ' to file names.
3911 If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
3912 DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact
3913 completion. This mirrors the optional behavior of tcsh.")
3914
3915 (defvar term-completion-recexact nil
3916 "*If non-nil, use shortest completion if characters cannot be added.
3917 This mirrors the optional behavior of tcsh.
3918
3919 A non-nil value is useful if `term-completion-autolist' is non-nil too.")
3920
3921 (defvar term-completion-fignore nil
3922 "*List of suffixes to be disregarded during file completion.
3923 This mirrors the optional behavior of bash and tcsh.
3924
3925 Note that this applies to `term-dynamic-complete-filename' only.")
3926
3927 (defvar term-file-name-prefix ""
3928 "Prefix prepended to absolute file names taken from process input.
3929 This is used by term's and shell's completion functions, and by shell's
3930 directory tracking functions.")
3931
3932
3933 (defun term-directory (directory)
3934 ;; Return expanded DIRECTORY, with `term-file-name-prefix' if absolute.
3935 (expand-file-name (if (file-name-absolute-p directory)
3936 (concat term-file-name-prefix directory)
3937 directory)))
3938
3939
3940 (defun term-word (word-chars)
3941 "Return the word of WORD-CHARS at point, or nil if none is found.
3942 Word constituents are considered to be those in WORD-CHARS, which is like the
3943 inside of a \"[...]\" (see `skip-chars-forward')."
3944 (save-excursion
3945 (let ((limit (point))
3946 (word (concat "[" word-chars "]"))
3947 (non-word (concat "[^" word-chars "]")))
3948 (when (re-search-backward non-word nil 'move)
3949 (forward-char 1))
3950 ;; Anchor the search forwards.
3951 (if (or (eolp) (looking-at non-word))
3952 nil
3953 (re-search-forward (concat word "+") limit)
3954 (buffer-substring (match-beginning 0) (match-end 0))))))
3955
3956
3957 (defun term-match-partial-filename ()
3958 "Return the filename at point, or nil if none is found.
3959 Environment variables are substituted. See `term-word'."
3960 (let ((filename (term-word "~/A-Za-z0-9+@:_.$#,={}-")))
3961 (and filename (substitute-in-file-name filename))))
3962
3963
3964 (defun term-dynamic-complete ()
3965 "Dynamically perform completion at point.
3966 Calls the functions in `term-dynamic-complete-functions' to perform
3967 completion until a function returns non-nil, at which point completion is
3968 assumed to have occurred."
3969 (interactive)
3970 (let ((functions term-dynamic-complete-functions))
3971 (while (and functions (null (funcall (car functions))))
3972 (setq functions (cdr functions)))))
3973
3974
3975 (defun term-dynamic-complete-filename ()
3976 "Dynamically complete the filename at point.
3977 Completes if after a filename. See `term-match-partial-filename' and
3978 `term-dynamic-complete-as-filename'.
3979 This function is similar to `term-replace-by-expanded-filename', except that
3980 it won't change parts of the filename already entered in the buffer; it just
3981 adds completion characters to the end of the filename. A completions listing
3982 may be shown in a help buffer if completion is ambiguous.
3983
3984 Completion is dependent on the value of `term-completion-addsuffix',
3985 `term-completion-recexact' and `term-completion-fignore', and the timing of
3986 completions listing is dependent on the value of `term-completion-autolist'.
3987
3988 Returns t if successful."
3989 (interactive)
3990 (when (term-match-partial-filename)
3991 (prog2 (or (eq (selected-window) (minibuffer-window))
3992 (message "Completing file name..."))
3993 (term-dynamic-complete-as-filename))))
3994
3995 (defun term-dynamic-complete-as-filename ()
3996 "Dynamically complete at point as a filename.
3997 See `term-dynamic-complete-filename'. Returns t if successful."
3998 (let* ((completion-ignore-case nil)
3999 (completion-ignored-extensions term-completion-fignore)
4000 (success t)
4001 (dirsuffix (cond ((not term-completion-addsuffix) "")
4002 ((not (consp term-completion-addsuffix)) "/")
4003 (t (car term-completion-addsuffix))))
4004 (filesuffix (cond ((not term-completion-addsuffix) "")
4005 ((not (consp term-completion-addsuffix)) " ")
4006 (t (cdr term-completion-addsuffix))))
4007 (filename (or (term-match-partial-filename) ""))
4008 (pathdir (file-name-directory filename))
4009 (pathnondir (file-name-nondirectory filename))
4010 (directory (if pathdir (term-directory pathdir) default-directory))
4011 (completion (file-name-completion pathnondir directory))
4012 (mini-flag (eq (selected-window) (minibuffer-window))))
4013 (cond ((null completion)
4014 (message "No completions of %s" filename)
4015 (setq success nil))
4016 ((eq completion t) ; Means already completed "file".
4017 (when term-completion-addsuffix (insert " "))
4018 (or mini-flag (message "Sole completion")))
4019 ((string-equal completion "") ; Means completion on "directory/".
4020 (term-dynamic-list-filename-completions))
4021 (t ; Completion string returned.
4022 (let ((file (concat (file-name-as-directory directory) completion)))
4023 (insert (substring (directory-file-name completion)
4024 (length pathnondir)))
4025 (cond ((symbolp (file-name-completion completion directory))
4026 ;; We inserted a unique completion.
4027 (insert (if (file-directory-p file) dirsuffix filesuffix))
4028 (or mini-flag (message "Completed")))
4029 ((and term-completion-recexact term-completion-addsuffix
4030 (string-equal pathnondir completion)
4031 (file-exists-p file))
4032 ;; It's not unique, but user wants shortest match.
4033 (insert (if (file-directory-p file) dirsuffix filesuffix))
4034 (or mini-flag (message "Completed shortest")))
4035 ((or term-completion-autolist
4036 (string-equal pathnondir completion))
4037 ;; It's not unique, list possible completions.
4038 (term-dynamic-list-filename-completions))
4039 (t
4040 (or mini-flag (message "Partially completed")))))))
4041 success))
4042
4043
4044 (defun term-replace-by-expanded-filename ()
4045 "Dynamically expand and complete the filename at point.
4046 Replace the filename with an expanded, canonicalized and completed replacement.
4047 \"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
4048 with the corresponding directories. \"Canonicalized\" means `..' and `.' are
4049 removed, and the filename is made absolute instead of relative. For expansion
4050 see `expand-file-name' and `substitute-in-file-name'. For completion see
4051 `term-dynamic-complete-filename'."
4052 (interactive)
4053 (replace-match (expand-file-name (term-match-partial-filename)) t t)
4054 (term-dynamic-complete-filename))
4055
4056
4057 (defun term-dynamic-simple-complete (stub candidates)
4058 "Dynamically complete STUB from CANDIDATES list.
4059 This function inserts completion characters at point by completing STUB from
4060 the strings in CANDIDATES. A completions listing may be shown in a help buffer
4061 if completion is ambiguous.
4062
4063 Returns nil if no completion was inserted.
4064 Returns `sole' if completed with the only completion match.
4065 Returns `shortest' if completed with the shortest of the completion matches.
4066 Returns `partial' if completed as far as possible with the completion matches.
4067 Returns `listed' if a completion listing was shown.
4068
4069 See also `term-dynamic-complete-filename'."
4070 (let* ((completion-ignore-case nil)
4071 (candidates (mapcar (function (lambda (x) (list x))) candidates))
4072 (completions (all-completions stub candidates)))
4073 (cond ((null completions)
4074 (message "No completions of %s" stub)
4075 nil)
4076 ((= 1 (length completions)) ; Gotcha!
4077 (let ((completion (car completions)))
4078 (if (string-equal completion stub)
4079 (message "Sole completion")
4080 (insert (substring completion (length stub)))
4081 (message "Completed"))
4082 (when term-completion-addsuffix (insert " "))
4083 'sole))
4084 (t ; There's no unique completion.
4085 (let ((completion (try-completion stub candidates)))
4086 ;; Insert the longest substring.
4087 (insert (substring completion (length stub)))
4088 (cond ((and term-completion-recexact term-completion-addsuffix
4089 (string-equal stub completion)
4090 (member completion completions))
4091 ;; It's not unique, but user wants shortest match.
4092 (insert " ")
4093 (message "Completed shortest")
4094 'shortest)
4095 ((or term-completion-autolist
4096 (string-equal stub completion))
4097 ;; It's not unique, list possible completions.
4098 (term-dynamic-list-completions completions)
4099 'listed)
4100 (t
4101 (message "Partially completed")
4102 'partial)))))))
4103
4104
4105 (defun term-dynamic-list-filename-completions ()
4106 "List in help buffer possible completions of the filename at point."
4107 (interactive)
4108 (let* ((completion-ignore-case nil)
4109 (filename (or (term-match-partial-filename) ""))
4110 (pathdir (file-name-directory filename))
4111 (pathnondir (file-name-nondirectory filename))
4112 (directory (if pathdir (term-directory pathdir) default-directory))
4113 (completions (file-name-all-completions pathnondir directory)))
4114 (if completions
4115 (term-dynamic-list-completions completions)
4116 (message "No completions of %s" filename))))
4117
4118
4119 (defun term-dynamic-list-completions (completions)
4120 "List in help buffer sorted COMPLETIONS.
4121 Typing SPC flushes the help buffer."
4122 (let ((conf (current-window-configuration)))
4123 (with-output-to-temp-buffer "*Completions*"
4124 (display-completion-list (sort completions 'string-lessp)))
4125 (message "Hit space to flush")
4126 (let (key first)
4127 (if (save-excursion
4128 (set-buffer (get-buffer "*Completions*"))
4129 (setq key (read-key-sequence nil)
4130 first (aref key 0))
4131 (and (consp first)
4132 (eq (window-buffer (posn-window (event-start first)))
4133 (get-buffer "*Completions*"))
4134 (eq (key-binding key) 'mouse-choose-completion)))
4135 ;; If the user does mouse-choose-completion with the mouse,
4136 ;; execute the command, then delete the completion window.
4137 (progn
4138 (mouse-choose-completion first)
4139 (set-window-configuration conf))
4140 (if (eq first ?\s)
4141 (set-window-configuration conf)
4142 (setq unread-command-events (listify-key-sequence key)))))))
4143
4144 ;;; I need a make-term that doesn't surround with *s -mm
4145 (defun term-ansi-make-term (name program &optional startfile &rest switches)
4146 "Make a term process NAME in a buffer, running PROGRAM.
4147 The name of the buffer is NAME.
4148 If there is already a running process in that buffer, it is not restarted.
4149 Optional third arg STARTFILE is the name of a file to send the contents of to
4150 the process. Any more args are arguments to PROGRAM."
4151 (let ((buffer (get-buffer-create name )))
4152 ;; If no process, or nuked process, crank up a new one and put buffer in
4153 ;; term mode. Otherwise, leave buffer and existing process alone.
4154 (cond ((not (term-check-proc buffer))
4155 (save-excursion
4156 (set-buffer buffer)
4157 (term-mode)) ; Install local vars, mode, keymap, ...
4158 (term-exec buffer name program startfile switches)))
4159 buffer))
4160
4161 (defvar term-ansi-buffer-name nil)
4162 (defvar term-ansi-default-program nil)
4163 (defvar term-ansi-buffer-base-name nil)
4164
4165 ;;;###autoload
4166 (defun ansi-term (program &optional new-buffer-name)
4167 "Start a terminal-emulator in a new buffer."
4168 (interactive (list (read-from-minibuffer "Run program: "
4169 (or explicit-shell-file-name
4170 (getenv "ESHELL")
4171 (getenv "SHELL")
4172 "/bin/sh"))))
4173
4174 ;; Pick the name of the new buffer.
4175 (setq term-ansi-buffer-name
4176 (if new-buffer-name
4177 new-buffer-name
4178 (if term-ansi-buffer-base-name
4179 (if (eq term-ansi-buffer-base-name t)
4180 (file-name-nondirectory program)
4181 term-ansi-buffer-base-name)
4182 "ansi-term")))
4183
4184 (setq term-ansi-buffer-name (concat "*" term-ansi-buffer-name "*"))
4185
4186 ;; In order to have more than one term active at a time
4187 ;; I'd like to have the term names have the *term-ansi-term<?>* form,
4188 ;; for now they have the *term-ansi-term*<?> form but we'll see...
4189
4190 (setq term-ansi-buffer-name (generate-new-buffer-name term-ansi-buffer-name))
4191 (setq term-ansi-buffer-name (term-ansi-make-term term-ansi-buffer-name program))
4192
4193 (set-buffer term-ansi-buffer-name)
4194 (term-mode)
4195 (term-char-mode)
4196
4197 ;; I wanna have find-file on C-x C-f -mm
4198 ;; your mileage may definitely vary, maybe it's better to put this in your
4199 ;; .emacs ...
4200
4201 (term-set-escape-char ?\C-x)
4202
4203 (switch-to-buffer term-ansi-buffer-name))
4204
4205 \f
4206 ;;; Converting process modes to use term mode
4207 ;;; ===========================================================================
4208 ;;; Renaming variables
4209 ;;; Most of the work is renaming variables and functions. These are the common
4210 ;;; ones:
4211 ;;; Local variables:
4212 ;;; last-input-start term-last-input-start
4213 ;;; last-input-end term-last-input-end
4214 ;;; shell-prompt-pattern term-prompt-regexp
4215 ;;; shell-set-directory-error-hook <no equivalent>
4216 ;;; Miscellaneous:
4217 ;;; shell-set-directory <unnecessary>
4218 ;;; shell-mode-map term-mode-map
4219 ;;; Commands:
4220 ;;; shell-send-input term-send-input
4221 ;;; shell-send-eof term-delchar-or-maybe-eof
4222 ;;; kill-shell-input term-kill-input
4223 ;;; interrupt-shell-subjob term-interrupt-subjob
4224 ;;; stop-shell-subjob term-stop-subjob
4225 ;;; quit-shell-subjob term-quit-subjob
4226 ;;; kill-shell-subjob term-kill-subjob
4227 ;;; kill-output-from-shell term-kill-output
4228 ;;; show-output-from-shell term-show-output
4229 ;;; copy-last-shell-input Use term-previous-input/term-next-input
4230 ;;;
4231 ;;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
4232 ;;; SHELL-DIRECTORY-TRACKER, the shell mode's term-input-filter-functions.
4233 ;;; Term mode does not provide functionality equivalent to
4234 ;;; shell-set-directory-error-hook; it is gone.
4235 ;;;
4236 ;;; term-last-input-start is provided for modes which want to munge
4237 ;;; the buffer after input is sent, perhaps because the inferior
4238 ;;; insists on echoing the input. The LAST-INPUT-START variable in
4239 ;;; the old shell package was used to implement a history mechanism,
4240 ;;; but you should think twice before using term-last-input-start
4241 ;;; for this; the input history ring often does the job better.
4242 ;;;
4243 ;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
4244 ;;; *not* create the term-mode local variables in your foo-mode function.
4245 ;;; This is not modular. Instead, call term-mode, and let *it* create the
4246 ;;; necessary term-specific local variables. Then create the
4247 ;;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
4248 ;;; be foo-mode-map, and its mode to be foo-mode. Set the term-mode hooks
4249 ;;; (term-{prompt-regexp, input-filter, input-filter-functions,
4250 ;;; get-old-input) that need to be different from the defaults. Call
4251 ;;; foo-mode-hook, and you're done. Don't run the term-mode hook yourself;
4252 ;;; term-mode will take care of it. The following example, from shell.el,
4253 ;;; is typical:
4254 ;;;
4255 ;;; (defvar shell-mode-map '())
4256 ;;; (cond ((not shell-mode-map)
4257 ;;; (setq shell-mode-map (copy-keymap term-mode-map))
4258 ;;; (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
4259 ;;; (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
4260 ;;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
4261 ;;; (define-key shell-mode-map "\M-?"
4262 ;;; 'term-dynamic-list-filename-completions)))
4263 ;;;
4264 ;;; (defun shell-mode ()
4265 ;;; (interactive)
4266 ;;; (term-mode)
4267 ;;; (setq term-prompt-regexp shell-prompt-pattern)
4268 ;;; (setq major-mode 'shell-mode)
4269 ;;; (setq mode-name "Shell")
4270 ;;; (use-local-map shell-mode-map)
4271 ;;; (make-local-variable 'shell-directory-stack)
4272 ;;; (setq shell-directory-stack nil)
4273 ;;; (add-hook 'term-input-filter-functions 'shell-directory-tracker)
4274 ;;; (run-mode-hooks 'shell-mode-hook))
4275 ;;;
4276 ;;;
4277 ;;; Completion for term-mode users
4278 ;;;
4279 ;;; For modes that use term-mode, term-dynamic-complete-functions is the
4280 ;;; hook to add completion functions to. Functions on this list should return
4281 ;;; non-nil if completion occurs (i.e., further completion should not occur).
4282 ;;; You could use term-dynamic-simple-complete to do the bulk of the
4283 ;;; completion job.
4284 \f
4285 (provide 'term)
4286
4287 ;; arch-tag: eee16bc8-2cd7-4147-9534-a5694752f716
4288 ;;; term.el ends here