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