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