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