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