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