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