1 ;;; term.el --- general command interpreter in a window stuff
3 ;; Copyright (C) 1988, 1990, 1992, 1994-1995, 2001-2018 Free Software
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>
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/>.
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'
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
83 ;; allow root 127.0.0.1
85 ;; # By default nobody can't do anything
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
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 ;; ----------------------------------------
115 ;; - Add hooks to allow raw-mode keys to be configurable
116 ;; - Which keys are better ? \eOA or \e[A ?
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.
129 ;; - Now all the supportable ANSI commands work well.
130 ;; - Reworked a little the code: much less jsh-inspired stuff
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
141 ;; - Implemented a maximum limit for the scroll buffer (stolen from
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
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.
186 ;; # Below, there should be one TERM entry for each termtype that is
190 ;; # EIGHTBIT, followed by '1' for on, '0' for off. (8-bit output)
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
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:
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
225 ;; .jpg 01;35 # image formats
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 ;; For troubleshooting in Bash, you can check the definition of the
239 ;; custom functions with the "type" command. e.g. "type cd". If you
240 ;; do not see the expected definition from the config below, then the
241 ;; directory tracking will not work.
243 ;; ----------------------------------------
245 ;; # Set HOSTNAME if not already set.
246 ;; : ${HOSTNAME=$(uname -n)}
248 ;; # su does not change this but I'd like it to
257 ;; -------------------------------------------------------------- \
259 ;; "Today is $(date)" \
260 ;; "We are on $HOSTNAME running $(uname) under Emacs term mode" \
261 ;; --------------------------------------------------------------
263 ;; # The \033 stands for ESC.
264 ;; # There is a space between "AnSiT?" and $whatever.
266 ;; cd() { command cd "$@"; printf '\033AnSiTc %s\n' "$PWD"; }
267 ;; pushd() { command pushd "$@"; printf '\033AnSiTc %s\n' "$PWD"; }
268 ;; popd() { command popd "$@"; printf '\033AnSiTc %s\n' "$PWD"; }
270 ;; printf '\033AnSiTc %s\n' "$PWD"
271 ;; printf '\033AnSiTh %s\n' "$HOSTNAME"
272 ;; printf '\033AnSiTu %s\n' "$USER"
274 ;; # Use custom dircolors in term buffers.
275 ;; # eval $(dircolors $HOME/.emacs_dircolors)
282 ;;; Original Commentary:
283 ;; ---------------------
285 ;; The changelog is at the end of this file.
287 ;; Please send me bug reports, bug fixes, and extensions, so that I can
288 ;; merge them into the master source.
289 ;; - Per Bothner (bothner@cygnus.com)
291 ;; This file defines a general command-interpreter-in-a-buffer package
292 ;; (term mode). The idea is that you can build specific process-in-a-buffer
293 ;; modes on top of term mode -- e.g., lisp, shell, scheme, T, soar, ....
294 ;; This way, all these specific packages share a common base functionality,
295 ;; and a common set of bindings, which makes them easier to use (and
296 ;; saves code, implementation time, etc., etc.).
298 ;; For hints on converting existing process modes (e.g., tex-mode,
299 ;; background, dbx, gdb, kermit, prolog, telnet) to use term-mode
300 ;; instead of shell-mode, see the notes at the end of this file.
303 ;; Brief Command Documentation:
304 ;;============================================================================
305 ;; Term Mode Commands: (common to all derived modes, like cmushell & cmulisp
308 ;; m-p term-previous-input Cycle backwards in input history
309 ;; m-n term-next-input Cycle forwards
310 ;; m-r term-previous-matching-input Previous input matching a regexp
311 ;; m-s comint-next-matching-input Next input that matches
312 ;; return term-send-input
313 ;; c-c c-a term-bol Beginning of line; skip prompt.
314 ;; c-d term-delchar-or-maybe-eof Delete char unless at end of buff.
315 ;; c-c c-u term-kill-input ^u
316 ;; c-c c-w backward-kill-word ^w
317 ;; c-c c-c term-interrupt-subjob ^c
318 ;; c-c c-z term-stop-subjob ^z
319 ;; c-c c-\ term-quit-subjob ^\
320 ;; c-c c-o term-kill-output Delete last batch of process output
321 ;; c-c c-r term-show-output Show last batch of process output
322 ;; c-c c-h term-dynamic-list-input-ring List input history
324 ;; Not bound by default in term-mode
325 ;; term-send-invisible Read a line w/o echo, and send to proc
326 ;; (These are bound in shell-mode)
327 ;; term-dynamic-complete Complete filename at point.
328 ;; term-dynamic-list-completions List completions in help buffer.
329 ;; term-replace-by-expanded-filename Expand and complete filename at point;
330 ;; replace with expanded/completed name.
331 ;; term-kill-subjob No mercy.
332 ;; term-show-maximum-output Show as much output as possible.
333 ;; term-continue-subjob Send CONT signal to buffer's process
334 ;; group. Useful if you accidentally
335 ;; suspend your process (with C-c C-z).
337 ;; term-mode-hook is the term mode hook. Basically for your keybindings.
338 ;; term-load-hook is run after loading in this package.
342 ;; This is passed to the inferior in the EMACS environment variable,
343 ;; so it is important to increase it if there are protocol-relevant changes.
344 (defconst term-protocol-version
"0.96")
346 (eval-when-compile (require 'ange-ftp
))
347 (eval-when-compile (require 'cl-lib
))
351 (declare-function ring-empty-p
"ring" (ring))
352 (declare-function ring-ref
"ring" (ring index
))
353 (declare-function ring-insert-at-beginning
"ring" (ring item
))
354 (declare-function ring-length
"ring" (ring))
355 (declare-function ring-insert
"ring" (ring item
))
358 "General command interpreter in a window."
362 ;;; Buffer Local Variables:
363 ;;============================================================================
364 ;; Term mode buffer local variables:
365 ;; term-prompt-regexp - string term-bol uses to match prompt.
366 ;; term-delimiter-argument-list - list For delimiters and arguments
367 ;; term-last-input-start - marker Handy if inferior always echoes
368 ;; term-last-input-end - marker For term-kill-output command
369 ;; For the input history mechanism:
370 (defvar term-input-ring-size
32 "Size of input history ring.")
371 ;; term-input-ring-size - integer
372 ;; term-input-ring - ring
373 ;; term-input-ring-index - number ...
374 ;; term-input-autoexpand - symbol ...
375 ;; term-input-ignoredups - boolean ...
376 ;; term-last-input-match - string ...
377 ;; term-dynamic-complete-functions - hook For the completion mechanism
378 ;; term-completion-fignore - list ...
379 ;; term-get-old-input - function Hooks for specific
380 ;; term-input-filter-functions - hook process-in-a-buffer
381 ;; term-input-filter - function modes.
382 ;; term-input-send - function
383 ;; term-scroll-to-bottom-on-output - symbol ...
384 ;; term-scroll-show-maximum-output - boolean...
385 (defvar term-height
) ; Number of lines in window.
386 (defvar term-width
) ; Number of columns in window.
387 (defvar term-home-marker
) ; Marks the "home" position for cursor addressing.
388 (defvar term-saved-home-marker nil
389 "When using alternate sub-buffer,
390 contains saved term-home-marker from original sub-buffer.")
391 (defvar term-start-line-column
0
392 "(current-column) at start of screen line, or nil if unknown.")
393 (defvar term-current-column
0 "If non-nil, is cache for (current-column).")
394 (defvar term-current-row
0
395 "Current vertical row (relative to home-marker) or nil if unknown.")
396 (defvar term-insert-mode nil
)
397 (defvar term-vertical-motion
)
398 (defvar term-terminal-state
0
399 "State of the terminal emulator:
400 state 0: Normal state
401 state 1: Last character was a graphic in the last column.
402 If next char is graphic, first move one column right
403 \(and line warp) before displaying it.
404 This emulates (more or less) the behavior of xterm.
406 state 3: seen ESC [ (or ESC [ ?)
407 state 4: term-terminal-parameter contains pending output.")
408 (defvar term-kill-echo-list nil
409 "A queue of strings whose echo we want suppressed.")
410 (defvar term-terminal-parameter
)
411 (defvar term-terminal-undecoded-bytes nil
)
412 (defvar term-terminal-previous-parameter
)
413 (defvar term-current-face
'term
)
414 (defvar term-scroll-start
0 "Top-most line (inclusive) of scrolling region.")
415 (defvar term-scroll-end
) ; Number of line (zero-based) after scrolling region.
416 (defvar term-pager-count nil
417 "Number of lines before we need to page; if nil, paging is disabled.")
418 (defvar term-saved-cursor nil
)
419 (defvar term-command-hook
)
420 (defvar term-log-buffer nil
)
421 (defvar term-scroll-with-delete nil
422 "If t, forward scrolling should be implemented by delete to
423 top-most line(s); and if nil, scrolling should be implemented
424 by moving term-home-marker. It is set to t if there is a
425 \(non-default) scroll-region OR the alternate buffer is used.")
426 (defvar term-pending-delete-marker
) ; New user input in line mode
427 ; needs to be deleted, because it gets echoed by the inferior.
428 ; To reduce flicker, we defer the delete until the next output.
429 (defvar term-old-mode-map nil
"Saves the old keymap when in char mode.")
430 (defvar term-old-mode-line-format
) ; Saves old mode-line-format while paging.
431 (defvar term-pager-old-local-map nil
"Saves old keymap while paging.")
432 (defvar term-pager-old-filter
) ; Saved process-filter while paging.
433 (defvar-local term-line-mode-buffer-read-only nil
434 "The `buffer-read-only' state to set in `term-line-mode'.")
436 (defcustom explicit-shell-file-name nil
437 "If non-nil, is file name to use for explicitly requested inferior shell."
438 :type
'(choice (const nil
) file
)
441 (defvar term-prompt-regexp
"^"
442 "Regexp to recognize prompts in the inferior process.
443 Defaults to \"^\", the null string at BOL.
446 Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
447 Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
448 franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
450 shell: \"^[^#$%>\\n]*[#$%>] *\"
453 This is a good thing to set in mode hooks.")
455 (defvar term-delimiter-argument-list
()
456 "List of characters to recognize as separate arguments in input.
457 Strings comprising a character in this list will separate the arguments
458 surrounding them, and also be regarded as arguments in their own right
459 \(unlike whitespace). See `term-arguments'.
460 Defaults to the empty list.
462 For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
464 This is a good thing to set in mode hooks.")
466 (defcustom term-input-autoexpand nil
467 "If non-nil, expand input command history references on completion.
468 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
470 If the value is `input', then the expansion is seen on input.
471 If the value is `history', then the expansion is only when inserting
472 into the buffer's input ring. See also `term-magic-space' and
473 `term-dynamic-complete'.
475 This variable is buffer-local."
476 :type
'(choice (const nil
) (const t
) (const input
) (const history
))
479 (defcustom term-input-ignoredups nil
480 "If non-nil, don't add input matching the last on the input ring.
481 This mirrors the optional behavior of bash.
483 This variable is buffer-local."
487 (defcustom term-input-ring-file-name nil
488 "If non-nil, name of the file to read/write input history.
489 See also `term-read-input-ring' and `term-write-input-ring'.
491 This variable is buffer-local, and is a good thing to set in mode hooks."
495 (defcustom term-char-mode-buffer-read-only t
496 "If non-nil, only the process filter may modify the buffer in char mode.
498 A non-nil value makes the buffer read-only in `term-char-mode',
499 which prevents editing commands from making the buffer state
500 inconsistent with the state of the terminal understood by the
501 inferior process. Only the process filter is allowed to make
502 changes to the buffer.
504 Customize this option to nil if you want the previous behavior."
509 (defcustom term-char-mode-point-at-process-mark t
510 "If non-nil, keep point at the process mark in char mode.
512 A non-nil value causes point to be moved to the current process
513 mark after each command in `term-char-mode' (provided that the
514 pre-command point position was also at the process mark). This
515 prevents commands that move point from making the buffer state
516 inconsistent with the state of the terminal understood by the
519 Mouse events are not affected, so moving point and selecting text
520 is still possible in char mode via the mouse, after which other
521 commands can be invoked on the mouse-selected point or region,
522 until the process filter (or user) moves point to the process
525 Customize this option to nil if you want the previous behavior."
530 (defcustom term-scroll-to-bottom-on-output nil
531 "Controls whether interpreter output causes window to scroll.
532 If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
533 If `this', scroll only the selected window.
534 If `others', scroll only those that are not the selected window.
538 See variable `term-scroll-show-maximum-output'.
539 This variable is buffer-local."
543 (defcustom term-scroll-show-maximum-output nil
544 "Controls how interpreter output causes window to scroll.
545 If non-nil, then show the maximum output when the window is scrolled.
547 See variable `term-scroll-to-bottom-on-output'.
548 This variable is buffer-local."
552 (defcustom term-suppress-hard-newline nil
553 "Non-nil means interpreter should not break long lines with newlines.
554 This means text can automatically reflow if the window is resized."
559 ;; Where gud-display-frame should put the debugging arrow. This is
560 ;; set by the marker-filter, which scans the debugger's output for
561 ;; indications of the current pc.
562 (defvar term-pending-frame nil
)
564 ;;; Here are the per-interpreter hooks.
565 (defvar term-get-old-input
(function term-get-old-input-default
)
566 "Function that submits old text in term mode.
567 This function is called when return is typed while the point is in old text.
568 It returns the text to be submitted as process input. The default is
569 `term-get-old-input-default', which grabs the current line, and strips off
570 leading text matching `term-prompt-regexp'.")
572 (defvar term-dynamic-complete-functions
573 '(term-replace-by-expanded-history term-dynamic-complete-filename
)
574 "List of functions called to perform completion.
575 Functions should return non-nil if completion was performed.
576 See also `term-dynamic-complete'.
578 This is a good thing to set in mode hooks.")
580 (defvar term-input-filter
581 (function (lambda (str) (not (string-match "\\`\\s *\\'" str
))))
582 "Predicate for filtering additions to input history.
583 Only inputs answering true to this function are saved on the input
584 history list. Default is to save anything that isn't all whitespace.")
586 (defvar term-input-filter-functions
'()
587 "Functions to call before input is sent to the process.
588 These functions get one argument, a string containing the text to send.
590 This variable is buffer-local.")
592 (defvar term-input-sender
(function term-simple-send
)
593 "Function to actually send to PROCESS the STRING submitted by user.
594 Usually this is just `term-simple-send', but if your mode needs to
595 massage the input string, this is your hook. This is called from
596 the user command `term-send-input'. `term-simple-send' just sends
597 the string plus a newline.")
599 (defvar term-partial-ansi-terminal-message nil
600 "Keep partial ansi terminal messages for future processing.")
602 (defcustom term-eol-on-send t
603 "Non-nil means go to the end of the line before sending input.
604 See `term-send-input'."
608 (defcustom term-mode-hook
'()
609 "Called upon entry into term mode.
610 This is run before the process is cranked up."
614 (defcustom term-exec-hook
'()
615 "Called each time a process is exec'd by `term-exec'.
616 This is called after the process is cranked up. It is useful for things that
617 must be done each time a process is executed in a term mode buffer (e.g.,
618 `set-process-query-on-exit-flag'). In contrast, `term-mode-hook' is only
619 executed once, when the buffer is created."
623 (defvar term-mode-map
624 (let ((map (make-sparse-keymap)))
625 (define-key map
"\ep" 'term-previous-input
)
626 (define-key map
"\en" 'term-next-input
)
627 (define-key map
"\er" 'term-previous-matching-input
)
628 (define-key map
"\es" 'term-next-matching-input
)
629 (unless (featurep 'xemacs
)
630 (define-key map
[?\A-\M-r
]
631 'term-previous-matching-input-from-input
)
632 (define-key map
[?\A-\M-s
] 'term-next-matching-input-from-input
))
633 (define-key map
"\e\C-l" 'term-show-output
)
634 (define-key map
"\C-m" 'term-send-input
)
635 (define-key map
"\C-d" 'term-delchar-or-maybe-eof
)
636 (define-key map
"\C-c\C-a" 'term-bol
)
637 (define-key map
"\C-c\C-u" 'term-kill-input
)
638 (define-key map
"\C-c\C-w" 'backward-kill-word
)
639 (define-key map
"\C-c\C-c" 'term-interrupt-subjob
)
640 (define-key map
"\C-c\C-z" 'term-stop-subjob
)
641 (define-key map
"\C-c\C-\\" 'term-quit-subjob
)
642 (define-key map
"\C-c\C-m" 'term-copy-old-input
)
643 (define-key map
"\C-c\C-o" 'term-kill-output
)
644 (define-key map
"\C-c\C-r" 'term-show-output
)
645 (define-key map
"\C-c\C-e" 'term-show-maximum-output
)
646 (define-key map
"\C-c\C-l" 'term-dynamic-list-input-ring
)
647 (define-key map
"\C-c\C-n" 'term-next-prompt
)
648 (define-key map
"\C-c\C-p" 'term-previous-prompt
)
649 (define-key map
"\C-c\C-d" 'term-send-eof
)
650 (define-key map
"\C-c\C-k" 'term-char-mode
)
651 (define-key map
"\C-c\C-j" 'term-line-mode
)
652 (define-key map
"\C-c\C-q" 'term-pager-toggle
)
653 ;; completion: (line mode only)
654 (easy-menu-define nil map
"Complete menu for Term mode."
656 ["Complete Before Point" term-dynamic-complete t
]
657 ["Complete File Name" term-dynamic-complete-filename t
]
658 ["File Completion Listing" term-dynamic-list-filename-completions t
]
659 ["Expand File Name" term-replace-by-expanded-filename t
]))
660 ;; Input history: (line mode only)
661 (easy-menu-define nil map
"In/Out menu for Term mode."
663 ["Expand History Before Point" term-replace-by-expanded-history
664 term-input-autoexpand
]
665 ["List Input History" term-dynamic-list-input-ring t
]
666 ["Previous Input" term-previous-input t
]
667 ["Next Input" term-next-input t
]
668 ["Previous Matching Current Input"
669 term-previous-matching-input-from-input t
]
670 ["Next Matching Current Input" term-next-matching-input-from-input t
]
671 ["Previous Matching Input..." term-previous-matching-input t
]
672 ["Next Matching Input..." term-next-matching-input t
]
673 ["Backward Matching Input..." term-backward-matching-input t
]
674 ["Forward Matching Input..." term-forward-matching-input t
]
675 ["Copy Old Input" term-copy-old-input t
]
676 ["Kill Current Input" term-kill-input t
]
677 ["Show Current Output Group" term-show-output t
]
678 ["Show Maximum Output" term-show-maximum-output t
]
679 ["Backward Output Group" term-previous-prompt t
]
680 ["Forward Output Group" term-next-prompt t
]
681 ["Kill Current Output Group" term-kill-output t
]))
683 "Keymap for Term mode.")
685 (defvar term-escape-char nil
686 "Escape character for char sub-mode of term mode.
687 Do not change it directly; use `term-set-escape-char' instead.")
689 (defvar term-pager-break-map
690 (let ((map (make-keymap)))
692 ;; (define-key map (make-string 1 i) 'term-send-raw))
693 (define-key map
"\e" (lookup-key (current-global-map) "\e"))
694 (define-key map
"\C-x" (lookup-key (current-global-map) "\C-x"))
695 (define-key map
"\C-u" (lookup-key (current-global-map) "\C-u"))
696 (define-key map
" " 'term-pager-page
)
697 (define-key map
"\r" 'term-pager-line
)
698 (define-key map
"?" 'term-pager-help
)
699 (define-key map
"h" 'term-pager-help
)
700 (define-key map
"b" 'term-pager-back-page
)
701 (define-key map
"\177" 'term-pager-back-line
)
702 (define-key map
"q" 'term-pager-discard
)
703 (define-key map
"D" 'term-pager-disable
)
704 (define-key map
"<" 'term-pager-bob
)
705 (define-key map
">" 'term-pager-eob
)
707 "Keymap used in Term pager mode.")
710 "True if communications via pty; false if by pipe. Buffer local.
711 This is to work around a bug in Emacs process signaling.")
713 (defvar term-last-input-match
""
714 "Last string searched for by term input history search, for defaulting.
715 Buffer local variable.")
717 (defvar term-input-ring nil
)
718 (defvar term-last-input-start
)
719 (defvar term-last-input-end
)
720 (defvar term-input-ring-index nil
721 "Index of last matched history element.")
722 (defvar term-matching-input-from-input-string
""
723 "Input previously used to match input history.")
724 ; This argument to set-process-filter disables reading from the process,
725 ; assuming this is Emacs 19.20 or newer.
726 (defvar term-pager-filter t
)
728 (put 'term-input-ring
'permanent-local t
)
729 (put 'term-input-ring-index
'permanent-local t
)
730 (put 'term-input-autoexpand
'permanent-local t
)
731 (put 'term-input-filter-functions
'permanent-local t
)
732 (put 'term-scroll-to-bottom-on-output
'permanent-local t
)
733 (put 'term-scroll-show-maximum-output
'permanent-local t
)
734 (put 'term-ptyp
'permanent-local t
)
736 (defmacro term-in-char-mode
() '(eq (current-local-map) term-raw-map
))
737 (defmacro term-in-line-mode
() '(not (term-in-char-mode)))
738 ;; True if currently doing PAGER handling.
739 (defmacro term-pager-enabled
() 'term-pager-count
)
740 (defmacro term-handling-pager
() 'term-pager-old-local-map
)
741 (defmacro term-using-alternate-sub-buffer
() 'term-saved-home-marker
)
743 ;; Let's silence the byte-compiler -mm
744 (defvar term-ansi-at-host nil
)
745 (defvar term-ansi-at-dir nil
)
746 (defvar term-ansi-at-user nil
)
747 (defvar term-ansi-at-message nil
)
748 (defvar term-ansi-at-save-user nil
)
749 (defvar term-ansi-at-save-pwd nil
)
750 (defvar term-ansi-at-save-anon nil
)
751 (defvar term-ansi-current-bold nil
)
752 (defvar term-ansi-current-color
0)
753 (defvar term-ansi-face-already-done nil
)
754 (defvar term-ansi-current-bg-color
0)
755 (defvar term-ansi-current-underline nil
)
756 (defvar term-ansi-current-reverse nil
)
757 (defvar term-ansi-current-invisible nil
)
759 ;; Four should be enough, if you want more, just add. -mm
760 (defvar term-terminal-more-parameters
0)
761 (defvar term-terminal-previous-parameter-2 -
1)
762 (defvar term-terminal-previous-parameter-3 -
1)
763 (defvar term-terminal-previous-parameter-4 -
1)
766 (defvar ansi-term-color-vector
777 (defcustom term-default-fg-color nil
778 "If non-nil, default color for foreground in Term mode."
780 :type
'(choice (const nil
) (string :tag
"color")))
781 (make-obsolete-variable 'term-default-fg-color
"use the face `term' instead."
784 (defcustom term-default-bg-color nil
785 "If non-nil, default color for foreground in Term mode."
787 :type
'(choice (const nil
) (string :tag
"color")))
788 (make-obsolete-variable 'term-default-bg-color
"use the face `term' instead."
793 :foreground
,term-default-fg-color
794 :background
,term-default-bg-color
796 "Default face to use in Term mode."
801 "Default face to use for bold text."
804 (defface term-underline
806 "Default face to use for underlined text."
809 (defface term-color-black
810 '((t :foreground
"black" :background
"black"))
811 "Face used to render black color code."
814 (defface term-color-red
815 '((t :foreground
"red3" :background
"red3"))
816 "Face used to render red color code."
819 (defface term-color-green
820 '((t :foreground
"green3" :background
"green3"))
821 "Face used to render green color code."
824 (defface term-color-yellow
825 '((t :foreground
"yellow3" :background
"yellow3"))
826 "Face used to render yellow color code."
829 (defface term-color-blue
830 '((t :foreground
"blue2" :background
"blue2"))
831 "Face used to render blue color code."
834 (defface term-color-magenta
835 '((t :foreground
"magenta3" :background
"magenta3"))
836 "Face used to render magenta color code."
839 (defface term-color-cyan
840 '((t :foreground
"cyan3" :background
"cyan3"))
841 "Face used to render cyan color code."
844 (defface term-color-white
845 '((t :foreground
"white" :background
"white"))
846 "Face used to render white color code."
849 ;; Inspiration came from comint.el -mm
850 (defcustom term-buffer-maximum-size
2048
851 "The maximum size in lines for term buffers.
852 Term buffers are truncated from the top to be no greater than this number.
853 Notice that a setting of 0 means \"don't truncate anything\". This variable
858 ;; Set up term-raw-map, etc.
861 (let* ((map (make-keymap))
862 (esc-map (make-keymap))
865 (define-key map
(make-string 1 i
) 'term-send-raw
)
866 ;; Avoid O and [. They are used in escape sequences for various keys.
867 (unless (or (eq i ?O
) (eq i
91))
868 (define-key esc-map
(make-string 1 i
) 'term-send-raw-meta
))
870 (define-key map
[remap self-insert-command
] 'term-send-raw
)
871 (define-key map
"\e" esc-map
)
873 ;; Added nearly all the 'gray keys' -mm
875 (if (featurep 'xemacs
)
876 (define-key map
[button2] 'term-mouse-paste)
877 (define-key map [mouse-2] 'term-mouse-paste))
878 (define-key map [up] 'term-send-up)
879 (define-key map [down] 'term-send-down)
880 (define-key map [right] 'term-send-right)
881 (define-key map [left] 'term-send-left)
882 (define-key map [C-up] 'term-send-ctrl-up)
883 (define-key map [C-down] 'term-send-ctrl-down)
884 (define-key map [C-right] 'term-send-ctrl-right)
885 (define-key map [C-left] 'term-send-ctrl-left)
886 (define-key map [delete] 'term-send-del)
887 (define-key map [deletechar] 'term-send-del)
888 (define-key map [backspace] 'term-send-backspace)
889 (define-key map [home] 'term-send-home)
890 (define-key map [end] 'term-send-end)
891 (define-key map [insert] 'term-send-insert)
892 (define-key map [S-prior] 'scroll-down)
893 (define-key map [S-next] 'scroll-up)
894 (define-key map [S-insert] 'term-paste)
895 (define-key map [prior] 'term-send-prior)
896 (define-key map [next] 'term-send-next)
897 (define-key map [xterm-paste] #'term--xterm-paste)
899 "Keyboard map for sending characters directly to the inferior process.")
901 (easy-menu-define term-terminal-menu
902 (list term-mode-map term-raw-map term-pager-break-map)
903 "Terminal menu for Term mode."
905 ["Line mode" term-line-mode :active (term-in-char-mode)
906 :help "Switch to line (cooked) sub-mode of term mode"]
907 ["Character mode" term-char-mode :active (term-in-line-mode)
908 :help "Switch to char (raw) sub-mode of term mode"]
909 ["Paging" term-pager-toggle :style toggle :selected term-pager-count
910 :help "Toggle paging feature"]))
912 (easy-menu-define term-signals-menu
913 (list term-mode-map term-raw-map term-pager-break-map)
914 "Signals menu for Term mode."
916 ["BREAK" term-interrupt-subjob :active t
917 :help "Interrupt the current subjob"]
918 ["STOP" term-stop-subjob :active t :help "Stop the current subjob"]
919 ["CONT" term-continue-subjob :active t
920 :help "Send CONT signal to process buffer's process group"]
921 ["QUIT" term-quit-subjob :active t
922 :help "Send quit signal to the current subjob"]
923 ["KILL" term-kill-subjob :active t
924 :help "Send kill signal to the current subjob"]
925 ["EOF" term-send-eof :active t
926 :help "Send an EOF to the current buffer's process"]))
928 (easy-menu-define term-pager-menu term-pager-break-map
929 "Menu for Term pager mode."
931 ["1 page forwards" term-pager-page t]
932 ["1 page backwards" term-pager-back-page t]
933 ["1 line backwards" term-pager-back-line t]
934 ["1 line forwards" term-pager-line t]
935 ["Goto to beginning" term-pager-bob t]
936 ["Goto to end" term-pager-eob t]
937 ["Discard remaining output" term-pager-discard t]
938 ["Disable paging" term-pager-toggle t]
939 ["Help" term-pager-help t]))
941 (defvar term-raw-escape-map
942 (let ((map (make-sparse-keymap)))
943 (set-keymap-parent map 'Control-X-prefix)
944 ;; Define standard bindings in term-raw-escape-map.
945 (define-key map "\C-v" (lookup-key (current-global-map) "\C-v"))
946 (define-key map "\C-u" (lookup-key (current-global-map) "\C-u"))
947 (define-key map "\C-q" 'term-pager-toggle)
948 ;; The keybinding for term-char-mode is needed by the menubar code.
949 (define-key map "\C-k" 'term-char-mode)
950 (define-key map "\C-j" 'term-line-mode)
951 ;; It's convenient to have execute-extended-command here.
952 (define-key map [?\M-x] 'execute-extended-command)
955 (defun term-set-escape-char (key)
956 "Change `term-escape-char' and keymaps that depend on it."
957 (when term-escape-char
958 ;; Undo previous term-set-escape-char.
959 (define-key term-raw-map term-escape-char 'term-send-raw))
960 (setq term-escape-char (if (vectorp key) key (vector key)))
961 (define-key term-raw-map term-escape-char term-raw-escape-map)
962 ;; FIXME: If we later call term-set-escape-char again with another key,
963 ;; we should undo this binding.
964 (define-key term-raw-escape-map term-escape-char 'term-send-raw))
966 (term-set-escape-char (or term-escape-char ?\C-c))
969 (put 'term-mode 'mode-class 'special)
972 ;; Use this variable as a display table for `term-mode'.
973 (defvar term-display-table
974 (let ((dt (or (copy-sequence standard-display-table)
975 (make-display-table)))
977 ;; avoid changing the display table for ^J
980 (aset dt i (vector i))
984 (aset dt i (vector i))
988 (aset dt i (vector i))
992 (defun term-ansi-reset ()
993 (setq term-current-face 'term)
994 (setq term-ansi-current-underline nil)
995 (setq term-ansi-current-bold nil)
996 (setq term-ansi-current-reverse nil)
997 (setq term-ansi-current-color 0)
998 (setq term-ansi-current-invisible nil)
999 ;; Stefan thought this should be t, but could not remember why.
1000 ;; Setting it to t seems to cause bug#11785. Setting it to nil
1001 ;; again to see if there are other consequences...
1002 (setq term-ansi-face-already-done nil)
1003 (setq term-ansi-current-bg-color 0))
1005 (define-derived-mode term-mode fundamental-mode "Term"
1006 "Major mode for interacting with an inferior interpreter.
1007 The interpreter name is same as buffer name, sans the asterisks.
1009 There are two submodes: line mode and char mode. By default, you are
1010 in char mode. In char sub-mode, each character (except
1011 `term-escape-char') is sent immediately to the subprocess.
1012 The escape character is equivalent to the usual meaning of C-x.
1014 In line mode, you send a line of input at a time; use
1015 \\[term-send-input] to send.
1017 In line mode, this maintains an input history of size
1018 `term-input-ring-size', and you can access it with the commands
1019 \\[term-next-input], \\[term-previous-input], and
1020 \\[term-dynamic-list-input-ring]. Input ring history expansion can be
1021 achieved with the commands \\[term-replace-by-expanded-history] or
1022 \\[term-magic-space]. Input ring expansion is controlled by the
1023 variable `term-input-autoexpand', and addition is controlled by the
1024 variable `term-input-ignoredups'.
1026 Input to, and output from, the subprocess can cause the window to scroll to
1027 the end of the buffer. See variables `term-scroll-to-bottom-on-input',
1028 and `term-scroll-to-bottom-on-output'.
1030 If you accidentally suspend your process, use \\[term-continue-subjob]
1033 This mode can be customized to create specific modes for running
1034 particular subprocesses. This can be done by setting the hooks
1035 `term-input-filter-functions', `term-input-filter',
1036 `term-input-sender' and `term-get-old-input' to appropriate functions,
1037 and the variable `term-prompt-regexp' to the appropriate regular
1040 Commands in raw mode:
1044 Commands in line mode:
1048 Entry to this mode runs the hooks on `term-mode-hook'."
1049 ;; we do not want indent to sneak in any tabs
1050 (setq indent-tabs-mode nil)
1051 (setq buffer-display-table term-display-table)
1052 (set (make-local-variable 'term-home-marker) (copy-marker 0))
1053 (set (make-local-variable 'term-height) (window-text-height))
1054 (set (make-local-variable 'term-width) (window-max-chars-per-line))
1055 (set (make-local-variable 'term-last-input-start) (make-marker))
1056 (set (make-local-variable 'term-last-input-end) (make-marker))
1057 (set (make-local-variable 'term-last-input-match) "")
1058 (set (make-local-variable 'term-command-hook)
1059 (symbol-function 'term-command-hook))
1061 ;; These local variables are set to their local values:
1062 (make-local-variable 'term-saved-home-marker)
1063 (make-local-variable 'term-saved-cursor)
1064 (make-local-variable 'term-prompt-regexp)
1065 (make-local-variable 'term-input-ring-size)
1066 (make-local-variable 'term-input-ring)
1067 (make-local-variable 'term-input-ring-file-name)
1068 (make-local-variable 'term-input-ring-index)
1069 (unless term-input-ring
1070 (setq term-input-ring (make-ring term-input-ring-size)))
1072 ;; I'm not sure these saves are necessary but, since I
1073 ;; haven't tested the whole thing on a net connected machine with
1074 ;; a properly configured ange-ftp, I've decided to be conservative
1075 ;; and put them in. -mm
1077 (set (make-local-variable 'term-ansi-at-host) (system-name))
1078 (set (make-local-variable 'term-ansi-at-dir) default-directory)
1079 (set (make-local-variable 'term-ansi-at-message) nil)
1081 ;; For user tracking purposes -mm
1082 (make-local-variable 'ange-ftp-default-user)
1083 (make-local-variable 'ange-ftp-default-password)
1084 (make-local-variable 'ange-ftp-generate-anonymous-password)
1086 (make-local-variable 'term-partial-ansi-terminal-message)
1088 ;; You may want to have different scroll-back sizes -mm
1089 (make-local-variable 'term-buffer-maximum-size)
1091 ;; Of course these have to be buffer-local -mm
1092 (make-local-variable 'term-ansi-current-bold)
1093 (make-local-variable 'term-ansi-current-color)
1094 (make-local-variable 'term-ansi-face-already-done)
1095 (make-local-variable 'term-ansi-current-bg-color)
1096 (make-local-variable 'term-ansi-current-underline)
1097 (make-local-variable 'term-ansi-current-reverse)
1098 (make-local-variable 'term-ansi-current-invisible)
1100 (make-local-variable 'term-terminal-parameter)
1101 (make-local-variable 'term-terminal-undecoded-bytes)
1102 (make-local-variable 'term-terminal-previous-parameter)
1103 (make-local-variable 'term-terminal-previous-parameter-2)
1104 (make-local-variable 'term-terminal-previous-parameter-3)
1105 (make-local-variable 'term-terminal-previous-parameter-4)
1106 (make-local-variable 'term-terminal-more-parameters)
1108 (make-local-variable 'term-terminal-state)
1109 (make-local-variable 'term-kill-echo-list)
1110 (make-local-variable 'term-start-line-column)
1111 (make-local-variable 'term-current-column)
1112 (make-local-variable 'term-current-row)
1113 (make-local-variable 'term-log-buffer)
1114 (make-local-variable 'term-scroll-start)
1115 (set (make-local-variable 'term-scroll-end) term-height)
1116 (make-local-variable 'term-scroll-with-delete)
1117 (make-local-variable 'term-pager-count)
1118 (make-local-variable 'term-pager-old-local-map)
1119 (make-local-variable 'term-old-mode-map)
1120 (make-local-variable 'term-insert-mode)
1121 (make-local-variable 'term-dynamic-complete-functions)
1122 (make-local-variable 'term-completion-fignore)
1123 (make-local-variable 'term-get-old-input)
1124 (make-local-variable 'term-matching-input-from-input-string)
1125 (make-local-variable 'term-input-autoexpand)
1126 (make-local-variable 'term-input-ignoredups)
1127 (make-local-variable 'term-delimiter-argument-list)
1128 (make-local-variable 'term-input-filter-functions)
1129 (make-local-variable 'term-input-filter)
1130 (make-local-variable 'term-input-sender)
1131 (make-local-variable 'term-eol-on-send)
1132 (make-local-variable 'term-scroll-to-bottom-on-output)
1133 (make-local-variable 'term-scroll-show-maximum-output)
1134 (make-local-variable 'term-ptyp)
1135 (make-local-variable 'term-exec-hook)
1136 (set (make-local-variable 'term-vertical-motion) 'vertical-motion)
1137 (set (make-local-variable 'term-pending-delete-marker) (make-marker))
1138 (make-local-variable 'term-current-face)
1140 (set (make-local-variable 'term-pending-frame) nil)
1141 ;; Cua-mode's keybindings interfere with the term keybindings, disable it.
1142 (set (make-local-variable 'cua-mode) nil)
1144 (set (make-local-variable 'font-lock-defaults) '(nil t))
1146 (add-function :filter-return
1147 (local 'window-adjust-process-window-size-function)
1150 (term-reset-size (cdr size) (car size)))
1152 '((name . term-maybe-reset-size)))
1154 (add-hook 'read-only-mode-hook #'term-line-mode-buffer-read-only-update nil t)
1156 (easy-menu-add term-terminal-menu)
1157 (easy-menu-add term-signals-menu)
1159 (setq term-input-ring (make-ring term-input-ring-size)))
1160 (term-update-mode-line))
1162 (defun term-reset-size (height width)
1163 (when (or (/= height term-height)
1164 (/= width term-width))
1165 (let ((point (point)))
1166 (setq term-height height)
1167 (setq term-width width)
1168 (setq term-start-line-column nil)
1169 (setq term-current-row nil)
1170 (setq term-current-column nil)
1171 (term-set-scroll-region 0 height)
1172 ;; `term-set-scroll-region' causes these to be set, we have to
1173 ;; clear them again since we're changing point (Bug#30544).
1174 (setq term-start-line-column nil)
1175 (setq term-current-row nil)
1176 (setq term-current-column nil)
1177 (goto-char point))))
1179 ;; Recursive routine used to check if any string in term-kill-echo-list
1180 ;; matches part of the buffer before point.
1181 ;; If so, delete that matched part of the buffer - this suppresses echo.
1182 ;; Also, remove that string from the term-kill-echo-list.
1183 ;; We *also* remove any older string on the list, as a sanity measure,
1184 ;; in case something gets out of sync. (Except for type-ahead, there
1185 ;; should only be one element in the list.)
1187 (defun term-check-kill-echo-list ()
1188 (let ((cur term-kill-echo-list) (found nil) (save-point (point)))
1193 (let* ((str (car cur)) (len (length str)) (start (- (point) len)))
1194 (if (and (>= start (point-min))
1195 (string= str (buffer-substring start (point))))
1196 (progn (delete-char (- len))
1197 (setq term-kill-echo-list (cdr cur))
1198 (setq term-current-column nil)
1199 (setq term-current-row nil)
1200 (setq term-start-line-column nil)
1201 (setq cur nil found t))
1202 (setq cur (cdr cur))))))
1204 (goto-char save-point)))
1207 (defun term-send-raw-string (chars)
1209 (let ((proc (get-buffer-process (current-buffer))))
1211 (error "Current buffer has no process")
1212 ;; Note that (term-current-row) must be called *after*
1213 ;; (point) has been updated to (process-mark proc).
1214 (goto-char (process-mark proc))
1215 (when (term-pager-enabled)
1216 (setq term-pager-count (term-current-row)))
1217 (process-send-string proc chars))))
1219 (defun term-send-raw ()
1220 "Send the last character typed through the terminal-emulator
1221 without any interpretation."
1223 (let ((keys (this-command-keys)))
1224 (term-send-raw-string (string (aref keys (1- (length keys)))))))
1226 (defun term-send-raw-meta ()
1228 (let ((char last-input-event))
1229 (when (symbolp char)
1230 ;; Convert `return' to C-m, etc.
1231 (let ((tmp (get char 'event-symbol-elements)))
1232 (if tmp (setq char (car tmp)))
1234 (setq tmp (get char 'ascii-character))
1236 (when (numberp char)
1237 (let ((base (event-basic-type char))
1238 (mods (delq 'meta (event-modifiers char))))
1239 (if (memq 'control mods)
1240 (setq mods (delq 'shift mods)))
1241 (term-send-raw-string
1243 (event-convert-list (append mods (list base)))))))))
1245 (defun term-mouse-paste (click)
1246 "Insert the primary selection at the position clicked on."
1248 (if (featurep 'xemacs)
1249 (term-send-raw-string
1250 (or (condition-case () (x-get-selection) (error ()))
1251 (error "No selection available")))
1252 ;; Give temporary modes such as isearch a chance to turn off.
1253 (run-hooks 'mouse-leave-buffer-hook)
1254 (setq this-command 'yank)
1255 (mouse-set-point click)
1256 (term-send-raw-string (gui-get-primary-selection))))
1258 (defun term-paste ()
1259 "Insert the last stretch of killed text at point."
1261 (term-send-raw-string (current-kill 0)))
1263 (defun term--xterm-paste ()
1264 "Insert the text pasted in an XTerm bracketed paste operation."
1266 (term-send-raw-string (xterm--pasted-text)))
1268 (declare-function xterm--pasted-text "term/xterm" ())
1270 ;; Which would be better: "\e[A" or "\eOA"? readline accepts either.
1271 ;; For my configuration it's definitely better \eOA but YMMV. -mm
1272 ;; For example: vi works with \eOA while elm wants \e[A ...
1273 ;; (terminfo: kcuu1, kcud1, kcuf1, kcub1, khome, kend, kpp, knp, kdch1, kbs)
1274 (defun term-send-up () (interactive) (term-send-raw-string "\eOA"))
1275 (defun term-send-down () (interactive) (term-send-raw-string "\eOB"))
1276 (defun term-send-right () (interactive) (term-send-raw-string "\eOC"))
1277 (defun term-send-left () (interactive) (term-send-raw-string "\eOD"))
1278 (defun term-send-ctrl-up () (interactive) (term-send-raw-string "\e[1;5A"))
1279 (defun term-send-ctrl-down () (interactive) (term-send-raw-string "\e[1;5B"))
1280 (defun term-send-ctrl-right () (interactive) (term-send-raw-string "\e[1;5C"))
1281 (defun term-send-ctrl-left () (interactive) (term-send-raw-string "\e[1;5D"))
1282 (defun term-send-home () (interactive) (term-send-raw-string "\e[1~"))
1283 (defun term-send-insert() (interactive) (term-send-raw-string "\e[2~"))
1284 (defun term-send-end () (interactive) (term-send-raw-string "\e[4~"))
1285 (defun term-send-prior () (interactive) (term-send-raw-string "\e[5~"))
1286 (defun term-send-next () (interactive) (term-send-raw-string "\e[6~"))
1287 (defun term-send-del () (interactive) (term-send-raw-string "\e[3~"))
1288 (defun term-send-backspace () (interactive) (term-send-raw-string "\C-?"))
1290 (defun term-char-mode ()
1291 "Switch to char (\"raw\") sub-mode of term mode.
1292 Each character you type is sent directly to the inferior without
1293 intervention from Emacs, except for the escape character (usually C-c)."
1295 ;; FIXME: Emit message? Cfr ilisp-raw-message
1296 (when (term-in-line-mode)
1297 (setq term-old-mode-map (current-local-map))
1298 (use-local-map term-raw-map)
1299 (easy-menu-add term-terminal-menu)
1300 (easy-menu-add term-signals-menu)
1302 ;; Don't allow changes to the buffer or to point which are not
1303 ;; caused by the process filter.
1304 (when term-char-mode-buffer-read-only
1305 (setq buffer-read-only t))
1306 (add-hook 'pre-command-hook #'term-set-goto-process-mark nil t)
1307 (add-hook 'post-command-hook #'term-goto-process-mark-maybe nil t)
1309 ;; Send existing partial line to inferior (without newline).
1310 (let ((pmark (process-mark (get-buffer-process (current-buffer))))
1311 (save-input-sender term-input-sender))
1312 (when (> (point) pmark)
1315 (setq term-input-sender
1316 (symbol-function 'term-send-string))
1319 (setq term-input-sender save-input-sender))))
1320 (term-update-mode-line)))
1322 (defun term-line-mode ()
1323 "Switch to line (\"cooked\") sub-mode of term mode.
1324 This means that Emacs editing commands work as normally, until
1325 you type \\[term-send-input] which sends the current line to the inferior."
1327 (when (term-in-char-mode)
1328 (when term-char-mode-buffer-read-only
1329 (setq buffer-read-only term-line-mode-buffer-read-only))
1330 (remove-hook 'pre-command-hook #'term-set-goto-process-mark t)
1331 (remove-hook 'post-command-hook #'term-goto-process-mark-maybe t)
1332 (use-local-map term-old-mode-map)
1333 (term-update-mode-line)))
1335 (defun term-line-mode-buffer-read-only-update ()
1336 "Update the user-set state of `buffer-read-only' in `term-line-mode'.
1338 Called as a buffer-local `read-only-mode-hook' function."
1339 (when (term-in-line-mode)
1340 (setq term-line-mode-buffer-read-only buffer-read-only)))
1342 (defun term-update-mode-line ()
1344 (if (term-in-char-mode)
1346 'help-echo "mouse-1: Switch to line mode"
1347 'mouse-face 'mode-line-highlight
1350 (mode-line keymap (down-mouse-1 . term-line-mode))))
1352 'help-echo "mouse-1: Switch to char mode"
1353 'mouse-face 'mode-line-highlight
1356 (mode-line keymap (down-mouse-1 . term-char-mode))))))
1358 (when (term-pager-enabled)
1362 'help-echo "mouse-1: Disable paging"
1363 'mouse-face 'mode-line-highlight
1366 (mode-line keymap (down-mouse-1 .
1367 term-pager-toggle)))))))
1369 (serial-item-config)
1370 (proc (get-buffer-process (current-buffer))))
1371 (when (and (term-check-proc (current-buffer))
1372 (equal (process-type nil) 'serial))
1373 (let ((temp (serial-speed)))
1374 (setq serial-item-speed
1376 ,(or (and temp (format " %d" temp)) "")
1377 help-echo "mouse-1: Change the speed of the serial port"
1378 mouse-face mode-line-highlight
1379 local-map (keymap (mode-line keymap
1380 (down-mouse-1 . serial-mode-line-speed-menu-1))))))
1381 (let ((temp (process-contact proc :summary)))
1382 (setq serial-item-config
1384 ,(or (and temp (format " %s" temp)) "")
1385 help-echo "mouse-1: Change the configuration of the serial port"
1386 mouse-face mode-line-highlight
1387 local-map (keymap (mode-line keymap
1388 (down-mouse-1 . serial-mode-line-config-menu-1)))))))
1389 (setq mode-line-process
1390 (list ": " term-mode term-page
1394 (force-mode-line-update))
1396 (defun term-check-proc (buffer)
1397 "True if there is a process associated w/buffer BUFFER, and it
1398 is alive. BUFFER can be either a buffer or the name of one."
1399 (let ((proc (get-buffer-process buffer)))
1400 (and proc (memq (process-status proc) '(run stop open listen connect)))))
1403 (defun make-term (name program &optional startfile &rest switches)
1404 "Make a term process NAME in a buffer, running PROGRAM.
1405 The name of the buffer is made by surrounding NAME with `*'s.
1406 If there is already a running process in that buffer, it is not restarted.
1407 Optional third arg STARTFILE is the name of a file to send the contents of to
1408 the process. Any more args are arguments to PROGRAM."
1409 (let ((buffer (get-buffer-create (concat "*" name "*"))))
1410 ;; If no process, or nuked process, crank up a new one and put buffer in
1411 ;; term mode. Otherwise, leave buffer and existing process alone.
1412 (cond ((not (term-check-proc buffer))
1413 (with-current-buffer buffer
1414 (term-mode)) ; Install local vars, mode, keymap, ...
1415 (term-exec buffer name program startfile switches)))
1419 (defun term (program)
1420 "Start a terminal-emulator in a new buffer.
1421 The buffer is in Term mode; see `term-mode' for the
1422 commands to use in that buffer.
1424 \\<term-raw-map>Type \\[switch-to-buffer] to switch to another buffer."
1425 (interactive (list (read-from-minibuffer "Run program: "
1426 (or explicit-shell-file-name
1429 (set-buffer (make-term "terminal" program))
1432 (switch-to-buffer "*terminal*"))
1434 (defun term-exec (buffer name command startfile switches)
1435 "Start up a process in buffer for term modes.
1436 Blasts any old process running in the buffer. Doesn't set the buffer mode.
1437 You can use this to cheaply run a series of processes in the same term
1438 buffer. The hook `term-exec-hook' is run after each exec."
1439 (with-current-buffer buffer
1440 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
1441 (when proc (delete-process proc)))
1442 ;; Crank up a new process
1443 (let ((proc (term-exec-1 name buffer command switches)))
1444 (make-local-variable 'term-ptyp)
1445 (setq term-ptyp process-connection-type) ; t if pty, nil if pipe.
1446 ;; Jump to the end, and set the process mark.
1447 (goto-char (point-max))
1448 (set-marker (process-mark proc) (point))
1449 (set-process-filter proc 'term-emulate-terminal)
1450 (set-process-sentinel proc 'term-sentinel)
1451 ;; Feed it the startfile.
1453 ;;This is guaranteed to wait long enough
1454 ;;but has bad results if the term does not prompt at all
1455 ;; (while (= size (buffer-size))
1457 ;;I hope 1 second is enough!
1459 (goto-char (point-max))
1460 (insert-file-contents startfile)
1462 proc (delete-and-extract-region (point) (point-max)))))
1463 (run-hooks 'term-exec-hook)
1466 (defun term-sentinel (proc msg)
1467 "Sentinel for term buffers.
1468 The main purpose is to get rid of the local keymap."
1469 (let ((buffer (process-buffer proc)))
1470 (when (memq (process-status proc) '(signal exit))
1471 (if (null (buffer-name buffer))
1473 (set-process-buffer proc nil)
1474 (with-current-buffer buffer
1475 ;; Write something in the compilation buffer
1476 ;; and hack its mode line.
1477 ;; Get rid of local keymap.
1479 (term-handle-exit (process-name proc) msg)
1480 ;; Since the buffer and mode line will show that the
1481 ;; process is dead, we can delete it now. Otherwise it
1482 ;; will stay around until M-x list-processes.
1483 (delete-process proc))))))
1485 (defun term-handle-exit (process-name msg)
1486 "Write process exit (or other change) message MSG in the current buffer."
1487 (let ((buffer-read-only nil)
1490 ;; Remove hooks to avoid errors due to dead process.
1491 (remove-hook 'pre-command-hook #'term-set-goto-process-mark t)
1492 (remove-hook 'post-command-hook #'term-goto-process-mark-maybe t)
1493 ;; Record where we put the message, so we can ignore it
1496 (insert ?\n "Process " process-name " " msg)
1497 ;; Force mode line redisplay soon.
1498 (force-mode-line-update)
1499 (when (and opoint (< opoint omax))
1500 (goto-char opoint))))
1503 (defvar term-term-name "eterm-color"
1504 "Name to use for TERM.
1505 Using \"emacs\" loses, because bash disables editing if $TERM == emacs.")
1506 ;; Format string, usage:
1507 ;; (format term-termcap-string emacs-term-name "TERMCAP=" 24 80)
1508 (defvar term-termcap-format
1509 "%s%s:li#%d:co#%d:cl=\\E[H\\E[J:cd=\\E[J:bs:am:xn:cm=\\E[%%i%%d;%%dH\
1510 :nd=\\E[C:up=\\E[A:ce=\\E[K:ho=\\E[H:pt\
1511 :al=\\E[L:dl=\\E[M:DL=\\E[%%dM:AL=\\E[%%dL:cs=\\E[%%i%%d;%%dr:sf=^J\
1512 :dc=\\E[P:DC=\\E[%%dP:IC=\\E[%%d@:im=\\E[4h:ei=\\E[4l:mi:\
1513 :so=\\E[7m:se=\\E[m:us=\\E[4m:ue=\\E[m:md=\\E[1m:mr=\\E[7m:me=\\E[m\
1514 :UP=\\E[%%dA:DO=\\E[%%dB:LE=\\E[%%dD:RI=\\E[%%dC\
1515 :kl=\\EOD:kd=\\EOB:kr=\\EOC:ku=\\EOA:kN=\\E[6~:kP=\\E[5~:@7=\\E[4~:kh=\\E[1~\
1516 :mk=\\E[8m:cb=\\E[1K:op=\\E[39;49m:Co#8:pa#64:AB=\\E[4%%dm:AF=\\E[3%%dm:cr=^M\
1517 :bl=^G:do=^J:le=^H:ta=^I:se=\\E[27m:ue=\\E[24m\
1518 :kb=^?:kD=^[[3~:sc=\\E7:rc=\\E8:r1=\\Ec:"
1520 ;; don't define :te=\\E[2J\\E[?47l\\E8:ti=\\E7\\E[?47h\
1521 "Termcap capabilities supported.")
1523 ;; This private hack is for backwards compatibility with Bash 4.3 and earlier.
1524 ;; It can be useful even when running a program other than Bash, as the
1525 ;; program might invoke Bash as an interactive subshell. See this thread:
1526 ;; https://lists.gnu.org/r/emacs-devel/2018-05/msg00670.html
1527 ;; Remove this hack and its uses once Bash 4.4-or-later is reasonably
1528 ;; universal, because it slows down execution slightly when
1529 ;; term--bash-needs-EMACSp is first called.
1530 (defvar term--bash-needs-EMACS-status nil
1531 "43 if Bash is so old that it needs EMACS set.
1532 Some other integer if Bash is new or not in use.
1534 (defun term--bash-needs-EMACSp ()
1535 "t if Bash is old, nil if it is new or not in use."
1537 (or term--bash-needs-EMACS-status
1539 term--bash-needs-EMACS-status
1540 (let ((process-environment
1541 (cons "BASH_ENV" process-environment)))
1544 "bash" nil nil nil "-c"
1545 "case $BASH_VERSION in [0123].*|4.[0123].*) exit 43;; esac")
1548 ;; This auxiliary function cranks up the process for term-exec in
1549 ;; the appropriate environment.
1551 (defun term-exec-1 (name buffer command switches)
1552 ;; We need to do an extra (fork-less) exec to run stty.
1553 ;; (This would not be needed if we had suitable Emacs primitives.)
1554 ;; The 'if ...; then shift; fi' hack is because Bourne shell
1555 ;; loses one arg when called with -c, and newer shells (bash, ksh) don't.
1556 ;; Thus we add an extra dummy argument "..", and then remove it.
1557 (let ((process-environment
1560 (format "TERM=%s" term-term-name)
1561 (format "TERMINFO=%s" data-directory)
1562 (format term-termcap-format "TERMCAP="
1563 term-term-name term-height term-width)
1565 (format "INSIDE_EMACS=%s,term:%s" emacs-version term-protocol-version)
1566 (format "LINES=%d" term-height)
1567 (format "COLUMNS=%d" term-width))
1568 process-environment))
1569 (process-connection-type t)
1570 ;; We should suppress conversion of end-of-line format.
1571 (inhibit-eol-conversion t)
1572 ;; The process's output contains not just chars but also binary
1573 ;; escape codes, so we need to see the raw output. We will have to
1574 ;; do the decoding by hand on the parts that are made of chars.
1575 (coding-system-for-read 'binary))
1576 (when (term--bash-needs-EMACSp)
1577 (push (format "EMACS=%s (term:%s)" emacs-version term-protocol-version)
1578 process-environment))
1579 (apply 'start-process name buffer
1581 (format "stty -nl echo rows %d columns %d sane 2>/dev/null;\
1582 if [ $1 = .. ]; then shift; fi; exec \"$@\""
1583 term-height term-width)
1588 ;;; Input history processing in a buffer
1589 ;; ===========================================================================
1590 ;; Useful input history functions, courtesy of the Ergo group.
1593 ;; term-dynamic-list-input-ring List history in help buffer.
1594 ;; term-previous-input Previous input...
1595 ;; term-previous-matching-input ...matching a string.
1596 ;; term-previous-matching-input-from-input ... matching the current input.
1597 ;; term-next-input Next input...
1598 ;; term-next-matching-input ...matching a string.
1599 ;; term-next-matching-input-from-input ... matching the current input.
1600 ;; term-backward-matching-input Backwards input...
1601 ;; term-forward-matching-input ...matching a string.
1602 ;; term-replace-by-expanded-history Expand history at point;
1603 ;; replace with expanded history.
1604 ;; term-magic-space Expand history and insert space.
1607 ;; term-read-input-ring Read into term-input-ring...
1608 ;; term-write-input-ring Write to term-input-ring-file-name.
1609 ;; term-replace-by-expanded-history-before-point Workhorse function.
1611 (defun term-read-input-ring (&optional silent)
1612 "Set the buffer's `term-input-ring' from a history file.
1613 The name of the file is given by the variable `term-input-ring-file-name'.
1614 The history ring is of size `term-input-ring-size', regardless of file size.
1615 If `term-input-ring-file-name' is nil this function does nothing.
1617 If the optional argument SILENT is non-nil, we say nothing about a
1618 failure to read the history file.
1620 This function is useful for major mode commands and mode hooks.
1622 The structure of the history file should be one input command per line,
1623 with the most recent command last.
1624 See also `term-input-ignoredups' and `term-write-input-ring'."
1625 (cond ((or (null term-input-ring-file-name)
1626 (equal term-input-ring-file-name ""))
1628 ((not (file-readable-p term-input-ring-file-name))
1630 (message "Cannot read history file %s"
1631 term-input-ring-file-name)))
1633 (let ((file term-input-ring-file-name)
1635 (ring (make-ring term-input-ring-size)))
1637 (insert-file-contents file)
1638 ;; Save restriction in case file is already visited...
1639 ;; Watch for those date stamps in history files!
1640 (goto-char (point-max))
1641 (while (and (< count term-input-ring-size)
1642 (re-search-backward "^[ \t]*\\([^#\n].*\\)[ \t]*$"
1644 (let ((history (buffer-substring (match-beginning 1)
1646 (when (or (null term-input-ignoredups)
1648 (not (string-equal (ring-ref ring 0) history)))
1649 (ring-insert-at-beginning ring history)))
1650 (setq count (1+ count))))
1651 (setq term-input-ring ring
1652 term-input-ring-index nil)))))
1654 (defun term-write-input-ring ()
1655 "Write the buffer's `term-input-ring' to a history file.
1656 The name of the file is given by the variable `term-input-ring-file-name'.
1657 The original contents of the file are lost if `term-input-ring' is not empty.
1658 If `term-input-ring-file-name' is nil this function does nothing.
1660 Useful within process sentinels.
1662 See also `term-read-input-ring'."
1663 (cond ((or (null term-input-ring-file-name)
1664 (equal term-input-ring-file-name "")
1665 (null term-input-ring) (ring-empty-p term-input-ring))
1667 ((not (file-writable-p term-input-ring-file-name))
1668 (message "Cannot write history file %s" term-input-ring-file-name))
1670 (let* ((history-buf (get-buffer-create " *Temp Input History*"))
1671 (ring term-input-ring)
1672 (file term-input-ring-file-name)
1673 (index (ring-length ring)))
1674 ;; Write it all out into a buffer first. Much faster, but messier,
1675 ;; than writing it one line at a time.
1676 (with-current-buffer history-buf
1679 (setq index (1- index))
1680 (insert (ring-ref ring index) ?\n))
1681 (write-region (buffer-string) nil file nil 'no-message)
1682 (kill-buffer nil))))))
1685 (defun term-dynamic-list-input-ring ()
1686 "List in help buffer the buffer's input history."
1688 (if (or (not (ring-p term-input-ring))
1689 (ring-empty-p term-input-ring))
1690 (message "No history")
1692 (history-buffer " *Input History*")
1693 (index (1- (ring-length term-input-ring)))
1694 (conf (current-window-configuration)))
1695 ;; We have to build up a list ourselves from the ring vector.
1697 (setq history (cons (ring-ref term-input-ring index) history)
1699 ;; Change "completion" to "history reference"
1700 ;; to make the display accurate.
1701 (with-output-to-temp-buffer history-buffer
1702 (display-completion-list history)
1703 (set-buffer history-buffer)
1705 (while (search-backward "completion" nil 'move)
1706 (replace-match "history reference")))
1708 (message "Hit space to flush")
1709 (let ((ch (read-event)))
1711 (set-window-configuration conf)
1712 (push ch unread-command-events))))))
1715 (defun term-regexp-arg (prompt)
1716 ;; Return list of regexp and prefix arg using PROMPT.
1717 (let* (;; Don't clobber this.
1718 (last-command last-command)
1719 (regexp (read-from-minibuffer prompt nil nil nil
1720 'minibuffer-history-search-history)))
1721 (list (if (string-equal regexp "")
1722 (setcar minibuffer-history-search-history
1723 (nth 1 minibuffer-history-search-history))
1725 (prefix-numeric-value current-prefix-arg))))
1727 (defun term-search-arg (arg)
1728 ;; First make sure there is a ring and that we are after the process mark
1729 (cond ((not (term-after-pmark-p))
1730 (error "Not at command line"))
1731 ((or (null term-input-ring)
1732 (ring-empty-p term-input-ring))
1733 (error "Empty input ring"))
1735 ;; arg of zero resets search from beginning, and uses arg of 1
1736 (setq term-input-ring-index nil)
1741 (defun term-search-start (arg)
1742 ;; Index to start a directional search, starting at term-input-ring-index
1743 (if term-input-ring-index
1744 ;; If a search is running, offset by 1 in direction of arg
1745 (mod (+ term-input-ring-index (if (> arg 0) 1 -1))
1746 (ring-length term-input-ring))
1747 ;; For a new search, start from beginning or end, as appropriate
1749 0 ; First elt for forward search
1750 (1- (ring-length term-input-ring))))) ; Last elt for backward search
1752 (defun term-previous-input-string (arg)
1753 "Return the string ARG places along the input ring.
1754 Moves relative to `term-input-ring-index'."
1755 (ring-ref term-input-ring (if term-input-ring-index
1756 (mod (+ arg term-input-ring-index)
1757 (ring-length term-input-ring))
1760 (defun term-previous-input (arg)
1761 "Cycle backwards through input history."
1763 (term-previous-matching-input "." arg))
1765 (defun term-next-input (arg)
1766 "Cycle forwards through input history."
1768 (term-previous-input (- arg)))
1770 (defun term-previous-matching-input-string (regexp arg)
1771 "Return the string matching REGEXP ARG places along the input ring.
1772 Moves relative to `term-input-ring-index'."
1773 (let* ((pos (term-previous-matching-input-string-position regexp arg)))
1774 (when pos (ring-ref term-input-ring pos))))
1776 (defun term-previous-matching-input-string-position
1777 (regexp arg &optional start)
1778 "Return the index matching REGEXP ARG places along the input ring.
1779 Moves relative to START, or `term-input-ring-index'."
1780 (when (or (not (ring-p term-input-ring))
1781 (ring-empty-p term-input-ring))
1782 (error "No history"))
1783 (let* ((len (ring-length term-input-ring))
1784 (motion (if (> arg 0) 1 -1))
1785 (n (mod (- (or start (term-search-start arg)) motion) len))
1786 (tried-each-ring-item nil)
1788 ;; Do the whole search as many times as the argument says.
1789 (while (and (/= arg 0) (not tried-each-ring-item))
1792 n (mod (+ n motion) len))
1793 ;; If we haven't reached a match, step some more.
1794 (while (and (< n len) (not tried-each-ring-item)
1795 (not (string-match regexp (ring-ref term-input-ring n))))
1796 (setq n (mod (+ n motion) len)
1797 ;; If we have gone all the way around in this search.
1798 tried-each-ring-item (= n prev)))
1799 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1800 ;; Now that we know which ring element to use, if we found it, return that.
1801 (when (string-match regexp (ring-ref term-input-ring n))
1804 (defun term-previous-matching-input (regexp n)
1805 "Search backwards through input history for match for REGEXP.
1806 \(Previous history elements are earlier commands.)
1807 With prefix argument N, search for Nth previous match.
1808 If N is negative, find the next or Nth next match."
1809 (interactive (term-regexp-arg "Previous input matching (regexp): "))
1810 (setq n (term-search-arg n))
1811 (let ((pos (term-previous-matching-input-string-position regexp n)))
1812 ;; Has a match been found?
1815 (setq term-input-ring-index pos)
1816 (message "History item: %d" (1+ pos))
1818 ;; Can't use kill-region as it sets this-command
1819 (process-mark (get-buffer-process (current-buffer))) (point))
1820 (insert (ring-ref term-input-ring pos)))))
1822 (defun term-next-matching-input (regexp n)
1823 "Search forwards through input history for match for REGEXP.
1824 \(Later history elements are more recent commands.)
1825 With prefix argument N, search for Nth following match.
1826 If N is negative, find the previous or Nth previous match."
1827 (interactive (term-regexp-arg "Next input matching (regexp): "))
1828 (term-previous-matching-input regexp (- n)))
1830 (defun term-previous-matching-input-from-input (n)
1831 "Search backwards through input history for match for current input.
1832 \(Previous history elements are earlier commands.)
1833 With prefix argument N, search for Nth previous match.
1834 If N is negative, search forwards for the -Nth following match."
1836 (when (not (memq last-command '(term-previous-matching-input-from-input
1837 term-next-matching-input-from-input)))
1838 ;; Starting a new search
1839 (setq term-matching-input-from-input-string
1841 (process-mark (get-buffer-process (current-buffer)))
1843 term-input-ring-index nil))
1844 (term-previous-matching-input
1845 (concat "^" (regexp-quote term-matching-input-from-input-string))
1848 (defun term-next-matching-input-from-input (n)
1849 "Search forwards through input history for match for current input.
1850 \(Following history elements are more recent commands.)
1851 With prefix argument N, search for Nth following match.
1852 If N is negative, search backwards for the -Nth previous match."
1854 (term-previous-matching-input-from-input (- n)))
1857 (defun term-replace-by-expanded-history (&optional silent)
1858 "Expand input command history references before point.
1859 Expansion is dependent on the value of `term-input-autoexpand'.
1861 This function depends on the buffer's idea of the input history, which may not
1862 match the command interpreter's idea, assuming it has one.
1864 Assumes history syntax is like typical Un*x shells'. However, since Emacs
1865 cannot know the interpreter's idea of input line numbers, assuming it has one,
1866 it cannot expand absolute input line number references.
1868 If the optional argument SILENT is non-nil, never complain
1869 even if history reference seems erroneous.
1871 See `term-magic-space' and `term-replace-by-expanded-history-before-point'.
1873 Returns t if successful."
1875 (when (and term-input-autoexpand
1876 (string-match "[!^]" (funcall term-get-old-input))
1877 (save-excursion (beginning-of-line)
1878 (looking-at term-prompt-regexp)))
1879 ;; Looks like there might be history references in the command.
1880 (let ((previous-modified-tick (buffer-modified-tick)))
1881 (message "Expanding history references...")
1882 (term-replace-by-expanded-history-before-point silent)
1883 (/= previous-modified-tick (buffer-modified-tick)))))
1886 (defun term-replace-by-expanded-history-before-point (silent)
1887 "Expand directory stack reference before point.
1888 See `term-replace-by-expanded-history'. Returns t if successful."
1890 (let ((toend (- (line-end-position) (point)))
1891 (start (progn (term-bol nil) (point))))
1893 (skip-chars-forward "^!^" (- (line-end-position) toend))
1894 (< (point) (- (line-end-position) toend)))
1895 ;; This seems a bit complex. We look for references such as !!, !-num,
1896 ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
1897 ;; If that wasn't enough, the plings can be suffixed with argument
1898 ;; range specifiers.
1899 ;; Argument ranges are complex too, so we hive off the input line,
1900 ;; referenced with plings, with the range string to `term-args'.
1901 (setq term-input-ring-index nil)
1902 (cond ((or (= (preceding-char) ?\\)
1903 (term-within-quotes start (point)))
1904 ;; The history is quoted, or we're in quotes.
1905 (goto-char (1+ (point))))
1906 ((looking-at "![0-9]+\\($\\|[^-]\\)")
1907 ;; We cannot know the interpreter's idea of input line numbers.
1908 (goto-char (match-end 0))
1909 (message "Absolute reference cannot be expanded"))
1910 ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
1911 ;; Just a number of args from `number' lines backward.
1912 (let ((number (1- (string-to-number
1913 (buffer-substring (match-beginning 1)
1915 (if (<= number (ring-length term-input-ring))
1918 (term-args (term-previous-input-string number)
1919 (match-beginning 2) (match-end 2))
1921 (setq term-input-ring-index number)
1922 (message "History item: %d" (1+ number)))
1923 (goto-char (match-end 0))
1924 (message "Relative reference exceeds input history size"))))
1925 ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
1926 ;; Just a number of args from the previous input line.
1928 (term-args (term-previous-input-string 0)
1929 (match-beginning 1) (match-end 1))
1931 (message "History item: previous"))
1933 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
1934 ;; Most recent input starting with or containing (possibly
1935 ;; protected) string, maybe just a number of args. Phew.
1936 (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
1937 (mb2 (match-beginning 2)) (me2 (match-end 2))
1938 (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
1939 (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
1940 (pos (save-match-data
1941 (term-previous-matching-input-string-position
1942 (concat pref (regexp-quote exp)) 1))))
1945 (goto-char (match-end 0))
1947 (progn (message "Not found")
1949 (setq term-input-ring-index pos)
1951 (term-args (ring-ref term-input-ring pos)
1952 (match-beginning 4) (match-end 4))
1954 (message "History item: %d" (1+ pos)))))
1955 ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
1956 ;; Quick substitution on the previous input line.
1957 (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
1958 (new (buffer-substring (match-beginning 2) (match-end 2)))
1960 (replace-match (term-previous-input-string 0) t t)
1962 (goto-char (match-beginning 0))
1963 (if (not (search-forward old pos t))
1965 (error "Not found"))
1966 (replace-match new t t)
1967 (message "History item: substituted"))))
1969 (goto-char (match-end 0))))))))
1972 (defun term-magic-space (arg)
1973 "Expand input history references before point and insert ARG spaces.
1974 A useful command to bind to SPC. See `term-replace-by-expanded-history'."
1976 (term-replace-by-expanded-history)
1977 (self-insert-command arg))
1979 (defun term-within-quotes (beg end)
1980 "Return t if the number of quotes between BEG and END is odd.
1981 Quotes are single and double."
1982 (let ((countsq (term-how-many-region "\\(^\\|[^\\\\]\\)'" beg end))
1983 (countdq (term-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
1984 (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
1986 (defun term-how-many-region (regexp beg end)
1987 "Return number of matches for REGEXP from BEG to END."
1992 (while (re-search-forward regexp end t)
1993 (setq count (1+ count)))))
1996 (defun term-args (string begin end)
1997 ;; From STRING, return the args depending on the range specified in the text
1998 ;; from BEGIN to END. If BEGIN is nil, assume all args. Ignore leading `:'.
1999 ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
2002 (term-arguments string 0 nil)
2003 (let* ((range (buffer-substring
2004 (if (eq (char-after begin) ?:) (1+ begin) begin) end))
2005 (nth (cond ((string-match "^[*^]" range) 1)
2006 ((string-match "^-" range) 0)
2007 ((string-equal range "$") nil)
2008 (t (string-to-number range))))
2009 (mth (cond ((string-match "[-*$]$" range) nil)
2010 ((string-match "-" range)
2011 (string-to-number (substring range (match-end 0))))
2013 (term-arguments string nth mth)))))
2015 ;; Return a list of arguments from ARG. Break it up at the
2016 ;; delimiters in term-delimiter-argument-list. Returned list is backwards.
2017 (defun term-delim-arg (arg)
2018 (if (null term-delimiter-argument-list)
2024 (let ((char (aref arg pos))
2026 (if (memq char term-delimiter-argument-list)
2027 (while (and (< pos len) (eq (aref arg pos) char))
2028 (setq pos (1+ pos)))
2029 (while (and (< pos len)
2030 (not (memq (aref arg pos)
2031 term-delimiter-argument-list)))
2032 (setq pos (1+ pos))))
2033 (setq args (cons (substring arg start pos) args))))
2036 (defun term-arguments (string nth mth)
2037 "Return from STRING the NTH to MTH arguments.
2038 NTH and/or MTH can be nil, which means the last argument.
2039 Returned arguments are separated by single spaces.
2040 We assume whitespace separates arguments, except within quotes.
2041 Also, a run of one or more of a single character
2042 in `term-delimiter-argument-list' is a separate argument.
2043 Argument 0 is the command name."
2044 (let ((argpart "[^ \n\t\"'`]+\\|\\(\"[^\"]*\"\\|'[^']*'\\|`[^`]*`\\)")
2048 ;; Build a list of all the args until we have as many as we want.
2049 (while (and (or (null mth) (<= count mth))
2050 (string-match argpart string pos))
2051 (if (and beg (= pos (match-beginning 0)))
2052 ;; It's contiguous, part of the same arg.
2053 (setq pos (match-end 0)
2054 quotes (or quotes (match-beginning 1)))
2055 ;; It's a new separate arg.
2057 ;; Put the previous arg, if there was one, onto ARGS.
2058 (setq str (substring string beg pos)
2059 args (if quotes (cons str args)
2060 (nconc (term-delim-arg str) args))
2062 (setq quotes (match-beginning 1))
2063 (setq beg (match-beginning 0))
2064 (setq pos (match-end 0))))
2066 (setq str (substring string beg pos)
2067 args (if quotes (cons str args)
2068 (nconc (term-delim-arg str) args))
2070 (let ((n (or nth (1- count)))
2071 (m (if mth (1- (- count mth)) 0)))
2073 (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
2076 ;;; Input processing stuff [line mode]
2079 (defun term-send-input ()
2080 "Send input to process.
2081 After the process output mark, sends all text from the process mark to
2082 point as input to the process. Before the process output mark, calls value
2083 of variable `term-get-old-input' to retrieve old input, copies it to the
2084 process mark, and sends it. A terminal newline is also inserted into the
2085 buffer and sent to the process. The functions in `term-input-filter-functions'
2086 are called on the input before sending it.
2088 The input is entered into the input history ring, if the value of variable
2089 `term-input-filter' returns non-nil when called on the input. Any history
2090 reference may be expanded depending on the value of the variable
2091 `term-input-autoexpand'.
2093 If variable `term-eol-on-send' is non-nil, then point is moved to the
2094 end of line before sending the input.
2096 The values of `term-get-old-input', `term-input-filter-functions', and
2097 `term-input-filter' are chosen according to the command interpreter running
2098 in the buffer. E.g.,
2100 If the interpreter is the csh,
2101 term-get-old-input is the default: take the current line, discard any
2102 initial string matching regexp term-prompt-regexp.
2103 term-input-filter-functions monitors input for \"cd\", \"pushd\", and
2104 \"popd\" commands. When it sees one, it cd's the buffer.
2105 term-input-filter is the default: returns t if the input isn't all white
2108 If the term is Lucid Common Lisp,
2109 term-get-old-input snarfs the sexp ending at point.
2110 term-input-filter-functions does nothing.
2111 term-input-filter returns nil if the input matches input-filter-regexp,
2112 which matches (1) all whitespace (2) :a, :c, etc.
2114 Similarly for Soar, Scheme, etc."
2116 ;; Note that the input string does not include its terminal newline.
2117 (let ((proc (get-buffer-process (current-buffer))))
2118 (if (not proc) (error "Current buffer has no process")
2119 (let* ((pmark (process-mark proc))
2120 (pmark-val (marker-position pmark))
2121 (input-is-new (>= (point) pmark-val))
2122 (intxt (if input-is-new
2123 (progn (if term-eol-on-send (end-of-line))
2124 (buffer-substring pmark (point)))
2125 (funcall term-get-old-input)))
2126 (input (if (not (eq term-input-autoexpand 'input))
2127 ;; Just whatever's already there
2129 ;; Expand and leave it visible in buffer
2130 (term-replace-by-expanded-history t)
2131 (buffer-substring pmark (point))))
2132 (history (if (not (eq term-input-autoexpand 'history))
2134 ;; This is messy 'cos ultimately the original
2135 ;; functions used do insertion, rather than return
2136 ;; strings. We have to expand, then insert back.
2137 (term-replace-by-expanded-history t)
2138 (let ((copy (buffer-substring pmark (point))))
2139 (delete-region pmark (point))
2142 (when (term-pager-enabled)
2144 (goto-char (process-mark proc))
2145 (setq term-pager-count (term-current-row))))
2146 (when (and (funcall term-input-filter history)
2147 (or (null term-input-ignoredups)
2148 (not (ring-p term-input-ring))
2149 (ring-empty-p term-input-ring)
2150 (not (string-equal (ring-ref term-input-ring 0)
2152 (ring-insert term-input-ring history))
2153 (let ((functions term-input-filter-functions))
2155 (funcall (car functions) (concat input "\n"))
2156 (setq functions (cdr functions))))
2157 (setq term-input-ring-index nil)
2159 ;; Update the markers before we send the input
2160 ;; in case we get output amidst sending the input.
2161 (set-marker term-last-input-start pmark)
2162 (set-marker term-last-input-end (point))
2164 ;; Set up to delete, because inferior should echo.
2165 (when (marker-buffer term-pending-delete-marker)
2166 (delete-region term-pending-delete-marker pmark))
2167 (set-marker term-pending-delete-marker pmark-val)
2168 (set-marker (process-mark proc) (point)))
2170 (funcall term-input-sender proc input)))))
2172 (defun term-get-old-input-default ()
2173 "Default for `term-get-old-input'.
2174 Take the current line, and discard any initial text matching
2175 `term-prompt-regexp'."
2179 (let ((beg (point)))
2181 (buffer-substring beg (point)))))
2183 (defun term-copy-old-input ()
2184 "Insert after prompt old input at point as new input to be edited.
2185 Calls `term-get-old-input' to get old input."
2187 (let ((input (funcall term-get-old-input))
2188 (process (get-buffer-process (current-buffer))))
2190 (error "Current buffer has no process")
2191 (goto-char (process-mark process))
2194 (defun term-skip-prompt ()
2195 "Skip past the text matching regexp `term-prompt-regexp'.
2196 If this takes us past the end of the current line, don't skip at all."
2197 (let ((eol (line-end-position)))
2198 (when (and (looking-at term-prompt-regexp)
2199 (<= (match-end 0) eol))
2200 (goto-char (match-end 0)))))
2203 (defun term-after-pmark-p ()
2204 "Is point after the process output marker?"
2205 ;; Since output could come into the buffer after we looked at the point
2206 ;; but before we looked at the process marker's value, we explicitly
2207 ;; serialize. This is just because I don't know whether or not Emacs
2208 ;; services input during execution of lisp commands.
2209 (let ((proc-pos (marker-position
2210 (process-mark (get-buffer-process (current-buffer))))))
2211 (<= proc-pos (point))))
2213 (defun term-simple-send (proc string)
2214 "Default function for sending to PROC input STRING.
2215 This just sends STRING plus a newline. To override this,
2216 set the hook `term-input-sender'."
2217 (term-send-string proc string)
2218 (term-send-string proc "\n"))
2220 (defun term-bol (arg)
2221 "Go to the beginning of line, then skip past the prompt, if any.
2222 If a prefix argument is given (\\[universal-argument]), then no prompt skip
2223 -- go straight to column 0.
2225 The prompt skip is done by skipping text matching the regular expression
2226 `term-prompt-regexp', a buffer local variable."
2229 (when (null arg) (term-skip-prompt)))
2231 ;; These two functions are for entering text you don't want echoed or
2232 ;; saved -- typically passwords to ftp, telnet, or somesuch.
2233 ;; Just enter m-x term-send-invisible and type in your line.
2235 (defun term-read-noecho (prompt &optional stars)
2236 "Read a single line of text from user without echoing, and return it.
2237 Prompt with argument PROMPT, a string. Optional argument STARS causes
2238 input to be echoed with `*' characters on the prompt line. Input ends with
2239 RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line. C-g aborts (if
2240 `inhibit-quit' is set because e.g. this function was called from a process
2241 filter and C-g is pressed, this function returns nil rather than a string).
2243 Note that the keystrokes comprising the text can still be recovered
2244 \(temporarily) with \\[view-lossage]. This may be a security bug for some
2249 (cursor-in-echo-area t)
2253 (message "%s%s" prompt (make-string (length ans) ?*))
2254 (message "%s" prompt))
2255 (setq c (read-char))
2257 ;; This function may get called from a process filter, where
2258 ;; inhibit-quit is set. In later versions of Emacs read-char
2259 ;; may clear quit-flag itself and return C-g. That would make
2260 ;; it impossible to quit this loop in a simple way, so
2261 ;; re-enable it here (for backward-compatibility the check for
2262 ;; quit-flag below would still be necessary, so this seems
2263 ;; like the simplest way to do things).
2266 ((or (= c ?\r) (= c ?\n) (= c ?\e))
2270 ((and (/= c ?\b) (/= c ?\177))
2271 (setq ans (concat ans (char-to-string c))))
2273 (setq ans (substring ans 0 -1)))))
2275 ;; Emulate a true quit, except that we have to return a value.
2277 (setq quit-flag nil)
2283 (defun term-send-invisible (str &optional proc)
2284 "Read a string without echoing.
2285 Then send it to the process running in the current buffer. A new-line
2286 is additionally sent. String is not saved on term input history list.
2287 Security bug: your string can still be temporarily recovered with
2289 (interactive "P") ; Defeat snooping via C-x esc
2290 (when (not (stringp str))
2291 (setq str (term-read-noecho "Non-echoed text: " t)))
2293 (setq proc (get-buffer-process (current-buffer))))
2294 (if (not proc) (error "Current buffer has no process")
2295 (setq term-kill-echo-list (nconc term-kill-echo-list
2297 (term-send-string proc str)
2298 (term-send-string proc "\n")))
2301 ;;; Low-level process communication
2303 (defcustom term-input-chunk-size 512
2304 "Long inputs send to term processes are broken up into chunks of this size.
2305 If your process is choking on big inputs, try lowering the value."
2309 (defun term-send-string (proc str)
2310 "Send to PROC the contents of STR as input.
2311 This is equivalent to `process-send-string', except that long input strings
2312 are broken up into chunks of size `term-input-chunk-size'. Processes
2313 are given a chance to output between chunks. This can help prevent processes
2314 from hanging when you send them long inputs on some OS's."
2315 (let* ((len (length str))
2316 (i (min len term-input-chunk-size)))
2317 (process-send-string proc (substring str 0 i))
2319 (let ((next-i (+ i term-input-chunk-size)))
2320 (accept-process-output)
2321 (process-send-string proc (substring str i (min len next-i)))
2324 (defun term-send-region (proc start end)
2325 "Send to PROC the region delimited by START and END.
2326 This is a replacement for `process-send-region' that tries to keep
2327 your process from hanging on long inputs. See `term-send-string'."
2328 (term-send-string proc (buffer-substring start end)))
2331 ;;; Random input hackage
2333 (defun term-kill-output ()
2334 "Kill all output from interpreter since last input."
2336 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2337 (kill-region term-last-input-end pmark)
2339 (insert "*** output flushed ***\n")
2340 (set-marker pmark (point))))
2342 (defun term-show-output ()
2343 "Display start of this batch of interpreter output at top of window.
2344 Sets mark to the value of point when this command is run."
2346 (goto-char term-last-input-end)
2349 (set-window-start (selected-window) (point))
2352 (defun term-interrupt-subjob ()
2353 "Interrupt the current subjob."
2355 (interrupt-process nil term-ptyp))
2357 (defun term-kill-subjob ()
2358 "Send kill signal to the current subjob."
2360 (kill-process nil term-ptyp))
2362 (defun term-quit-subjob ()
2363 "Send quit signal to the current subjob."
2365 (quit-process nil term-ptyp))
2367 (defun term-stop-subjob ()
2368 "Stop the current subjob.
2369 WARNING: if there is no current subjob, you can end up suspending
2370 the top-level process running in the buffer. If you accidentally do
2371 this, use \\[term-continue-subjob] to resume the process. (This
2372 is not a problem with most shells, since they ignore this signal.)"
2374 (stop-process nil term-ptyp))
2376 (defun term-continue-subjob ()
2377 "Send CONT signal to process buffer's process group.
2378 Useful if you accidentally suspend the top-level process."
2380 (continue-process nil term-ptyp))
2382 (defun term-kill-input ()
2383 "Kill all text from last stuff output by interpreter to point."
2385 (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
2386 (p-pos (marker-position pmark)))
2387 (when (> (point) p-pos)
2388 (kill-region pmark (point)))))
2390 (defun term-delchar-or-maybe-eof (arg)
2391 "Delete ARG characters forward, or send an EOF to process if at end of
2398 (defun term-send-eof ()
2399 "Send an EOF to the current buffer's process."
2403 (defun term-backward-matching-input (regexp n)
2404 "Search backward through buffer for match for REGEXP.
2405 Matches are searched for on lines that match `term-prompt-regexp'.
2406 With prefix argument N, search for Nth previous match.
2407 If N is negative, find the next or Nth next match."
2408 (interactive (term-regexp-arg "Backward input matching (regexp): "))
2409 (let* ((re (concat term-prompt-regexp ".*" regexp))
2410 (pos (save-excursion (end-of-line (if (> n 0) 0 1))
2411 (when (re-search-backward re nil t n)
2414 (progn (message "Not found")
2419 (defun term-forward-matching-input (regexp n)
2420 "Search forward through buffer for match for REGEXP.
2421 Matches are searched for on lines that match `term-prompt-regexp'.
2422 With prefix argument N, search for Nth following match.
2423 If N is negative, find the previous or Nth previous match."
2424 (interactive (term-regexp-arg "Forward input matching (regexp): "))
2425 (term-backward-matching-input regexp (- n)))
2428 (defun term-next-prompt (n)
2429 "Move to end of Nth next prompt in the buffer.
2430 See `term-prompt-regexp'."
2432 (let ((paragraph-start term-prompt-regexp))
2433 (end-of-line (if (> n 0) 1 0))
2434 (forward-paragraph n)
2435 (term-skip-prompt)))
2437 (defun term-previous-prompt (n)
2438 "Move to end of Nth previous prompt in the buffer.
2439 See `term-prompt-regexp'."
2441 (term-next-prompt (- n)))
2443 ;;; Support for source-file processing commands.
2444 ;;============================================================================
2445 ;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
2446 ;; commands that process files of source text (e.g. loading or compiling
2447 ;; files). So the corresponding process-in-a-buffer modes have commands
2448 ;; for doing this (e.g., lisp-load-file). The functions below are useful
2449 ;; for defining these commands.
2451 ;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
2452 ;; and Soar, in that they don't know anything about file extensions.
2453 ;; So the compile/load interface gets the wrong default occasionally.
2454 ;; The load-file/compile-file default mechanism could be smarter -- it
2455 ;; doesn't know about the relationship between filename extensions and
2456 ;; whether the file is source or executable. If you compile foo.lisp
2457 ;; with compile-file, then the next load-file should use foo.bin for
2458 ;; the default, not foo.lisp. This is tricky to do right, particularly
2459 ;; because the extension for executable files varies so much (.o, .bin,
2460 ;; .lbin, .mo, .vo, .ao, ...).
2463 ;; TERM-SOURCE-DEFAULT -- determines defaults for source-file processing
2466 ;; TERM-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
2467 ;; want to save the buffer before issuing any process requests to the command
2470 ;; TERM-GET-SOURCE -- used by the source-file processing commands to prompt
2471 ;; for the file to process.
2473 ;; (TERM-SOURCE-DEFAULT previous-dir/file source-modes)
2474 ;;============================================================================
2475 ;; This function computes the defaults for the load-file and compile-file
2476 ;; commands for tea, soar, cmulisp, and cmuscheme modes.
2478 ;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
2479 ;; source-file processing command, or nil if there hasn't been one yet.
2480 ;; - SOURCE-MODES is a list used to determine what buffers contain source
2481 ;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
2482 ;; Typically, (lisp-mode) or (scheme-mode).
2484 ;; If the command is given while the cursor is inside a string, *and*
2485 ;; the string is an existing filename, *and* the filename is not a directory,
2486 ;; then the string is taken as default. This allows you to just position
2487 ;; your cursor over a string that's a filename and have it taken as default.
2489 ;; If the command is given in a file buffer whose major mode is in
2490 ;; SOURCE-MODES, then the filename is the default file, and the
2491 ;; file's directory is the default directory.
2493 ;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
2494 ;; then the default directory & file are what was used in the last source-file
2495 ;; processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
2496 ;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
2497 ;; is the cwd, with no default file. (\"no default file\" = nil)
2499 ;; SOURCE-REGEXP is typically going to be something like (tea-mode)
2500 ;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
2501 ;; for Soar programs, etc.
2503 ;; The function returns a pair: (default-directory . default-file).
2505 (defun term-source-default (previous-dir/file source-modes)
2506 (cond ((and buffer-file-name (memq major-mode source-modes))
2507 (cons (file-name-directory buffer-file-name)
2508 (file-name-nondirectory buffer-file-name)))
2511 (cons default-directory nil))))
2514 ;; (TERM-CHECK-SOURCE fname)
2515 ;;============================================================================
2516 ;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
2517 ;; process-in-a-buffer modes), this function can be called on the filename.
2518 ;; If the file is loaded into a buffer, and the buffer is modified, the user
2519 ;; is queried to see if he wants to save the buffer before proceeding with
2520 ;; the load or compile.
2522 (defun term-check-source (fname)
2523 (let ((buff (get-file-buffer fname)))
2525 (buffer-modified-p buff)
2526 (y-or-n-p (format "Save buffer %s first? "
2527 (buffer-name buff))))
2529 (with-current-buffer buff
2533 ;; (TERM-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
2534 ;;============================================================================
2535 ;; TERM-GET-SOURCE is used to prompt for filenames in command-interpreter
2536 ;; commands that process source files (like loading or compiling a file).
2537 ;; It prompts for the filename, provides a default, if there is one,
2538 ;; and returns the result filename.
2540 ;; See TERM-SOURCE-DEFAULT for more on determining defaults.
2542 ;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
2543 ;; from the last source processing command. SOURCE-MODES is a list of major
2544 ;; modes used to determine what file buffers contain source files. (These
2545 ;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
2546 ;; then the filename reader will only accept a file that exists.
2549 ;; (interactive (term-get-source "Compile file: " prev-lisp-dir/file
2552 ;; This is pretty stupid about strings. It decides we're in a string
2553 ;; if there's a quote on both sides of point on the current line.
2554 (defun term-extract-string ()
2555 "Return string around `point' that starts the current line or nil."
2557 (let* ((point (point))
2558 (bol (line-beginning-position))
2559 (eol (line-end-position))
2560 (start (and (search-backward "\"" bol t)
2562 (end (progn (goto-char point)
2563 (and (search-forward "\"" eol t)
2566 (buffer-substring start end)))))
2568 (defun term-get-source (prompt prev-dir/file source-modes mustmatch-p)
2569 (let* ((def (term-source-default prev-dir/file source-modes))
2570 (stringfile (term-extract-string))
2571 (sfile-p (and stringfile
2573 (file-exists-p stringfile)
2575 (not (file-directory-p stringfile))))
2576 (defdir (if sfile-p (file-name-directory stringfile)
2578 (deffile (if sfile-p (file-name-nondirectory stringfile)
2580 (ans (read-file-name (if deffile (format "%s(default %s) "
2584 (concat defdir deffile)
2586 (list (expand-file-name (substitute-in-file-name ans)))))
2588 ;; I am somewhat divided on this string-default feature. It seems
2589 ;; to violate the principle-of-least-astonishment, in that it makes
2590 ;; the default harder to predict, so you actually have to look and see
2591 ;; what the default really is before choosing it. This can trip you up.
2592 ;; On the other hand, it can be useful, I guess. I would appreciate feedback
2597 ;;; Simple process query facility.
2598 ;; ===========================================================================
2599 ;; This function is for commands that want to send a query to the process
2600 ;; and show the response to the user. For example, a command to get the
2601 ;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
2602 ;; to an inferior Common Lisp process.
2604 ;; This simple facility just sends strings to the inferior process and pops
2605 ;; up a window for the process buffer so you can see what the process
2606 ;; responds with. We don't do anything fancy like try to intercept what the
2607 ;; process responds with and put it in a pop-up window or on the message
2608 ;; line. We just display the buffer. Low tech. Simple. Works good.
2610 ;; Send to the inferior process PROC the string STR. Pop-up but do not select
2611 ;; a window for the inferior process so that its response can be seen.
2612 (defun term-proc-query (proc str)
2613 (let* ((proc-buf (process-buffer proc))
2614 (proc-mark (process-mark proc)))
2615 (display-buffer proc-buf)
2616 (set-buffer proc-buf) ; but it's not the selected *window*
2617 (let ((proc-win (get-buffer-window proc-buf))
2618 (proc-pt (marker-position proc-mark)))
2619 (term-send-string proc str) ; send the query
2620 (accept-process-output proc) ; wait for some output
2621 ;; Try to position the proc window so you can see the answer.
2622 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
2623 ;; I don't know why. Wizards invited to improve it.
2624 (when (not (pos-visible-in-window-p proc-pt proc-win))
2625 (let ((opoint (window-point proc-win)))
2626 (set-window-point proc-win proc-mark) (sit-for 0)
2627 (if (not (pos-visible-in-window-p opoint proc-win))
2629 (set-window-point proc-win opoint)))))))
2631 ;; Returns the current column in the current screen line.
2632 ;; Note: (current-column) yields column in buffer line.
2634 (defun term-horizontal-column ()
2635 (- (term-current-column) (term-start-line-column)))
2637 ;; Calls either vertical-motion or term-buffer-vertical-motion
2638 (defmacro term-vertical-motion (count)
2639 (list 'funcall 'term-vertical-motion count))
2641 ; An emulation of vertical-motion that is independent of having a window.
2642 ; Instead, it uses the term-width variable as the logical window width.
2644 (defun term-buffer-vertical-motion (count)
2646 (move-to-column (* term-width (/ (current-column) term-width)))
2650 (todo (+ count (/ (current-column) term-width))))
2652 ;; The loop iterates over buffer lines;
2653 ;; H is the number of screen lines in the current line, i.e.
2654 ;; the ceiling of dividing the buffer line width by term-width.
2655 (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2660 (setq todo (- todo H))
2661 (forward-char) ;; Move past the ?\n
2662 (end-of-line)) ;; and on to the end of the next line.
2663 (if (and (>= todo H) (> todo 0))
2664 (+ (- count todo) H -1) ;; Hit end of buffer.
2665 (move-to-column (* todo term-width))
2667 (t ;; (< count 0) ;; Similar algorithm, but for upward motion.
2670 (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2674 (progn (beginning-of-line)
2676 (setq todo (- todo H))
2677 (backward-char)) ;; Move to end of previous line.
2678 (if (and (>= todo H) (> todo 0))
2679 (+ count todo (- 1 H)) ;; Hit beginning of buffer.
2680 (move-to-column (* (- H todo 1) term-width))
2683 ;; The term-start-line-column variable is used as a cache.
2684 (defun term-start-line-column ()
2685 (cond (term-start-line-column)
2686 ((let ((save-pos (point)))
2687 (term-vertical-motion 0)
2688 (setq term-start-line-column (current-column))
2689 (goto-char save-pos)
2690 term-start-line-column))))
2692 ;; Same as (current-column), but uses term-current-column as a cache.
2693 (defun term-current-column ()
2694 (cond (term-current-column)
2695 ((setq term-current-column (current-column)))))
2697 ;; Move DELTA column right (or left if delta < 0 limiting at column 0).
2699 (defun term-move-columns (delta)
2700 (setq term-current-column (max 0 (+ (term-current-column) delta)))
2701 (let ((point-at-eol (line-end-position)))
2702 (move-to-column term-current-column t)
2703 ;; If move-to-column extends the current line it will use the face
2704 ;; from the last character on the line, set the face for the chars
2706 (when (> (point) point-at-eol)
2707 (put-text-property point-at-eol (point) 'font-lock-face 'default))))
2709 ;; Insert COUNT copies of CHAR in the default face.
2710 (defun term-insert-char (char count)
2711 (let ((old-point (point)))
2712 (insert-char char count)
2713 (put-text-property old-point (point) 'font-lock-face 'default)))
2715 (defun term-current-row ()
2716 (cond (term-current-row)
2717 ((setq term-current-row
2720 (narrow-to-region term-home-marker (point-max))
2721 (- (term-vertical-motion -9999))))))))
2723 (defun term-adjust-current-row-cache (delta)
2724 (when term-current-row
2725 (setq term-current-row
2726 (max 0 (+ term-current-row delta)))))
2728 (defun term-terminal-pos ()
2729 (save-excursion ; save-restriction
2730 (let ((save-col (term-current-column))
2732 (term-vertical-motion 0)
2733 (setq x (- save-col (current-column)))
2734 (setq y (term-vertical-motion term-height))
2737 ;;Function that handles term messages: code by rms (and you can see the
2738 ;;difference ;-) -mm
2740 (defun term-handle-ansi-terminal-messages (message)
2741 ;; Handle stored partial message
2742 (when term-partial-ansi-terminal-message
2743 (setq message (concat term-partial-ansi-terminal-message message))
2744 (setq term-partial-ansi-terminal-message nil))
2746 ;; Is there a command here?
2747 (while (string-match "\eAnSiT.+\n" message)
2748 ;; Extract the command code and the argument.
2749 (let* ((start (match-beginning 0))
2750 (command-code (aref message (+ start 6)))
2755 (string-match "\r?\n" message
2758 ;; Delete this command from MESSAGE.
2759 (setq message (replace-match "" t t message))
2761 ;; If we recognize the type of command, set the appropriate variable.
2762 (cond ((= command-code ?c)
2763 (setq term-ansi-at-dir argument))
2764 ((= command-code ?h)
2765 (setq term-ansi-at-host argument))
2766 ((= command-code ?u)
2767 (setq term-ansi-at-user argument))
2768 ;; Otherwise ignore this one.
2772 ;; Update default-directory based on the changes this command made.
2775 (setq default-directory
2776 (file-name-as-directory
2777 (if (and (string= term-ansi-at-host (system-name))
2778 (string= term-ansi-at-user (user-real-login-name)))
2779 (expand-file-name term-ansi-at-dir)
2780 (concat "/-:" term-ansi-at-user "@" term-ansi-at-host ":"
2781 term-ansi-at-dir))))
2783 ;; I'm not sure this is necessary,
2784 ;; but it's best to be on the safe side.
2785 (if (string= term-ansi-at-host (system-name))
2787 (setq ange-ftp-default-user term-ansi-at-save-user)
2788 (setq ange-ftp-default-password term-ansi-at-save-pwd)
2789 (setq ange-ftp-generate-anonymous-password term-ansi-at-save-anon))
2790 (setq term-ansi-at-save-user ange-ftp-default-user)
2791 (setq term-ansi-at-save-pwd ange-ftp-default-password)
2792 (setq term-ansi-at-save-anon ange-ftp-generate-anonymous-password)
2793 (setq ange-ftp-default-user nil)
2794 (setq ange-ftp-default-password nil)
2795 (setq ange-ftp-generate-anonymous-password nil)))))
2796 ;; If there is a partial message at the end of the string, store it
2798 (when (string-match "\eAnSiT.+$" message)
2799 (setq term-partial-ansi-terminal-message (match-string 0 message))
2800 (setq message (replace-match "" t t message)))
2804 ;; Terminal emulation
2805 ;; This is the standard process filter for term buffers.
2806 ;; It emulates (most of the features of) a VT100/ANSI-style terminal.
2808 (defun term-emulate-terminal (proc str)
2809 (with-current-buffer (process-buffer proc)
2810 (let* ((i 0) char funny
2811 count ; number of decoded chars in substring
2812 count-bytes ; number of bytes
2814 save-point save-marker old-point temp win
2815 (inhibit-read-only t)
2816 (buffer-undo-list t)
2817 (selected (selected-window))
2819 handled-ansi-message
2820 (str-length (length str)))
2821 (save-selected-window
2823 (let ((newstr (term-handle-ansi-terminal-messages str)))
2824 (unless (eq str newstr)
2825 (setq handled-ansi-message t
2827 (setq str-length (length str))
2829 (when (marker-buffer term-pending-delete-marker)
2830 ;; Delete text following term-pending-delete-marker.
2831 (delete-region term-pending-delete-marker (process-mark proc))
2832 (set-marker term-pending-delete-marker nil))
2834 (when (/= (point) (process-mark proc))
2835 (setq save-point (point-marker)))
2837 (setf term-vertical-motion
2838 (if (eq (window-buffer) (current-buffer))
2840 'term-buffer-vertical-motion))
2841 (setq save-marker (copy-marker (process-mark proc)))
2842 (goto-char (process-mark proc))
2845 ;; If the buffer is in line mode, and there is a partial
2846 ;; input line, save the line (by narrowing to leave it
2847 ;; outside the restriction ) until we're done with output.
2848 (when (and (> (point-max) (process-mark proc))
2849 (term-in-line-mode))
2850 (narrow-to-region (point-min) (process-mark proc)))
2852 (when term-log-buffer
2853 (princ str term-log-buffer))
2854 (when term-terminal-undecoded-bytes
2855 (setq str (concat term-terminal-undecoded-bytes str))
2856 (setq str-length (length str))
2857 (setq term-terminal-undecoded-bytes nil))
2858 (cond ((eq term-terminal-state 4) ;; Have saved pending output.
2859 (setq str (concat term-terminal-parameter str))
2860 (setq term-terminal-parameter nil)
2861 (setq str-length (length str))
2862 (setq term-terminal-state 0)))
2864 (while (< i str-length)
2865 (setq char (aref str i))
2866 (cond ((< term-terminal-state 2)
2867 ;; Look for prefix of regular chars
2869 (string-match "[\r\n\000\007\033\t\b\032\016\017]"
2871 (when (not funny) (setq funny str-length))
2873 (cond ((eq term-terminal-state 1)
2874 ;; We are in state 1, we need to wrap
2875 ;; around. Go to the beginning of
2876 ;; the next line and switch to state
2879 (term-move-columns (- (term-current-column)))
2880 (setq term-terminal-state 0)))
2881 ;; Decode the string before counting
2882 ;; characters, to avoid garbling of certain
2883 ;; multibyte characters (bug#1006).
2884 (setq decoded-substring
2885 (decode-coding-string
2886 (substring str i funny)
2887 locale-coding-system))
2888 (setq count (length decoded-substring))
2889 ;; Check for multibyte characters that ends
2890 ;; before end of string, and save it for
2892 (when (= funny str-length)
2894 (while (eq (char-charset (aref decoded-substring
2895 (- count 1 partial)))
2899 (setq term-terminal-undecoded-bytes
2900 (substring decoded-substring (- partial)))
2901 (setq decoded-substring
2902 (substring decoded-substring 0 (- partial)))
2903 (cl-decf str-length partial)
2904 (cl-decf count partial)
2905 (cl-decf funny partial))))
2906 (setq temp (- (+ (term-horizontal-column) count)
2908 (cond ((or term-suppress-hard-newline (<= temp 0)))
2909 ;; All count chars fit in line.
2910 ((> count temp) ;; Some chars fit.
2911 ;; This iteration, handle only what fits.
2912 (setq count (- count temp))
2915 (encode-coding-string
2916 (substring decoded-substring 0 count)
2919 (setq funny (+ count-bytes i)))
2920 ((or (not (or term-pager-count
2921 term-scroll-with-delete))
2922 (> (term-handle-scroll 1) 0))
2923 (term-adjust-current-row-cache 1)
2924 (setq count (min count term-width))
2927 (encode-coding-string
2928 (substring decoded-substring 0 count)
2930 (setq funny (+ count-bytes i))
2931 (setq term-start-line-column
2932 term-current-column))
2933 (t ;; Doing PAGER processing.
2934 (setq count 0 funny i)
2935 (setq term-current-column nil)
2936 (setq term-start-line-column nil)))
2937 (setq old-point (point))
2939 ;; Insert a string, check how many columns
2940 ;; we moved, then delete that many columns
2941 ;; following point if not eob nor insert-mode.
2942 (let ((old-column (current-column))
2944 (insert (decode-coding-string (substring str i funny) locale-coding-system))
2945 (setq term-current-column (current-column)
2946 columns (- term-current-column old-column))
2947 (when (not (or (eobp) term-insert-mode))
2949 (term-move-columns columns)
2950 (delete-region pos (point)))
2951 ;; In insert mode if the current line
2952 ;; has become too long it needs to be
2954 (when term-insert-mode
2957 (when (> (current-column) term-width)
2958 (delete-region (- (point) (- (current-column) term-width))
2961 (setq term-current-column nil)
2963 (put-text-property old-point (point)
2964 'font-lock-face term-current-face)
2965 ;; If the last char was written in last column,
2966 ;; back up one column, but remember we did so.
2967 ;; Thus we emulate xterm/vt100-style line-wrapping.
2969 (term-move-columns -1)
2970 (setq term-terminal-state 1)))
2971 (setq i (1- funny)))
2972 ((and (setq term-terminal-state 0)
2973 (eq char ?\^I)) ; TAB (terminfo: ht)
2974 (setq count (term-current-column))
2975 ;; The line cannot exceed term-width. TAB at
2976 ;; the end of a line should not cause wrapping.
2977 (setq count (min term-width
2978 (+ count 8 (- (mod count 8)))))
2979 (if (> term-width count)
2982 (- count (term-current-column)))
2983 (setq term-current-column count))
2984 (when (> term-width (term-current-column))
2986 (1- (- term-width (term-current-column)))))
2987 (when (= term-width (term-current-column))
2988 (term-move-columns -1))))
2989 ((eq char ?\r) ;; (terminfo: cr)
2990 (term-vertical-motion 0)
2991 (setq term-current-column term-start-line-column))
2992 ((eq char ?\n) ;; (terminfo: cud1, ind)
2993 (unless (and term-kill-echo-list
2994 (term-check-kill-echo-list))
2996 ((eq char ?\b) ;; (terminfo: cub1)
2997 (term-move-columns -1))
2998 ((eq char ?\033) ; Escape
2999 (setq term-terminal-state 2))
3000 ((eq char 0)) ; NUL: Do nothing
3001 ((eq char ?\016)) ; Shift Out - ignored
3002 ((eq char ?\017)) ; Shift In - ignored
3003 ((eq char ?\^G) ;; (terminfo: bel)
3006 (let ((end (string-match "\r?\n" str i)))
3009 (unless handled-ansi-message
3010 (funcall term-command-hook
3011 (decode-coding-string
3012 (substring str (1+ i) end)
3013 locale-coding-system)))
3014 (setq i (1- (match-end 0))))
3015 (setq term-terminal-parameter (substring str i))
3016 (setq term-terminal-state 4)
3017 (setq i str-length))))
3018 (t ; insert char FIXME: Should never happen
3019 (term-move-columns 1)
3020 (backward-delete-char 1)
3022 ((eq term-terminal-state 2) ; Seen Esc
3023 (cond ((eq char ?\133) ;; ?\133 = ?[
3025 ;; Some modifications to cope with multiple
3026 ;; settings like ^[[01;32;43m -mm
3027 ;; Note that now the init value of
3028 ;; term-terminal-previous-parameter has been
3031 (setq term-terminal-parameter 0)
3032 (setq term-terminal-previous-parameter -1)
3033 (setq term-terminal-previous-parameter-2 -1)
3034 (setq term-terminal-previous-parameter-3 -1)
3035 (setq term-terminal-previous-parameter-4 -1)
3036 (setq term-terminal-more-parameters 0)
3037 (setq term-terminal-state 3))
3038 ((eq char ?D) ;; scroll forward
3039 (term-handle-deferred-scroll)
3041 (setq term-terminal-state 0))
3042 ;; ((eq char ?E) ;; (terminfo: nw), not used for
3043 ;; ;; now, but this is a working
3044 ;; ;; implementation
3046 ;; (term-goto term-current-row 0)
3047 ;; (setq term-terminal-state 0))
3048 ((eq char ?M) ;; scroll reversed (terminfo: ri)
3049 (if (or (< (term-current-row) term-scroll-start)
3050 (>= (1- (term-current-row))
3052 ;; Scrolling up will not move outside
3053 ;; the scroll region.
3055 ;; Scrolling the scroll region is needed.
3057 (setq term-terminal-state 0))
3058 ((eq char ?7) ;; Save cursor (terminfo: sc)
3059 (term-handle-deferred-scroll)
3060 (setq term-saved-cursor
3061 (list (term-current-row)
3062 (term-horizontal-column)
3063 term-ansi-current-bg-color
3064 term-ansi-current-bold
3065 term-ansi-current-color
3066 term-ansi-current-invisible
3067 term-ansi-current-reverse
3068 term-ansi-current-underline
3071 (setq term-terminal-state 0))
3072 ((eq char ?8) ;; Restore cursor (terminfo: rc)
3073 (when term-saved-cursor
3074 (term-goto (nth 0 term-saved-cursor)
3075 (nth 1 term-saved-cursor))
3076 (setq term-ansi-current-bg-color
3077 (nth 2 term-saved-cursor)
3078 term-ansi-current-bold
3079 (nth 3 term-saved-cursor)
3080 term-ansi-current-color
3081 (nth 4 term-saved-cursor)
3082 term-ansi-current-invisible
3083 (nth 5 term-saved-cursor)
3084 term-ansi-current-reverse
3085 (nth 6 term-saved-cursor)
3086 term-ansi-current-underline
3087 (nth 7 term-saved-cursor)
3089 (nth 8 term-saved-cursor)))
3090 (setq term-terminal-state 0))
3091 ((eq char ?c) ;; \Ec - Reset (terminfo: rs1)
3092 ;; This is used by the "clear" program.
3093 (setq term-terminal-state 0)
3094 (term-reset-terminal))
3095 ;; The \E#8 reset sequence for xterm. We
3096 ;; probably don't need to handle it, but this
3097 ;; is the code to parse it.
3099 ;; (when (eq (aref str (1+ i)) ?8)
3101 ;; (setq term-scroll-start 0)
3102 ;; (setq term-scroll-end term-height)
3103 ;; (setq term-terminal-state 0)))
3104 ((setq term-terminal-state 0))))
3105 ((eq term-terminal-state 3) ; Seen Esc [
3106 (cond ((and (>= char ?0) (<= char ?9))
3107 (setq term-terminal-parameter
3108 (+ (* 10 term-terminal-parameter) (- char ?0))))
3110 ;; Some modifications to cope with multiple
3111 ;; settings like ^[[01;32;43m -mm
3112 (setq term-terminal-more-parameters 1)
3113 (setq term-terminal-previous-parameter-4
3114 term-terminal-previous-parameter-3)
3115 (setq term-terminal-previous-parameter-3
3116 term-terminal-previous-parameter-2)
3117 (setq term-terminal-previous-parameter-2
3118 term-terminal-previous-parameter)
3119 (setq term-terminal-previous-parameter
3120 term-terminal-parameter)
3121 (setq term-terminal-parameter 0))
3122 ((eq char ??)) ; Ignore ?
3124 (term-handle-ansi-escape proc char)
3125 (setq term-terminal-more-parameters 0)
3126 (setq term-terminal-previous-parameter-4 -1)
3127 (setq term-terminal-previous-parameter-3 -1)
3128 (setq term-terminal-previous-parameter-2 -1)
3129 (setq term-terminal-previous-parameter -1)
3130 (setq term-terminal-state 0)))))
3131 (when (term-handling-pager)
3132 ;; Finish stuff to get ready to handle PAGER.
3133 (if (> (% (current-column) term-width) 0)
3134 (setq term-terminal-parameter
3136 ;; We're at column 0. Goto end of buffer; to compensate,
3137 ;; prepend a ?\r for later. This looks more consistent.
3139 (setq term-terminal-parameter
3140 (concat "\r" (substring str i)))
3141 (setq term-terminal-parameter (substring str (1- i)))
3142 (aset term-terminal-parameter 0 ?\r))
3143 (goto-char (point-max)))
3144 (setq term-terminal-state 4)
3145 (make-local-variable 'term-pager-old-filter)
3146 (setq term-pager-old-filter (process-filter proc))
3147 (set-process-filter proc term-pager-filter)
3148 (setq i str-length))
3151 (when (>= (term-current-row) term-height)
3152 (term-handle-deferred-scroll))
3154 (set-marker (process-mark proc) (point))
3156 (goto-char save-point)
3157 (set-marker save-point nil))
3159 ;; Check for a pending filename-and-line number to display.
3160 ;; We do this before scrolling, because we might create a new window.
3161 (when (and term-pending-frame
3162 (eq (window-buffer selected) (current-buffer)))
3163 (term-display-line (car term-pending-frame)
3164 (cdr term-pending-frame))
3165 (setq term-pending-frame nil))
3167 ;; Scroll each window displaying the buffer but (by default)
3168 ;; only if the point matches the process-mark we started with.
3170 ;; Avoid infinite loop in strange case where minibuffer window
3171 ;; is selected but not active.
3172 (while (window-minibuffer-p win)
3173 (setq win (next-window win nil t)))
3176 (setq win (next-window win nil t))
3177 (when (eq (window-buffer win) (process-buffer proc))
3178 (let ((scroll term-scroll-to-bottom-on-output))
3180 (when (or (= (point) save-marker)
3181 (eq scroll t) (eq scroll 'all)
3182 ;; Maybe user wants point to jump to the end.
3183 (and (eq selected win)
3184 (or (eq scroll 'this) (not save-point)))
3185 (and (eq scroll 'others)
3186 (not (eq selected win))))
3187 (goto-char term-home-marker)
3189 (goto-char (process-mark proc))
3190 (if (not (pos-visible-in-window-p (point) win))
3192 ;; Optionally scroll so that the text
3193 ;; ends at the bottom of the window.
3194 (when (and term-scroll-show-maximum-output
3195 (>= (point) (process-mark proc)))
3197 (goto-char (point-max))
3199 (not (eq win last-win))))
3201 ;; Stolen from comint.el and adapted -mm
3202 (when (> term-buffer-maximum-size 0)
3204 (goto-char (process-mark (get-buffer-process (current-buffer))))
3205 (forward-line (- term-buffer-maximum-size))
3207 (delete-region (point-min) (point))))
3208 (set-marker save-marker nil)))
3209 ;; This might be expensive, but we need it to handle something
3210 ;; like `sleep 5 | less -c' in more-or-less real time.
3211 (when (get-buffer-window (current-buffer))
3214 (defvar-local term-goto-process-mark t
3215 "Whether to reset point to the current process mark after this command.
3217 Set in `pre-command-hook' in char mode by `term-set-goto-process-mark'.")
3219 (defun term-set-goto-process-mark ()
3220 "Sets `term-goto-process-mark'.
3222 Always set to nil if `term-char-mode-point-at-process-mark' is nil.
3224 Called as a buffer-local `pre-command-hook' function in
3225 `term-char-mode' so that when point is equal to the process mark
3226 at the pre-command stage, we know to restore point to the process
3227 mark at the post-command stage.
3229 See also `term-goto-process-mark-maybe'."
3230 (setq term-goto-process-mark
3231 (and term-char-mode-point-at-process-mark
3232 (eq (point) (marker-position (term-process-mark))))))
3234 (defun term-goto-process-mark-maybe ()
3235 "Move point to the term buffer's process mark upon keyboard input.
3237 Called as a buffer-local `post-command-hook' function in
3238 `term-char-mode' to prevent commands from putting the buffer into
3239 an inconsistent state by unexpectedly moving point.
3241 Mouse events are ignored so that mouse selection is unimpeded.
3243 Only acts when the pre-command position of point was equal to the
3244 process mark, and the `term-char-mode-point-at-process-mark'
3245 option is enabled. See `term-set-goto-process-mark'."
3246 (when term-goto-process-mark
3247 (unless (mouse-event-p last-command-event)
3248 (goto-char (term-process-mark)))))
3250 (defun term-process-mark ()
3251 "The current `process-mark' for the term buffer process."
3252 (process-mark (get-buffer-process (current-buffer))))
3254 (defun term-handle-deferred-scroll ()
3255 (let ((count (- (term-current-row) term-height)))
3258 (goto-char term-home-marker)
3259 (term-vertical-motion (1+ count))
3260 (set-marker term-home-marker (point))
3261 (setq term-current-row (1- term-height))))))
3263 (defun term-reset-terminal ()
3264 "Reset the terminal, delete all the content and set the face to the default one."
3267 (setq term-current-row 0)
3268 (setq term-current-column 1)
3269 (setq term-scroll-start 0)
3270 (setq term-scroll-end term-height)
3271 (setq term-insert-mode nil)
3272 ;; FIXME: No idea why this is here, it looks wrong. --Stef
3273 (setq term-ansi-face-already-done nil))
3275 ;; New function to deal with ansi colorized output, as you can see you can
3276 ;; have any bold/underline/fg/bg/reverse combination. -mm
3278 (defun term-handle-colors-array (parameter)
3281 ;; Bold (terminfo: bold)
3283 (setq term-ansi-current-bold t))
3287 (setq term-ansi-current-underline t))
3289 ;; Blink (unsupported by Emacs), will be translated to bold.
3290 ;; This may change in the future though.
3292 (setq term-ansi-current-bold t))
3294 ;; Reverse (terminfo: smso)
3296 (setq term-ansi-current-reverse t))
3300 (setq term-ansi-current-invisible t))
3302 ;; Reset underline (terminfo: rmul)
3304 (setq term-ansi-current-underline nil))
3306 ;; Reset reverse (terminfo: rmso)
3308 (setq term-ansi-current-reverse nil))
3311 ((and (>= parameter 30) (<= parameter 37))
3312 (setq term-ansi-current-color (- parameter 29)))
3316 (setq term-ansi-current-color 0))
3319 ((and (>= parameter 40) (<= parameter 47))
3320 (setq term-ansi-current-bg-color (- parameter 39)))
3324 (setq term-ansi-current-bg-color 0))
3326 ;; 0 (Reset) or unknown (reset anyway)
3330 ;; (message "Debug: U-%d R-%d B-%d I-%d D-%d F-%d B-%d"
3331 ;; term-ansi-current-underline
3332 ;; term-ansi-current-reverse
3333 ;; term-ansi-current-bold
3334 ;; term-ansi-current-invisible
3335 ;; term-ansi-face-already-done
3336 ;; term-ansi-current-color
3337 ;; term-ansi-current-bg-color)
3339 (unless term-ansi-face-already-done
3340 (if term-ansi-current-invisible
3342 (if term-ansi-current-reverse
3344 (elt ansi-term-color-vector term-ansi-current-color)
3347 (elt ansi-term-color-vector term-ansi-current-bg-color)
3349 (setq term-current-face
3350 (list :background color
3352 ) ;; No need to bother with anything else if it's invisible.
3353 (setq term-current-face
3356 (elt ansi-term-color-vector term-ansi-current-color)
3360 (elt ansi-term-color-vector term-ansi-current-bg-color)
3362 :inverse-video term-ansi-current-reverse))
3364 (when term-ansi-current-bold
3365 (setq term-current-face
3366 `(,term-current-face :inherit term-bold)))
3368 (when term-ansi-current-underline
3369 (setq term-current-face
3370 `(,term-current-face :inherit term-underline)))))
3372 ;; (message "Debug %S" term-current-face)
3373 ;; FIXME: shouldn't we set term-ansi-face-already-done to t here? --Stef
3374 (setq term-ansi-face-already-done nil))
3377 ;; Handle a character assuming (eq terminal-state 2) -
3378 ;; i.e. we have previously seen Escape followed by ?[.
3380 (defun term-handle-ansi-escape (proc char)
3382 ((or (eq char ?H) ;; cursor motion (terminfo: cup,home)
3383 ;; (eq char ?f) ;; xterm seems to handle this sequence too, not
3386 (when (<= term-terminal-parameter 0)
3387 (setq term-terminal-parameter 1))
3388 (when (<= term-terminal-previous-parameter 0)
3389 (setq term-terminal-previous-parameter 1))
3390 (when (> term-terminal-previous-parameter term-height)
3391 (setq term-terminal-previous-parameter term-height))
3392 (when (> term-terminal-parameter term-width)
3393 (setq term-terminal-parameter term-width))
3395 (1- term-terminal-previous-parameter)
3396 (1- term-terminal-parameter)))
3397 ;; \E[A - cursor up (terminfo: cuu, cuu1)
3399 (term-handle-deferred-scroll)
3400 (let ((tcr (term-current-row)))
3402 (if (< (- tcr term-terminal-parameter) term-scroll-start)
3403 ;; If the amount to move is before scroll start, move
3405 (- term-scroll-start tcr)
3406 (if (>= term-terminal-parameter tcr)
3408 (- (max 1 term-terminal-parameter)))) t)))
3409 ;; \E[B - cursor down (terminfo: cud)
3411 (let ((tcr (term-current-row)))
3412 (unless (>= tcr term-scroll-end)
3414 (min (- term-scroll-end tcr) (max 1 term-terminal-parameter))
3416 ;; \E[C - cursor right (terminfo: cuf, cuf1)
3420 (if (>= (+ term-terminal-parameter (term-current-column)) term-width)
3421 (- term-width (term-current-column) 1)
3422 term-terminal-parameter))))
3423 ;; \E[D - cursor left (terminfo: cub)
3425 (term-move-columns (- (max 1 term-terminal-parameter))))
3426 ;; \E[G - cursor motion to absolute column (terminfo: hpa)
3428 (term-move-columns (- (max 0 (min term-width term-terminal-parameter))
3429 (term-current-column))))
3430 ;; \E[J - clear to end of screen (terminfo: ed, clear)
3432 (term-erase-in-display term-terminal-parameter))
3433 ;; \E[K - clear to end of line (terminfo: el, el1)
3435 (term-erase-in-line term-terminal-parameter))
3436 ;; \E[L - insert lines (terminfo: il, il1)
3438 (term-insert-lines (max 1 term-terminal-parameter)))
3439 ;; \E[M - delete lines (terminfo: dl, dl1)
3441 (term-delete-lines (max 1 term-terminal-parameter)))
3442 ;; \E[P - delete chars (terminfo: dch, dch1)
3444 (term-delete-chars (max 1 term-terminal-parameter)))
3445 ;; \E[@ - insert spaces (terminfo: ich)
3447 (term-insert-spaces (max 1 term-terminal-parameter)))
3448 ;; \E[?h - DEC Private Mode Set
3450 (cond ((eq term-terminal-parameter 4) ;; (terminfo: smir)
3451 (setq term-insert-mode t))
3452 ;; ((eq term-terminal-parameter 47) ;; (terminfo: smcup)
3453 ;; (term-switch-to-alternate-sub-buffer t))
3455 ;; \E[?l - DEC Private Mode Reset
3457 (cond ((eq term-terminal-parameter 4) ;; (terminfo: rmir)
3458 (setq term-insert-mode nil))
3459 ;; ((eq term-terminal-parameter 47) ;; (terminfo: rmcup)
3460 ;; (term-switch-to-alternate-sub-buffer nil))
3463 ;; Modified to allow ansi coloring -mm
3464 ;; \E[m - Set/reset modes, set bg/fg
3465 ;;(terminfo: smso,rmso,smul,rmul,rev,bold,sgr0,invis,op,setab,setaf)
3467 (when (= term-terminal-more-parameters 1)
3468 (when (>= term-terminal-previous-parameter-4 0)
3469 (term-handle-colors-array term-terminal-previous-parameter-4))
3470 (when (>= term-terminal-previous-parameter-3 0)
3471 (term-handle-colors-array term-terminal-previous-parameter-3))
3472 (when (>= term-terminal-previous-parameter-2 0)
3473 (term-handle-colors-array term-terminal-previous-parameter-2))
3474 (term-handle-colors-array term-terminal-previous-parameter))
3475 (term-handle-colors-array term-terminal-parameter))
3477 ;; \E[6n - Report cursor position (terminfo: u7)
3479 (term-handle-deferred-scroll)
3480 (process-send-string proc
3483 (1+ (term-current-row))
3484 (1+ (term-horizontal-column)))))
3485 ;; \E[r - Set scrolling region (terminfo: csr)
3487 (term-set-scroll-region
3488 (1- term-terminal-previous-parameter)
3489 (1- term-terminal-parameter)))
3492 (defun term-set-scroll-region (top bottom)
3493 "Set scrolling region.
3494 TOP is the top-most line (inclusive) of the new scrolling region,
3495 while BOTTOM is the line following the new scrolling region (e.g. exclusive).
3496 The top-most line is line 0."
3497 (setq term-scroll-start
3498 (if (or (< top 0) (>= top term-height))
3501 (setq term-scroll-end
3502 (if (or (<= bottom term-scroll-start) (> bottom term-height))
3505 (setq term-scroll-with-delete
3506 (or (term-using-alternate-sub-buffer)
3507 (not (and (= term-scroll-start 0)
3508 (= term-scroll-end term-height)))))
3509 (term-move-columns (- (term-current-column)))
3512 ;; (defun term-switch-to-alternate-sub-buffer (set)
3513 ;; ;; If asked to switch to (from) the alternate sub-buffer, and already (not)
3514 ;; ;; using it, do nothing. This test is needed for some programs (including
3515 ;; ;; Emacs) that emit the ti termcap string twice, for unknown reason.
3516 ;; (term-handle-deferred-scroll)
3517 ;; (if (eq set (not (term-using-alternate-sub-buffer)))
3518 ;; (let ((row (term-current-row))
3519 ;; (col (term-horizontal-column)))
3521 ;; (goto-char (point-max))
3522 ;; (if (not (eq (preceding-char) ?\n))
3523 ;; (term-insert-char ?\n 1))
3524 ;; (setq term-scroll-with-delete t)
3525 ;; (setq term-saved-home-marker (copy-marker term-home-marker))
3526 ;; (set-marker term-home-marker (point)))
3528 ;; (setq term-scroll-with-delete
3529 ;; (not (and (= term-scroll-start 0)
3530 ;; (= term-scroll-end term-height))))
3531 ;; (set-marker term-home-marker term-saved-home-marker)
3532 ;; (set-marker term-saved-home-marker nil)
3533 ;; (setq term-saved-home-marker nil)
3534 ;; (goto-char term-home-marker)))
3535 ;; (setq term-current-column nil)
3536 ;; (setq term-current-row 0)
3537 ;; (term-goto row col))))
3539 ;; Default value for the symbol term-command-hook.
3541 (defun term-command-hook (string)
3542 (cond ((equal string "")
3544 ((= (aref string 0) ?\032)
3545 ;; gdb (when invoked with -fullname) prints:
3546 ;; \032\032FULLFILENAME:LINENUMBER:CHARPOS:BEG_OR_MIDDLE:PC\n
3547 (let* ((first-colon (string-match ":" string 1))
3549 (string-match ":" string (1+ first-colon)))
3550 (filename (substring string 1 first-colon))
3551 (fileline (string-to-number
3552 (substring string (1+ first-colon) second-colon))))
3553 (setq term-pending-frame (cons filename fileline))))
3554 ((= (aref string 0) ?/)
3555 (cd (substring string 1)))
3556 ;; Allowing the inferior to call functions in Emacs is
3557 ;; probably too big a security hole.
3558 ;; ((= (aref string 0) ?!)
3559 ;; (eval (car (read-from-string string 1))))
3560 (t)));; Otherwise ignore it
3562 ;; Make sure the file named TRUE-FILE is in a buffer that appears on the screen
3563 ;; and that its line LINE is visible.
3564 ;; Put the overlay-arrow on the line LINE in that buffer.
3565 ;; This is mainly used by gdb.
3567 (defun term-display-line (true-file line)
3568 (term-display-buffer-line (find-file-noselect true-file) line))
3570 (defun term-display-buffer-line (buffer line)
3571 (let* ((window (display-buffer buffer t))
3573 (with-current-buffer buffer
3576 (goto-char (point-min))
3577 (forward-line (1- line))
3579 (setq overlay-arrow-string "=>")
3580 (or overlay-arrow-position
3581 (setq overlay-arrow-position (make-marker)))
3582 (set-marker overlay-arrow-position (point) (current-buffer)))
3583 (cond ((or (< pos (point-min)) (> pos (point-max)))
3586 (set-window-point window overlay-arrow-position)))
3588 ;; The buffer-local marker term-home-marker defines the "home position"
3589 ;; (in terms of cursor motion). However, we move the term-home-marker
3590 ;; "down" as needed so that is no more that a window-full above (point-max).
3592 (defun term-goto-home ()
3593 (term-handle-deferred-scroll)
3594 (goto-char term-home-marker)
3595 (setq term-current-row 0)
3596 (setq term-current-column (current-column))
3597 (setq term-start-line-column term-current-column))
3599 (defun term-goto (row col)
3600 (term-handle-deferred-scroll)
3601 (cond ((and term-current-row (>= row term-current-row))
3602 ;; I assume this is a worthwhile optimization.
3603 (term-vertical-motion 0)
3604 (setq term-current-column term-start-line-column)
3605 (setq row (- row term-current-row)))
3609 (term-move-columns col))
3611 ;; The page is full, so enter "pager" mode, and wait for input.
3613 (defun term-process-pager ()
3614 ;; (let ((process (get-buffer-process (current-buffer))))
3615 ;; (stop-process process))
3616 (setq term-pager-old-local-map (current-local-map))
3617 (use-local-map term-pager-break-map)
3618 (easy-menu-add term-terminal-menu)
3619 (easy-menu-add term-signals-menu)
3620 (easy-menu-add term-pager-menu)
3621 (make-local-variable 'term-old-mode-line-format)
3622 (setq term-old-mode-line-format mode-line-format)
3623 (setq mode-line-format
3624 (list "-- **MORE** "
3625 mode-line-buffer-identification
3626 " [Type ? for help] "
3628 (force-mode-line-update))
3630 (defun term-pager-line (lines)
3632 (let* ((moved (vertical-motion (1+ lines)))
3633 (deficit (- lines moved)))
3634 (when (> moved lines)
3636 (cond ((<= deficit 0) ;; OK, had enough in the buffer for request.
3637 (recenter (1- term-height)))
3638 ((term-pager-continue deficit)))))
3640 (defun term-pager-page (arg)
3641 "Proceed past the **MORE** break, allowing the next page of output to appear."
3643 (term-pager-line (* arg term-height)))
3645 ;; Pager mode command to go to beginning of buffer.
3646 (defun term-pager-bob ()
3648 (goto-char (point-min))
3649 (when (= (vertical-motion term-height) term-height)
3651 (recenter (1- term-height)))
3653 ;; Pager mode command to go to end of buffer.
3654 (defun term-pager-eob ()
3656 (goto-char term-home-marker)
3658 (goto-char (process-mark (get-buffer-process (current-buffer)))))
3660 (defun term-pager-back-line (lines)
3662 (vertical-motion (- 1 lines))
3666 ;; Move cursor to end of window.
3667 (vertical-motion term-height)
3669 (recenter (1- term-height)))
3671 (defun term-pager-back-page (arg)
3673 (term-pager-back-line (* arg term-height)))
3675 (defun term-pager-discard ()
3677 (setq term-terminal-parameter "")
3678 (interrupt-process nil t)
3679 (term-pager-continue term-height))
3681 ;; Disable pager processing.
3682 ;; Only callable while in pager mode. (Contrast term-disable-pager.)
3683 (defun term-pager-disable ()
3685 (if (term-handling-pager)
3686 (term-pager-continue nil)
3687 (setq term-pager-count nil))
3688 (term-update-mode-line))
3690 ;; Enable pager processing.
3691 (defun term-pager-enable ()
3693 (or (term-pager-enabled)
3694 (setq term-pager-count 0)) ;; Or maybe set to (term-current-row) ??
3695 (term-update-mode-line))
3697 (defun term-pager-toggle ()
3699 (if (term-pager-enabled) (term-pager-disable) (term-pager-enable)))
3701 (defun term-pager-help ()
3702 "Provide help on commands available in a terminal-emulator **MORE** break."
3704 (message "Terminal-emulator pager break help...")
3707 (function (lambda ()
3708 (princ (substitute-command-keys
3709 "\\<term-pager-break-map>\
3710 Terminal-emulator MORE break.\n\
3711 Type one of the following keys:\n\n\
3712 \\[term-pager-page]\t\tMove forward one page.\n\
3713 \\[term-pager-line]\t\tMove forward one line.\n\
3714 \\[universal-argument] N \\[term-pager-page]\tMove N pages forward.\n\
3715 \\[universal-argument] N \\[term-pager-line]\tMove N lines forward.\n\
3716 \\[universal-argument] N \\[term-pager-back-line]\tMove N lines back.\n\
3717 \\[universal-argument] N \\[term-pager-back-page]\t\tMove N pages back.\n\
3718 \\[term-pager-bob]\t\tMove to the beginning of the buffer.\n\
3719 \\[term-pager-eob]\t\tMove to the end of the buffer.\n\
3720 \\[term-pager-discard]\t\tKill pending output and kill process.\n\
3721 \\[term-pager-disable]\t\tDisable PAGER handling.\n\n\
3722 \\{term-pager-break-map}\n\
3723 Any other key is passed through to the program
3724 running under the terminal emulator and disables pager processing until
3725 all pending output has been dealt with."))
3728 (defun term-pager-continue (new-count)
3729 (let ((process (get-buffer-process (current-buffer))))
3730 (use-local-map term-pager-old-local-map)
3731 (setq term-pager-old-local-map nil)
3732 (setq mode-line-format term-old-mode-line-format)
3733 (force-mode-line-update)
3734 (setq term-pager-count new-count)
3735 (set-process-filter process term-pager-old-filter)
3736 (funcall term-pager-old-filter process "")
3737 (continue-process process)))
3739 ;; Make sure there are DOWN blank lines below the current one.
3740 ;; Return 0 if we're unable (because of PAGER handling), else return DOWN.
3742 (defun term-handle-scroll (down)
3743 (let ((scroll-needed
3744 (- (+ (term-current-row) down)
3745 (if (< down 0) term-scroll-start term-scroll-end))))
3746 (when (or (and (< down 0) (< scroll-needed 0))
3747 (and (> down 0) (> scroll-needed 0)))
3748 (let ((save-point (point-marker)) (save-top))
3749 (goto-char term-home-marker)
3750 (cond (term-scroll-with-delete
3753 ;; Delete scroll-needed lines at term-scroll-end,
3754 ;; then insert scroll-needed lines.
3755 (term-vertical-motion term-scroll-end)
3757 (setq save-top (point))
3758 (term-vertical-motion scroll-needed)
3760 (delete-region save-top (point))
3761 (goto-char save-point)
3762 (setq down (- scroll-needed down))
3763 (term-vertical-motion down))
3764 ;; Delete scroll-needed lines at term-scroll-start.
3765 (term-vertical-motion term-scroll-start)
3766 (setq save-top (point))
3767 (term-vertical-motion scroll-needed)
3768 (delete-region save-top (point))
3769 (goto-char save-point)
3770 (term-vertical-motion down)
3771 (term-adjust-current-row-cache (- scroll-needed)))
3772 (setq term-current-column nil)
3773 (term-insert-char ?\n (abs scroll-needed)))
3774 ((and (numberp term-pager-count)
3775 (< (setq term-pager-count (- term-pager-count down))
3778 (term-process-pager))
3780 (term-adjust-current-row-cache (- scroll-needed))
3781 (term-vertical-motion scroll-needed)
3782 (set-marker term-home-marker (point))))
3783 (goto-char save-point)
3784 (set-marker save-point nil))))
3787 (defun term-down (down &optional check-for-scroll)
3788 "Move down DOWN screen lines vertically."
3789 (let ((start-column (term-horizontal-column)))
3790 (when (and check-for-scroll (or term-scroll-with-delete term-pager-count))
3791 (setq down (term-handle-scroll down)))
3792 (unless (and (= (term-current-row) 0) (< down 0))
3793 (term-adjust-current-row-cache down)
3794 (when (or (/= (point) (point-max)) (< down 0))
3795 (setq down (- down (term-vertical-motion down)))))
3797 ;; Extend buffer with extra blank lines if needed.
3798 (term-insert-char ?\n down)
3799 (setq term-current-column 0)
3800 (setq term-start-line-column 0))
3802 (when (= (term-current-row) 0)
3803 ;; Insert lines if at the beginning.
3804 (save-excursion (term-insert-char ?\n (- down)))
3807 ;; Delete lines from the end.
3808 (forward-line term-height)
3810 (forward-line (- down))
3811 (delete-region p (point)))))
3812 (setq term-current-column 0)
3813 (setq term-start-line-column (current-column))))
3815 (term-move-columns start-column))))
3817 ;; Assuming point is at the beginning of a screen line,
3818 ;; if the line above point wraps around, add a ?\n to undo the wrapping.
3819 ;; FIXME: Probably should be called more than it is.
3820 (defun term-unwrap-line ()
3821 (when (not (bolp)) (insert-before-markers ?\n)))
3823 (defun term-erase-in-line (kind)
3824 (when (= kind 1) ;; erase left of point
3825 (let ((cols (term-horizontal-column)) (saved-point (point)))
3826 (term-vertical-motion 0)
3827 (delete-region (point) saved-point)
3828 (term-insert-char ? cols)))
3829 (when (not (eq kind 1)) ;; erase right of point
3830 (let ((saved-point (point))
3831 (wrapped (and (zerop (term-horizontal-column))
3832 (not (zerop (term-current-column))))))
3833 (term-vertical-motion 1)
3834 (delete-region saved-point (point))
3835 ;; wrapped is true if we're at the beginning of screen line,
3836 ;; but not a buffer line. If we delete the current screen line
3837 ;; that will make the previous line no longer wrap, and (because
3838 ;; of the way Emacs display works) point will be at the end of
3839 ;; the previous screen line rather then the beginning of the
3840 ;; current one. To avoid that, we make sure that current line
3841 ;; contain a space, to force the previous line to continue to wrap.
3842 ;; We could do this always, but it seems preferable to not add the
3843 ;; extra space when wrapped is false.
3847 (put-text-property saved-point (point) 'font-lock-face 'default)
3848 (goto-char saved-point))))
3850 (defun term-erase-in-display (kind)
3851 "Erase (that is blank out) part of the window.
3852 If KIND is 0, erase from (point) to (point-max);
3853 if KIND is 1, erase from home to point; else erase from home to point-max."
3854 (term-handle-deferred-scroll)
3855 (cond ((eq term-terminal-parameter 0)
3856 (let ((need-unwrap (bolp)))
3857 (delete-region (point) (point-max))
3858 (when need-unwrap (term-unwrap-line))))
3859 ((let ((row (term-current-row))
3860 (col (term-horizontal-column))
3861 (start-region term-home-marker)
3862 (end-region (if (eq kind 1) (point) (point-max))))
3863 (delete-region start-region end-region)
3866 (term-insert-char ?\n row))
3867 (setq term-current-column nil)
3868 (setq term-current-row nil)
3869 (term-goto row col)))))
3871 (defun term-delete-chars (count)
3872 (let ((save-point (point)))
3873 (term-vertical-motion 1)
3875 (goto-char save-point)
3876 (move-to-column (+ (term-current-column) count) t)
3877 (delete-region save-point (point))))
3879 ;; Insert COUNT spaces after point, but do not change any of
3880 ;; following screen lines. Hence we may have to delete characters
3881 ;; at the end of this screen line to make room.
3883 (defun term-insert-spaces (count)
3884 (let ((save-point (point)) (save-eol) (pnt-at-eol))
3885 (term-vertical-motion 1)
3888 (setq save-eol (point)
3889 pnt-at-eol (line-end-position))
3890 (move-to-column (+ (term-start-line-column) (- term-width count)) t)
3891 ;; If move-to-column extends the current line it will use the face
3892 ;; from the last character on the line, set the face for the chars
3894 (when (>= (point) pnt-at-eol)
3895 (put-text-property pnt-at-eol (point) 'font-lock-face 'default))
3896 (when (> save-eol (point))
3897 (delete-region (point) save-eol))
3898 (goto-char save-point)
3899 (term-insert-char ? count)
3900 (goto-char save-point)))
3902 (defun term-delete-lines (lines)
3903 (let ((start (point))
3904 (save-current-column term-current-column)
3905 (save-start-line-column term-start-line-column)
3906 (save-current-row (term-current-row)))
3907 ;; The number of inserted lines shouldn't exceed the scroll region end.
3908 ;; The `term-scroll-end' line is part of the scrolling region, so
3909 ;; we need to go one line past it in order to ensure correct
3911 (when (> (+ save-current-row lines) (1+ term-scroll-end))
3912 (setq lines (- lines (- (+ save-current-row lines) (1+ term-scroll-end)))))
3914 (delete-region start (point))
3915 (term-down (- (1+ term-scroll-end) save-current-row lines))
3916 (term-insert-char ?\n lines)
3917 (setq term-current-column save-current-column)
3918 (setq term-start-line-column save-start-line-column)
3919 (setq term-current-row save-current-row)
3922 (defun term-insert-lines (lines)
3923 (let ((start (point))
3925 (save-current-column term-current-column)
3926 (save-start-line-column term-start-line-column)
3927 (save-current-row (term-current-row)))
3928 ;; Inserting lines should take into account the scroll region.
3929 ;; The `term-scroll-end' line is part of the scrolling region, so
3930 ;; we need to go one line past it in order to ensure correct
3932 (if (< save-current-row term-scroll-start)
3933 ;; If point is before scroll start,
3935 (setq lines (- lines (- term-scroll-start save-current-row)))
3936 (term-down (- term-scroll-start save-current-row))
3937 (setq start (point)))
3938 ;; The number of inserted lines shouldn't exceed the scroll region end.
3939 (when (> (+ save-current-row lines) (1+ term-scroll-end))
3940 (setq lines (- lines (- (+ save-current-row lines)(1+ term-scroll-end)))))
3941 (term-down (- (1+ term-scroll-end) save-current-row lines)))
3942 (setq start-deleted (point))
3944 (delete-region start-deleted (point))
3946 (setq term-current-column save-current-column)
3947 (setq term-start-line-column save-start-line-column)
3948 (setq term-current-row save-current-row)
3949 (term-insert-char ?\n lines)
3952 (defun term-start-output-log (name)
3953 "Record raw inferior process output in a buffer."
3954 (interactive (list (if term-log-buffer
3956 (read-buffer "Record output in buffer: "
3957 (format "%s output-log"
3958 (buffer-name (current-buffer)))
3960 (if (or (null name) (equal name ""))
3961 (progn (setq term-log-buffer nil)
3962 (message "Output logging off."))
3963 (if (get-buffer name)
3965 (with-current-buffer (get-buffer-create name)
3967 (buffer-disable-undo (current-buffer))
3969 (setq term-log-buffer (get-buffer name))
3970 (message "Recording terminal emulator output into buffer \"%s\""
3971 (buffer-name term-log-buffer))))
3973 (defun term-stop-output-log ()
3974 "Discontinue raw inferior process logging."
3976 (term-start-output-log nil))
3978 (defun term-show-maximum-output ()
3979 "Put the end of the buffer at the bottom of the window."
3981 (goto-char (point-max))
3984 ;;; Do the user's customization...
3986 (defvar term-load-hook nil
3987 "This hook is run when term is loaded in.
3988 This is a good place to put keybindings.")
3990 (run-hooks 'term-load-hook)
3993 ;;; Filename/command/history completion in a buffer
3994 ;; ===========================================================================
3995 ;; Useful completion functions, courtesy of the Ergo group.
3998 ;; term-dynamic-complete Complete or expand command, filename,
3999 ;; history at point.
4000 ;; term-dynamic-complete-filename Complete filename at point.
4001 ;; term-dynamic-list-filename-completions List completions in help buffer.
4002 ;; term-replace-by-expanded-filename Expand and complete filename at point;
4003 ;; replace with expanded/completed name.
4005 ;; These are not installed in the term-mode keymap. But they are
4006 ;; available for people who want them. Shell-mode installs them:
4007 ;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
4008 ;; (define-key shell-mode-map "\M-?"
4009 ;; 'term-dynamic-list-filename-completions)))
4011 ;; Commands like this are fine things to put in load hooks if you
4012 ;; want them present in specific modes.
4014 (defcustom term-completion-autolist nil
4015 "If non-nil, automatically list possibilities on partial completion.
4016 This mirrors the optional behavior of tcsh."
4020 (defcustom term-completion-addsuffix t
4021 "If non-nil, add a `/' to completed directories, ` ' to file names.
4022 If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
4023 DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact
4024 completion. This mirrors the optional behavior of tcsh."
4026 :type '(choice (const :tag "No suffix" nil)
4027 (cons (string :tag "dirsuffix") (string :tag "filesuffix"))
4028 (other :tag "Suffix" t)))
4030 (defcustom term-completion-recexact nil
4031 "If non-nil, use shortest completion if characters cannot be added.
4032 This mirrors the optional behavior of tcsh.
4034 A non-nil value is useful if `term-completion-autolist' is non-nil too."
4038 (defcustom term-completion-fignore nil
4039 "List of suffixes to be disregarded during file completion.
4040 This mirrors the optional behavior of bash and tcsh.
4042 Note that this applies to `term-dynamic-complete-filename' only."
4044 :type '(choice (const nil)
4045 (repeat :tag "List of suffixes" string)))
4047 (defvar term-file-name-prefix ""
4048 "Prefix prepended to absolute file names taken from process input.
4049 This is used by term's and shell's completion functions, and by shell's
4050 directory tracking functions.")
4053 (defun term-directory (directory)
4054 ;; Return expanded DIRECTORY, with `term-file-name-prefix' if absolute.
4055 (expand-file-name (if (file-name-absolute-p directory)
4056 (concat term-file-name-prefix directory)
4060 (defun term-word (word-chars)
4061 "Return the word of WORD-CHARS at point, or nil if none is found.
4062 Word constituents are considered to be those in WORD-CHARS, which is like the
4063 inside of a \"[...]\" (see `skip-chars-forward')."
4065 (let ((limit (point))
4066 (word (concat "[" word-chars "]"))
4067 (non-word (concat "[^" word-chars "]")))
4068 (when (re-search-backward non-word nil 'move)
4070 ;; Anchor the search forwards.
4071 (if (or (eolp) (looking-at non-word))
4073 (re-search-forward (concat word "+") limit)
4074 (buffer-substring (match-beginning 0) (match-end 0))))))
4077 (defun term-match-partial-filename ()
4078 "Return the filename at point, or nil if none is found.
4079 Environment variables are substituted. See `term-word'."
4080 (let ((filename (term-word "~/A-Za-z0-9+@:_.$#,={}-")))
4081 (and filename (substitute-in-file-name filename))))
4084 (defun term-dynamic-complete ()
4085 "Dynamically perform completion at point.
4086 Calls the functions in `term-dynamic-complete-functions' to perform
4087 completion until a function returns non-nil, at which point completion is
4088 assumed to have occurred."
4090 (let ((functions term-dynamic-complete-functions))
4091 (while (and functions (null (funcall (car functions))))
4092 (setq functions (cdr functions)))))
4095 (defun term-dynamic-complete-filename ()
4096 "Dynamically complete the filename at point.
4097 Completes if after a filename. See `term-match-partial-filename' and
4098 `term-dynamic-complete-as-filename'.
4099 This function is similar to `term-replace-by-expanded-filename', except that
4100 it won't change parts of the filename already entered in the buffer; it just
4101 adds completion characters to the end of the filename. A completions listing
4102 may be shown in a help buffer if completion is ambiguous.
4104 Completion is dependent on the value of `term-completion-addsuffix',
4105 `term-completion-recexact' and `term-completion-fignore', and the timing of
4106 completions listing is dependent on the value of `term-completion-autolist'.
4108 Returns t if successful."
4110 (when (term-match-partial-filename)
4111 (prog2 (or (eq (selected-window) (minibuffer-window))
4112 (message "Completing file name..."))
4113 (term-dynamic-complete-as-filename))))
4115 (defun term-dynamic-complete-as-filename ()
4116 "Dynamically complete at point as a filename.
4117 See `term-dynamic-complete-filename'. Returns t if successful."
4118 (let* ((completion-ignore-case nil)
4119 (completion-ignored-extensions term-completion-fignore)
4121 (dirsuffix (cond ((not term-completion-addsuffix) "")
4122 ((not (consp term-completion-addsuffix)) "/")
4123 (t (car term-completion-addsuffix))))
4124 (filesuffix (cond ((not term-completion-addsuffix) "")
4125 ((not (consp term-completion-addsuffix)) " ")
4126 (t (cdr term-completion-addsuffix))))
4127 (filename (or (term-match-partial-filename) ""))
4128 (pathdir (file-name-directory filename))
4129 (pathnondir (file-name-nondirectory filename))
4130 (directory (if pathdir (term-directory pathdir) default-directory))
4131 (completion (file-name-completion pathnondir directory))
4132 (mini-flag (eq (selected-window) (minibuffer-window))))
4133 (cond ((null completion)
4134 (message "No completions of %s" filename)
4136 ((eq completion t) ; Means already completed "file".
4137 (when term-completion-addsuffix (insert " "))
4138 (or mini-flag (message "Sole completion")))
4139 ((string-equal completion "") ; Means completion on "directory/".
4140 (term-dynamic-list-filename-completions))
4141 (t ; Completion string returned.
4142 (let ((file (concat (file-name-as-directory directory) completion)))
4143 (insert (substring (directory-file-name completion)
4144 (length pathnondir)))
4145 (cond ((symbolp (file-name-completion completion directory))
4146 ;; We inserted a unique completion.
4147 (insert (if (file-directory-p file) dirsuffix filesuffix))
4148 (or mini-flag (message "Completed")))
4149 ((and term-completion-recexact term-completion-addsuffix
4150 (string-equal pathnondir completion)
4151 (file-exists-p file))
4152 ;; It's not unique, but user wants shortest match.
4153 (insert (if (file-directory-p file) dirsuffix filesuffix))
4154 (or mini-flag (message "Completed shortest")))
4155 ((or term-completion-autolist
4156 (string-equal pathnondir completion))
4157 ;; It's not unique, list possible completions.
4158 (term-dynamic-list-filename-completions))
4160 (or mini-flag (message "Partially completed")))))))
4164 (defun term-replace-by-expanded-filename ()
4165 "Dynamically expand and complete the filename at point.
4166 Replace the filename with an expanded, canonicalized and completed replacement.
4167 \"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
4168 with the corresponding directories. \"Canonicalized\" means `..' and `.' are
4169 removed, and the filename is made absolute instead of relative. For expansion
4170 see `expand-file-name' and `substitute-in-file-name'. For completion see
4171 `term-dynamic-complete-filename'."
4173 (replace-match (expand-file-name (term-match-partial-filename)) t t)
4174 (term-dynamic-complete-filename))
4177 (defun term-dynamic-simple-complete (stub candidates)
4178 "Dynamically complete STUB from CANDIDATES list.
4179 This function inserts completion characters at point by completing STUB from
4180 the strings in CANDIDATES. A completions listing may be shown in a help buffer
4181 if completion is ambiguous.
4183 Returns nil if no completion was inserted.
4184 Returns `sole' if completed with the only completion match.
4185 Returns `shortest' if completed with the shortest of the completion matches.
4186 Returns `partial' if completed as far as possible with the completion matches.
4187 Returns `listed' if a completion listing was shown.
4189 See also `term-dynamic-complete-filename'."
4190 (declare (obsolete completion-in-region "23.2"))
4191 (let* ((completion-ignore-case nil)
4192 (candidates (mapcar (function (lambda (x) (list x))) candidates))
4193 (completions (all-completions stub candidates)))
4194 (cond ((null completions)
4195 (message "No completions of %s" stub)
4197 ((= 1 (length completions)) ; Gotcha!
4198 (let ((completion (car completions)))
4199 (if (string-equal completion stub)
4200 (message "Sole completion")
4201 (insert (substring completion (length stub)))
4202 (message "Completed"))
4203 (when term-completion-addsuffix (insert " "))
4205 (t ; There's no unique completion.
4206 (let ((completion (try-completion stub candidates)))
4207 ;; Insert the longest substring.
4208 (insert (substring completion (length stub)))
4209 (cond ((and term-completion-recexact term-completion-addsuffix
4210 (string-equal stub completion)
4211 (member completion completions))
4212 ;; It's not unique, but user wants shortest match.
4214 (message "Completed shortest")
4216 ((or term-completion-autolist
4217 (string-equal stub completion))
4218 ;; It's not unique, list possible completions.
4219 (term-dynamic-list-completions completions)
4222 (message "Partially completed")
4225 (defun term-dynamic-list-filename-completions ()
4226 "List in help buffer possible completions of the filename at point."
4228 (let* ((completion-ignore-case nil)
4229 (filename (or (term-match-partial-filename) ""))
4230 (pathdir (file-name-directory filename))
4231 (pathnondir (file-name-nondirectory filename))
4232 (directory (if pathdir (term-directory pathdir) default-directory))
4233 (completions (file-name-all-completions pathnondir directory)))
4235 (term-dynamic-list-completions completions)
4236 (message "No completions of %s" filename))))
4239 (defun term-dynamic-list-completions (completions)
4240 "List in help buffer sorted COMPLETIONS.
4241 Typing SPC flushes the help buffer."
4242 (let ((conf (current-window-configuration)))
4243 (with-output-to-temp-buffer "*Completions*"
4244 (display-completion-list (sort completions 'string-lessp)))
4245 (message "Hit space to flush")
4247 (if (with-current-buffer (get-buffer "*Completions*")
4248 (setq key (read-key-sequence nil)
4251 (eq (window-buffer (posn-window (event-start first)))
4252 (get-buffer "*Completions*"))
4253 (memq (key-binding key)
4254 '(mouse-choose-completion choose-completion))))
4255 ;; If the user does choose-completion with the mouse,
4256 ;; execute the command, then delete the completion window.
4258 (choose-completion first)
4259 (set-window-configuration conf))
4261 (set-window-configuration conf)
4262 (setq unread-command-events
4263 (nconc (listify-key-sequence key)
4264 unread-command-events)))))))
4266 ;; I need a make-term that doesn't surround with *s -mm
4267 (defun term-ansi-make-term (name program &optional startfile &rest switches)
4268 "Make a term process NAME in a buffer, running PROGRAM.
4269 The name of the buffer is NAME.
4270 If there is already a running process in that buffer, it is not restarted.
4271 Optional third arg STARTFILE is the name of a file to send the contents of to
4272 the process. Any more args are arguments to PROGRAM."
4273 (let ((buffer (get-buffer-create name )))
4274 ;; If no process, or nuked process, crank up a new one and put buffer in
4275 ;; term mode. Otherwise, leave buffer and existing process alone.
4276 (cond ((not (term-check-proc buffer))
4277 (with-current-buffer buffer
4278 (term-mode)) ; Install local vars, mode, keymap, ...
4279 (term-exec buffer name program startfile switches)))
4282 (defvar term-ansi-buffer-name nil)
4283 (defvar term-ansi-default-program nil)
4284 (defvar term-ansi-buffer-base-name nil)
4287 (defun ansi-term (program &optional new-buffer-name)
4288 "Start a terminal-emulator in a new buffer.
4289 This is almost the same as `term' apart from always creating a new buffer,
4290 and `C-x' being marked as a `term-escape-char'. "
4291 (interactive (list (read-from-minibuffer "Run program: "
4292 (or explicit-shell-file-name
4296 ;; Pick the name of the new buffer.
4297 (setq term-ansi-buffer-name
4300 (if term-ansi-buffer-base-name
4301 (if (eq term-ansi-buffer-base-name t)
4302 (file-name-nondirectory program)
4303 term-ansi-buffer-base-name)
4306 (setq term-ansi-buffer-name (concat "*" term-ansi-buffer-name "*"))
4308 ;; In order to have more than one term active at a time
4309 ;; I'd like to have the term names have the *term-ansi-term<?>* form,
4310 ;; for now they have the *term-ansi-term*<?> form but we'll see...
4312 (setq term-ansi-buffer-name (generate-new-buffer-name term-ansi-buffer-name))
4313 (setq term-ansi-buffer-name (term-ansi-make-term term-ansi-buffer-name program))
4315 (set-buffer term-ansi-buffer-name)
4319 ;; Historical baggage. A call to term-set-escape-char used to not
4320 ;; undo any previous call to t-s-e-c. Because of this, ansi-term
4321 ;; ended up with both C-x and C-c as escape chars. Who knows what
4322 ;; the original intention was, but people could have become used to
4323 ;; either. (Bug#12842)
4324 (let (term-escape-char)
4325 ;; I wanna have find-file on C-x C-f -mm
4326 ;; your mileage may definitely vary, maybe it's better to put this in your
4328 (term-set-escape-char ?\C-x))
4330 (switch-to-buffer term-ansi-buffer-name))
4333 ;;; Serial terminals
4334 ;; ===========================================================================
4335 (defun serial-port-is-file-p ()
4336 "Guess whether serial ports are files on this system.
4337 Return t if this is a Unix-based system, where serial ports are
4338 files, such as /dev/ttyS0.
4339 Return nil if this is Windows or DOS, where serial ports have
4340 special identifiers such as COM1."
4341 (not (memq system-type '(windows-nt cygwin ms-dos))))
4343 (defvar serial-name-history
4344 (if (serial-port-is-file-p)
4345 (or (when (file-exists-p "/dev/ttys0") (list "/dev/ttys0"))
4346 (when (file-exists-p "/dev/ttyS0") (list "/dev/ttyS0")))
4348 "History of serial ports used by `serial-read-name'.")
4350 (defvar serial-speed-history
4351 ;; Initialized with reasonable values for newbies.
4352 (list "9600" ;; Given twice because 9600 b/s is the most common speed
4353 "1200" "2400" "4800" "9600" "14400" "19200"
4354 "28800" "38400" "57600" "115200")
4355 "History of serial port speeds used by `serial-read-speed'.")
4357 (defun serial-nice-speed-history ()
4358 "Return `serial-speed-history' cleaned up for a mouse-menu."
4362 (copy-sequence serial-speed-history)
4363 (lambda (a b) (when (and (stringp a) (stringp b))
4364 (> (string-to-number a) (string-to-number b))))))
4365 (dolist (i x) (when (not (equal i (car y))) (push i y)))
4368 (defconst serial-no-speed "nil"
4369 "String for `serial-read-speed' for special serial ports.
4370 If `serial-read-speed' reads this string from the user, it
4371 returns nil, which is recognized by `serial-process-configure'
4372 for special serial ports that cannot be configured.")
4374 (defun serial-supported-or-barf ()
4375 "Signal an error if serial processes are not supported."
4376 (unless (fboundp 'make-serial-process)
4377 (error "Serial processes are not supported on this system")))
4379 (defun serial-read-name ()
4380 "Read a serial port name from the user.
4381 Try to be nice by providing useful defaults and history.
4382 On Windows, prepend \\.\ to the port name unless it already
4383 contains a backslash. This handles the legacy ports COM1-COM9 as
4384 well as the newer ports COM10 and higher."
4385 (serial-supported-or-barf)
4386 (let* ((file-name-history serial-name-history)
4387 (h (car file-name-history))
4388 (x (if (serial-port-is-file-p)
4390 ;; `prompt': The most recently used port is provided as
4391 ;; the default value, which is used when the user
4392 ;; simply presses return.
4393 (if (stringp h) (format "Serial port (default %s): " h)
4395 ;; `directory': Most systems have their serial ports
4396 ;; in the same directory, so start in the directory
4397 ;; of the most recently used port, or in a reasonable
4398 ;; default directory.
4399 (or (and h (file-name-directory h))
4400 (and (file-exists-p "/dev/") "/dev/")
4401 (and (file-exists-p "/") "/"))
4402 ;; `default': This causes (read-file-name) to return
4403 ;; the empty string if he user simply presses return.
4404 ;; Using nil here may result in a default directory
4405 ;; of the current buffer, which is not useful for
4408 (read-from-minibuffer
4409 (if (stringp h) (format "Serial port (default %s): " h)
4411 nil nil nil '(file-name-history . 1) nil nil))))
4412 (if (or (null x) (and (stringp x) (zerop (length x))))
4414 (setq serial-name-history file-name-history))
4415 (when (or (null x) (and (stringp x) (zerop (length x))))
4416 (error "No serial port selected"))
4417 (when (and (not (serial-port-is-file-p))
4418 (not (string-match "\\\\" x)))
4419 (set 'x (concat "\\\\.\\" x)))
4422 (defun serial-read-speed ()
4423 "Read a serial port speed (in bits per second) from the user.
4424 Try to be nice by providing useful defaults and history."
4425 (serial-supported-or-barf)
4426 (let* ((history serial-speed-history)
4428 (x (read-from-minibuffer
4429 (cond ((string= h serial-no-speed)
4430 "Speed (default nil = set by port): ")
4432 (format "Speed (default %s b/s): " h))
4434 (format "Speed (b/s): ")))
4435 nil nil nil '(history . 1) nil nil)))
4436 (when (or (null x) (and (stringp x) (zerop (length x))))
4438 (when (or (null x) (not (stringp x)) (zerop (length x)))
4439 (error "Invalid speed"))
4440 (if (string= x serial-no-speed)
4442 (setq x (string-to-number x))
4443 (when (or (null x) (not (integerp x)) (<= x 0))
4444 (error "Invalid speed")))
4445 (setq serial-speed-history history)
4449 (defun serial-term (port speed)
4450 "Start a terminal-emulator for a serial port in a new buffer.
4451 PORT is the path or name of the serial port. For example, this
4452 could be \"/dev/ttyS0\" on Unix. On Windows, this could be
4453 \"COM1\" or \"\\\\.\\COM10\".
4454 SPEED is the speed of the serial port in bits per second. 9600
4455 is a common value. SPEED can be nil, see
4456 `serial-process-configure' for details.
4457 The buffer is in Term mode; see `term-mode' for the commands to
4459 \\<term-raw-map>Type \\[switch-to-buffer] to switch to another buffer."
4460 (interactive (list (serial-read-name) (serial-read-speed)))
4461 (serial-supported-or-barf)
4462 (let* ((process (make-serial-process
4465 :coding 'no-conversion
4467 (buffer (process-buffer process)))
4468 (with-current-buffer buffer
4471 (goto-char (point-max))
4472 (set-marker (process-mark process) (point))
4473 (set-process-filter process 'term-emulate-terminal)
4474 (set-process-sentinel process 'term-sentinel))
4475 (switch-to-buffer buffer)
4478 (defvar serial-mode-line-speed-menu nil)
4479 (defvar serial-mode-line-config-menu nil)
4481 (defun serial-speed ()
4482 "Return the speed of the serial port of the current buffer's process.
4483 The return value may be nil for a special serial port."
4484 (process-contact (get-buffer-process (current-buffer)) :speed))
4486 (defun serial-mode-line-speed-menu-1 (event)
4488 (save-selected-window
4489 (select-window (posn-window (event-start event)))
4490 (serial-update-speed-menu)
4491 (let* ((selection (serial-mode-line-speed-menu event))
4492 (binding (and selection (lookup-key serial-mode-line-speed-menu
4493 (vector (car selection))))))
4494 (when binding (call-interactively binding)))))
4496 (defun serial-mode-line-speed-menu (event)
4497 (x-popup-menu event serial-mode-line-speed-menu))
4499 (defun serial-update-speed-menu ()
4500 (setq serial-mode-line-speed-menu (make-sparse-keymap "Speed (b/s)"))
4501 (define-key serial-mode-line-speed-menu [serial-mode-line-speed-menu-other]
4502 '(menu-item "Other..."
4503 (lambda (event) (interactive "e")
4504 (let ((speed (serial-read-speed)))
4505 (serial-process-configure :speed speed)
4506 (term-update-mode-line)
4507 (message "Speed set to %d b/s" speed)))))
4508 (dolist (str (serial-nice-speed-history))
4509 (let ((num (or (and (stringp str) (string-to-number str)) 0)))
4511 serial-mode-line-speed-menu
4512 (vector (make-symbol (format "serial-mode-line-speed-menu-%s" str)))
4515 (lambda (event) (interactive "e")
4516 (serial-process-configure :speed ,num)
4517 (term-update-mode-line)
4518 (message "Speed set to %d b/s" ,num))
4519 :button (:toggle . (= (serial-speed) ,num)))))))
4521 (defun serial-mode-line-config-menu-1 (event)
4523 (save-selected-window
4524 (select-window (posn-window (event-start event)))
4525 (serial-update-config-menu)
4526 (let* ((selection (serial-mode-line-config-menu event))
4527 (binding (and selection (lookup-key serial-mode-line-config-menu
4528 (vector (car selection))))))
4529 (when binding (call-interactively binding)))))
4531 (defun serial-mode-line-config-menu (event)
4532 (x-popup-menu event serial-mode-line-config-menu))
4534 (defun serial-update-config-menu ()
4535 (setq serial-mode-line-config-menu (make-sparse-keymap "Configuration"))
4536 (let ((config (process-contact
4537 (get-buffer-process (current-buffer)) t)))
4538 (dolist (y '((:flowcontrol hw "Hardware flowcontrol (RTS/CTS)")
4539 (:flowcontrol sw "Software flowcontrol (XON/XOFF)")
4540 (:flowcontrol nil "No flowcontrol")
4541 (:stopbits 2 "2 stopbits")
4542 (:stopbits 1 "1 stopbit")
4543 (:parity odd "Odd parity")
4544 (:parity even "Even parity")
4545 (:parity nil "No parity")
4546 (:bytesize 7 "7 bits per byte")
4547 (:bytesize 8 "8 bits per byte")))
4548 (define-key serial-mode-line-config-menu
4549 (vector (make-symbol (format "%s-%s" (nth 0 y) (nth 1 y))))
4552 (lambda (event) (interactive "e")
4553 (serial-process-configure ,(nth 0 y) ',(nth 1 y))
4554 (term-update-mode-line)
4555 (message "%s" ,(nth 2 y)))
4556 ;; Use :toggle instead of :radio because a non-standard port
4557 ;; configuration may not match any menu items.
4558 :button (:toggle . ,(equal (plist-get config (nth 0 y))
4562 ;;; Converting process modes to use term mode
4563 ;; ===========================================================================
4564 ;; Renaming variables
4565 ;; Most of the work is renaming variables and functions. These are the common
4568 ;; last-input-start term-last-input-start
4569 ;; last-input-end term-last-input-end
4570 ;; shell-prompt-pattern term-prompt-regexp
4571 ;; shell-set-directory-error-hook <no equivalent>
4573 ;; shell-set-directory <unnecessary>
4574 ;; shell-mode-map term-mode-map
4576 ;; shell-send-input term-send-input
4577 ;; shell-send-eof term-delchar-or-maybe-eof
4578 ;; kill-shell-input term-kill-input
4579 ;; interrupt-shell-subjob term-interrupt-subjob
4580 ;; stop-shell-subjob term-stop-subjob
4581 ;; quit-shell-subjob term-quit-subjob
4582 ;; kill-shell-subjob term-kill-subjob
4583 ;; kill-output-from-shell term-kill-output
4584 ;; show-output-from-shell term-show-output
4585 ;; copy-last-shell-input Use term-previous-input/term-next-input
4587 ;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
4588 ;; SHELL-DIRECTORY-TRACKER, the shell mode's term-input-filter-functions.
4589 ;; Term mode does not provide functionality equivalent to
4590 ;; shell-set-directory-error-hook; it is gone.
4592 ;; term-last-input-start is provided for modes which want to munge
4593 ;; the buffer after input is sent, perhaps because the inferior
4594 ;; insists on echoing the input. The LAST-INPUT-START variable in
4595 ;; the old shell package was used to implement a history mechanism,
4596 ;; but you should think twice before using term-last-input-start
4597 ;; for this; the input history ring often does the job better.
4599 ;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
4600 ;; *not* create the term-mode local variables in your foo-mode function.
4601 ;; This is not modular. Instead, call term-mode, and let *it* create the
4602 ;; necessary term-specific local variables. Then create the
4603 ;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
4604 ;; be foo-mode-map, and its mode to be foo-mode. Set the term-mode hooks
4605 ;; (term-{prompt-regexp, input-filter, input-filter-functions,
4606 ;; get-old-input) that need to be different from the defaults. Call
4607 ;; foo-mode-hook, and you're done. Don't run the term-mode hook yourself;
4608 ;; term-mode will take care of it. The following example, from shell.el,
4611 ;; (defvar shell-mode-map '())
4612 ;; (cond ((not shell-mode-map)
4613 ;; (setq shell-mode-map (copy-keymap term-mode-map))
4614 ;; (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
4615 ;; (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
4616 ;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
4617 ;; (define-key shell-mode-map "\M-?"
4618 ;; 'term-dynamic-list-filename-completions)))
4620 ;; (defun shell-mode ()
4623 ;; (setq term-prompt-regexp shell-prompt-pattern)
4624 ;; (setq major-mode 'shell-mode)
4625 ;; (setq mode-name "Shell")
4626 ;; (use-local-map shell-mode-map)
4627 ;; (make-local-variable 'shell-directory-stack)
4628 ;; (setq shell-directory-stack nil)
4629 ;; (add-hook 'term-input-filter-functions 'shell-directory-tracker)
4630 ;; (run-mode-hooks 'shell-mode-hook))
4633 ;; Completion for term-mode users
4635 ;; For modes that use term-mode, term-dynamic-complete-functions is the
4636 ;; hook to add completion functions to. Functions on this list should return
4637 ;; non-nil if completion occurs (i.e., further completion should not occur).
4638 ;; You could use completion-in-region to do the bulk of the
4643 ;;; term.el ends here