Merge from origin/emacs-26
[emacs.git] / lisp / term.el
blobc64c64e6ecdc52720e0bd70e41809f509f1f7699
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 list of function names contained in the
2025 value of `term-input-filter-functions' is called on the input before sending
2026 it. The input is entered into the input history ring, if the value of variable
2027 `term-input-filter' returns non-nil when called on the input.
2029 Any history reference may be expanded depending on the value of the variable
2030 `term-input-autoexpand'. The list of function names contained in the value
2031 of `term-input-filter-functions' is called on the input before sending it.
2032 The input is entered into the input history ring, if the value of variable
2033 `term-input-filter' returns non-nil when called on the input.
2035 If variable `term-eol-on-send' is non-nil, then point is moved to the
2036 end of line before sending the input.
2038 The values of `term-get-old-input', `term-input-filter-functions', and
2039 `term-input-filter' are chosen according to the command interpreter running
2040 in the buffer. E.g.,
2042 If the interpreter is the csh,
2043 term-get-old-input is the default: take the current line, discard any
2044 initial string matching regexp term-prompt-regexp.
2045 term-input-filter-functions monitors input for \"cd\", \"pushd\", and
2046 \"popd\" commands. When it sees one, it cd's the buffer.
2047 term-input-filter is the default: returns t if the input isn't all white
2048 space.
2050 If the term is Lucid Common Lisp,
2051 term-get-old-input snarfs the sexp ending at point.
2052 term-input-filter-functions does nothing.
2053 term-input-filter returns nil if the input matches input-filter-regexp,
2054 which matches (1) all whitespace (2) :a, :c, etc.
2056 Similarly for Soar, Scheme, etc."
2057 (interactive)
2058 ;; Note that the input string does not include its terminal newline.
2059 (let ((proc (get-buffer-process (current-buffer))))
2060 (if (not proc) (error "Current buffer has no process")
2061 (let* ((pmark (process-mark proc))
2062 (pmark-val (marker-position pmark))
2063 (input-is-new (>= (point) pmark-val))
2064 (intxt (if input-is-new
2065 (progn (if term-eol-on-send (end-of-line))
2066 (buffer-substring pmark (point)))
2067 (funcall term-get-old-input)))
2068 (input (if (not (eq term-input-autoexpand 'input))
2069 ;; Just whatever's already there
2070 intxt
2071 ;; Expand and leave it visible in buffer
2072 (term-replace-by-expanded-history t)
2073 (buffer-substring pmark (point))))
2074 (history (if (not (eq term-input-autoexpand 'history))
2075 input
2076 ;; This is messy 'cos ultimately the original
2077 ;; functions used do insertion, rather than return
2078 ;; strings. We have to expand, then insert back.
2079 (term-replace-by-expanded-history t)
2080 (let ((copy (buffer-substring pmark (point))))
2081 (delete-region pmark (point))
2082 (insert input)
2083 copy))))
2084 (when (term-pager-enabled)
2085 (save-excursion
2086 (goto-char (process-mark proc))
2087 (setq term-pager-count (term-current-row))))
2088 (when (and (funcall term-input-filter history)
2089 (or (null term-input-ignoredups)
2090 (not (ring-p term-input-ring))
2091 (ring-empty-p term-input-ring)
2092 (not (string-equal (ring-ref term-input-ring 0)
2093 history))))
2094 (ring-insert term-input-ring history))
2095 (let ((functions term-input-filter-functions))
2096 (while functions
2097 (funcall (car functions) (concat input "\n"))
2098 (setq functions (cdr functions))))
2099 (setq term-input-ring-index nil)
2101 ;; Update the markers before we send the input
2102 ;; in case we get output amidst sending the input.
2103 (set-marker term-last-input-start pmark)
2104 (set-marker term-last-input-end (point))
2105 (when input-is-new
2106 ;; Set up to delete, because inferior should echo.
2107 (when (marker-buffer term-pending-delete-marker)
2108 (delete-region term-pending-delete-marker pmark))
2109 (set-marker term-pending-delete-marker pmark-val)
2110 (set-marker (process-mark proc) (point)))
2111 (goto-char pmark)
2112 (funcall term-input-sender proc input)))))
2114 (defun term-get-old-input-default ()
2115 "Default for `term-get-old-input'.
2116 Take the current line, and discard any initial text matching
2117 `term-prompt-regexp'."
2118 (save-excursion
2119 (beginning-of-line)
2120 (term-skip-prompt)
2121 (let ((beg (point)))
2122 (end-of-line)
2123 (buffer-substring beg (point)))))
2125 (defun term-copy-old-input ()
2126 "Insert after prompt old input at point as new input to be edited.
2127 Calls `term-get-old-input' to get old input."
2128 (interactive)
2129 (let ((input (funcall term-get-old-input))
2130 (process (get-buffer-process (current-buffer))))
2131 (if (not process)
2132 (error "Current buffer has no process")
2133 (goto-char (process-mark process))
2134 (insert input))))
2136 (defun term-skip-prompt ()
2137 "Skip past the text matching regexp `term-prompt-regexp'.
2138 If this takes us past the end of the current line, don't skip at all."
2139 (let ((eol (line-end-position)))
2140 (when (and (looking-at term-prompt-regexp)
2141 (<= (match-end 0) eol))
2142 (goto-char (match-end 0)))))
2145 (defun term-after-pmark-p ()
2146 "Is point after the process output marker?"
2147 ;; Since output could come into the buffer after we looked at the point
2148 ;; but before we looked at the process marker's value, we explicitly
2149 ;; serialize. This is just because I don't know whether or not Emacs
2150 ;; services input during execution of lisp commands.
2151 (let ((proc-pos (marker-position
2152 (process-mark (get-buffer-process (current-buffer))))))
2153 (<= proc-pos (point))))
2155 (defun term-simple-send (proc string)
2156 "Default function for sending to PROC input STRING.
2157 This just sends STRING plus a newline. To override this,
2158 set the hook `term-input-sender'."
2159 (term-send-string proc string)
2160 (term-send-string proc "\n"))
2162 (defun term-bol (arg)
2163 "Go to the beginning of line, then skip past the prompt, if any.
2164 If a prefix argument is given (\\[universal-argument]), then no prompt skip
2165 -- go straight to column 0.
2167 The prompt skip is done by skipping text matching the regular expression
2168 `term-prompt-regexp', a buffer local variable."
2169 (interactive "P")
2170 (beginning-of-line)
2171 (when (null arg) (term-skip-prompt)))
2173 ;; These two functions are for entering text you don't want echoed or
2174 ;; saved -- typically passwords to ftp, telnet, or somesuch.
2175 ;; Just enter m-x term-send-invisible and type in your line.
2177 (defun term-read-noecho (prompt &optional stars)
2178 "Read a single line of text from user without echoing, and return it.
2179 Prompt with argument PROMPT, a string. Optional argument STARS causes
2180 input to be echoed with `*' characters on the prompt line. Input ends with
2181 RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line. C-g aborts (if
2182 `inhibit-quit' is set because e.g. this function was called from a process
2183 filter and C-g is pressed, this function returns nil rather than a string).
2185 Note that the keystrokes comprising the text can still be recovered
2186 \(temporarily) with \\[view-lossage]. This may be a security bug for some
2187 applications."
2188 (let ((ans "")
2189 (c 0)
2190 (echo-keystrokes 0)
2191 (cursor-in-echo-area t)
2192 (done nil))
2193 (while (not done)
2194 (if stars
2195 (message "%s%s" prompt (make-string (length ans) ?*))
2196 (message "%s" prompt))
2197 (setq c (read-char))
2198 (cond ((= c ?\C-g)
2199 ;; This function may get called from a process filter, where
2200 ;; inhibit-quit is set. In later versions of Emacs read-char
2201 ;; may clear quit-flag itself and return C-g. That would make
2202 ;; it impossible to quit this loop in a simple way, so
2203 ;; re-enable it here (for backward-compatibility the check for
2204 ;; quit-flag below would still be necessary, so this seems
2205 ;; like the simplest way to do things).
2206 (setq quit-flag t
2207 done t))
2208 ((or (= c ?\r) (= c ?\n) (= c ?\e))
2209 (setq done t))
2210 ((= c ?\C-u)
2211 (setq ans ""))
2212 ((and (/= c ?\b) (/= c ?\177))
2213 (setq ans (concat ans (char-to-string c))))
2214 ((> (length ans) 0)
2215 (setq ans (substring ans 0 -1)))))
2216 (if quit-flag
2217 ;; Emulate a true quit, except that we have to return a value.
2218 (prog1
2219 (setq quit-flag nil)
2220 (message "Quit")
2221 (beep t))
2222 (message "")
2223 ans)))
2225 (defun term-send-invisible (str &optional proc)
2226 "Read a string without echoing.
2227 Then send it to the process running in the current buffer. A new-line
2228 is additionally sent. String is not saved on term input history list.
2229 Security bug: your string can still be temporarily recovered with
2230 \\[view-lossage]."
2231 (interactive "P") ; Defeat snooping via C-x esc
2232 (when (not (stringp str))
2233 (setq str (term-read-noecho "Non-echoed text: " t)))
2234 (when (not proc)
2235 (setq proc (get-buffer-process (current-buffer))))
2236 (if (not proc) (error "Current buffer has no process")
2237 (setq term-kill-echo-list (nconc term-kill-echo-list
2238 (cons str nil)))
2239 (term-send-string proc str)
2240 (term-send-string proc "\n")))
2243 ;;; Low-level process communication
2245 (defcustom term-input-chunk-size 512
2246 "Long inputs send to term processes are broken up into chunks of this size.
2247 If your process is choking on big inputs, try lowering the value."
2248 :group 'term
2249 :type 'integer)
2251 (defun term-send-string (proc str)
2252 "Send to PROC the contents of STR as input.
2253 This is equivalent to `process-send-string', except that long input strings
2254 are broken up into chunks of size `term-input-chunk-size'. Processes
2255 are given a chance to output between chunks. This can help prevent processes
2256 from hanging when you send them long inputs on some OS's."
2257 (let* ((len (length str))
2258 (i (min len term-input-chunk-size)))
2259 (process-send-string proc (substring str 0 i))
2260 (while (< i len)
2261 (let ((next-i (+ i term-input-chunk-size)))
2262 (accept-process-output)
2263 (process-send-string proc (substring str i (min len next-i)))
2264 (setq i next-i)))))
2266 (defun term-send-region (proc start end)
2267 "Send to PROC the region delimited by START and END.
2268 This is a replacement for `process-send-region' that tries to keep
2269 your process from hanging on long inputs. See `term-send-string'."
2270 (term-send-string proc (buffer-substring start end)))
2273 ;;; Random input hackage
2275 (defun term-kill-output ()
2276 "Kill all output from interpreter since last input."
2277 (interactive)
2278 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2279 (kill-region term-last-input-end pmark)
2280 (goto-char pmark)
2281 (insert "*** output flushed ***\n")
2282 (set-marker pmark (point))))
2284 (defun term-show-output ()
2285 "Display start of this batch of interpreter output at top of window.
2286 Sets mark to the value of point when this command is run."
2287 (interactive)
2288 (goto-char term-last-input-end)
2289 (backward-char)
2290 (beginning-of-line)
2291 (set-window-start (selected-window) (point))
2292 (end-of-line))
2294 (defun term-interrupt-subjob ()
2295 "Interrupt the current subjob."
2296 (interactive)
2297 (interrupt-process nil term-ptyp))
2299 (defun term-kill-subjob ()
2300 "Send kill signal to the current subjob."
2301 (interactive)
2302 (kill-process nil term-ptyp))
2304 (defun term-quit-subjob ()
2305 "Send quit signal to the current subjob."
2306 (interactive)
2307 (quit-process nil term-ptyp))
2309 (defun term-stop-subjob ()
2310 "Stop the current subjob.
2311 WARNING: if there is no current subjob, you can end up suspending
2312 the top-level process running in the buffer. If you accidentally do
2313 this, use \\[term-continue-subjob] to resume the process. (This
2314 is not a problem with most shells, since they ignore this signal.)"
2315 (interactive)
2316 (stop-process nil term-ptyp))
2318 (defun term-continue-subjob ()
2319 "Send CONT signal to process buffer's process group.
2320 Useful if you accidentally suspend the top-level process."
2321 (interactive)
2322 (continue-process nil term-ptyp))
2324 (defun term-kill-input ()
2325 "Kill all text from last stuff output by interpreter to point."
2326 (interactive)
2327 (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
2328 (p-pos (marker-position pmark)))
2329 (when (> (point) p-pos)
2330 (kill-region pmark (point)))))
2332 (defun term-delchar-or-maybe-eof (arg)
2333 "Delete ARG characters forward, or send an EOF to process if at end of
2334 buffer."
2335 (interactive "p")
2336 (if (eobp)
2337 (process-send-eof)
2338 (delete-char arg)))
2340 (defun term-send-eof ()
2341 "Send an EOF to the current buffer's process."
2342 (interactive)
2343 (process-send-eof))
2345 (defun term-backward-matching-input (regexp n)
2346 "Search backward through buffer for match for REGEXP.
2347 Matches are searched for on lines that match `term-prompt-regexp'.
2348 With prefix argument N, search for Nth previous match.
2349 If N is negative, find the next or Nth next match."
2350 (interactive (term-regexp-arg "Backward input matching (regexp): "))
2351 (let* ((re (concat term-prompt-regexp ".*" regexp))
2352 (pos (save-excursion (end-of-line (if (> n 0) 0 1))
2353 (when (re-search-backward re nil t n)
2354 (point)))))
2355 (if (null pos)
2356 (progn (message "Not found")
2357 (ding))
2358 (goto-char pos)
2359 (term-bol nil))))
2361 (defun term-forward-matching-input (regexp n)
2362 "Search forward through buffer for match for REGEXP.
2363 Matches are searched for on lines that match `term-prompt-regexp'.
2364 With prefix argument N, search for Nth following match.
2365 If N is negative, find the previous or Nth previous match."
2366 (interactive (term-regexp-arg "Forward input matching (regexp): "))
2367 (term-backward-matching-input regexp (- n)))
2370 (defun term-next-prompt (n)
2371 "Move to end of Nth next prompt in the buffer.
2372 See `term-prompt-regexp'."
2373 (interactive "p")
2374 (let ((paragraph-start term-prompt-regexp))
2375 (end-of-line (if (> n 0) 1 0))
2376 (forward-paragraph n)
2377 (term-skip-prompt)))
2379 (defun term-previous-prompt (n)
2380 "Move to end of Nth previous prompt in the buffer.
2381 See `term-prompt-regexp'."
2382 (interactive "p")
2383 (term-next-prompt (- n)))
2385 ;;; Support for source-file processing commands.
2386 ;;============================================================================
2387 ;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
2388 ;; commands that process files of source text (e.g. loading or compiling
2389 ;; files). So the corresponding process-in-a-buffer modes have commands
2390 ;; for doing this (e.g., lisp-load-file). The functions below are useful
2391 ;; for defining these commands.
2393 ;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
2394 ;; and Soar, in that they don't know anything about file extensions.
2395 ;; So the compile/load interface gets the wrong default occasionally.
2396 ;; The load-file/compile-file default mechanism could be smarter -- it
2397 ;; doesn't know about the relationship between filename extensions and
2398 ;; whether the file is source or executable. If you compile foo.lisp
2399 ;; with compile-file, then the next load-file should use foo.bin for
2400 ;; the default, not foo.lisp. This is tricky to do right, particularly
2401 ;; because the extension for executable files varies so much (.o, .bin,
2402 ;; .lbin, .mo, .vo, .ao, ...).
2405 ;; TERM-SOURCE-DEFAULT -- determines defaults for source-file processing
2406 ;; commands.
2408 ;; TERM-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
2409 ;; want to save the buffer before issuing any process requests to the command
2410 ;; interpreter.
2412 ;; TERM-GET-SOURCE -- used by the source-file processing commands to prompt
2413 ;; for the file to process.
2415 ;; (TERM-SOURCE-DEFAULT previous-dir/file source-modes)
2416 ;;============================================================================
2417 ;; This function computes the defaults for the load-file and compile-file
2418 ;; commands for tea, soar, cmulisp, and cmuscheme modes.
2420 ;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
2421 ;; source-file processing command, or nil if there hasn't been one yet.
2422 ;; - SOURCE-MODES is a list used to determine what buffers contain source
2423 ;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
2424 ;; Typically, (lisp-mode) or (scheme-mode).
2426 ;; If the command is given while the cursor is inside a string, *and*
2427 ;; the string is an existing filename, *and* the filename is not a directory,
2428 ;; then the string is taken as default. This allows you to just position
2429 ;; your cursor over a string that's a filename and have it taken as default.
2431 ;; If the command is given in a file buffer whose major mode is in
2432 ;; SOURCE-MODES, then the filename is the default file, and the
2433 ;; file's directory is the default directory.
2435 ;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
2436 ;; then the default directory & file are what was used in the last source-file
2437 ;; processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
2438 ;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
2439 ;; is the cwd, with no default file. (\"no default file\" = nil)
2441 ;; SOURCE-REGEXP is typically going to be something like (tea-mode)
2442 ;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
2443 ;; for Soar programs, etc.
2445 ;; The function returns a pair: (default-directory . default-file).
2447 (defun term-source-default (previous-dir/file source-modes)
2448 (cond ((and buffer-file-name (memq major-mode source-modes))
2449 (cons (file-name-directory buffer-file-name)
2450 (file-name-nondirectory buffer-file-name)))
2451 (previous-dir/file)
2453 (cons default-directory nil))))
2456 ;; (TERM-CHECK-SOURCE fname)
2457 ;;============================================================================
2458 ;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
2459 ;; process-in-a-buffer modes), this function can be called on the filename.
2460 ;; If the file is loaded into a buffer, and the buffer is modified, the user
2461 ;; is queried to see if he wants to save the buffer before proceeding with
2462 ;; the load or compile.
2464 (defun term-check-source (fname)
2465 (let ((buff (get-file-buffer fname)))
2466 (when (and buff
2467 (buffer-modified-p buff)
2468 (y-or-n-p (format "Save buffer %s first? "
2469 (buffer-name buff))))
2470 ;; save BUFF.
2471 (with-current-buffer buff
2472 (save-buffer)))))
2475 ;; (TERM-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
2476 ;;============================================================================
2477 ;; TERM-GET-SOURCE is used to prompt for filenames in command-interpreter
2478 ;; commands that process source files (like loading or compiling a file).
2479 ;; It prompts for the filename, provides a default, if there is one,
2480 ;; and returns the result filename.
2482 ;; See TERM-SOURCE-DEFAULT for more on determining defaults.
2484 ;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
2485 ;; from the last source processing command. SOURCE-MODES is a list of major
2486 ;; modes used to determine what file buffers contain source files. (These
2487 ;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
2488 ;; then the filename reader will only accept a file that exists.
2490 ;; A typical use:
2491 ;; (interactive (term-get-source "Compile file: " prev-lisp-dir/file
2492 ;; '(lisp-mode) t))
2494 ;; This is pretty stupid about strings. It decides we're in a string
2495 ;; if there's a quote on both sides of point on the current line.
2496 (defun term-extract-string ()
2497 "Return string around `point' that starts the current line or nil."
2498 (save-excursion
2499 (let* ((point (point))
2500 (bol (line-beginning-position))
2501 (eol (line-end-position))
2502 (start (and (search-backward "\"" bol t)
2503 (1+ (point))))
2504 (end (progn (goto-char point)
2505 (and (search-forward "\"" eol t)
2506 (1- (point))))))
2507 (and start end
2508 (buffer-substring start end)))))
2510 (defun term-get-source (prompt prev-dir/file source-modes mustmatch-p)
2511 (let* ((def (term-source-default prev-dir/file source-modes))
2512 (stringfile (term-extract-string))
2513 (sfile-p (and stringfile
2514 (condition-case ()
2515 (file-exists-p stringfile)
2516 (error nil))
2517 (not (file-directory-p stringfile))))
2518 (defdir (if sfile-p (file-name-directory stringfile)
2519 (car def)))
2520 (deffile (if sfile-p (file-name-nondirectory stringfile)
2521 (cdr def)))
2522 (ans (read-file-name (if deffile (format "%s(default %s) "
2523 prompt deffile)
2524 prompt)
2525 defdir
2526 (concat defdir deffile)
2527 mustmatch-p)))
2528 (list (expand-file-name (substitute-in-file-name ans)))))
2530 ;; I am somewhat divided on this string-default feature. It seems
2531 ;; to violate the principle-of-least-astonishment, in that it makes
2532 ;; the default harder to predict, so you actually have to look and see
2533 ;; what the default really is before choosing it. This can trip you up.
2534 ;; On the other hand, it can be useful, I guess. I would appreciate feedback
2535 ;; on this.
2536 ;; -Olin
2539 ;;; Simple process query facility.
2540 ;; ===========================================================================
2541 ;; This function is for commands that want to send a query to the process
2542 ;; and show the response to the user. For example, a command to get the
2543 ;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
2544 ;; to an inferior Common Lisp process.
2546 ;; This simple facility just sends strings to the inferior process and pops
2547 ;; up a window for the process buffer so you can see what the process
2548 ;; responds with. We don't do anything fancy like try to intercept what the
2549 ;; process responds with and put it in a pop-up window or on the message
2550 ;; line. We just display the buffer. Low tech. Simple. Works good.
2552 ;; Send to the inferior process PROC the string STR. Pop-up but do not select
2553 ;; a window for the inferior process so that its response can be seen.
2554 (defun term-proc-query (proc str)
2555 (let* ((proc-buf (process-buffer proc))
2556 (proc-mark (process-mark proc)))
2557 (display-buffer proc-buf)
2558 (set-buffer proc-buf) ; but it's not the selected *window*
2559 (let ((proc-win (get-buffer-window proc-buf))
2560 (proc-pt (marker-position proc-mark)))
2561 (term-send-string proc str) ; send the query
2562 (accept-process-output proc) ; wait for some output
2563 ;; Try to position the proc window so you can see the answer.
2564 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
2565 ;; I don't know why. Wizards invited to improve it.
2566 (when (not (pos-visible-in-window-p proc-pt proc-win))
2567 (let ((opoint (window-point proc-win)))
2568 (set-window-point proc-win proc-mark) (sit-for 0)
2569 (if (not (pos-visible-in-window-p opoint proc-win))
2570 (push-mark opoint)
2571 (set-window-point proc-win opoint)))))))
2573 ;; Returns the current column in the current screen line.
2574 ;; Note: (current-column) yields column in buffer line.
2576 (defun term-horizontal-column ()
2577 (- (term-current-column) (term-start-line-column)))
2579 ;; Calls either vertical-motion or term-buffer-vertical-motion
2580 (defmacro term-vertical-motion (count)
2581 (list 'funcall 'term-vertical-motion count))
2583 ; An emulation of vertical-motion that is independent of having a window.
2584 ; Instead, it uses the term-width variable as the logical window width.
2586 (defun term-buffer-vertical-motion (count)
2587 (cond ((= count 0)
2588 (move-to-column (* term-width (/ (current-column) term-width)))
2590 ((> count 0)
2591 (let ((H)
2592 (todo (+ count (/ (current-column) term-width))))
2593 (end-of-line)
2594 ;; The loop iterates over buffer lines;
2595 ;; H is the number of screen lines in the current line, i.e.
2596 ;; the ceiling of dividing the buffer line width by term-width.
2597 (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2598 term-width)
2600 todo)
2601 (not (eobp)))
2602 (setq todo (- todo H))
2603 (forward-char) ;; Move past the ?\n
2604 (end-of-line)) ;; and on to the end of the next line.
2605 (if (and (>= todo H) (> todo 0))
2606 (+ (- count todo) H -1) ;; Hit end of buffer.
2607 (move-to-column (* todo term-width))
2608 count)))
2609 (t ;; (< count 0) ;; Similar algorithm, but for upward motion.
2610 (let ((H)
2611 (todo (- count)))
2612 (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2613 term-width)
2615 todo)
2616 (progn (beginning-of-line)
2617 (not (bobp))))
2618 (setq todo (- todo H))
2619 (backward-char)) ;; Move to end of previous line.
2620 (if (and (>= todo H) (> todo 0))
2621 (+ count todo (- 1 H)) ;; Hit beginning of buffer.
2622 (move-to-column (* (- H todo 1) term-width))
2623 count)))))
2625 ;; The term-start-line-column variable is used as a cache.
2626 (defun term-start-line-column ()
2627 (cond (term-start-line-column)
2628 ((let ((save-pos (point)))
2629 (term-vertical-motion 0)
2630 (setq term-start-line-column (current-column))
2631 (goto-char save-pos)
2632 term-start-line-column))))
2634 ;; Same as (current-column), but uses term-current-column as a cache.
2635 (defun term-current-column ()
2636 (cond (term-current-column)
2637 ((setq term-current-column (current-column)))))
2639 (defun term-move-to-column (column)
2640 (setq term-current-column column)
2641 (let ((point-at-eol (line-end-position)))
2642 (move-to-column term-current-column t)
2643 ;; If move-to-column extends the current line it will use the face
2644 ;; from the last character on the line, set the face for the chars
2645 ;; to default.
2646 (when (> (point) point-at-eol)
2647 (put-text-property point-at-eol (point) 'font-lock-face 'default))))
2649 ;; Move DELTA column right (or left if delta < 0 limiting at column 0).
2650 (defun term-move-columns (delta)
2651 (term-move-to-column
2652 (max 0 (+ (term-current-column) delta))))
2654 ;; Insert COUNT copies of CHAR in the default face.
2655 (defun term-insert-char (char count)
2656 (let ((old-point (point)))
2657 (insert-char char count)
2658 (put-text-property old-point (point) 'font-lock-face 'default)))
2660 (defun term-current-row ()
2661 (cond (term-current-row)
2662 ((setq term-current-row
2663 (save-restriction
2664 (save-excursion
2665 (narrow-to-region term-home-marker (point-max))
2666 (- (term-vertical-motion -9999))))))))
2668 (defun term-adjust-current-row-cache (delta)
2669 (when term-current-row
2670 (setq term-current-row
2671 (max 0 (+ term-current-row delta)))))
2673 (defun term-terminal-pos ()
2674 (save-excursion ; save-restriction
2675 (let ((save-col (term-current-column))
2676 x y)
2677 (term-vertical-motion 0)
2678 (setq x (- save-col (current-column)))
2679 (setq y (term-vertical-motion term-height))
2680 (cons x y))))
2682 ;;Function that handles term messages: code by rms (and you can see the
2683 ;;difference ;-) -mm
2685 (defun term-handle-ansi-terminal-messages (message)
2686 ;; Is there a command here?
2687 (while (string-match "\eAnSiT.+\n" message)
2688 ;; Extract the command code and the argument.
2689 (let* ((start (match-beginning 0))
2690 (command-code (aref message (+ start 6)))
2691 (argument
2692 (save-match-data
2693 (substring message
2694 (+ start 8)
2695 (string-match "\r?\n" message
2696 (+ start 8)))))
2697 ignore)
2698 ;; Delete this command from MESSAGE.
2699 (setq message (replace-match "" t t message))
2701 ;; If we recognize the type of command, set the appropriate variable.
2702 (cond ((= command-code ?c)
2703 (setq term-ansi-at-dir argument))
2704 ((= command-code ?h)
2705 (setq term-ansi-at-host argument))
2706 ((= command-code ?u)
2707 (setq term-ansi-at-user argument))
2708 ;; Otherwise ignore this one.
2710 (setq ignore t)))
2712 ;; Update default-directory based on the changes this command made.
2713 (if ignore
2715 (setq default-directory
2716 (file-name-as-directory
2717 (if (and (string= term-ansi-at-host (system-name))
2718 (string= term-ansi-at-user (user-real-login-name)))
2719 (expand-file-name term-ansi-at-dir)
2720 (if (string= term-ansi-at-user (user-real-login-name))
2721 (concat "/" term-ansi-at-host ":" term-ansi-at-dir)
2722 (concat "/" term-ansi-at-user "@" term-ansi-at-host ":"
2723 term-ansi-at-dir)))))
2725 ;; I'm not sure this is necessary,
2726 ;; but it's best to be on the safe side.
2727 (if (string= term-ansi-at-host (system-name))
2728 (progn
2729 (setq ange-ftp-default-user term-ansi-at-save-user)
2730 (setq ange-ftp-default-password term-ansi-at-save-pwd)
2731 (setq ange-ftp-generate-anonymous-password term-ansi-at-save-anon))
2732 (setq term-ansi-at-save-user ange-ftp-default-user)
2733 (setq term-ansi-at-save-pwd ange-ftp-default-password)
2734 (setq term-ansi-at-save-anon ange-ftp-generate-anonymous-password)
2735 (setq ange-ftp-default-user nil)
2736 (setq ange-ftp-default-password nil)
2737 (setq ange-ftp-generate-anonymous-password nil)))))
2738 message)
2741 ;; Terminal emulation
2742 ;; This is the standard process filter for term buffers.
2743 ;; It emulates (most of the features of) a VT100/ANSI-style terminal.
2745 ;; References:
2746 ;; [ctlseqs]: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
2747 ;; [ECMA-48]: http://www.ecma-international.org/publications/standards/Ecma-048.htm
2748 ;; [vt100]: https://vt100.net/docs/vt100-ug/chapter3.html
2750 (defconst term-control-seq-regexp
2751 (concat
2752 ;; A control character,
2753 "\\(?:[\r\n\000\007\t\b\016\017]\\|"
2754 ;; some Emacs specific control sequences, implemented by
2755 ;; `term-command-hook',
2756 "\032[^\n]+\r?\n\\|"
2757 ;; a C1 escape coded character (see [ECMA-48] section 5.3 "Elements
2758 ;; of the C1 set"),
2759 "\e\\(?:[DM78c]\\|"
2760 ;; another Emacs specific control sequence,
2761 "AnSiT[^\n]+\r?\n\\|"
2762 ;; or an escape sequence (section 5.4 "Control Sequences"),
2763 "\\[\\([\x30-\x3F]*\\)[\x20-\x2F]*[\x40-\x7E]\\)\\)")
2764 "Regexp matching control sequences handled by term.el.")
2766 (defconst term-control-seq-prefix-regexp
2767 "[\032\e]")
2769 (defun term-emulate-terminal (proc str)
2770 (with-current-buffer (process-buffer proc)
2771 (let* ((i 0) funny
2772 decoded-substring
2773 save-point save-marker win
2774 (inhibit-read-only t)
2775 (buffer-undo-list t)
2776 (selected (selected-window))
2777 last-win
2778 (str-length (length str)))
2779 (save-selected-window
2781 (when (marker-buffer term-pending-delete-marker)
2782 ;; Delete text following term-pending-delete-marker.
2783 (delete-region term-pending-delete-marker (process-mark proc))
2784 (set-marker term-pending-delete-marker nil))
2786 (when (/= (point) (process-mark proc))
2787 (setq save-point (point-marker)))
2789 (setf term-vertical-motion
2790 (if (eq (window-buffer) (current-buffer))
2791 'vertical-motion
2792 'term-buffer-vertical-motion))
2793 (setq save-marker (copy-marker (process-mark proc)))
2794 (goto-char (process-mark proc))
2796 (save-restriction
2797 ;; If the buffer is in line mode, and there is a partial
2798 ;; input line, save the line (by narrowing to leave it
2799 ;; outside the restriction ) until we're done with output.
2800 (when (and (> (point-max) (process-mark proc))
2801 (term-in-line-mode))
2802 (narrow-to-region (point-min) (process-mark proc)))
2804 (when term-log-buffer
2805 (princ str term-log-buffer))
2806 (when term-terminal-undecoded-bytes
2807 (setq str (concat term-terminal-undecoded-bytes str))
2808 (setq str-length (length str))
2809 (setq term-terminal-undecoded-bytes nil))
2811 (while (< i str-length)
2812 (setq funny (string-match term-control-seq-regexp str i))
2813 (let ((ctl-params (and funny (match-string 1 str)))
2814 (ctl-params-end (and funny (match-end 1)))
2815 (ctl-end (if funny (match-end 0)
2816 (setq funny (string-match term-control-seq-prefix-regexp str i))
2817 (if funny
2818 (setq term-terminal-undecoded-bytes
2819 (substring str funny))
2820 (setq funny str-length))
2821 ;; The control sequence ends somewhere
2822 ;; past the end of this string.
2823 (1+ str-length))))
2824 (when (> funny i)
2825 (when term-do-line-wrapping
2826 (term-down 1 t)
2827 (term-move-to-column 0)
2828 (setq term-do-line-wrapping nil))
2829 ;; Handle non-control data. Decode the string before
2830 ;; counting characters, to avoid garbling of certain
2831 ;; multibyte characters (bug#1006).
2832 (setq decoded-substring
2833 (decode-coding-string
2834 (substring str i funny)
2835 locale-coding-system t))
2836 ;; Check for multibyte characters that ends
2837 ;; before end of string, and save it for
2838 ;; next time.
2839 (when (= funny str-length)
2840 (let ((partial 0)
2841 (count (length decoded-substring)))
2842 (while (eq (char-charset (aref decoded-substring
2843 (- count 1 partial)))
2844 'eight-bit)
2845 (cl-incf partial))
2846 (when (> partial 0)
2847 (setq term-terminal-undecoded-bytes
2848 (substring decoded-substring (- partial)))
2849 (setq decoded-substring
2850 (substring decoded-substring 0 (- partial)))
2851 (cl-decf str-length partial)
2852 (cl-decf funny partial))))
2854 ;; Insert a string, check how many columns
2855 ;; we moved, then delete that many columns
2856 ;; following point if not eob nor insert-mode.
2857 (let ((old-column (term-horizontal-column))
2858 (old-point (point))
2859 columns)
2860 (unless term-suppress-hard-newline
2861 (while (> (+ (length decoded-substring) old-column)
2862 term-width)
2863 (insert (substring decoded-substring 0
2864 (- term-width old-column)))
2865 ;; Since we've enough text to fill the whole line,
2866 ;; delete previous text regardless of
2867 ;; `term-insert-mode's value.
2868 (delete-region (point) (line-end-position))
2869 (term-down 1 t)
2870 (term-move-columns (- (term-current-column)))
2871 (setq decoded-substring
2872 (substring decoded-substring (- term-width old-column)))
2873 (setq old-column 0)))
2874 (insert decoded-substring)
2875 (setq term-current-column (current-column)
2876 columns (- term-current-column old-column))
2877 (when (not (or (eobp) term-insert-mode))
2878 (let ((pos (point)))
2879 (term-move-columns columns)
2880 (delete-region pos (point))))
2881 ;; In insert mode if the current line
2882 ;; has become too long it needs to be
2883 ;; chopped off.
2884 (when term-insert-mode
2885 (let ((pos (point)))
2886 (end-of-line)
2887 (when (> (current-column) term-width)
2888 (delete-region (- (point) (- (current-column) term-width))
2889 (point)))
2890 (goto-char pos)))
2892 (put-text-property old-point (point)
2893 'font-lock-face term-current-face))
2894 ;; If the last char was written in last column,
2895 ;; back up one column, but remember we did so.
2896 ;; Thus we emulate xterm/vt100-style line-wrapping.
2897 (cond ((eq (term-current-column) term-width)
2898 (term-move-columns -1)
2899 (setq term-do-line-wrapping t)))
2900 (setq term-current-column nil)
2901 (setq i funny))
2902 (pcase-exhaustive (and (<= ctl-end str-length) (aref str i))
2903 (?\t ;; TAB (terminfo: ht)
2904 ;; The line cannot exceed term-width. TAB at
2905 ;; the end of a line should not cause wrapping.
2906 (let ((col (term-current-column)))
2907 (term-move-to-column
2908 (min (1- term-width)
2909 (+ col 8 (- (mod col 8)))))))
2910 (?\r ;; (terminfo: cr)
2911 (term-vertical-motion 0)
2912 (setq term-current-column term-start-line-column))
2913 (?\n ;; (terminfo: cud1, ind)
2914 (unless (and term-kill-echo-list
2915 (term-check-kill-echo-list))
2916 (term-down 1 t)))
2917 (?\b ;; (terminfo: cub1)
2918 (term-move-columns -1))
2919 (?\C-g ;; (terminfo: bel)
2920 (beep t))
2921 (?\032 ; Emacs specific control sequence.
2922 (funcall term-command-hook
2923 (decode-coding-string
2924 (substring str (1+ i)
2925 (- ctl-end
2926 (if (eq (aref str (- ctl-end 2)) ?\r)
2927 2 1)))
2928 locale-coding-system t)))
2929 (?\e
2930 (pcase (aref str (1+ i))
2931 (?\[
2932 ;; We only handle control sequences with a single
2933 ;; "Final" byte (see [ECMA-48] section 5.4).
2934 (when (eq ctl-params-end (1- ctl-end))
2935 (term-handle-ansi-escape
2936 proc
2937 (mapcar ;; We don't distinguish empty params
2938 ;; from 0 (according to [ECMA-48] we
2939 ;; should, but all commands we support
2940 ;; default to 0 values anyway).
2941 #'string-to-number
2942 (split-string ctl-params ";"))
2943 (aref str (1- ctl-end)))))
2944 (?D ;; Scroll forward (apparently not documented in
2945 ;; [ECMA-48], [ctlseqs] mentions it as C1
2946 ;; character "Index" though).
2947 (term-handle-deferred-scroll)
2948 (term-down 1 t))
2949 (?M ;; Scroll reversed (terminfo: ri, ECMA-48
2950 ;; "Reverse Linefeed").
2951 (if (or (< (term-current-row) term-scroll-start)
2952 (>= (1- (term-current-row))
2953 term-scroll-start))
2954 ;; Scrolling up will not move outside
2955 ;; the scroll region.
2956 (term-down -1)
2957 ;; Scrolling the scroll region is needed.
2958 (term-down -1 t)))
2959 (?7 ;; Save cursor (terminfo: sc, not in [ECMA-48],
2960 ;; [ctlseqs] has it as "DECSC").
2961 (term-handle-deferred-scroll)
2962 (setq term-saved-cursor
2963 (list (term-current-row)
2964 (term-horizontal-column)
2965 term-ansi-current-bg-color
2966 term-ansi-current-bold
2967 term-ansi-current-color
2968 term-ansi-current-invisible
2969 term-ansi-current-reverse
2970 term-ansi-current-underline
2971 term-current-face)))
2972 (?8 ;; Restore cursor (terminfo: rc, [ctlseqs]
2973 ;; "DECRC").
2974 (when term-saved-cursor
2975 (term-goto (nth 0 term-saved-cursor)
2976 (nth 1 term-saved-cursor))
2977 (setq term-ansi-current-bg-color
2978 (nth 2 term-saved-cursor)
2979 term-ansi-current-bold
2980 (nth 3 term-saved-cursor)
2981 term-ansi-current-color
2982 (nth 4 term-saved-cursor)
2983 term-ansi-current-invisible
2984 (nth 5 term-saved-cursor)
2985 term-ansi-current-reverse
2986 (nth 6 term-saved-cursor)
2987 term-ansi-current-underline
2988 (nth 7 term-saved-cursor)
2989 term-current-face
2990 (nth 8 term-saved-cursor))))
2991 (?c ;; \Ec - Reset (terminfo: rs1, [ctlseqs] "RIS").
2992 ;; This is used by the "clear" program.
2993 (term-reset-terminal))
2994 (?A ;; An \eAnSiT sequence (Emacs specific).
2995 (term-handle-ansi-terminal-messages
2996 (substring str i ctl-end)))))
2997 ;; Ignore NUL, Shift Out, Shift In.
2998 ((or ?\0 #xE #xF 'nil) nil))
2999 (if (term-handling-pager)
3000 (progn
3001 ;; Finish stuff to get ready to handle PAGER.
3002 (if (> (% (current-column) term-width) 0)
3003 (setq term-terminal-undecoded-bytes
3004 (substring str i))
3005 ;; We're at column 0. Goto end of buffer; to compensate,
3006 ;; prepend a ?\r for later. This looks more consistent.
3007 (if (zerop i)
3008 (setq term-terminal-undecoded-bytes
3009 (concat "\r" (substring str i)))
3010 (setq term-terminal-undecoded-bytes (substring str (1- i)))
3011 (aset term-terminal-undecoded-bytes 0 ?\r))
3012 (goto-char (point-max)))
3013 (make-local-variable 'term-pager-old-filter)
3014 (setq term-pager-old-filter (process-filter proc))
3015 (set-process-filter proc term-pager-filter)
3016 (setq i str-length))
3017 (setq i ctl-end)))))
3019 (when (>= (term-current-row) term-height)
3020 (term-handle-deferred-scroll))
3022 (set-marker (process-mark proc) (point))
3023 (when save-point
3024 (goto-char save-point)
3025 (set-marker save-point nil))
3027 ;; Check for a pending filename-and-line number to display.
3028 ;; We do this before scrolling, because we might create a new window.
3029 (when (and term-pending-frame
3030 (eq (window-buffer selected) (current-buffer)))
3031 (term-display-line (car term-pending-frame)
3032 (cdr term-pending-frame))
3033 (setq term-pending-frame nil))
3035 ;; Scroll each window displaying the buffer but (by default)
3036 ;; only if the point matches the process-mark we started with.
3037 (setq win selected)
3038 ;; Avoid infinite loop in strange case where minibuffer window
3039 ;; is selected but not active.
3040 (while (window-minibuffer-p win)
3041 (setq win (next-window win nil t)))
3042 (setq last-win win)
3043 (while (progn
3044 (setq win (next-window win nil t))
3045 (when (eq (window-buffer win) (process-buffer proc))
3046 (let ((scroll term-scroll-to-bottom-on-output))
3047 (select-window win)
3048 (when (or (= (point) save-marker)
3049 (eq scroll t) (eq scroll 'all)
3050 ;; Maybe user wants point to jump to the end.
3051 (and (eq selected win)
3052 (or (eq scroll 'this) (not save-point)))
3053 (and (eq scroll 'others)
3054 (not (eq selected win))))
3055 (goto-char term-home-marker)
3056 (recenter 0)
3057 (goto-char (process-mark proc))
3058 (if (not (pos-visible-in-window-p (point) win))
3059 (recenter -1)))
3060 ;; Optionally scroll so that the text
3061 ;; ends at the bottom of the window.
3062 (when (and term-scroll-show-maximum-output
3063 (>= (point) (process-mark proc)))
3064 (save-excursion
3065 (goto-char (point-max))
3066 (recenter -1)))))
3067 (not (eq win last-win))))
3069 ;; Stolen from comint.el and adapted -mm
3070 (when (> term-buffer-maximum-size 0)
3071 (save-excursion
3072 (goto-char (process-mark (get-buffer-process (current-buffer))))
3073 (forward-line (- term-buffer-maximum-size))
3074 (beginning-of-line)
3075 (delete-region (point-min) (point))))
3076 (set-marker save-marker nil)))
3077 ;; This might be expensive, but we need it to handle something
3078 ;; like `sleep 5 | less -c' in more-or-less real time.
3079 (when (get-buffer-window (current-buffer))
3080 (redisplay))))
3082 (defvar-local term-goto-process-mark t
3083 "Whether to reset point to the current process mark after this command.
3085 Set in `pre-command-hook' in char mode by `term-set-goto-process-mark'.")
3087 (defun term-set-goto-process-mark ()
3088 "Sets `term-goto-process-mark'.
3090 Always set to nil if `term-char-mode-point-at-process-mark' is nil.
3092 Called as a buffer-local `pre-command-hook' function in
3093 `term-char-mode' so that when point is equal to the process mark
3094 at the pre-command stage, we know to restore point to the process
3095 mark at the post-command stage.
3097 See also `term-goto-process-mark-maybe'."
3098 (setq term-goto-process-mark
3099 (and term-char-mode-point-at-process-mark
3100 (eq (point) (marker-position (term-process-mark))))))
3102 (defun term-goto-process-mark-maybe ()
3103 "Move point to the term buffer's process mark upon keyboard input.
3105 Called as a buffer-local `post-command-hook' function in
3106 `term-char-mode' to prevent commands from putting the buffer into
3107 an inconsistent state by unexpectedly moving point.
3109 Mouse events are ignored so that mouse selection is unimpeded.
3111 Only acts when the pre-command position of point was equal to the
3112 process mark, and the `term-char-mode-point-at-process-mark'
3113 option is enabled. See `term-set-goto-process-mark'."
3114 (when term-goto-process-mark
3115 (unless (mouse-event-p last-command-event)
3116 (goto-char (term-process-mark)))))
3118 (defun term-process-mark ()
3119 "The current `process-mark' for the term buffer process."
3120 (process-mark (get-buffer-process (current-buffer))))
3122 (defun term-handle-deferred-scroll ()
3123 (let ((count (- (term-current-row) term-height)))
3124 (when (>= count 0)
3125 (save-excursion
3126 (goto-char term-home-marker)
3127 (term-vertical-motion (1+ count))
3128 (set-marker term-home-marker (point))
3129 (setq term-current-row (1- term-height))))))
3131 (defun term-reset-terminal ()
3132 "Reset the terminal, delete all the content and set the face to the default one."
3133 (erase-buffer)
3134 (term-ansi-reset)
3135 (setq term-current-row 0)
3136 (setq term-current-column 1)
3137 (setq term-scroll-start 0)
3138 (setq term-scroll-end term-height)
3139 (setq term-insert-mode nil)
3140 ;; FIXME: No idea why this is here, it looks wrong. --Stef
3141 (setq term-ansi-face-already-done nil))
3143 ;; New function to deal with ansi colorized output, as you can see you can
3144 ;; have any bold/underline/fg/bg/reverse combination. -mm
3146 (defun term-handle-colors-array (parameter)
3147 (cond
3149 ;; Bold (terminfo: bold)
3150 ((eq parameter 1)
3151 (setq term-ansi-current-bold t))
3153 ;; Underline
3154 ((eq parameter 4)
3155 (setq term-ansi-current-underline t))
3157 ;; Blink (unsupported by Emacs), will be translated to bold.
3158 ;; This may change in the future though.
3159 ((eq parameter 5)
3160 (setq term-ansi-current-bold t))
3162 ;; Reverse (terminfo: smso)
3163 ((eq parameter 7)
3164 (setq term-ansi-current-reverse t))
3166 ;; Invisible
3167 ((eq parameter 8)
3168 (setq term-ansi-current-invisible t))
3170 ;; Reset underline (terminfo: rmul)
3171 ((eq parameter 24)
3172 (setq term-ansi-current-underline nil))
3174 ;; Reset reverse (terminfo: rmso)
3175 ((eq parameter 27)
3176 (setq term-ansi-current-reverse nil))
3178 ;; Foreground
3179 ((and (>= parameter 30) (<= parameter 37))
3180 (setq term-ansi-current-color (- parameter 29)))
3182 ;; Reset foreground
3183 ((eq parameter 39)
3184 (setq term-ansi-current-color 0))
3186 ;; Background
3187 ((and (>= parameter 40) (<= parameter 47))
3188 (setq term-ansi-current-bg-color (- parameter 39)))
3190 ;; Reset background
3191 ((eq parameter 49)
3192 (setq term-ansi-current-bg-color 0))
3194 ;; 0 (Reset) or unknown (reset anyway)
3196 (term-ansi-reset)))
3198 ;; (message "Debug: U-%d R-%d B-%d I-%d D-%d F-%d B-%d"
3199 ;; term-ansi-current-underline
3200 ;; term-ansi-current-reverse
3201 ;; term-ansi-current-bold
3202 ;; term-ansi-current-invisible
3203 ;; term-ansi-face-already-done
3204 ;; term-ansi-current-color
3205 ;; term-ansi-current-bg-color)
3207 (unless term-ansi-face-already-done
3208 (if term-ansi-current-invisible
3209 (let ((color
3210 (if term-ansi-current-reverse
3211 (face-foreground
3212 (elt ansi-term-color-vector term-ansi-current-color)
3213 nil 'default)
3214 (face-background
3215 (elt ansi-term-color-vector term-ansi-current-bg-color)
3216 nil 'default))))
3217 (setq term-current-face
3218 (list :background color
3219 :foreground color))
3220 ) ;; No need to bother with anything else if it's invisible.
3221 (setq term-current-face
3222 (list :foreground
3223 (face-foreground
3224 (elt ansi-term-color-vector term-ansi-current-color)
3225 nil 'default)
3226 :background
3227 (face-background
3228 (elt ansi-term-color-vector term-ansi-current-bg-color)
3229 nil 'default)
3230 :inverse-video term-ansi-current-reverse))
3232 (when term-ansi-current-bold
3233 (setq term-current-face
3234 `(,term-current-face :inherit term-bold)))
3236 (when term-ansi-current-underline
3237 (setq term-current-face
3238 `(,term-current-face :inherit term-underline)))))
3240 ;; (message "Debug %S" term-current-face)
3241 ;; FIXME: shouldn't we set term-ansi-face-already-done to t here? --Stef
3242 (setq term-ansi-face-already-done nil))
3245 ;; Handle a character assuming (eq terminal-state 2) -
3246 ;; i.e. we have previously seen Escape followed by ?[.
3248 (defun term-handle-ansi-escape (proc params char)
3249 (cond
3250 ((or (eq char ?H) ;; cursor motion (terminfo: cup,home)
3251 ;; (eq char ?f) ;; xterm seems to handle this sequence too, not
3252 ;; needed for now
3254 (term-goto
3255 (1- (max 1 (min (or (nth 0 params) 0) term-height)))
3256 (1- (max 1 (min (or (nth 1 params) 0) term-width)))))
3257 ;; \E[A - cursor up (terminfo: cuu, cuu1)
3258 ((eq char ?A)
3259 (term-handle-deferred-scroll)
3260 (let ((tcr (term-current-row))
3261 (scroll-amount (car params)))
3262 (term-down
3263 (if (< (- tcr scroll-amount) term-scroll-start)
3264 ;; If the amount to move is before scroll start, move
3265 ;; to scroll start.
3266 (- term-scroll-start tcr)
3267 (if (>= scroll-amount tcr)
3268 (- tcr)
3269 (- (max 1 scroll-amount))))
3270 t)))
3271 ;; \E[B - cursor down (terminfo: cud)
3272 ((eq char ?B)
3273 (let ((tcr (term-current-row))
3274 (scroll-amount (car params)))
3275 (unless (= tcr (1- term-scroll-end))
3276 (term-down
3277 (if (> (+ tcr scroll-amount) term-scroll-end)
3278 (- term-scroll-end 1 tcr)
3279 (max 1 scroll-amount))
3280 t))))
3281 ;; \E[C - cursor right (terminfo: cuf, cuf1)
3282 ((eq char ?C)
3283 (term-move-columns
3284 (max 1
3285 (if (>= (+ (car params) (term-current-column)) term-width)
3286 (- term-width (term-current-column) 1)
3287 (car params)))))
3288 ;; \E[D - cursor left (terminfo: cub)
3289 ((eq char ?D)
3290 (term-move-columns (- (max 1 (car params)))))
3291 ;; \E[G - cursor motion to absolute column (terminfo: hpa)
3292 ((eq char ?G)
3293 (term-move-columns (- (max 0 (min term-width (car params)))
3294 (term-current-column))))
3295 ;; \E[J - clear to end of screen (terminfo: ed, clear)
3296 ((eq char ?J)
3297 (term-erase-in-display (car params)))
3298 ;; \E[K - clear to end of line (terminfo: el, el1)
3299 ((eq char ?K)
3300 (term-erase-in-line (car params)))
3301 ;; \E[L - insert lines (terminfo: il, il1)
3302 ((eq char ?L)
3303 (term-insert-lines (max 1 (car params))))
3304 ;; \E[M - delete lines (terminfo: dl, dl1)
3305 ((eq char ?M)
3306 (term-delete-lines (max 1 (car params))))
3307 ;; \E[P - delete chars (terminfo: dch, dch1)
3308 ((eq char ?P)
3309 (term-delete-chars (max 1 (car params))))
3310 ;; \E[@ - insert spaces (terminfo: ich)
3311 ((eq char ?@)
3312 (term-insert-spaces (max 1 (car params))))
3313 ;; \E[?h - DEC Private Mode Set
3314 ((eq char ?h)
3315 (cond ((eq (car params) 4) ;; (terminfo: smir)
3316 (setq term-insert-mode t))
3317 ;; ((eq (car params) 47) ;; (terminfo: smcup)
3318 ;; (term-switch-to-alternate-sub-buffer t))
3320 ;; \E[?l - DEC Private Mode Reset
3321 ((eq char ?l)
3322 (cond ((eq (car params) 4) ;; (terminfo: rmir)
3323 (setq term-insert-mode nil))
3324 ;; ((eq (car params) 47) ;; (terminfo: rmcup)
3325 ;; (term-switch-to-alternate-sub-buffer nil))
3328 ;; Modified to allow ansi coloring -mm
3329 ;; \E[m - Set/reset modes, set bg/fg
3330 ;;(terminfo: smso,rmso,smul,rmul,rev,bold,sgr0,invis,op,setab,setaf)
3331 ((eq char ?m)
3332 (mapc #'term-handle-colors-array params))
3334 ;; \E[6n - Report cursor position (terminfo: u7)
3335 ((eq char ?n)
3336 (term-handle-deferred-scroll)
3337 (process-send-string proc
3338 ;; (terminfo: u6)
3339 (format "\e[%s;%sR"
3340 (1+ (term-current-row))
3341 (1+ (term-horizontal-column)))))
3342 ;; \E[r - Set scrolling region (terminfo: csr)
3343 ((eq char ?r)
3344 (term-set-scroll-region
3345 (1- (or (nth 0 params) 0))
3346 (1- (or (nth 1 params) 0))))
3347 (t)))
3349 (defun term-set-scroll-region (top bottom)
3350 "Set scrolling region.
3351 TOP is the top-most line (inclusive) of the new scrolling region,
3352 while BOTTOM is the line following the new scrolling region (e.g. exclusive).
3353 The top-most line is line 0."
3354 (setq term-scroll-start
3355 (if (or (< top 0) (>= top term-height))
3357 top))
3358 (setq term-scroll-end
3359 (if (or (<= bottom term-scroll-start) (> bottom term-height))
3360 term-height
3361 bottom))
3362 (setq term-scroll-with-delete
3363 (or (term-using-alternate-sub-buffer)
3364 (not (and (= term-scroll-start 0)
3365 (= term-scroll-end term-height)))))
3366 (term-move-columns (- (term-current-column)))
3367 (term-goto 0 0))
3369 ;; (defun term-switch-to-alternate-sub-buffer (set)
3370 ;; ;; If asked to switch to (from) the alternate sub-buffer, and already (not)
3371 ;; ;; using it, do nothing. This test is needed for some programs (including
3372 ;; ;; Emacs) that emit the ti termcap string twice, for unknown reason.
3373 ;; (term-handle-deferred-scroll)
3374 ;; (if (eq set (not (term-using-alternate-sub-buffer)))
3375 ;; (let ((row (term-current-row))
3376 ;; (col (term-horizontal-column)))
3377 ;; (cond (set
3378 ;; (goto-char (point-max))
3379 ;; (if (not (eq (preceding-char) ?\n))
3380 ;; (term-insert-char ?\n 1))
3381 ;; (setq term-scroll-with-delete t)
3382 ;; (setq term-saved-home-marker (copy-marker term-home-marker))
3383 ;; (set-marker term-home-marker (point)))
3384 ;; (t
3385 ;; (setq term-scroll-with-delete
3386 ;; (not (and (= term-scroll-start 0)
3387 ;; (= term-scroll-end term-height))))
3388 ;; (set-marker term-home-marker term-saved-home-marker)
3389 ;; (set-marker term-saved-home-marker nil)
3390 ;; (setq term-saved-home-marker nil)
3391 ;; (goto-char term-home-marker)))
3392 ;; (setq term-current-column nil)
3393 ;; (setq term-current-row 0)
3394 ;; (term-goto row col))))
3396 ;; Default value for the symbol term-command-hook.
3398 (defun term-command-hook (string)
3399 (cond ((equal string "")
3401 ((= (aref string 0) ?\032)
3402 ;; gdb (when invoked with -fullname) prints:
3403 ;; \032\032FULLFILENAME:LINENUMBER:CHARPOS:BEG_OR_MIDDLE:PC\n
3404 (let* ((first-colon (string-match ":" string 1))
3405 (second-colon
3406 (string-match ":" string (1+ first-colon)))
3407 (filename (substring string 1 first-colon))
3408 (fileline (string-to-number
3409 (substring string (1+ first-colon) second-colon))))
3410 (setq term-pending-frame (cons filename fileline))))
3411 ((= (aref string 0) ?/)
3412 (cd (substring string 1)))
3413 ;; Allowing the inferior to call functions in Emacs is
3414 ;; probably too big a security hole.
3415 ;; ((= (aref string 0) ?!)
3416 ;; (eval (car (read-from-string string 1))))
3417 (t)));; Otherwise ignore it
3419 ;; Make sure the file named TRUE-FILE is in a buffer that appears on the screen
3420 ;; and that its line LINE is visible.
3421 ;; Put the overlay-arrow on the line LINE in that buffer.
3422 ;; This is mainly used by gdb.
3424 (defun term-display-line (true-file line)
3425 (term-display-buffer-line (find-file-noselect true-file) line))
3427 (defun term-display-buffer-line (buffer line)
3428 (let* ((window (display-buffer buffer t))
3429 (pos))
3430 (with-current-buffer buffer
3431 (save-restriction
3432 (widen)
3433 (goto-char (point-min))
3434 (forward-line (1- line))
3435 (setq pos (point))
3436 (setq overlay-arrow-string "=>")
3437 (or overlay-arrow-position
3438 (setq overlay-arrow-position (make-marker)))
3439 (set-marker overlay-arrow-position (point) (current-buffer)))
3440 (cond ((or (< pos (point-min)) (> pos (point-max)))
3441 (widen)
3442 (goto-char pos))))
3443 (set-window-point window overlay-arrow-position)))
3445 ;; The buffer-local marker term-home-marker defines the "home position"
3446 ;; (in terms of cursor motion). However, we move the term-home-marker
3447 ;; "down" as needed so that is no more that a window-full above (point-max).
3449 (defun term-goto-home ()
3450 (term-handle-deferred-scroll)
3451 (goto-char term-home-marker)
3452 (setq term-current-row 0)
3453 (setq term-current-column (current-column))
3454 (setq term-start-line-column term-current-column))
3456 (defun term-goto (row col)
3457 (term-handle-deferred-scroll)
3458 (cond ((and term-current-row (>= row term-current-row))
3459 ;; I assume this is a worthwhile optimization.
3460 (term-vertical-motion 0)
3461 (setq term-current-column term-start-line-column)
3462 (setq row (- row term-current-row)))
3464 (term-goto-home)))
3465 (term-down row)
3466 (term-move-columns col))
3468 ;; The page is full, so enter "pager" mode, and wait for input.
3470 (defun term-process-pager ()
3471 ;; (let ((process (get-buffer-process (current-buffer))))
3472 ;; (stop-process process))
3473 (setq term-pager-old-local-map (current-local-map))
3474 (use-local-map term-pager-break-map)
3475 (easy-menu-add term-terminal-menu)
3476 (easy-menu-add term-signals-menu)
3477 (easy-menu-add term-pager-menu)
3478 (make-local-variable 'term-old-mode-line-format)
3479 (setq term-old-mode-line-format mode-line-format)
3480 (setq mode-line-format
3481 (list "-- **MORE** "
3482 mode-line-buffer-identification
3483 " [Type ? for help] "
3484 "%-"))
3485 (force-mode-line-update))
3487 (defun term-pager-line (lines)
3488 (interactive "p")
3489 (let* ((moved (vertical-motion (1+ lines)))
3490 (deficit (- lines moved)))
3491 (when (> moved lines)
3492 (backward-char))
3493 (cond ((<= deficit 0) ;; OK, had enough in the buffer for request.
3494 (recenter (1- term-height)))
3495 ((term-pager-continue deficit)))))
3497 (defun term-pager-page (arg)
3498 "Proceed past the **MORE** break, allowing the next page of output to appear."
3499 (interactive "p")
3500 (term-pager-line (* arg term-height)))
3502 ;; Pager mode command to go to beginning of buffer.
3503 (defun term-pager-bob ()
3504 (interactive)
3505 (goto-char (point-min))
3506 (when (= (vertical-motion term-height) term-height)
3507 (backward-char))
3508 (recenter (1- term-height)))
3510 ;; Pager mode command to go to end of buffer.
3511 (defun term-pager-eob ()
3512 (interactive)
3513 (goto-char term-home-marker)
3514 (recenter 0)
3515 (goto-char (process-mark (get-buffer-process (current-buffer)))))
3517 (defun term-pager-back-line (lines)
3518 (interactive "p")
3519 (vertical-motion (- 1 lines))
3520 (if (not (bobp))
3521 (backward-char)
3522 (beep)
3523 ;; Move cursor to end of window.
3524 (vertical-motion term-height)
3525 (backward-char))
3526 (recenter (1- term-height)))
3528 (defun term-pager-back-page (arg)
3529 (interactive "p")
3530 (term-pager-back-line (* arg term-height)))
3532 (defun term-pager-discard ()
3533 (interactive)
3534 (setq term-terminal-undecoded-bytes "")
3535 (interrupt-process nil t)
3536 (term-pager-continue term-height))
3538 ;; Disable pager processing.
3539 ;; Only callable while in pager mode. (Contrast term-disable-pager.)
3540 (defun term-pager-disable ()
3541 (interactive)
3542 (if (term-handling-pager)
3543 (term-pager-continue nil)
3544 (setq term-pager-count nil))
3545 (term-update-mode-line))
3547 ;; Enable pager processing.
3548 (defun term-pager-enable ()
3549 (interactive)
3550 (or (term-pager-enabled)
3551 (setq term-pager-count 0)) ;; Or maybe set to (term-current-row) ??
3552 (term-update-mode-line))
3554 (defun term-pager-toggle ()
3555 (interactive)
3556 (if (term-pager-enabled) (term-pager-disable) (term-pager-enable)))
3558 (defun term-pager-help ()
3559 "Provide help on commands available in a terminal-emulator **MORE** break."
3560 (interactive)
3561 (message "Terminal-emulator pager break help...")
3562 (sit-for 0)
3563 (with-electric-help
3564 (function (lambda ()
3565 (princ (substitute-command-keys
3566 "\\<term-pager-break-map>\
3567 Terminal-emulator MORE break.\n\
3568 Type one of the following keys:\n\n\
3569 \\[term-pager-page]\t\tMove forward one page.\n\
3570 \\[term-pager-line]\t\tMove forward one line.\n\
3571 \\[universal-argument] N \\[term-pager-page]\tMove N pages forward.\n\
3572 \\[universal-argument] N \\[term-pager-line]\tMove N lines forward.\n\
3573 \\[universal-argument] N \\[term-pager-back-line]\tMove N lines back.\n\
3574 \\[universal-argument] N \\[term-pager-back-page]\t\tMove N pages back.\n\
3575 \\[term-pager-bob]\t\tMove to the beginning of the buffer.\n\
3576 \\[term-pager-eob]\t\tMove to the end of the buffer.\n\
3577 \\[term-pager-discard]\t\tKill pending output and kill process.\n\
3578 \\[term-pager-disable]\t\tDisable PAGER handling.\n\n\
3579 \\{term-pager-break-map}\n\
3580 Any other key is passed through to the program
3581 running under the terminal emulator and disables pager processing until
3582 all pending output has been dealt with."))
3583 nil))))
3585 (defun term-pager-continue (new-count)
3586 (let ((process (get-buffer-process (current-buffer))))
3587 (use-local-map term-pager-old-local-map)
3588 (setq term-pager-old-local-map nil)
3589 (setq mode-line-format term-old-mode-line-format)
3590 (force-mode-line-update)
3591 (setq term-pager-count new-count)
3592 (set-process-filter process term-pager-old-filter)
3593 (funcall term-pager-old-filter process "")
3594 (continue-process process)))
3596 ;; Make sure there are DOWN blank lines below the current one.
3597 ;; Return 0 if we're unable (because of PAGER handling), else return DOWN.
3599 (defun term-handle-scroll (down)
3600 (let ((scroll-needed
3601 (- (+ (term-current-row) down)
3602 (if (< down 0) term-scroll-start term-scroll-end))))
3603 (when (or (and (< down 0) (< scroll-needed 0))
3604 (and (> down 0) (> scroll-needed 0)))
3605 (let ((save-point (point-marker)) (save-top))
3606 (goto-char term-home-marker)
3607 (cond (term-scroll-with-delete
3608 (if (< down 0)
3609 (progn
3610 ;; Delete scroll-needed lines at term-scroll-end,
3611 ;; then insert scroll-needed lines.
3612 (term-vertical-motion term-scroll-end)
3613 (end-of-line)
3614 (setq save-top (point))
3615 (term-vertical-motion scroll-needed)
3616 (end-of-line)
3617 (delete-region save-top (point))
3618 (goto-char save-point)
3619 (setq down (- scroll-needed down))
3620 (term-vertical-motion down))
3621 ;; Delete scroll-needed lines at term-scroll-start.
3622 (term-vertical-motion term-scroll-start)
3623 (setq save-top (point))
3624 (term-vertical-motion scroll-needed)
3625 (delete-region save-top (point))
3626 (goto-char save-point)
3627 (term-vertical-motion down)
3628 (term-adjust-current-row-cache (- scroll-needed)))
3629 (setq term-current-column nil)
3630 (term-insert-char ?\n (abs scroll-needed)))
3631 ((and (numberp term-pager-count)
3632 (< (setq term-pager-count (- term-pager-count down))
3634 (setq down 0)
3635 (term-process-pager))
3637 (term-adjust-current-row-cache (- scroll-needed))
3638 (term-vertical-motion scroll-needed)
3639 (set-marker term-home-marker (point))))
3640 (goto-char save-point)
3641 (set-marker save-point nil))))
3642 down)
3644 (defun term-down (down &optional check-for-scroll)
3645 "Move down DOWN screen lines vertically."
3646 (let ((start-column (term-horizontal-column)))
3647 (when (and check-for-scroll (or term-scroll-with-delete term-pager-count))
3648 (setq down (term-handle-scroll down)))
3649 (unless (and (= term-current-row 0) (< down 0))
3650 (term-adjust-current-row-cache down)
3651 (when (or (/= (point) (point-max)) (< down 0))
3652 (setq down (- down (term-vertical-motion down)))))
3653 (cond ((>= down 0)
3654 ;; Extend buffer with extra blank lines if needed.
3655 (term-insert-char ?\n down)
3656 (setq term-current-column 0)
3657 (setq term-start-line-column 0))
3659 (when (= term-current-row 0)
3660 ;; Insert lines if at the beginning.
3661 (save-excursion (term-insert-char ?\n (- down)))
3662 (save-excursion
3663 (let (p)
3664 ;; Delete lines from the end.
3665 (forward-line term-height)
3666 (setq p (point))
3667 (forward-line (- down))
3668 (delete-region p (point)))))
3669 (setq term-current-column 0)
3670 (setq term-start-line-column (current-column))))
3671 (when start-column
3672 (term-move-columns start-column))))
3674 ;; Assuming point is at the beginning of a screen line,
3675 ;; if the line above point wraps around, add a ?\n to undo the wrapping.
3676 ;; FIXME: Probably should be called more than it is.
3677 (defun term-unwrap-line ()
3678 (when (not (bolp)) (insert-before-markers ?\n)))
3680 (defun term-erase-in-line (kind)
3681 (when (= kind 1) ;; erase left of point
3682 (let ((cols (term-horizontal-column)) (saved-point (point)))
3683 (term-vertical-motion 0)
3684 (delete-region (point) saved-point)
3685 (term-insert-char ? cols)))
3686 (when (not (eq kind 1)) ;; erase right of point
3687 (let ((saved-point (point))
3688 (wrapped (and (zerop (term-horizontal-column))
3689 (not (zerop (term-current-column))))))
3690 (term-vertical-motion 1)
3691 (delete-region saved-point (point))
3692 ;; wrapped is true if we're at the beginning of screen line,
3693 ;; but not a buffer line. If we delete the current screen line
3694 ;; that will make the previous line no longer wrap, and (because
3695 ;; of the way Emacs display works) point will be at the end of
3696 ;; the previous screen line rather then the beginning of the
3697 ;; current one. To avoid that, we make sure that current line
3698 ;; contain a space, to force the previous line to continue to wrap.
3699 ;; We could do this always, but it seems preferable to not add the
3700 ;; extra space when wrapped is false.
3701 (when wrapped
3702 (insert ? ))
3703 (insert ?\n)
3704 (put-text-property saved-point (point) 'font-lock-face 'default)
3705 (goto-char saved-point))))
3707 (defun term-erase-in-display (kind)
3708 "Erase (that is blank out) part of the window.
3709 If KIND is 0, erase from (point) to (point-max);
3710 if KIND is 1, erase from home to point; else erase from home to point-max."
3711 (term-handle-deferred-scroll)
3712 (cond ((eq kind 0)
3713 (let ((need-unwrap (bolp)))
3714 (delete-region (point) (point-max))
3715 (when need-unwrap (term-unwrap-line))))
3716 ((let ((row (term-current-row))
3717 (col (term-horizontal-column))
3718 (start-region term-home-marker)
3719 (end-region (if (eq kind 1) (point) (point-max))))
3720 (delete-region start-region end-region)
3721 (term-unwrap-line)
3722 (when (eq kind 1)
3723 (term-insert-char ?\n row))
3724 (setq term-current-column nil)
3725 (setq term-current-row nil)
3726 (term-goto row col)))))
3728 (defun term-delete-chars (count)
3729 (let ((save-point (point)))
3730 (term-vertical-motion 1)
3731 (term-unwrap-line)
3732 (goto-char save-point)
3733 (move-to-column (+ (term-current-column) count) t)
3734 (delete-region save-point (point))))
3736 ;; Insert COUNT spaces after point, but do not change any of
3737 ;; following screen lines. Hence we may have to delete characters
3738 ;; at the end of this screen line to make room.
3740 (defun term-insert-spaces (count)
3741 (let ((save-point (point)) (save-eol) (pnt-at-eol))
3742 (term-vertical-motion 1)
3743 (when (bolp)
3744 (backward-char))
3745 (setq save-eol (point)
3746 pnt-at-eol (line-end-position))
3747 (move-to-column (+ (term-start-line-column) (- term-width count)) t)
3748 ;; If move-to-column extends the current line it will use the face
3749 ;; from the last character on the line, set the face for the chars
3750 ;; to default.
3751 (when (>= (point) pnt-at-eol)
3752 (put-text-property pnt-at-eol (point) 'font-lock-face 'default))
3753 (when (> save-eol (point))
3754 (delete-region (point) save-eol))
3755 (goto-char save-point)
3756 (term-insert-char ? count)
3757 (goto-char save-point)))
3759 (defun term-delete-lines (lines)
3760 (let ((start (point))
3761 (save-current-column term-current-column)
3762 (save-start-line-column term-start-line-column)
3763 (save-current-row (term-current-row)))
3764 ;; The number of inserted lines shouldn't exceed the scroll region end.
3765 ;; The `term-scroll-end' line is part of the scrolling region, so
3766 ;; we need to go one line past it in order to ensure correct
3767 ;; scrolling.
3768 (when (> (+ save-current-row lines) (1+ term-scroll-end))
3769 (setq lines (- lines (- (+ save-current-row lines) (1+ term-scroll-end)))))
3770 (term-down lines)
3771 (delete-region start (point))
3772 (term-down (- (1+ term-scroll-end) save-current-row lines))
3773 (term-insert-char ?\n lines)
3774 (setq term-current-column save-current-column)
3775 (setq term-start-line-column save-start-line-column)
3776 (setq term-current-row save-current-row)
3777 (goto-char start)))
3779 (defun term-insert-lines (lines)
3780 (let ((start (point))
3781 (start-deleted)
3782 (save-current-column term-current-column)
3783 (save-start-line-column term-start-line-column)
3784 (save-current-row (term-current-row)))
3785 ;; Inserting lines should take into account the scroll region.
3786 ;; The `term-scroll-end' line is part of the scrolling region, so
3787 ;; we need to go one line past it in order to ensure correct
3788 ;; scrolling.
3789 (if (< save-current-row term-scroll-start)
3790 ;; If point is before scroll start,
3791 (progn
3792 (setq lines (- lines (- term-scroll-start save-current-row)))
3793 (term-down (- term-scroll-start save-current-row))
3794 (setq start (point)))
3795 ;; The number of inserted lines shouldn't exceed the scroll region end.
3796 (when (> (+ save-current-row lines) (1+ term-scroll-end))
3797 (setq lines (- lines (- (+ save-current-row lines)(1+ term-scroll-end)))))
3798 (term-down (- (1+ term-scroll-end) save-current-row lines)))
3799 (setq start-deleted (point))
3800 (term-down lines)
3801 (delete-region start-deleted (point))
3802 (goto-char start)
3803 (setq term-current-column save-current-column)
3804 (setq term-start-line-column save-start-line-column)
3805 (setq term-current-row save-current-row)
3806 (term-insert-char ?\n lines)
3807 (goto-char start)))
3809 (defun term-start-output-log (name)
3810 "Record raw inferior process output in a buffer."
3811 (interactive (list (if term-log-buffer
3813 (read-buffer "Record output in buffer: "
3814 (format "%s output-log"
3815 (buffer-name (current-buffer)))
3816 nil))))
3817 (if (or (null name) (equal name ""))
3818 (progn (setq term-log-buffer nil)
3819 (message "Output logging off."))
3820 (if (get-buffer name)
3822 (with-current-buffer (get-buffer-create name)
3823 (fundamental-mode)
3824 (buffer-disable-undo (current-buffer))
3825 (erase-buffer)))
3826 (setq term-log-buffer (get-buffer name))
3827 (message "Recording terminal emulator output into buffer \"%s\""
3828 (buffer-name term-log-buffer))))
3830 (defun term-stop-output-log ()
3831 "Discontinue raw inferior process logging."
3832 (interactive)
3833 (term-start-output-log nil))
3835 (defun term-show-maximum-output ()
3836 "Put the end of the buffer at the bottom of the window."
3837 (interactive)
3838 (goto-char (point-max))
3839 (recenter -1))
3841 ;;; Do the user's customization...
3843 (defvar term-load-hook nil
3844 "This hook is run when term is loaded in.
3845 This is a good place to put keybindings.")
3847 (run-hooks 'term-load-hook)
3850 ;;; Filename/command/history completion in a buffer
3851 ;; ===========================================================================
3852 ;; Useful completion functions, courtesy of the Ergo group.
3854 ;; Six commands:
3855 ;; term-dynamic-complete Complete or expand command, filename,
3856 ;; history at point.
3857 ;; term-dynamic-complete-filename Complete filename at point.
3858 ;; term-dynamic-list-filename-completions List completions in help buffer.
3859 ;; term-replace-by-expanded-filename Expand and complete filename at point;
3860 ;; replace with expanded/completed name.
3862 ;; These are not installed in the term-mode keymap. But they are
3863 ;; available for people who want them. Shell-mode installs them:
3864 ;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
3865 ;; (define-key shell-mode-map "\M-?"
3866 ;; 'term-dynamic-list-filename-completions)))
3868 ;; Commands like this are fine things to put in load hooks if you
3869 ;; want them present in specific modes.
3871 (defcustom term-completion-autolist nil
3872 "If non-nil, automatically list possibilities on partial completion.
3873 This mirrors the optional behavior of tcsh."
3874 :group 'term
3875 :type 'boolean)
3877 (defcustom term-completion-addsuffix t
3878 "If non-nil, add a `/' to completed directories, ` ' to file names.
3879 If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
3880 DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact
3881 completion. This mirrors the optional behavior of tcsh."
3882 :group 'term
3883 :type '(choice (const :tag "No suffix" nil)
3884 (cons (string :tag "dirsuffix") (string :tag "filesuffix"))
3885 (other :tag "Suffix" t)))
3887 (defcustom term-completion-recexact nil
3888 "If non-nil, use shortest completion if characters cannot be added.
3889 This mirrors the optional behavior of tcsh.
3891 A non-nil value is useful if `term-completion-autolist' is non-nil too."
3892 :group 'term
3893 :type 'boolean)
3895 (defcustom term-completion-fignore nil
3896 "List of suffixes to be disregarded during file completion.
3897 This mirrors the optional behavior of bash and tcsh.
3899 Note that this applies to `term-dynamic-complete-filename' only."
3900 :group 'term
3901 :type '(choice (const nil)
3902 (repeat :tag "List of suffixes" string)))
3904 (defvar term-file-name-prefix ""
3905 "Prefix prepended to absolute file names taken from process input.
3906 This is used by term's and shell's completion functions, and by shell's
3907 directory tracking functions.")
3910 (defun term-directory (directory)
3911 ;; Return expanded DIRECTORY, with `term-file-name-prefix' if absolute.
3912 (expand-file-name (if (file-name-absolute-p directory)
3913 (concat term-file-name-prefix directory)
3914 directory)))
3917 (defun term-word (word-chars)
3918 "Return the word of WORD-CHARS at point, or nil if none is found.
3919 Word constituents are considered to be those in WORD-CHARS, which is like the
3920 inside of a \"[...]\" (see `skip-chars-forward')."
3921 (save-excursion
3922 (let ((limit (point))
3923 (word (concat "[" word-chars "]"))
3924 (non-word (concat "[^" word-chars "]")))
3925 (when (re-search-backward non-word nil 'move)
3926 (forward-char 1))
3927 ;; Anchor the search forwards.
3928 (if (or (eolp) (looking-at non-word))
3930 (re-search-forward (concat word "+") limit)
3931 (buffer-substring (match-beginning 0) (match-end 0))))))
3934 (defun term-match-partial-filename ()
3935 "Return the filename at point, or nil if none is found.
3936 Environment variables are substituted. See `term-word'."
3937 (let ((filename (term-word "~/A-Za-z0-9+@:_.$#,={}-")))
3938 (and filename (substitute-in-file-name filename))))
3941 (defun term-dynamic-complete ()
3942 "Dynamically perform completion at point.
3943 Calls the functions in `term-dynamic-complete-functions' to perform
3944 completion until a function returns non-nil, at which point completion is
3945 assumed to have occurred."
3946 (interactive)
3947 (let ((functions term-dynamic-complete-functions))
3948 (while (and functions (null (funcall (car functions))))
3949 (setq functions (cdr functions)))))
3952 (defun term-dynamic-complete-filename ()
3953 "Dynamically complete the filename at point.
3954 Completes if after a filename. See `term-match-partial-filename' and
3955 `term-dynamic-complete-as-filename'.
3956 This function is similar to `term-replace-by-expanded-filename', except that
3957 it won't change parts of the filename already entered in the buffer; it just
3958 adds completion characters to the end of the filename. A completions listing
3959 may be shown in a help buffer if completion is ambiguous.
3961 Completion is dependent on the value of `term-completion-addsuffix',
3962 `term-completion-recexact' and `term-completion-fignore', and the timing of
3963 completions listing is dependent on the value of `term-completion-autolist'.
3965 Returns t if successful."
3966 (interactive)
3967 (when (term-match-partial-filename)
3968 (prog2 (or (eq (selected-window) (minibuffer-window))
3969 (message "Completing file name..."))
3970 (term-dynamic-complete-as-filename))))
3972 (defun term-dynamic-complete-as-filename ()
3973 "Dynamically complete at point as a filename.
3974 See `term-dynamic-complete-filename'. Returns t if successful."
3975 (let* ((completion-ignore-case nil)
3976 (completion-ignored-extensions term-completion-fignore)
3977 (success t)
3978 (dirsuffix (cond ((not term-completion-addsuffix) "")
3979 ((not (consp term-completion-addsuffix)) "/")
3980 (t (car term-completion-addsuffix))))
3981 (filesuffix (cond ((not term-completion-addsuffix) "")
3982 ((not (consp term-completion-addsuffix)) " ")
3983 (t (cdr term-completion-addsuffix))))
3984 (filename (or (term-match-partial-filename) ""))
3985 (pathdir (file-name-directory filename))
3986 (pathnondir (file-name-nondirectory filename))
3987 (directory (if pathdir (term-directory pathdir) default-directory))
3988 (completion (file-name-completion pathnondir directory))
3989 (mini-flag (eq (selected-window) (minibuffer-window))))
3990 (cond ((null completion)
3991 (message "No completions of %s" filename)
3992 (setq success nil))
3993 ((eq completion t) ; Means already completed "file".
3994 (when term-completion-addsuffix (insert " "))
3995 (or mini-flag (message "Sole completion")))
3996 ((string-equal completion "") ; Means completion on "directory/".
3997 (term-dynamic-list-filename-completions))
3998 (t ; Completion string returned.
3999 (let ((file (concat (file-name-as-directory directory) completion)))
4000 (insert (substring (directory-file-name completion)
4001 (length pathnondir)))
4002 (cond ((symbolp (file-name-completion completion directory))
4003 ;; We inserted a unique completion.
4004 (insert (if (file-directory-p file) dirsuffix filesuffix))
4005 (or mini-flag (message "Completed")))
4006 ((and term-completion-recexact term-completion-addsuffix
4007 (string-equal pathnondir completion)
4008 (file-exists-p file))
4009 ;; It's not unique, but user wants shortest match.
4010 (insert (if (file-directory-p file) dirsuffix filesuffix))
4011 (or mini-flag (message "Completed shortest")))
4012 ((or term-completion-autolist
4013 (string-equal pathnondir completion))
4014 ;; It's not unique, list possible completions.
4015 (term-dynamic-list-filename-completions))
4017 (or mini-flag (message "Partially completed")))))))
4018 success))
4021 (defun term-replace-by-expanded-filename ()
4022 "Dynamically expand and complete the filename at point.
4023 Replace the filename with an expanded, canonicalized and completed replacement.
4024 \"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
4025 with the corresponding directories. \"Canonicalized\" means `..' and `.' are
4026 removed, and the filename is made absolute instead of relative. For expansion
4027 see `expand-file-name' and `substitute-in-file-name'. For completion see
4028 `term-dynamic-complete-filename'."
4029 (interactive)
4030 (replace-match (expand-file-name (term-match-partial-filename)) t t)
4031 (term-dynamic-complete-filename))
4034 (defun term-dynamic-simple-complete (stub candidates)
4035 "Dynamically complete STUB from CANDIDATES list.
4036 This function inserts completion characters at point by completing STUB from
4037 the strings in CANDIDATES. A completions listing may be shown in a help buffer
4038 if completion is ambiguous.
4040 Returns nil if no completion was inserted.
4041 Returns `sole' if completed with the only completion match.
4042 Returns `shortest' if completed with the shortest of the completion matches.
4043 Returns `partial' if completed as far as possible with the completion matches.
4044 Returns `listed' if a completion listing was shown.
4046 See also `term-dynamic-complete-filename'."
4047 (declare (obsolete completion-in-region "23.2"))
4048 (let* ((completion-ignore-case nil)
4049 (candidates (mapcar (function (lambda (x) (list x))) candidates))
4050 (completions (all-completions stub candidates)))
4051 (cond ((null completions)
4052 (message "No completions of %s" stub)
4053 nil)
4054 ((= 1 (length completions)) ; Gotcha!
4055 (let ((completion (car completions)))
4056 (if (string-equal completion stub)
4057 (message "Sole completion")
4058 (insert (substring completion (length stub)))
4059 (message "Completed"))
4060 (when term-completion-addsuffix (insert " "))
4061 'sole))
4062 (t ; There's no unique completion.
4063 (let ((completion (try-completion stub candidates)))
4064 ;; Insert the longest substring.
4065 (insert (substring completion (length stub)))
4066 (cond ((and term-completion-recexact term-completion-addsuffix
4067 (string-equal stub completion)
4068 (member completion completions))
4069 ;; It's not unique, but user wants shortest match.
4070 (insert " ")
4071 (message "Completed shortest")
4072 'shortest)
4073 ((or term-completion-autolist
4074 (string-equal stub completion))
4075 ;; It's not unique, list possible completions.
4076 (term-dynamic-list-completions completions)
4077 'listed)
4079 (message "Partially completed")
4080 'partial)))))))
4082 (defun term-dynamic-list-filename-completions ()
4083 "List in help buffer possible completions of the filename at point."
4084 (interactive)
4085 (let* ((completion-ignore-case nil)
4086 (filename (or (term-match-partial-filename) ""))
4087 (pathdir (file-name-directory filename))
4088 (pathnondir (file-name-nondirectory filename))
4089 (directory (if pathdir (term-directory pathdir) default-directory))
4090 (completions (file-name-all-completions pathnondir directory)))
4091 (if completions
4092 (term-dynamic-list-completions completions)
4093 (message "No completions of %s" filename))))
4096 (defun term-dynamic-list-completions (completions)
4097 "List in help buffer sorted COMPLETIONS.
4098 Typing SPC flushes the help buffer."
4099 (let ((conf (current-window-configuration)))
4100 (with-output-to-temp-buffer "*Completions*"
4101 (display-completion-list (sort completions 'string-lessp)))
4102 (message "Hit space to flush")
4103 (let (key first)
4104 (if (with-current-buffer (get-buffer "*Completions*")
4105 (setq key (read-key-sequence nil)
4106 first (aref key 0))
4107 (and (consp first)
4108 (eq (window-buffer (posn-window (event-start first)))
4109 (get-buffer "*Completions*"))
4110 (memq (key-binding key)
4111 '(mouse-choose-completion choose-completion))))
4112 ;; If the user does choose-completion with the mouse,
4113 ;; execute the command, then delete the completion window.
4114 (progn
4115 (choose-completion first)
4116 (set-window-configuration conf))
4117 (if (eq first ?\s)
4118 (set-window-configuration conf)
4119 (setq unread-command-events
4120 (nconc (listify-key-sequence key)
4121 unread-command-events)))))))
4123 ;; I need a make-term that doesn't surround with *s -mm
4124 (defun term-ansi-make-term (name program &optional startfile &rest switches)
4125 "Make a term process NAME in a buffer, running PROGRAM.
4126 The name of the buffer is NAME.
4127 If there is already a running process in that buffer, it is not restarted.
4128 Optional third arg STARTFILE is the name of a file to send the contents of to
4129 the process. Any more args are arguments to PROGRAM."
4130 (let ((buffer (get-buffer-create name )))
4131 ;; If no process, or nuked process, crank up a new one and put buffer in
4132 ;; term mode. Otherwise, leave buffer and existing process alone.
4133 (cond ((not (term-check-proc buffer))
4134 (with-current-buffer buffer
4135 (term-mode)) ; Install local vars, mode, keymap, ...
4136 (term-exec buffer name program startfile switches)))
4137 buffer))
4139 (defvar term-ansi-buffer-name nil)
4140 (defvar term-ansi-default-program nil)
4141 (defvar term-ansi-buffer-base-name nil)
4143 ;;;###autoload
4144 (defun ansi-term (program &optional new-buffer-name)
4145 "Start a terminal-emulator in a new buffer."
4146 (interactive (list (read-from-minibuffer "Run program: "
4147 (or explicit-shell-file-name
4148 (getenv "ESHELL")
4149 shell-file-name))))
4151 ;; Pick the name of the new buffer.
4152 (setq term-ansi-buffer-name
4153 (if new-buffer-name
4154 new-buffer-name
4155 (if term-ansi-buffer-base-name
4156 (if (eq term-ansi-buffer-base-name t)
4157 (file-name-nondirectory program)
4158 term-ansi-buffer-base-name)
4159 "ansi-term")))
4161 (setq term-ansi-buffer-name (concat "*" term-ansi-buffer-name "*"))
4163 ;; In order to have more than one term active at a time
4164 ;; I'd like to have the term names have the *term-ansi-term<?>* form,
4165 ;; for now they have the *term-ansi-term*<?> form but we'll see...
4167 (setq term-ansi-buffer-name (generate-new-buffer-name term-ansi-buffer-name))
4168 (setq term-ansi-buffer-name (term-ansi-make-term term-ansi-buffer-name program))
4170 (set-buffer term-ansi-buffer-name)
4171 (term-mode)
4172 (term-char-mode)
4174 ;; Historical baggage. A call to term-set-escape-char used to not
4175 ;; undo any previous call to t-s-e-c. Because of this, ansi-term
4176 ;; ended up with both C-x and C-c as escape chars. Who knows what
4177 ;; the original intention was, but people could have become used to
4178 ;; either. (Bug#12842)
4179 (let (term-escape-char)
4180 ;; I wanna have find-file on C-x C-f -mm
4181 ;; your mileage may definitely vary, maybe it's better to put this in your
4182 ;; .emacs ...
4183 (term-set-escape-char ?\C-x))
4185 (switch-to-buffer term-ansi-buffer-name))
4188 ;;; Serial terminals
4189 ;; ===========================================================================
4190 (defun serial-port-is-file-p ()
4191 "Guess whether serial ports are files on this system.
4192 Return t if this is a Unix-based system, where serial ports are
4193 files, such as /dev/ttyS0.
4194 Return nil if this is Windows or DOS, where serial ports have
4195 special identifiers such as COM1."
4196 (not (memq system-type '(windows-nt cygwin ms-dos))))
4198 (defvar serial-name-history
4199 (if (serial-port-is-file-p)
4200 (or (when (file-exists-p "/dev/ttys0") (list "/dev/ttys0"))
4201 (when (file-exists-p "/dev/ttyS0") (list "/dev/ttyS0")))
4202 (list "COM1"))
4203 "History of serial ports used by `serial-read-name'.")
4205 (defvar serial-speed-history
4206 ;; Initialized with reasonable values for newbies.
4207 (list "9600" ;; Given twice because 9600 b/s is the most common speed
4208 "1200" "2400" "4800" "9600" "14400" "19200"
4209 "28800" "38400" "57600" "115200")
4210 "History of serial port speeds used by `serial-read-speed'.")
4212 (defun serial-nice-speed-history ()
4213 "Return `serial-speed-history' cleaned up for a mouse-menu."
4214 (let ((x) (y))
4215 (setq x
4216 (sort
4217 (copy-sequence serial-speed-history)
4218 (lambda (a b) (when (and (stringp a) (stringp b))
4219 (> (string-to-number a) (string-to-number b))))))
4220 (dolist (i x) (when (not (equal i (car y))) (push i y)))
4223 (defconst serial-no-speed "nil"
4224 "String for `serial-read-speed' for special serial ports.
4225 If `serial-read-speed' reads this string from the user, it
4226 returns nil, which is recognized by `serial-process-configure'
4227 for special serial ports that cannot be configured.")
4229 (defun serial-supported-or-barf ()
4230 "Signal an error if serial processes are not supported."
4231 (unless (fboundp 'make-serial-process)
4232 (error "Serial processes are not supported on this system")))
4234 (defun serial-read-name ()
4235 "Read a serial port name from the user.
4236 Try to be nice by providing useful defaults and history.
4237 On Windows, prepend \\.\ to the port name unless it already
4238 contains a backslash. This handles the legacy ports COM1-COM9 as
4239 well as the newer ports COM10 and higher."
4240 (serial-supported-or-barf)
4241 (let* ((file-name-history serial-name-history)
4242 (h (car file-name-history))
4243 (x (if (serial-port-is-file-p)
4244 (read-file-name
4245 ;; `prompt': The most recently used port is provided as
4246 ;; the default value, which is used when the user
4247 ;; simply presses return.
4248 (if (stringp h) (format "Serial port (default %s): " h)
4249 "Serial port: ")
4250 ;; `directory': Most systems have their serial ports
4251 ;; in the same directory, so start in the directory
4252 ;; of the most recently used port, or in a reasonable
4253 ;; default directory.
4254 (or (and h (file-name-directory h))
4255 (and (file-exists-p "/dev/") "/dev/")
4256 (and (file-exists-p "/") "/"))
4257 ;; `default': This causes (read-file-name) to return
4258 ;; the empty string if he user simply presses return.
4259 ;; Using nil here may result in a default directory
4260 ;; of the current buffer, which is not useful for
4261 ;; serial port.
4263 (read-from-minibuffer
4264 (if (stringp h) (format "Serial port (default %s): " h)
4265 "Serial port: ")
4266 nil nil nil '(file-name-history . 1) nil nil))))
4267 (if (or (null x) (and (stringp x) (zerop (length x))))
4268 (setq x h)
4269 (setq serial-name-history file-name-history))
4270 (when (or (null x) (and (stringp x) (zerop (length x))))
4271 (error "No serial port selected"))
4272 (when (and (not (serial-port-is-file-p))
4273 (not (string-match "\\\\" x)))
4274 (set 'x (concat "\\\\.\\" x)))
4277 (defun serial-read-speed ()
4278 "Read a serial port speed (in bits per second) from the user.
4279 Try to be nice by providing useful defaults and history."
4280 (serial-supported-or-barf)
4281 (let* ((history serial-speed-history)
4282 (h (car history))
4283 (x (read-from-minibuffer
4284 (cond ((string= h serial-no-speed)
4285 "Speed (default nil = set by port): ")
4287 (format "Speed (default %s b/s): " h))
4289 (format "Speed (b/s): ")))
4290 nil nil nil '(history . 1) nil nil)))
4291 (when (or (null x) (and (stringp x) (zerop (length x))))
4292 (setq x h))
4293 (when (or (null x) (not (stringp x)) (zerop (length x)))
4294 (error "Invalid speed"))
4295 (if (string= x serial-no-speed)
4296 (setq x nil)
4297 (setq x (string-to-number x))
4298 (when (or (null x) (not (integerp x)) (<= x 0))
4299 (error "Invalid speed")))
4300 (setq serial-speed-history history)
4303 ;;;###autoload
4304 (defun serial-term (port speed)
4305 "Start a terminal-emulator for a serial port in a new buffer.
4306 PORT is the path or name of the serial port. For example, this
4307 could be \"/dev/ttyS0\" on Unix. On Windows, this could be
4308 \"COM1\" or \"\\\\.\\COM10\".
4309 SPEED is the speed of the serial port in bits per second. 9600
4310 is a common value. SPEED can be nil, see
4311 `serial-process-configure' for details.
4312 The buffer is in Term mode; see `term-mode' for the commands to
4313 use in that buffer.
4314 \\<term-raw-map>Type \\[switch-to-buffer] to switch to another buffer."
4315 (interactive (list (serial-read-name) (serial-read-speed)))
4316 (serial-supported-or-barf)
4317 (let* ((process (make-serial-process
4318 :port port
4319 :speed speed
4320 :coding 'no-conversion
4321 :noquery t))
4322 (buffer (process-buffer process)))
4323 (with-current-buffer buffer
4324 (term-mode)
4325 (term-char-mode)
4326 (goto-char (point-max))
4327 (set-marker (process-mark process) (point))
4328 (set-process-filter process 'term-emulate-terminal)
4329 (set-process-sentinel process 'term-sentinel))
4330 (switch-to-buffer buffer)
4331 buffer))
4333 (defvar serial-mode-line-speed-menu nil)
4334 (defvar serial-mode-line-config-menu nil)
4336 (defun serial-speed ()
4337 "Return the speed of the serial port of the current buffer's process.
4338 The return value may be nil for a special serial port."
4339 (process-contact (get-buffer-process (current-buffer)) :speed))
4341 (defun serial-mode-line-speed-menu-1 (event)
4342 (interactive "e")
4343 (save-selected-window
4344 (select-window (posn-window (event-start event)))
4345 (serial-update-speed-menu)
4346 (let* ((selection (serial-mode-line-speed-menu event))
4347 (binding (and selection (lookup-key serial-mode-line-speed-menu
4348 (vector (car selection))))))
4349 (when binding (call-interactively binding)))))
4351 (defun serial-mode-line-speed-menu (event)
4352 (x-popup-menu event serial-mode-line-speed-menu))
4354 (defun serial-update-speed-menu ()
4355 (setq serial-mode-line-speed-menu (make-sparse-keymap "Speed (b/s)"))
4356 (define-key serial-mode-line-speed-menu [serial-mode-line-speed-menu-other]
4357 '(menu-item "Other..."
4358 (lambda (event) (interactive "e")
4359 (let ((speed (serial-read-speed)))
4360 (serial-process-configure :speed speed)
4361 (term-update-mode-line)
4362 (message "Speed set to %d b/s" speed)))))
4363 (dolist (str (serial-nice-speed-history))
4364 (let ((num (or (and (stringp str) (string-to-number str)) 0)))
4365 (define-key
4366 serial-mode-line-speed-menu
4367 (vector (make-symbol (format "serial-mode-line-speed-menu-%s" str)))
4368 `(menu-item
4369 ,str
4370 (lambda (event) (interactive "e")
4371 (serial-process-configure :speed ,num)
4372 (term-update-mode-line)
4373 (message "Speed set to %d b/s" ,num))
4374 :button (:toggle . (= (serial-speed) ,num)))))))
4376 (defun serial-mode-line-config-menu-1 (event)
4377 (interactive "e")
4378 (save-selected-window
4379 (select-window (posn-window (event-start event)))
4380 (serial-update-config-menu)
4381 (let* ((selection (serial-mode-line-config-menu event))
4382 (binding (and selection (lookup-key serial-mode-line-config-menu
4383 (vector (car selection))))))
4384 (when binding (call-interactively binding)))))
4386 (defun serial-mode-line-config-menu (event)
4387 (x-popup-menu event serial-mode-line-config-menu))
4389 (defun serial-update-config-menu ()
4390 (setq serial-mode-line-config-menu (make-sparse-keymap "Configuration"))
4391 (let ((config (process-contact
4392 (get-buffer-process (current-buffer)) t)))
4393 (dolist (y '((:flowcontrol hw "Hardware flowcontrol (RTS/CTS)")
4394 (:flowcontrol sw "Software flowcontrol (XON/XOFF)")
4395 (:flowcontrol nil "No flowcontrol")
4396 (:stopbits 2 "2 stopbits")
4397 (:stopbits 1 "1 stopbit")
4398 (:parity odd "Odd parity")
4399 (:parity even "Even parity")
4400 (:parity nil "No parity")
4401 (:bytesize 7 "7 bits per byte")
4402 (:bytesize 8 "8 bits per byte")))
4403 (define-key serial-mode-line-config-menu
4404 (vector (make-symbol (format "%s-%s" (nth 0 y) (nth 1 y))))
4405 `(menu-item
4406 ,(nth 2 y)
4407 (lambda (event) (interactive "e")
4408 (serial-process-configure ,(nth 0 y) ',(nth 1 y))
4409 (term-update-mode-line)
4410 (message "%s" ,(nth 2 y)))
4411 ;; Use :toggle instead of :radio because a non-standard port
4412 ;; configuration may not match any menu items.
4413 :button (:toggle . ,(equal (plist-get config (nth 0 y))
4414 (nth 1 y))))))))
4417 ;;; Converting process modes to use term mode
4418 ;; ===========================================================================
4419 ;; Renaming variables
4420 ;; Most of the work is renaming variables and functions. These are the common
4421 ;; ones:
4422 ;; Local variables:
4423 ;; last-input-start term-last-input-start
4424 ;; last-input-end term-last-input-end
4425 ;; shell-prompt-pattern term-prompt-regexp
4426 ;; shell-set-directory-error-hook <no equivalent>
4427 ;; Miscellaneous:
4428 ;; shell-set-directory <unnecessary>
4429 ;; shell-mode-map term-mode-map
4430 ;; Commands:
4431 ;; shell-send-input term-send-input
4432 ;; shell-send-eof term-delchar-or-maybe-eof
4433 ;; kill-shell-input term-kill-input
4434 ;; interrupt-shell-subjob term-interrupt-subjob
4435 ;; stop-shell-subjob term-stop-subjob
4436 ;; quit-shell-subjob term-quit-subjob
4437 ;; kill-shell-subjob term-kill-subjob
4438 ;; kill-output-from-shell term-kill-output
4439 ;; show-output-from-shell term-show-output
4440 ;; copy-last-shell-input Use term-previous-input/term-next-input
4442 ;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
4443 ;; SHELL-DIRECTORY-TRACKER, the shell mode's term-input-filter-functions.
4444 ;; Term mode does not provide functionality equivalent to
4445 ;; shell-set-directory-error-hook; it is gone.
4447 ;; term-last-input-start is provided for modes which want to munge
4448 ;; the buffer after input is sent, perhaps because the inferior
4449 ;; insists on echoing the input. The LAST-INPUT-START variable in
4450 ;; the old shell package was used to implement a history mechanism,
4451 ;; but you should think twice before using term-last-input-start
4452 ;; for this; the input history ring often does the job better.
4454 ;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
4455 ;; *not* create the term-mode local variables in your foo-mode function.
4456 ;; This is not modular. Instead, call term-mode, and let *it* create the
4457 ;; necessary term-specific local variables. Then create the
4458 ;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
4459 ;; be foo-mode-map, and its mode to be foo-mode. Set the term-mode hooks
4460 ;; (term-{prompt-regexp, input-filter, input-filter-functions,
4461 ;; get-old-input) that need to be different from the defaults. Call
4462 ;; foo-mode-hook, and you're done. Don't run the term-mode hook yourself;
4463 ;; term-mode will take care of it. The following example, from shell.el,
4464 ;; is typical:
4466 ;; (defvar shell-mode-map '())
4467 ;; (cond ((not shell-mode-map)
4468 ;; (setq shell-mode-map (copy-keymap term-mode-map))
4469 ;; (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
4470 ;; (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
4471 ;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
4472 ;; (define-key shell-mode-map "\M-?"
4473 ;; 'term-dynamic-list-filename-completions)))
4475 ;; (defun shell-mode ()
4476 ;; (interactive)
4477 ;; (term-mode)
4478 ;; (setq term-prompt-regexp shell-prompt-pattern)
4479 ;; (setq major-mode 'shell-mode)
4480 ;; (setq mode-name "Shell")
4481 ;; (use-local-map shell-mode-map)
4482 ;; (make-local-variable 'shell-directory-stack)
4483 ;; (setq shell-directory-stack nil)
4484 ;; (add-hook 'term-input-filter-functions 'shell-directory-tracker)
4485 ;; (run-mode-hooks 'shell-mode-hook))
4488 ;; Completion for term-mode users
4490 ;; For modes that use term-mode, term-dynamic-complete-functions is the
4491 ;; hook to add completion functions to. Functions on this list should return
4492 ;; non-nil if completion occurs (i.e., further completion should not occur).
4493 ;; You could use completion-in-region to do the bulk of the
4494 ;; completion job.
4496 (provide 'term)
4498 ;;; term.el ends here