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