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