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