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