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