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