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