1 ;;; term.el --- general command interpreter in a window stuff
3 ;; Copyright (C) 1988, 1990, 1992, 1994-1995, 2001-2015 Free Software
6 ;; Author: Per Bothner <per@bothner.com>
7 ;; Maintainer: Dan Nicolaescu <dann@ics.uci.edu>, Per Bothner <per@bothner.com>
8 ;; Based on comint mode written by: Olin Shivers <shivers@cs.cmu.edu>
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; Fixes for CJK support by Yong Lu <lyongu@yahoo.com>.
29 ;; Dir/Hostname tracking and ANSI colorization by
30 ;; Marco Melgazzi <marco@techie.com>.
32 ;; To see what I've modified and where it came from search for '-mm'
36 ;; Speed considerations and a few caveats
37 ;; --------------------------------------
39 ;; While the message passing and the colorization surely introduce some
40 ;; overhead this has became so small that IMHO it is surely outweighed by
41 ;; the benefits you get but, as usual, YMMV.
43 ;; Important caveat, when deciding the cursor/'gray keys' keycodes I had to
44 ;; make a choice: on my Linux box this choice allows me to run all the
45 ;; ncurses applications without problems but make these keys
46 ;; incomprehensible to all the cursesX programs. Your mileage may vary so
47 ;; you may consider changing the default 'emulation'. Just search for this
48 ;; piece of code and modify it as you like:
50 ;; ;; Which would be better: "\e[A" or "\eOA"? readline accepts either.
51 ;; ;; For my configuration it's definitely better \eOA but YMMV. -mm
52 ;; ;; For example: vi works with \eOA while elm wants \e[A ...
53 ;; (defun term-send-up () (interactive) (term-send-raw-string "\eOA"))
54 ;; (defun term-send-down () (interactive) (term-send-raw-string "\eOB"))
55 ;; (defun term-send-right () (interactive) (term-send-raw-string "\eOC"))
56 ;; (defun term-send-left () (interactive) (term-send-raw-string "\eOD"))
59 ;; IMPORTANT: additions & changes
60 ;; ------------------------------
62 ;; With this enhanced ansi-term.el you will get a reliable mechanism of
63 ;; directory/username/host tracking: the only drawback is that you will
64 ;; have to modify your shell start-up script. It's worth it, believe me :).
66 ;; When you rlogin/su/telnet and the account you access has a modified
67 ;; startup script, you will be able to access the remote files as usual
68 ;; with C-x C-f, if it's needed you will have to enter a password,
69 ;; otherwise the file should get loaded straight away.
71 ;; This is useful even if you work only on one host: it often happens that,
72 ;; for maintenance reasons, you have to edit files 'as root': before
73 ;; patching term.el, I su-ed in a term.el buffer and used vi :), now I
74 ;; simply do a C-x C-f and, via ange-ftp, the file is automatically loaded
75 ;; 'as-root'. ( If you don't want to enter the root password every time you
76 ;; can put it in your .netrc: note that this is -not- advisable if you're
77 ;; connected to the internet or if somebody else works on your workstation!)
79 ;; If you use wu-ftpd you can use some of its features to avoid root ftp
80 ;; access to the rest of the world: just put in /etc/ftphosts something like
83 ;; allow root 127.0.0.1
85 ;; # By default nobody can't do anything
89 ;; ----------------------------------------
91 ;; If, instead of 'term', you call 'ansi-term', you get multiple term
92 ;; buffers, after every new call ansi-term opens a new *ansi-term*<xx> window,
93 ;; where <xx> is, as usual, a number...
95 ;; ----------------------------------------
97 ;; With the term-buffer-maximum-size you can finally decide how many
98 ;; scrollback lines to keep: its default is 2048 but you can change it as
101 ;; ----------------------------------------
104 ;; ANSI colorization should work well, I've decided to limit the interpreter
105 ;; to five outstanding commands (like ESC [ 01;04;32;41;07m.
106 ;; You shouldn't need more, if you do, tell me and I'll increase it. It's
107 ;; so easy you could do it yourself...
109 ;; Blink, is not supported. Currently it's mapped as bold.
111 ;; ----------------------------------------
113 ;; If you'd like to check out my complete configuration, you can download
114 ;; it from http://www.polito.it/~s64912/things.html, it's ~500k in size and
115 ;; contains my .cshrc, .emacs and my whole site-lisp subdirectory. (notice
116 ;; that this term.el may be newer/older than the one in there, please
119 ;; This complete configuration contains, among other things, a complete
120 ;; rectangular marking solution (based on rect-mark.el and
121 ;; pc-bindings.el) and should be a good example of how extensively Emacs
122 ;; can be configured on a ppp-connected ws.
124 ;; ----------------------------------------
128 ;; - Add hooks to allow raw-mode keys to be configurable
129 ;; - Which keys are better ? \eOA or \e[A ?
136 ;; - Huge reworking of the faces code: now we only have roughly 20-30
137 ;; faces for everything so we're even faster than the old md-term.el !
138 ;; - Finished removing all the J-Shell code.
142 ;; - Now all the supportable ANSI commands work well.
143 ;; - Reworked a little the code: much less jsh-inspired stuff
147 ;; - Now all the faces are accessed through an array: much cleaner code.
149 ;; V2.2 November 4 1996
151 ;; - Implemented ANSI output colorization ( a bit rough but enough for
154 ;; - Implemented a maximum limit for the scroll buffer (stolen from
157 ;; v2.1 October 28 1996, first public release
159 ;; - Some new keybindings for term-char mode ( notably home/end/...)
160 ;; - Directory, hostname and username tracking via ange-ftp
161 ;; - Multi-term capability via the ansi-term call
163 ;; ----------------------------------------------------------------
164 ;; You should/could have something like this in your .emacs to take
165 ;; full advantage of this package
167 ;; (add-hook 'term-mode-hook
170 ;; (setq term-prompt-regexp "^[^#$%>\n]*[#$%>] *")
171 ;; (setq-local mouse-yank-at-point t)
172 ;; (setq-local transient-mark-mode nil)
173 ;; (auto-fill-mode -1)
174 ;; (setq tab-width 8 ))))
177 ;; ----------------------------------------
179 ;; If you want to use color ls the best setup is to have a different file
180 ;; when you use eterm ( see above, mine is named .emacs_dircolors ). This
181 ;; is necessary because some terminals, rxvt for example, need non-ansi
182 ;; hacks to work ( for example on my rxvt white is wired to fg, and to
183 ;; obtain normal white I have to do bold-white :)
185 ;; ----------------------------------------
188 ;; # Configuration file for the color ls utility
189 ;; # This file goes in the /etc directory, and must be world readable.
190 ;; # You can copy this file to .dir_colors in your $HOME directory to
191 ;; # override the system defaults.
193 ;; # COLOR needs one of these arguments: 'tty' colorizes output to ttys, but
194 ;; # not pipes. 'all' adds color characters to all output. 'none' shuts
195 ;; # colorization off.
199 ;; # Below, there should be one TERM entry for each termtype that is
203 ;; # EIGHTBIT, followed by '1' for on, '0' for off. (8-bit output)
206 ;; # Below are the color init strings for the basic file types. A color init
207 ;; # string consists of one or more of the following numeric codes:
208 ;; # Attribute codes:
209 ;; # 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
210 ;; # Text color codes:
211 ;; # 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
212 ;; # Background color codes:
213 ;; # 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
214 ;; NORMAL 00 # global default, although everything should be something.
215 ;; FILE 00 # normal file
216 ;; DIR 00;37 # directory
217 ;; LINK 00;36 # symbolic link
219 ;; SOCK 40;35 # socket
220 ;; BLK 33;01 # block device driver
221 ;; CHR 33;01 # character device driver
223 ;; # This is for files with execute permission:
226 ;; # List any file extensions like '.gz' or '.tar' that you would like ls
227 ;; # to colorize below. Put the extension, a space, and the color init
228 ;; # string. (and any comments you want to add after a '#')
229 ;; .tar 01;33 # archives or compressed
238 ;; .jpg 01;35 # image formats
245 ;; ----------------------------------------
247 ;; Notice: for directory/host/user tracking you need to have something
248 ;; like this in your shell startup script ( this is for tcsh but should
249 ;; be quite easy to port to other shells )
251 ;; ----------------------------------------
255 ;; set host = `hostname`
258 ;; # su does not change this but I'd like it to
260 ;; set user = `whoami`
264 ;; if ( eterm =~ $TERM ) then
266 ;; echo --------------------------------------------------------------
268 ;; echo Today is $date
269 ;; echo We are on $host running $os under Emacs term mode
270 ;; echo --------------------------------------------------------------
272 ;; setenv EDITOR emacsclient
274 ;; # Notice: $host and $user have been set before to 'hostname' and 'whoami'
275 ;; # this is necessary because, f.e., certain versions of 'su' do not change
276 ;; # $user, YMMV: if you don't want to fiddle with them define a couple
277 ;; # of new variables and use these instead.
278 ;; # NOTICE that there is a space between "AnSiT?" and $whatever NOTICE
280 ;; # These are because we want the real cwd in the messages, not the login
283 ;; set cwd_hack='$cwd'
284 ;; set host_hack='$host'
285 ;; set user_hack='$user'
287 ;; # Notice that the ^[ character is an ESC, not two chars. You can
288 ;; # get it in various ways, for example by typing
289 ;; # echo -e '\033' > escape.file
290 ;; # or by using your favorite editor
292 ;; foreach temp (cd pushd)
293 ;; alias $temp "$temp \!* ; echo '\eAnSiTc' $cwd_hack"
295 ;; alias popd 'popd ;echo "\eAnSiTc" $cwd'
297 ;; # Every command that can modify the user/host/directory should be aliased
298 ;; # as follows for the tracking mechanism to work.
300 ;; foreach temp ( rlogin telnet rsh sh ksh csh tcsh zsh bash tcl su )
301 ;; alias $temp "$temp \!* ; echo '\eAnSiTh' $host_hack ; \
302 ;; echo '\eAnSiTu' $user_hack ;echo '\eAnSiTc' $cwd_hack"
305 ;; # Start up & use color ls
307 ;; echo "\eAnSiTh" $host
308 ;; echo "\eAnSiTu" $user
309 ;; echo "\eAnSiTc" $cwd
311 ;; # some housekeeping
318 ;; eval `/bin/dircolors /home/marco/.emacs_dircolors`
323 ;; # Let's not clutter user space
330 ;;; Original Commentary:
331 ;; ---------------------
333 ;; The changelog is at the end of this file.
335 ;; Please send me bug reports, bug fixes, and extensions, so that I can
336 ;; merge them into the master source.
337 ;; - Per Bothner (bothner@cygnus.com)
339 ;; This file defines a general command-interpreter-in-a-buffer package
340 ;; (term mode). The idea is that you can build specific process-in-a-buffer
341 ;; modes on top of term mode -- e.g., lisp, shell, scheme, T, soar, ....
342 ;; This way, all these specific packages share a common base functionality,
343 ;; and a common set of bindings, which makes them easier to use (and
344 ;; saves code, implementation time, etc., etc.).
346 ;; For hints on converting existing process modes (e.g., tex-mode,
347 ;; background, dbx, gdb, kermit, prolog, telnet) to use term-mode
348 ;; instead of shell-mode, see the notes at the end of this file.
351 ;; Brief Command Documentation:
352 ;;============================================================================
353 ;; Term Mode Commands: (common to all derived modes, like cmushell & cmulisp
356 ;; m-p term-previous-input Cycle backwards in input history
357 ;; m-n term-next-input Cycle forwards
358 ;; m-r term-previous-matching-input Previous input matching a regexp
359 ;; m-s comint-next-matching-input Next input that matches
360 ;; return term-send-input
361 ;; c-c c-a term-bol Beginning of line; skip prompt.
362 ;; c-d term-delchar-or-maybe-eof Delete char unless at end of buff.
363 ;; c-c c-u term-kill-input ^u
364 ;; c-c c-w backward-kill-word ^w
365 ;; c-c c-c term-interrupt-subjob ^c
366 ;; c-c c-z term-stop-subjob ^z
367 ;; c-c c-\ term-quit-subjob ^\
368 ;; c-c c-o term-kill-output Delete last batch of process output
369 ;; c-c c-r term-show-output Show last batch of process output
370 ;; c-c c-h term-dynamic-list-input-ring List input history
372 ;; Not bound by default in term-mode
373 ;; term-send-invisible Read a line w/o echo, and send to proc
374 ;; (These are bound in shell-mode)
375 ;; term-dynamic-complete Complete filename at point.
376 ;; term-dynamic-list-completions List completions in help buffer.
377 ;; term-replace-by-expanded-filename Expand and complete filename at point;
378 ;; replace with expanded/completed name.
379 ;; term-kill-subjob No mercy.
380 ;; term-show-maximum-output Show as much output as possible.
381 ;; term-continue-subjob Send CONT signal to buffer's process
382 ;; group. Useful if you accidentally
383 ;; suspend your process (with C-c C-z).
385 ;; term-mode-hook is the term mode hook. Basically for your keybindings.
386 ;; term-load-hook is run after loading in this package.
390 ;; This is passed to the inferior in the EMACS environment variable,
391 ;; so it is important to increase it if there are protocol-relevant changes.
392 (defconst term-protocol-version
"0.96")
394 (eval-when-compile (require 'ange-ftp
))
398 (declare-function ring-empty-p
"ring" (ring))
399 (declare-function ring-ref
"ring" (ring index
))
400 (declare-function ring-insert-at-beginning
"ring" (ring item
))
401 (declare-function ring-length
"ring" (ring))
402 (declare-function ring-insert
"ring" (ring item
))
405 "General command interpreter in a window."
409 ;;; Buffer Local Variables:
410 ;;============================================================================
411 ;; Term mode buffer local variables:
412 ;; term-prompt-regexp - string term-bol uses to match prompt.
413 ;; term-delimiter-argument-list - list For delimiters and arguments
414 ;; term-last-input-start - marker Handy if inferior always echoes
415 ;; term-last-input-end - marker For term-kill-output command
416 ;; For the input history mechanism:
417 (defvar term-input-ring-size
32 "Size of input history ring.")
418 ;; term-input-ring-size - integer
419 ;; term-input-ring - ring
420 ;; term-input-ring-index - number ...
421 ;; term-input-autoexpand - symbol ...
422 ;; term-input-ignoredups - boolean ...
423 ;; term-last-input-match - string ...
424 ;; term-dynamic-complete-functions - hook For the completion mechanism
425 ;; term-completion-fignore - list ...
426 ;; term-get-old-input - function Hooks for specific
427 ;; term-input-filter-functions - hook process-in-a-buffer
428 ;; term-input-filter - function modes.
429 ;; term-input-send - function
430 ;; term-scroll-to-bottom-on-output - symbol ...
431 ;; term-scroll-show-maximum-output - boolean...
432 (defvar term-height
) ; Number of lines in window.
433 (defvar term-width
) ; Number of columns in window.
434 (defvar term-home-marker
) ; Marks the "home" position for cursor addressing.
435 (defvar term-saved-home-marker nil
436 "When using alternate sub-buffer,
437 contains saved term-home-marker from original sub-buffer.")
438 (defvar term-start-line-column
0
439 "(current-column) at start of screen line, or nil if unknown.")
440 (defvar term-current-column
0 "If non-nil, is cache for (current-column).")
441 (defvar term-current-row
0
442 "Current vertical row (relative to home-marker) or nil if unknown.")
443 (defvar term-insert-mode nil
)
444 (defvar term-vertical-motion
)
445 (defvar term-terminal-state
0
446 "State of the terminal emulator:
447 state 0: Normal state
448 state 1: Last character was a graphic in the last column.
449 If next char is graphic, first move one column right
450 \(and line warp) before displaying it.
451 This emulates (more or less) the behavior of xterm.
453 state 3: seen ESC [ (or ESC [ ?)
454 state 4: term-terminal-parameter contains pending output.")
455 (defvar term-kill-echo-list nil
456 "A queue of strings whose echo we want suppressed.")
457 (defvar term-terminal-parameter
)
458 (defvar term-terminal-previous-parameter
)
459 (defvar term-current-face
'term
)
460 (defvar term-scroll-start
0 "Top-most line (inclusive) of scrolling region.")
461 (defvar term-scroll-end
) ; Number of line (zero-based) after scrolling region.
462 (defvar term-pager-count nil
463 "Number of lines before we need to page; if nil, paging is disabled.")
464 (defvar term-saved-cursor nil
)
465 (defvar term-command-hook
)
466 (defvar term-log-buffer nil
)
467 (defvar term-scroll-with-delete nil
468 "If t, forward scrolling should be implemented by delete to
469 top-most line(s); and if nil, scrolling should be implemented
470 by moving term-home-marker. It is set to t if there is a
471 \(non-default) scroll-region OR the alternate buffer is used.")
472 (defvar term-pending-delete-marker
) ; New user input in line mode
473 ; needs to be deleted, because it gets echoed by the inferior.
474 ; To reduce flicker, we defer the delete until the next output.
475 (defvar term-old-mode-map nil
"Saves the old keymap when in char mode.")
476 (defvar term-old-mode-line-format
) ; Saves old mode-line-format while paging.
477 (defvar term-pager-old-local-map nil
"Saves old keymap while paging.")
478 (defvar term-pager-old-filter
) ; Saved process-filter while paging.
480 (defcustom explicit-shell-file-name nil
481 "If non-nil, is file name to use for explicitly requested inferior shell."
482 :type
'(choice (const nil
) file
)
485 (defvar term-prompt-regexp
"^"
486 "Regexp to recognize prompts in the inferior process.
487 Defaults to \"^\", the null string at BOL.
490 Canonical Lisp: \"^[^> \\n]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
491 Lucid Common Lisp: \"^\\\\(>\\\\|\\\\(->\\\\)+\\\\) *\"
492 franz: \"^\\\\(->\\\\|<[0-9]*>:\\\\) *\"
494 shell: \"^[^#$%>\\n]*[#$%>] *\"
497 This is a good thing to set in mode hooks.")
499 (defvar term-delimiter-argument-list
()
500 "List of characters to recognize as separate arguments in input.
501 Strings comprising a character in this list will separate the arguments
502 surrounding them, and also be regarded as arguments in their own right
503 \(unlike whitespace). See `term-arguments'.
504 Defaults to the empty list.
506 For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
508 This is a good thing to set in mode hooks.")
510 (defcustom term-input-autoexpand nil
511 "If non-nil, expand input command history references on completion.
512 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
514 If the value is `input', then the expansion is seen on input.
515 If the value is `history', then the expansion is only when inserting
516 into the buffer's input ring. See also `term-magic-space' and
517 `term-dynamic-complete'.
519 This variable is buffer-local."
520 :type
'(choice (const nil
) (const t
) (const input
) (const history
))
523 (defcustom term-input-ignoredups nil
524 "If non-nil, don't add input matching the last on the input ring.
525 This mirrors the optional behavior of bash.
527 This variable is buffer-local."
531 (defcustom term-input-ring-file-name nil
532 "If non-nil, name of the file to read/write input history.
533 See also `term-read-input-ring' and `term-write-input-ring'.
535 This variable is buffer-local, and is a good thing to set in mode hooks."
539 (defcustom term-scroll-to-bottom-on-output nil
540 "Controls whether interpreter output causes window to scroll.
541 If nil, then do not scroll. If t or `all', scroll all windows showing buffer.
542 If `this', scroll only the selected window.
543 If `others', scroll only those that are not the selected window.
547 See variable `term-scroll-show-maximum-output'.
548 This variable is buffer-local."
552 (defcustom term-scroll-show-maximum-output nil
553 "Controls how interpreter output causes window to scroll.
554 If non-nil, then show the maximum output when the window is scrolled.
556 See variable `term-scroll-to-bottom-on-output'.
557 This variable is buffer-local."
561 (defcustom term-suppress-hard-newline nil
562 "Non-nil means interpreter should not break long lines with newlines.
563 This means text can automatically reflow if the window is resized."
568 ;; Where gud-display-frame should put the debugging arrow. This is
569 ;; set by the marker-filter, which scans the debugger's output for
570 ;; indications of the current pc.
571 (defvar term-pending-frame nil
)
573 ;;; Here are the per-interpreter hooks.
574 (defvar term-get-old-input
(function term-get-old-input-default
)
575 "Function that submits old text in term mode.
576 This function is called when return is typed while the point is in old text.
577 It returns the text to be submitted as process input. The default is
578 `term-get-old-input-default', which grabs the current line, and strips off
579 leading text matching `term-prompt-regexp'.")
581 (defvar term-dynamic-complete-functions
582 '(term-replace-by-expanded-history term-dynamic-complete-filename
)
583 "List of functions called to perform completion.
584 Functions should return non-nil if completion was performed.
585 See also `term-dynamic-complete'.
587 This is a good thing to set in mode hooks.")
589 (defvar term-input-filter
590 (function (lambda (str) (not (string-match "\\`\\s *\\'" str
))))
591 "Predicate for filtering additions to input history.
592 Only inputs answering true to this function are saved on the input
593 history list. Default is to save anything that isn't all whitespace.")
595 (defvar term-input-filter-functions
'()
596 "Functions to call before input is sent to the process.
597 These functions get one argument, a string containing the text to send.
599 This variable is buffer-local.")
601 (defvar term-input-sender
(function term-simple-send
)
602 "Function to actually send to PROCESS the STRING submitted by user.
603 Usually this is just `term-simple-send', but if your mode needs to
604 massage the input string, this is your hook. This is called from
605 the user command `term-send-input'. `term-simple-send' just sends
606 the string plus a newline.")
608 (defcustom term-eol-on-send t
609 "Non-nil means go to the end of the line before sending input.
610 See `term-send-input'."
614 (defcustom term-mode-hook
'()
615 "Called upon entry into term mode.
616 This is run before the process is cranked up."
620 (defcustom term-exec-hook
'()
621 "Called each time a process is exec'd by `term-exec'.
622 This is called after the process is cranked up. It is useful for things that
623 must be done each time a process is executed in a term mode buffer (e.g.,
624 `process-kill-without-query'). In contrast, `term-mode-hook' is only
625 executed once when the buffer is created."
629 (defvar term-mode-map
630 (let ((map (make-sparse-keymap)))
631 (define-key map
"\ep" 'term-previous-input
)
632 (define-key map
"\en" 'term-next-input
)
633 (define-key map
"\er" 'term-previous-matching-input
)
634 (define-key map
"\es" 'term-next-matching-input
)
635 (unless (featurep 'xemacs
)
636 (define-key map
[?\A-\M-r
]
637 'term-previous-matching-input-from-input
)
638 (define-key map
[?\A-\M-s
] 'term-next-matching-input-from-input
))
639 (define-key map
"\e\C-l" 'term-show-output
)
640 (define-key map
"\C-m" 'term-send-input
)
641 (define-key map
"\C-d" 'term-delchar-or-maybe-eof
)
642 (define-key map
"\C-c\C-a" 'term-bol
)
643 (define-key map
"\C-c\C-u" 'term-kill-input
)
644 (define-key map
"\C-c\C-w" 'backward-kill-word
)
645 (define-key map
"\C-c\C-c" 'term-interrupt-subjob
)
646 (define-key map
"\C-c\C-z" 'term-stop-subjob
)
647 (define-key map
"\C-c\C-\\" 'term-quit-subjob
)
648 (define-key map
"\C-c\C-m" 'term-copy-old-input
)
649 (define-key map
"\C-c\C-o" 'term-kill-output
)
650 (define-key map
"\C-c\C-r" 'term-show-output
)
651 (define-key map
"\C-c\C-e" 'term-show-maximum-output
)
652 (define-key map
"\C-c\C-l" 'term-dynamic-list-input-ring
)
653 (define-key map
"\C-c\C-n" 'term-next-prompt
)
654 (define-key map
"\C-c\C-p" 'term-previous-prompt
)
655 (define-key map
"\C-c\C-d" 'term-send-eof
)
656 (define-key map
"\C-c\C-k" 'term-char-mode
)
657 (define-key map
"\C-c\C-j" 'term-line-mode
)
658 (define-key map
"\C-c\C-q" 'term-pager-toggle
)
659 ;; completion: (line mode only)
660 (easy-menu-define nil map
"Complete menu for Term mode."
662 ["Complete Before Point" term-dynamic-complete t
]
663 ["Complete File Name" term-dynamic-complete-filename t
]
664 ["File Completion Listing" term-dynamic-list-filename-completions t
]
665 ["Expand File Name" term-replace-by-expanded-filename t
]))
666 ;; Input history: (line mode only)
667 (easy-menu-define nil map
"In/Out menu for Term mode."
669 ["Expand History Before Point" term-replace-by-expanded-history
670 term-input-autoexpand
]
671 ["List Input History" term-dynamic-list-input-ring t
]
672 ["Previous Input" term-previous-input t
]
673 ["Next Input" term-next-input t
]
674 ["Previous Matching Current Input"
675 term-previous-matching-input-from-input t
]
676 ["Next Matching Current Input" term-next-matching-input-from-input t
]
677 ["Previous Matching Input..." term-previous-matching-input t
]
678 ["Next Matching Input..." term-next-matching-input t
]
679 ["Backward Matching Input..." term-backward-matching-input t
]
680 ["Forward Matching Input..." term-forward-matching-input t
]
681 ["Copy Old Input" term-copy-old-input t
]
682 ["Kill Current Input" term-kill-input t
]
683 ["Show Current Output Group" term-show-output t
]
684 ["Show Maximum Output" term-show-maximum-output t
]
685 ["Backward Output Group" term-previous-prompt t
]
686 ["Forward Output Group" term-next-prompt t
]
687 ["Kill Current Output Group" term-kill-output t
]))
689 "Keymap for Term mode.")
691 (defvar term-escape-char nil
692 "Escape character for char sub-mode of term mode.
693 Do not change it directly; use `term-set-escape-char' instead.")
695 (defvar term-pager-break-map
696 (let ((map (make-keymap)))
698 ;; (define-key map (make-string 1 i) 'term-send-raw))
699 (define-key map
"\e" (lookup-key (current-global-map) "\e"))
700 (define-key map
"\C-x" (lookup-key (current-global-map) "\C-x"))
701 (define-key map
"\C-u" (lookup-key (current-global-map) "\C-u"))
702 (define-key map
" " 'term-pager-page
)
703 (define-key map
"\r" 'term-pager-line
)
704 (define-key map
"?" 'term-pager-help
)
705 (define-key map
"h" 'term-pager-help
)
706 (define-key map
"b" 'term-pager-back-page
)
707 (define-key map
"\177" 'term-pager-back-line
)
708 (define-key map
"q" 'term-pager-discard
)
709 (define-key map
"D" 'term-pager-disable
)
710 (define-key map
"<" 'term-pager-bob
)
711 (define-key map
">" 'term-pager-eob
)
713 "Keymap used in Term pager mode.")
716 "True if communications via pty; false if by pipe. Buffer local.
717 This is to work around a bug in Emacs process signaling.")
719 (defvar term-last-input-match
""
720 "Last string searched for by term input history search, for defaulting.
721 Buffer local variable.")
723 (defvar term-input-ring nil
)
724 (defvar term-last-input-start
)
725 (defvar term-last-input-end
)
726 (defvar term-input-ring-index nil
727 "Index of last matched history element.")
728 (defvar term-matching-input-from-input-string
""
729 "Input previously used to match input history.")
730 ; This argument to set-process-filter disables reading from the process,
731 ; assuming this is Emacs 19.20 or newer.
732 (defvar term-pager-filter t
)
734 (put 'term-input-ring
'permanent-local t
)
735 (put 'term-input-ring-index
'permanent-local t
)
736 (put 'term-input-autoexpand
'permanent-local t
)
737 (put 'term-input-filter-functions
'permanent-local t
)
738 (put 'term-scroll-to-bottom-on-output
'permanent-local t
)
739 (put 'term-scroll-show-maximum-output
'permanent-local t
)
740 (put 'term-ptyp
'permanent-local t
)
742 (defmacro term-in-char-mode
() '(eq (current-local-map) term-raw-map
))
743 (defmacro term-in-line-mode
() '(not (term-in-char-mode)))
744 ;; True if currently doing PAGER handling.
745 (defmacro term-pager-enabled
() 'term-pager-count
)
746 (defmacro term-handling-pager
() 'term-pager-old-local-map
)
747 (defmacro term-using-alternate-sub-buffer
() 'term-saved-home-marker
)
749 ;; Let's silence the byte-compiler -mm
750 (defvar term-ansi-at-host nil
)
751 (defvar term-ansi-at-dir nil
)
752 (defvar term-ansi-at-user nil
)
753 (defvar term-ansi-at-message nil
)
754 (defvar term-ansi-at-save-user nil
)
755 (defvar term-ansi-at-save-pwd nil
)
756 (defvar term-ansi-at-save-anon nil
)
757 (defvar term-ansi-current-bold nil
)
758 (defvar term-ansi-current-color
0)
759 (defvar term-ansi-face-already-done nil
)
760 (defvar term-ansi-current-bg-color
0)
761 (defvar term-ansi-current-underline nil
)
762 (defvar term-ansi-current-reverse nil
)
763 (defvar term-ansi-current-invisible nil
)
765 ;; Four should be enough, if you want more, just add. -mm
766 (defvar term-terminal-more-parameters
0)
767 (defvar term-terminal-previous-parameter-2 -
1)
768 (defvar term-terminal-previous-parameter-3 -
1)
769 (defvar term-terminal-previous-parameter-4 -
1)
772 (defvar ansi-term-color-vector
783 (defcustom term-default-fg-color nil
784 "If non-nil, default color for foreground in Term mode."
786 :type
'(choice (const nil
) (string :tag
"color")))
787 (make-obsolete-variable 'term-default-fg-color
"use the face `term' instead."
790 (defcustom term-default-bg-color nil
791 "If non-nil, default color for foreground in Term mode."
793 :type
'(choice (const nil
) (string :tag
"color")))
794 (make-obsolete-variable 'term-default-bg-color
"use the face `term' instead."
799 :foreground
,term-default-fg-color
800 :background
,term-default-bg-color
802 "Default face to use in Term mode."
807 "Default face to use for bold text."
810 (defface term-underline
812 "Default face to use for underlined text."
815 (defface term-color-black
816 '((t :foreground
"black" :background
"black"))
817 "Face used to render black color code."
820 (defface term-color-red
821 '((t :foreground
"red3" :background
"red3"))
822 "Face used to render red color code."
825 (defface term-color-green
826 '((t :foreground
"green3" :background
"green3"))
827 "Face used to render green color code."
830 (defface term-color-yellow
831 '((t :foreground
"yellow3" :background
"yellow3"))
832 "Face used to render yellow color code."
835 (defface term-color-blue
836 '((t :foreground
"blue2" :background
"blue2"))
837 "Face used to render blue color code."
840 (defface term-color-magenta
841 '((t :foreground
"magenta3" :background
"magenta3"))
842 "Face used to render magenta color code."
845 (defface term-color-cyan
846 '((t :foreground
"cyan3" :background
"cyan3"))
847 "Face used to render cyan color code."
850 (defface term-color-white
851 '((t :foreground
"white" :background
"white"))
852 "Face used to render white color code."
855 ;; Inspiration came from comint.el -mm
856 (defcustom term-buffer-maximum-size
2048
857 "The maximum size in lines for term buffers.
858 Term buffers are truncated from the top to be no greater than this number.
859 Notice that a setting of 0 means \"don't truncate anything\". This variable
864 ;; Set up term-raw-map, etc.
867 (let* ((map (make-keymap))
868 (esc-map (make-keymap))
871 (define-key map
(make-string 1 i
) 'term-send-raw
)
872 ;; Avoid O and [. They are used in escape sequences for various keys.
873 (unless (or (eq i ?O
) (eq i
91))
874 (define-key esc-map
(make-string 1 i
) 'term-send-raw-meta
))
876 (define-key map
[remap self-insert-command
] 'term-send-raw
)
877 (define-key map
"\e" esc-map
)
879 ;; Added nearly all the 'gray keys' -mm
881 (if (featurep 'xemacs
)
882 (define-key map
[button2] 'term-mouse-paste)
883 (define-key map [mouse-2] 'term-mouse-paste))
884 (define-key map [up] 'term-send-up)
885 (define-key map [down] 'term-send-down)
886 (define-key map [right] 'term-send-right)
887 (define-key map [left] 'term-send-left)
888 (define-key map [delete] 'term-send-del)
889 (define-key map [deletechar] 'term-send-del)
890 (define-key map [backspace] 'term-send-backspace)
891 (define-key map [home] 'term-send-home)
892 (define-key map [end] 'term-send-end)
893 (define-key map [insert] 'term-send-insert)
894 (define-key map [S-prior] 'scroll-down)
895 (define-key map [S-next] 'scroll-up)
896 (define-key map [S-insert] 'term-paste)
897 (define-key map [prior] 'term-send-prior)
898 (define-key map [next] 'term-send-next)
900 "Keyboard map for sending characters directly to the inferior process.")
902 (easy-menu-define term-terminal-menu
903 (list term-mode-map term-raw-map term-pager-break-map)
904 "Terminal menu for Term mode."
906 ["Line mode" term-line-mode :active (term-in-char-mode)
907 :help "Switch to line (cooked) sub-mode of term mode"]
908 ["Character mode" term-char-mode :active (term-in-line-mode)
909 :help "Switch to char (raw) sub-mode of term mode"]
910 ["Paging" term-pager-toggle :style toggle :selected term-pager-count
911 :help "Toggle paging feature"]))
913 (easy-menu-define term-signals-menu
914 (list term-mode-map term-raw-map term-pager-break-map)
915 "Signals menu for Term mode."
917 ["BREAK" term-interrupt-subjob :active t
918 :help "Interrupt the current subjob"]
919 ["STOP" term-stop-subjob :active t :help "Stop the current subjob"]
920 ["CONT" term-continue-subjob :active t
921 :help "Send CONT signal to process buffer's process group"]
922 ["QUIT" term-quit-subjob :active t
923 :help "Send quit signal to the current subjob"]
924 ["KILL" term-kill-subjob :active t
925 :help "Send kill signal to the current subjob"]
926 ["EOF" term-send-eof :active t
927 :help "Send an EOF to the current buffer's process"]))
929 (easy-menu-define term-pager-menu term-pager-break-map
930 "Menu for Term pager mode."
932 ["1 page forwards" term-pager-page t]
933 ["1 page backwards" term-pager-back-page t]
934 ["1 line backwards" term-pager-back-line t]
935 ["1 line forwards" term-pager-line t]
936 ["Goto to beginning" term-pager-bob t]
937 ["Goto to end" term-pager-eob t]
938 ["Discard remaining output" term-pager-discard t]
939 ["Disable paging" term-pager-toggle t]
940 ["Help" term-pager-help t]))
942 (defvar term-raw-escape-map
943 (let ((map (make-sparse-keymap)))
944 (set-keymap-parent map 'Control-X-prefix)
945 ;; Define standard bindings in term-raw-escape-map.
946 (define-key map "\C-v" (lookup-key (current-global-map) "\C-v"))
947 (define-key map "\C-u" (lookup-key (current-global-map) "\C-u"))
948 (define-key map "\C-q" 'term-pager-toggle)
949 ;; The keybinding for term-char-mode is needed by the menubar code.
950 (define-key map "\C-k" 'term-char-mode)
951 (define-key map "\C-j" 'term-line-mode)
952 ;; It's convenient to have execute-extended-command here.
953 (define-key map [?\M-x] 'execute-extended-command)
956 (defun term-set-escape-char (key)
957 "Change `term-escape-char' and keymaps that depend on it."
958 (when term-escape-char
959 ;; Undo previous term-set-escape-char.
960 (define-key term-raw-map term-escape-char 'term-send-raw))
961 (setq term-escape-char (if (vectorp key) key (vector key)))
962 (define-key term-raw-map term-escape-char term-raw-escape-map)
963 ;; FIXME: If we later call term-set-escape-char again with another key,
964 ;; we should undo this binding.
965 (define-key term-raw-escape-map term-escape-char 'term-send-raw))
967 (term-set-escape-char (or term-escape-char ?\C-c))
969 (defvar overflow-newline-into-fringe)
971 (defun term-window-width ()
972 (if (and (not (featurep 'xemacs))
974 overflow-newline-into-fringe
975 ;; Subtract 1 from the width when any fringe has zero width,
976 ;; not just the right fringe. Bug#18601.
977 (/= (frame-parameter nil 'left-fringe) 0)
978 (/= (frame-parameter nil 'right-fringe) 0))
980 (1- (window-body-width))))
983 (put 'term-mode 'mode-class 'special)
986 ;; Use this variable as a display table for `term-mode'.
987 (defvar term-display-table
988 (let ((dt (or (copy-sequence standard-display-table)
989 (make-display-table)))
991 ;; avoid changing the display table for ^J
994 (aset dt i (vector i))
998 (aset dt i (vector i))
1002 (aset dt i (vector i))
1006 (defun term-ansi-reset ()
1007 (setq term-current-face 'term)
1008 (setq term-ansi-current-underline nil)
1009 (setq term-ansi-current-bold nil)
1010 (setq term-ansi-current-reverse nil)
1011 (setq term-ansi-current-color 0)
1012 (setq term-ansi-current-invisible nil)
1013 ;; Stefan thought this should be t, but could not remember why.
1014 ;; Setting it to t seems to cause bug#11785. Setting it to nil
1015 ;; again to see if there are other consequences...
1016 (setq term-ansi-face-already-done nil)
1017 (setq term-ansi-current-bg-color 0))
1019 (define-derived-mode term-mode fundamental-mode "Term"
1020 "Major mode for interacting with an inferior interpreter.
1021 The interpreter name is same as buffer name, sans the asterisks.
1023 There are two submodes: line mode and char mode. By default, you are
1024 in char mode. In char sub-mode, each character (except
1025 `term-escape-char') is sent immediately to the subprocess.
1026 The escape character is equivalent to the usual meaning of C-x.
1028 In line mode, you send a line of input at a time; use
1029 \\[term-send-input] to send.
1031 In line mode, this maintains an input history of size
1032 `term-input-ring-size', and you can access it with the commands
1033 \\[term-next-input], \\[term-previous-input], and
1034 \\[term-dynamic-list-input-ring]. Input ring history expansion can be
1035 achieved with the commands \\[term-replace-by-expanded-history] or
1036 \\[term-magic-space]. Input ring expansion is controlled by the
1037 variable `term-input-autoexpand', and addition is controlled by the
1038 variable `term-input-ignoredups'.
1040 Input to, and output from, the subprocess can cause the window to scroll to
1041 the end of the buffer. See variables `term-scroll-to-bottom-on-input',
1042 and `term-scroll-to-bottom-on-output'.
1044 If you accidentally suspend your process, use \\[term-continue-subjob]
1047 This mode can be customized to create specific modes for running
1048 particular subprocesses. This can be done by setting the hooks
1049 `term-input-filter-functions', `term-input-filter',
1050 `term-input-sender' and `term-get-old-input' to appropriate functions,
1051 and the variable `term-prompt-regexp' to the appropriate regular
1054 Commands in raw mode:
1058 Commands in line mode:
1062 Entry to this mode runs the hooks on `term-mode-hook'."
1063 ;; we do not want indent to sneak in any tabs
1064 (setq indent-tabs-mode nil)
1065 (setq buffer-display-table term-display-table)
1066 (set (make-local-variable 'term-home-marker) (copy-marker 0))
1067 (set (make-local-variable 'term-height) (1- (window-height)))
1068 (set (make-local-variable 'term-width) (term-window-width))
1069 (set (make-local-variable 'term-last-input-start) (make-marker))
1070 (set (make-local-variable 'term-last-input-end) (make-marker))
1071 (set (make-local-variable 'term-last-input-match) "")
1072 (set (make-local-variable 'term-command-hook)
1073 (symbol-function 'term-command-hook))
1075 ;; These local variables are set to their local values:
1076 (make-local-variable 'term-saved-home-marker)
1077 (make-local-variable 'term-terminal-parameter)
1078 (make-local-variable 'term-saved-cursor)
1079 (make-local-variable 'term-prompt-regexp)
1080 (make-local-variable 'term-input-ring-size)
1081 (make-local-variable 'term-input-ring)
1082 (make-local-variable 'term-input-ring-file-name)
1083 (make-local-variable 'term-input-ring-index)
1084 (unless term-input-ring
1085 (setq term-input-ring (make-ring term-input-ring-size)))
1087 ;; I'm not sure these saves are necessary but, since I
1088 ;; haven't tested the whole thing on a net connected machine with
1089 ;; a properly configured ange-ftp, I've decided to be conservative
1090 ;; and put them in. -mm
1092 (set (make-local-variable 'term-ansi-at-host) (system-name))
1093 (set (make-local-variable 'term-ansi-at-dir) default-directory)
1094 (set (make-local-variable 'term-ansi-at-message) nil)
1096 ;; For user tracking purposes -mm
1097 (make-local-variable 'ange-ftp-default-user)
1098 (make-local-variable 'ange-ftp-default-password)
1099 (make-local-variable 'ange-ftp-generate-anonymous-password)
1101 ;; You may want to have different scroll-back sizes -mm
1102 (make-local-variable 'term-buffer-maximum-size)
1104 ;; Of course these have to be buffer-local -mm
1105 (make-local-variable 'term-ansi-current-bold)
1106 (make-local-variable 'term-ansi-current-color)
1107 (make-local-variable 'term-ansi-face-already-done)
1108 (make-local-variable 'term-ansi-current-bg-color)
1109 (make-local-variable 'term-ansi-current-underline)
1110 (make-local-variable 'term-ansi-current-reverse)
1111 (make-local-variable 'term-ansi-current-invisible)
1113 (make-local-variable 'term-terminal-parameter)
1114 (make-local-variable 'term-terminal-previous-parameter)
1115 (make-local-variable 'term-terminal-previous-parameter-2)
1116 (make-local-variable 'term-terminal-previous-parameter-3)
1117 (make-local-variable 'term-terminal-previous-parameter-4)
1118 (make-local-variable 'term-terminal-more-parameters)
1120 (make-local-variable 'term-terminal-state)
1121 (make-local-variable 'term-kill-echo-list)
1122 (make-local-variable 'term-start-line-column)
1123 (make-local-variable 'term-current-column)
1124 (make-local-variable 'term-current-row)
1125 (make-local-variable 'term-log-buffer)
1126 (make-local-variable 'term-scroll-start)
1127 (set (make-local-variable 'term-scroll-end) term-height)
1128 (make-local-variable 'term-scroll-with-delete)
1129 (make-local-variable 'term-pager-count)
1130 (make-local-variable 'term-pager-old-local-map)
1131 (make-local-variable 'term-old-mode-map)
1132 (make-local-variable 'term-insert-mode)
1133 (make-local-variable 'term-dynamic-complete-functions)
1134 (make-local-variable 'term-completion-fignore)
1135 (make-local-variable 'term-get-old-input)
1136 (make-local-variable 'term-matching-input-from-input-string)
1137 (make-local-variable 'term-input-autoexpand)
1138 (make-local-variable 'term-input-ignoredups)
1139 (make-local-variable 'term-delimiter-argument-list)
1140 (make-local-variable 'term-input-filter-functions)
1141 (make-local-variable 'term-input-filter)
1142 (make-local-variable 'term-input-sender)
1143 (make-local-variable 'term-eol-on-send)
1144 (make-local-variable 'term-scroll-to-bottom-on-output)
1145 (make-local-variable 'term-scroll-show-maximum-output)
1146 (make-local-variable 'term-ptyp)
1147 (make-local-variable 'term-exec-hook)
1148 (make-local-variable 'term-vertical-motion)
1149 (set (make-local-variable 'term-pending-delete-marker) (make-marker))
1150 (make-local-variable 'term-current-face)
1152 (set (make-local-variable 'term-pending-frame) nil)
1153 ;; Cua-mode's keybindings interfere with the term keybindings, disable it.
1154 (set (make-local-variable 'cua-mode) nil)
1156 (set (make-local-variable 'font-lock-defaults) '(nil t))
1158 (easy-menu-add term-terminal-menu)
1159 (easy-menu-add term-signals-menu)
1161 (setq term-input-ring (make-ring term-input-ring-size)))
1162 (term-update-mode-line))
1164 (defun term-reset-size (height width)
1165 (setq term-height height)
1166 (setq term-width width)
1167 (setq term-start-line-column nil)
1168 (setq term-current-row nil)
1169 (setq term-current-column nil)
1170 (term-set-scroll-region 0 height))
1172 ;; Recursive routine used to check if any string in term-kill-echo-list
1173 ;; matches part of the buffer before point.
1174 ;; If so, delete that matched part of the buffer - this suppresses echo.
1175 ;; Also, remove that string from the term-kill-echo-list.
1176 ;; We *also* remove any older string on the list, as a sanity measure,
1177 ;; in case something gets out of sync. (Except for type-ahead, there
1178 ;; should only be one element in the list.)
1180 (defun term-check-kill-echo-list ()
1181 (let ((cur term-kill-echo-list) (found nil) (save-point (point)))
1186 (let* ((str (car cur)) (len (length str)) (start (- (point) len)))
1187 (if (and (>= start (point-min))
1188 (string= str (buffer-substring start (point))))
1189 (progn (delete-char (- len))
1190 (setq term-kill-echo-list (cdr cur))
1191 (setq term-current-column nil)
1192 (setq term-current-row nil)
1193 (setq term-start-line-column nil)
1194 (setq cur nil found t))
1195 (setq cur (cdr cur))))))
1197 (goto-char save-point)))
1200 (defun term-check-size (process)
1201 (when (or (/= term-height (window-text-height))
1202 (/= term-width (term-window-width)))
1203 (term-reset-size (window-text-height) (term-window-width))
1204 (set-process-window-size process term-height term-width)))
1206 (defun term-send-raw-string (chars)
1208 (let ((proc (get-buffer-process (current-buffer))))
1210 (error "Current buffer has no process")
1211 ;; Note that (term-current-row) must be called *after*
1212 ;; (point) has been updated to (process-mark proc).
1213 (goto-char (process-mark proc))
1214 (when (term-pager-enabled)
1215 (setq term-pager-count (term-current-row)))
1216 (process-send-string proc chars))))
1218 (defun term-send-raw ()
1219 "Send the last character typed through the terminal-emulator
1220 without any interpretation."
1222 (let ((keys (this-command-keys)))
1223 (term-send-raw-string (string (aref keys (1- (length keys)))))))
1225 (defun term-send-raw-meta ()
1227 (let ((char last-input-event))
1228 (when (symbolp char)
1229 ;; Convert `return' to C-m, etc.
1230 (let ((tmp (get char 'event-symbol-elements)))
1231 (if tmp (setq char (car tmp)))
1233 (setq tmp (get char 'ascii-character))
1235 (when (numberp char)
1236 (let ((base (event-basic-type char))
1237 (mods (delq 'meta (event-modifiers char))))
1238 (if (memq 'control mods)
1239 (setq mods (delq 'shift mods)))
1240 (term-send-raw-string
1242 (event-convert-list (append mods (list base)))))))))
1244 (defun term-mouse-paste (click)
1245 "Insert the primary selection at the position clicked on."
1247 (if (featurep 'xemacs)
1248 (term-send-raw-string
1249 (or (condition-case () (x-get-selection) (error ()))
1250 (error "No selection available")))
1251 ;; Give temporary modes such as isearch a chance to turn off.
1252 (run-hooks 'mouse-leave-buffer-hook)
1253 (setq this-command 'yank)
1254 (mouse-set-point click)
1255 (term-send-raw-string (gui-get-primary-selection))))
1257 (defun term-paste ()
1258 "Insert the last stretch of killed text at point."
1260 (term-send-raw-string (current-kill 0)))
1262 ;; Which would be better: "\e[A" or "\eOA"? readline accepts either.
1263 ;; For my configuration it's definitely better \eOA but YMMV. -mm
1264 ;; For example: vi works with \eOA while elm wants \e[A ...
1265 ;; (terminfo: kcuu1, kcud1, kcuf1, kcub1, khome, kend, kpp, knp, kdch1, kbs)
1266 (defun term-send-up () (interactive) (term-send-raw-string "\eOA"))
1267 (defun term-send-down () (interactive) (term-send-raw-string "\eOB"))
1268 (defun term-send-right () (interactive) (term-send-raw-string "\eOC"))
1269 (defun term-send-left () (interactive) (term-send-raw-string "\eOD"))
1270 (defun term-send-home () (interactive) (term-send-raw-string "\e[1~"))
1271 (defun term-send-insert() (interactive) (term-send-raw-string "\e[2~"))
1272 (defun term-send-end () (interactive) (term-send-raw-string "\e[4~"))
1273 (defun term-send-prior () (interactive) (term-send-raw-string "\e[5~"))
1274 (defun term-send-next () (interactive) (term-send-raw-string "\e[6~"))
1275 (defun term-send-del () (interactive) (term-send-raw-string "\e[3~"))
1276 (defun term-send-backspace () (interactive) (term-send-raw-string "\C-?"))
1278 (defun term-char-mode ()
1279 "Switch to char (\"raw\") sub-mode of term mode.
1280 Each character you type is sent directly to the inferior without
1281 intervention from Emacs, except for the escape character (usually C-c)."
1283 ;; FIXME: Emit message? Cfr ilisp-raw-message
1284 (when (term-in-line-mode)
1285 (setq term-old-mode-map (current-local-map))
1286 (use-local-map term-raw-map)
1287 (easy-menu-add term-terminal-menu)
1288 (easy-menu-add term-signals-menu)
1290 ;; Send existing partial line to inferior (without newline).
1291 (let ((pmark (process-mark (get-buffer-process (current-buffer))))
1292 (save-input-sender term-input-sender))
1293 (when (> (point) pmark)
1296 (setq term-input-sender
1297 (symbol-function 'term-send-string))
1300 (setq term-input-sender save-input-sender))))
1301 (term-update-mode-line)))
1303 (defun term-line-mode ()
1304 "Switch to line (\"cooked\") sub-mode of term mode.
1305 This means that Emacs editing commands work as normally, until
1306 you type \\[term-send-input] which sends the current line to the inferior."
1308 (when (term-in-char-mode)
1309 (use-local-map term-old-mode-map)
1310 (term-update-mode-line)))
1312 (defun term-update-mode-line ()
1314 (if (term-in-char-mode)
1316 'help-echo "mouse-1: Switch to line mode"
1317 'mouse-face 'mode-line-highlight
1320 (mode-line keymap (down-mouse-1 . term-line-mode))))
1322 'help-echo "mouse-1: Switch to char mode"
1323 'mouse-face 'mode-line-highlight
1326 (mode-line keymap (down-mouse-1 . term-char-mode))))))
1328 (when (term-pager-enabled)
1332 'help-echo "mouse-1: Disable paging"
1333 'mouse-face 'mode-line-highlight
1336 (mode-line keymap (down-mouse-1 .
1337 term-pager-toggle)))))))
1339 (serial-item-config)
1340 (proc (get-buffer-process (current-buffer))))
1341 (when (and (term-check-proc (current-buffer))
1342 (equal (process-type nil) 'serial))
1343 (let ((temp (serial-speed)))
1344 (setq serial-item-speed
1346 ,(or (and temp (format " %d" temp)) "")
1347 help-echo "mouse-1: Change the speed of the serial port"
1348 mouse-face mode-line-highlight
1349 local-map (keymap (mode-line keymap
1350 (down-mouse-1 . serial-mode-line-speed-menu-1))))))
1351 (let ((temp (process-contact proc :summary)))
1352 (setq serial-item-config
1354 ,(or (and temp (format " %s" temp)) "")
1355 help-echo "mouse-1: Change the configuration of the serial port"
1356 mouse-face mode-line-highlight
1357 local-map (keymap (mode-line keymap
1358 (down-mouse-1 . serial-mode-line-config-menu-1)))))))
1359 (setq mode-line-process
1360 (list ": " term-mode term-page
1364 (force-mode-line-update))
1366 (defun term-check-proc (buffer)
1367 "True if there is a process associated w/buffer BUFFER, and it
1368 is alive. BUFFER can be either a buffer or the name of one."
1369 (let ((proc (get-buffer-process buffer)))
1370 (and proc (memq (process-status proc) '(run stop open listen connect)))))
1373 (defun make-term (name program &optional startfile &rest switches)
1374 "Make a term process NAME in a buffer, running PROGRAM.
1375 The name of the buffer is made by surrounding NAME with `*'s.
1376 If there is already a running process in that buffer, it is not restarted.
1377 Optional third arg STARTFILE is the name of a file to send the contents of to
1378 the process. Any more args are arguments to PROGRAM."
1379 (let ((buffer (get-buffer-create (concat "*" name "*"))))
1380 ;; If no process, or nuked process, crank up a new one and put buffer in
1381 ;; term mode. Otherwise, leave buffer and existing process alone.
1382 (cond ((not (term-check-proc buffer))
1383 (with-current-buffer buffer
1384 (term-mode)) ; Install local vars, mode, keymap, ...
1385 (term-exec buffer name program startfile switches)))
1389 (defun term (program)
1390 "Start a terminal-emulator in a new buffer.
1391 The buffer is in Term mode; see `term-mode' for the
1392 commands to use in that buffer.
1394 \\<term-raw-map>Type \\[switch-to-buffer] to switch to another buffer."
1395 (interactive (list (read-from-minibuffer "Run program: "
1396 (or explicit-shell-file-name
1400 (set-buffer (make-term "terminal" program))
1403 (switch-to-buffer "*terminal*"))
1405 (defun term-exec (buffer name command startfile switches)
1406 "Start up a process in buffer for term modes.
1407 Blasts any old process running in the buffer. Doesn't set the buffer mode.
1408 You can use this to cheaply run a series of processes in the same term
1409 buffer. The hook `term-exec-hook' is run after each exec."
1410 (with-current-buffer buffer
1411 (let ((proc (get-buffer-process buffer))) ; Blast any old process.
1412 (when proc (delete-process proc)))
1413 ;; Crank up a new process
1414 (let ((proc (term-exec-1 name buffer command switches)))
1415 (make-local-variable 'term-ptyp)
1416 (setq term-ptyp process-connection-type) ; t if pty, nil if pipe.
1417 ;; Jump to the end, and set the process mark.
1418 (goto-char (point-max))
1419 (set-marker (process-mark proc) (point))
1420 (set-process-filter proc 'term-emulate-terminal)
1421 (set-process-sentinel proc 'term-sentinel)
1422 ;; Feed it the startfile.
1424 ;;This is guaranteed to wait long enough
1425 ;;but has bad results if the term does not prompt at all
1426 ;; (while (= size (buffer-size))
1428 ;;I hope 1 second is enough!
1430 (goto-char (point-max))
1431 (insert-file-contents startfile)
1433 proc (delete-and-extract-region (point) (point-max)))))
1434 (run-hooks 'term-exec-hook)
1437 (defun term-sentinel (proc msg)
1438 "Sentinel for term buffers.
1439 The main purpose is to get rid of the local keymap."
1440 (let ((buffer (process-buffer proc)))
1441 (when (memq (process-status proc) '(signal exit))
1442 (if (null (buffer-name buffer))
1444 (set-process-buffer proc nil)
1445 (with-current-buffer buffer
1446 ;; Write something in the compilation buffer
1447 ;; and hack its mode line.
1448 ;; Get rid of local keymap.
1450 (term-handle-exit (process-name proc) msg)
1451 ;; Since the buffer and mode line will show that the
1452 ;; process is dead, we can delete it now. Otherwise it
1453 ;; will stay around until M-x list-processes.
1454 (delete-process proc))))))
1456 (defun term-handle-exit (process-name msg)
1457 "Write process exit (or other change) message MSG in the current buffer."
1458 (let ((buffer-read-only nil)
1461 ;; Record where we put the message, so we can ignore it
1464 (insert ?\n "Process " process-name " " msg)
1465 ;; Force mode line redisplay soon.
1466 (force-mode-line-update)
1467 (when (and opoint (< opoint omax))
1468 (goto-char opoint))))
1471 (defvar term-term-name "eterm-color"
1472 "Name to use for TERM.
1473 Using \"emacs\" loses, because bash disables editing if $TERM == emacs.")
1474 ;; Format string, usage:
1475 ;; (format term-termcap-string emacs-term-name "TERMCAP=" 24 80)
1476 (defvar term-termcap-format
1477 "%s%s:li#%d:co#%d:cl=\\E[H\\E[J:cd=\\E[J:bs:am:xn:cm=\\E[%%i%%d;%%dH\
1478 :nd=\\E[C:up=\\E[A:ce=\\E[K:ho=\\E[H:pt\
1479 :al=\\E[L:dl=\\E[M:DL=\\E[%%dM:AL=\\E[%%dL:cs=\\E[%%i%%d;%%dr:sf=^J\
1480 :dc=\\E[P:DC=\\E[%%dP:IC=\\E[%%d@:im=\\E[4h:ei=\\E[4l:mi:\
1481 :so=\\E[7m:se=\\E[m:us=\\E[4m:ue=\\E[m:md=\\E[1m:mr=\\E[7m:me=\\E[m\
1482 :UP=\\E[%%dA:DO=\\E[%%dB:LE=\\E[%%dD:RI=\\E[%%dC\
1483 :kl=\\EOD:kd=\\EOB:kr=\\EOC:ku=\\EOA:kN=\\E[6~:kP=\\E[5~:@7=\\E[4~:kh=\\E[1~\
1484 :mk=\\E[8m:cb=\\E[1K:op=\\E[39;49m:Co#8:pa#64:AB=\\E[4%%dm:AF=\\E[3%%dm:cr=^M\
1485 :bl=^G:do=^J:le=^H:ta=^I:se=\\E[27m:ue=\\E24m\
1486 :kb=^?:kD=^[[3~:sc=\\E7:rc=\\E8:r1=\\Ec:"
1488 ;; don't define :te=\\E[2J\\E[?47l\\E8:ti=\\E7\\E[?47h\
1489 "Termcap capabilities supported.")
1491 ;; This auxiliary function cranks up the process for term-exec in
1492 ;; the appropriate environment.
1494 (defun term-exec-1 (name buffer command switches)
1495 ;; We need to do an extra (fork-less) exec to run stty.
1496 ;; (This would not be needed if we had suitable Emacs primitives.)
1497 ;; The 'if ...; then shift; fi' hack is because Bourne shell
1498 ;; loses one arg when called with -c, and newer shells (bash, ksh) don't.
1499 ;; Thus we add an extra dummy argument "..", and then remove it.
1500 (let ((process-environment
1503 (format "TERM=%s" term-term-name)
1504 (format "TERMINFO=%s" data-directory)
1505 (format term-termcap-format "TERMCAP="
1506 term-term-name term-height term-width)
1507 ;; We are going to get rid of the binding for EMACS,
1508 ;; probably in Emacs 23, because it breaks
1509 ;; `./configure' of some packages that expect it to
1510 ;; say where to find EMACS.
1511 (format "EMACS=%s (term:%s)" emacs-version term-protocol-version)
1512 (format "INSIDE_EMACS=%s,term:%s" emacs-version term-protocol-version)
1513 (format "LINES=%d" term-height)
1514 (format "COLUMNS=%d" term-width))
1515 process-environment))
1516 (process-connection-type t)
1517 ;; We should suppress conversion of end-of-line format.
1518 (inhibit-eol-conversion t)
1519 ;; The process's output contains not just chars but also binary
1520 ;; escape codes, so we need to see the raw output. We will have to
1521 ;; do the decoding by hand on the parts that are made of chars.
1522 (coding-system-for-read 'binary))
1523 (apply 'start-process name buffer
1525 (format "stty -nl echo rows %d columns %d sane 2>/dev/null;\
1526 if [ $1 = .. ]; then shift; fi; exec \"$@\""
1527 term-height term-width)
1532 ;;; Input history processing in a buffer
1533 ;; ===========================================================================
1534 ;; Useful input history functions, courtesy of the Ergo group.
1537 ;; term-dynamic-list-input-ring List history in help buffer.
1538 ;; term-previous-input Previous input...
1539 ;; term-previous-matching-input ...matching a string.
1540 ;; term-previous-matching-input-from-input ... matching the current input.
1541 ;; term-next-input Next input...
1542 ;; term-next-matching-input ...matching a string.
1543 ;; term-next-matching-input-from-input ... matching the current input.
1544 ;; term-backward-matching-input Backwards input...
1545 ;; term-forward-matching-input ...matching a string.
1546 ;; term-replace-by-expanded-history Expand history at point;
1547 ;; replace with expanded history.
1548 ;; term-magic-space Expand history and insert space.
1551 ;; term-read-input-ring Read into term-input-ring...
1552 ;; term-write-input-ring Write to term-input-ring-file-name.
1553 ;; term-replace-by-expanded-history-before-point Workhorse function.
1555 (defun term-read-input-ring (&optional silent)
1556 "Set the buffer's `term-input-ring' from a history file.
1557 The name of the file is given by the variable `term-input-ring-file-name'.
1558 The history ring is of size `term-input-ring-size', regardless of file size.
1559 If `term-input-ring-file-name' is nil this function does nothing.
1561 If the optional argument SILENT is non-nil, we say nothing about a
1562 failure to read the history file.
1564 This function is useful for major mode commands and mode hooks.
1566 The structure of the history file should be one input command per line,
1567 with the most recent command last.
1568 See also `term-input-ignoredups' and `term-write-input-ring'."
1569 (cond ((or (null term-input-ring-file-name)
1570 (equal term-input-ring-file-name ""))
1572 ((not (file-readable-p term-input-ring-file-name))
1574 (message "Cannot read history file %s"
1575 term-input-ring-file-name)))
1577 (let ((file term-input-ring-file-name)
1579 (ring (make-ring term-input-ring-size)))
1581 (insert-file-contents file)
1582 ;; Save restriction in case file is already visited...
1583 ;; Watch for those date stamps in history files!
1584 (goto-char (point-max))
1585 (while (and (< count term-input-ring-size)
1586 (re-search-backward "^[ \t]*\\([^#\n].*\\)[ \t]*$"
1588 (let ((history (buffer-substring (match-beginning 1)
1590 (when (or (null term-input-ignoredups)
1592 (not (string-equal (ring-ref ring 0) history)))
1593 (ring-insert-at-beginning ring history)))
1594 (setq count (1+ count))))
1595 (setq term-input-ring ring
1596 term-input-ring-index nil)))))
1598 (defun term-write-input-ring ()
1599 "Write the buffer's `term-input-ring' to a history file.
1600 The name of the file is given by the variable `term-input-ring-file-name'.
1601 The original contents of the file are lost if `term-input-ring' is not empty.
1602 If `term-input-ring-file-name' is nil this function does nothing.
1604 Useful within process sentinels.
1606 See also `term-read-input-ring'."
1607 (cond ((or (null term-input-ring-file-name)
1608 (equal term-input-ring-file-name "")
1609 (null term-input-ring) (ring-empty-p term-input-ring))
1611 ((not (file-writable-p term-input-ring-file-name))
1612 (message "Cannot write history file %s" term-input-ring-file-name))
1614 (let* ((history-buf (get-buffer-create " *Temp Input History*"))
1615 (ring term-input-ring)
1616 (file term-input-ring-file-name)
1617 (index (ring-length ring)))
1618 ;; Write it all out into a buffer first. Much faster, but messier,
1619 ;; than writing it one line at a time.
1620 (with-current-buffer history-buf
1623 (setq index (1- index))
1624 (insert (ring-ref ring index) ?\n))
1625 (write-region (buffer-string) nil file nil 'no-message)
1626 (kill-buffer nil))))))
1629 (defun term-dynamic-list-input-ring ()
1630 "List in help buffer the buffer's input history."
1632 (if (or (not (ring-p term-input-ring))
1633 (ring-empty-p term-input-ring))
1634 (message "No history")
1636 (history-buffer " *Input History*")
1637 (index (1- (ring-length term-input-ring)))
1638 (conf (current-window-configuration)))
1639 ;; We have to build up a list ourselves from the ring vector.
1641 (setq history (cons (ring-ref term-input-ring index) history)
1643 ;; Change "completion" to "history reference"
1644 ;; to make the display accurate.
1645 (with-output-to-temp-buffer history-buffer
1646 (display-completion-list history)
1647 (set-buffer history-buffer)
1649 (while (search-backward "completion" nil 'move)
1650 (replace-match "history reference")))
1652 (message "Hit space to flush")
1653 (let ((ch (read-event)))
1655 (set-window-configuration conf)
1656 (setq unread-command-events (list ch)))))))
1659 (defun term-regexp-arg (prompt)
1660 ;; Return list of regexp and prefix arg using PROMPT.
1661 (let* (;; Don't clobber this.
1662 (last-command last-command)
1663 (regexp (read-from-minibuffer prompt nil nil nil
1664 'minibuffer-history-search-history)))
1665 (list (if (string-equal regexp "")
1666 (setcar minibuffer-history-search-history
1667 (nth 1 minibuffer-history-search-history))
1669 (prefix-numeric-value current-prefix-arg))))
1671 (defun term-search-arg (arg)
1672 ;; First make sure there is a ring and that we are after the process mark
1673 (cond ((not (term-after-pmark-p))
1674 (error "Not at command line"))
1675 ((or (null term-input-ring)
1676 (ring-empty-p term-input-ring))
1677 (error "Empty input ring"))
1679 ;; arg of zero resets search from beginning, and uses arg of 1
1680 (setq term-input-ring-index nil)
1685 (defun term-search-start (arg)
1686 ;; Index to start a directional search, starting at term-input-ring-index
1687 (if term-input-ring-index
1688 ;; If a search is running, offset by 1 in direction of arg
1689 (mod (+ term-input-ring-index (if (> arg 0) 1 -1))
1690 (ring-length term-input-ring))
1691 ;; For a new search, start from beginning or end, as appropriate
1693 0 ; First elt for forward search
1694 (1- (ring-length term-input-ring))))) ; Last elt for backward search
1696 (defun term-previous-input-string (arg)
1697 "Return the string ARG places along the input ring.
1698 Moves relative to `term-input-ring-index'."
1699 (ring-ref term-input-ring (if term-input-ring-index
1700 (mod (+ arg term-input-ring-index)
1701 (ring-length term-input-ring))
1704 (defun term-previous-input (arg)
1705 "Cycle backwards through input history."
1707 (term-previous-matching-input "." arg))
1709 (defun term-next-input (arg)
1710 "Cycle forwards through input history."
1712 (term-previous-input (- arg)))
1714 (defun term-previous-matching-input-string (regexp arg)
1715 "Return the string matching REGEXP ARG places along the input ring.
1716 Moves relative to `term-input-ring-index'."
1717 (let* ((pos (term-previous-matching-input-string-position regexp arg)))
1718 (when pos (ring-ref term-input-ring pos))))
1720 (defun term-previous-matching-input-string-position
1721 (regexp arg &optional start)
1722 "Return the index matching REGEXP ARG places along the input ring.
1723 Moves relative to START, or `term-input-ring-index'."
1724 (when (or (not (ring-p term-input-ring))
1725 (ring-empty-p term-input-ring))
1726 (error "No history"))
1727 (let* ((len (ring-length term-input-ring))
1728 (motion (if (> arg 0) 1 -1))
1729 (n (mod (- (or start (term-search-start arg)) motion) len))
1730 (tried-each-ring-item nil)
1732 ;; Do the whole search as many times as the argument says.
1733 (while (and (/= arg 0) (not tried-each-ring-item))
1736 n (mod (+ n motion) len))
1737 ;; If we haven't reached a match, step some more.
1738 (while (and (< n len) (not tried-each-ring-item)
1739 (not (string-match regexp (ring-ref term-input-ring n))))
1740 (setq n (mod (+ n motion) len)
1741 ;; If we have gone all the way around in this search.
1742 tried-each-ring-item (= n prev)))
1743 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1744 ;; Now that we know which ring element to use, if we found it, return that.
1745 (when (string-match regexp (ring-ref term-input-ring n))
1748 (defun term-previous-matching-input (regexp n)
1749 "Search backwards through input history for match for REGEXP.
1750 \(Previous history elements are earlier commands.)
1751 With prefix argument N, search for Nth previous match.
1752 If N is negative, find the next or Nth next match."
1753 (interactive (term-regexp-arg "Previous input matching (regexp): "))
1754 (setq n (term-search-arg n))
1755 (let ((pos (term-previous-matching-input-string-position regexp n)))
1756 ;; Has a match been found?
1759 (setq term-input-ring-index pos)
1760 (message "History item: %d" (1+ pos))
1762 ;; Can't use kill-region as it sets this-command
1763 (process-mark (get-buffer-process (current-buffer))) (point))
1764 (insert (ring-ref term-input-ring pos)))))
1766 (defun term-next-matching-input (regexp n)
1767 "Search forwards through input history for match for REGEXP.
1768 \(Later history elements are more recent commands.)
1769 With prefix argument N, search for Nth following match.
1770 If N is negative, find the previous or Nth previous match."
1771 (interactive (term-regexp-arg "Next input matching (regexp): "))
1772 (term-previous-matching-input regexp (- n)))
1774 (defun term-previous-matching-input-from-input (n)
1775 "Search backwards through input history for match for current input.
1776 \(Previous history elements are earlier commands.)
1777 With prefix argument N, search for Nth previous match.
1778 If N is negative, search forwards for the -Nth following match."
1780 (when (not (memq last-command '(term-previous-matching-input-from-input
1781 term-next-matching-input-from-input)))
1782 ;; Starting a new search
1783 (setq term-matching-input-from-input-string
1785 (process-mark (get-buffer-process (current-buffer)))
1787 term-input-ring-index nil))
1788 (term-previous-matching-input
1789 (concat "^" (regexp-quote term-matching-input-from-input-string))
1792 (defun term-next-matching-input-from-input (n)
1793 "Search forwards through input history for match for current input.
1794 \(Following history elements are more recent commands.)
1795 With prefix argument N, search for Nth following match.
1796 If N is negative, search backwards for the -Nth previous match."
1798 (term-previous-matching-input-from-input (- n)))
1801 (defun term-replace-by-expanded-history (&optional silent)
1802 "Expand input command history references before point.
1803 Expansion is dependent on the value of `term-input-autoexpand'.
1805 This function depends on the buffer's idea of the input history, which may not
1806 match the command interpreter's idea, assuming it has one.
1808 Assumes history syntax is like typical Un*x shells'. However, since Emacs
1809 cannot know the interpreter's idea of input line numbers, assuming it has one,
1810 it cannot expand absolute input line number references.
1812 If the optional argument SILENT is non-nil, never complain
1813 even if history reference seems erroneous.
1815 See `term-magic-space' and `term-replace-by-expanded-history-before-point'.
1817 Returns t if successful."
1819 (when (and term-input-autoexpand
1820 (string-match "[!^]" (funcall term-get-old-input))
1821 (save-excursion (beginning-of-line)
1822 (looking-at term-prompt-regexp)))
1823 ;; Looks like there might be history references in the command.
1824 (let ((previous-modified-tick (buffer-modified-tick)))
1825 (message "Expanding history references...")
1826 (term-replace-by-expanded-history-before-point silent)
1827 (/= previous-modified-tick (buffer-modified-tick)))))
1830 (defun term-replace-by-expanded-history-before-point (silent)
1831 "Expand directory stack reference before point.
1832 See `term-replace-by-expanded-history'. Returns t if successful."
1834 (let ((toend (- (line-end-position) (point)))
1835 (start (progn (term-bol nil) (point))))
1837 (skip-chars-forward "^!^" (- (line-end-position) toend))
1838 (< (point) (- (line-end-position) toend)))
1839 ;; This seems a bit complex. We look for references such as !!, !-num,
1840 ;; !foo, !?foo, !{bar}, !?{bar}, ^oh, ^my^, ^god^it, ^never^ends^.
1841 ;; If that wasn't enough, the plings can be suffixed with argument
1842 ;; range specifiers.
1843 ;; Argument ranges are complex too, so we hive off the input line,
1844 ;; referenced with plings, with the range string to `term-args'.
1845 (setq term-input-ring-index nil)
1846 (cond ((or (= (preceding-char) ?\\)
1847 (term-within-quotes start (point)))
1848 ;; The history is quoted, or we're in quotes.
1849 (goto-char (1+ (point))))
1850 ((looking-at "![0-9]+\\($\\|[^-]\\)")
1851 ;; We cannot know the interpreter's idea of input line numbers.
1852 (goto-char (match-end 0))
1853 (message "Absolute reference cannot be expanded"))
1854 ((looking-at "!-\\([0-9]+\\)\\(:?[0-9^$*-]+\\)?")
1855 ;; Just a number of args from `number' lines backward.
1856 (let ((number (1- (string-to-number
1857 (buffer-substring (match-beginning 1)
1859 (if (<= number (ring-length term-input-ring))
1862 (term-args (term-previous-input-string number)
1863 (match-beginning 2) (match-end 2))
1865 (setq term-input-ring-index number)
1866 (message "History item: %d" (1+ number)))
1867 (goto-char (match-end 0))
1868 (message "Relative reference exceeds input history size"))))
1869 ((or (looking-at "!!?:?\\([0-9^$*-]+\\)") (looking-at "!!"))
1870 ;; Just a number of args from the previous input line.
1872 (term-args (term-previous-input-string 0)
1873 (match-beginning 1) (match-end 1))
1875 (message "History item: previous"))
1877 "!\\??\\({\\(.+\\)}\\|\\(\\sw+\\)\\)\\(:?[0-9^$*-]+\\)?")
1878 ;; Most recent input starting with or containing (possibly
1879 ;; protected) string, maybe just a number of args. Phew.
1880 (let* ((mb1 (match-beginning 1)) (me1 (match-end 1))
1881 (mb2 (match-beginning 2)) (me2 (match-end 2))
1882 (exp (buffer-substring (or mb2 mb1) (or me2 me1)))
1883 (pref (if (save-match-data (looking-at "!\\?")) "" "^"))
1884 (pos (save-match-data
1885 (term-previous-matching-input-string-position
1886 (concat pref (regexp-quote exp)) 1))))
1889 (goto-char (match-end 0))
1891 (progn (message "Not found")
1893 (setq term-input-ring-index pos)
1895 (term-args (ring-ref term-input-ring pos)
1896 (match-beginning 4) (match-end 4))
1898 (message "History item: %d" (1+ pos)))))
1899 ((looking-at "\\^\\([^^]+\\)\\^?\\([^^]*\\)\\^?")
1900 ;; Quick substitution on the previous input line.
1901 (let ((old (buffer-substring (match-beginning 1) (match-end 1)))
1902 (new (buffer-substring (match-beginning 2) (match-end 2)))
1904 (replace-match (term-previous-input-string 0) t t)
1906 (goto-char (match-beginning 0))
1907 (if (not (search-forward old pos t))
1909 (error "Not found"))
1910 (replace-match new t t)
1911 (message "History item: substituted"))))
1913 (goto-char (match-end 0))))))))
1916 (defun term-magic-space (arg)
1917 "Expand input history references before point and insert ARG spaces.
1918 A useful command to bind to SPC. See `term-replace-by-expanded-history'."
1920 (term-replace-by-expanded-history)
1921 (self-insert-command arg))
1923 (defun term-within-quotes (beg end)
1924 "Return t if the number of quotes between BEG and END is odd.
1925 Quotes are single and double."
1926 (let ((countsq (term-how-many-region "\\(^\\|[^\\\\]\\)\'" beg end))
1927 (countdq (term-how-many-region "\\(^\\|[^\\\\]\\)\"" beg end)))
1928 (or (= (mod countsq 2) 1) (= (mod countdq 2) 1))))
1930 (defun term-how-many-region (regexp beg end)
1931 "Return number of matches for REGEXP from BEG to END."
1936 (while (re-search-forward regexp end t)
1937 (setq count (1+ count)))))
1940 (defun term-args (string begin end)
1941 ;; From STRING, return the args depending on the range specified in the text
1942 ;; from BEGIN to END. If BEGIN is nil, assume all args. Ignore leading `:'.
1943 ;; Range can be x-y, x-, -y, where x/y can be [0-9], *, ^, $.
1946 (term-arguments string 0 nil)
1947 (let* ((range (buffer-substring
1948 (if (eq (char-after begin) ?:) (1+ begin) begin) end))
1949 (nth (cond ((string-match "^[*^]" range) 1)
1950 ((string-match "^-" range) 0)
1951 ((string-equal range "$") nil)
1952 (t (string-to-number range))))
1953 (mth (cond ((string-match "[-*$]$" range) nil)
1954 ((string-match "-" range)
1955 (string-to-number (substring range (match-end 0))))
1957 (term-arguments string nth mth)))))
1959 ;; Return a list of arguments from ARG. Break it up at the
1960 ;; delimiters in term-delimiter-argument-list. Returned list is backwards.
1961 (defun term-delim-arg (arg)
1962 (if (null term-delimiter-argument-list)
1968 (let ((char (aref arg pos))
1970 (if (memq char term-delimiter-argument-list)
1971 (while (and (< pos len) (eq (aref arg pos) char))
1972 (setq pos (1+ pos)))
1973 (while (and (< pos len)
1974 (not (memq (aref arg pos)
1975 term-delimiter-argument-list)))
1976 (setq pos (1+ pos))))
1977 (setq args (cons (substring arg start pos) args))))
1980 (defun term-arguments (string nth mth)
1981 "Return from STRING the NTH to MTH arguments.
1982 NTH and/or MTH can be nil, which means the last argument.
1983 Returned arguments are separated by single spaces.
1984 We assume whitespace separates arguments, except within quotes.
1985 Also, a run of one or more of a single character
1986 in `term-delimiter-argument-list' is a separate argument.
1987 Argument 0 is the command name."
1988 (let ((argpart "[^ \n\t\"'`]+\\|\\(\"[^\"]*\"\\|'[^']*'\\|`[^`]*`\\)")
1992 ;; Build a list of all the args until we have as many as we want.
1993 (while (and (or (null mth) (<= count mth))
1994 (string-match argpart string pos))
1995 (if (and beg (= pos (match-beginning 0)))
1996 ;; It's contiguous, part of the same arg.
1997 (setq pos (match-end 0)
1998 quotes (or quotes (match-beginning 1)))
1999 ;; It's a new separate arg.
2001 ;; Put the previous arg, if there was one, onto ARGS.
2002 (setq str (substring string beg pos)
2003 args (if quotes (cons str args)
2004 (nconc (term-delim-arg str) args))
2006 (setq quotes (match-beginning 1))
2007 (setq beg (match-beginning 0))
2008 (setq pos (match-end 0))))
2010 (setq str (substring string beg pos)
2011 args (if quotes (cons str args)
2012 (nconc (term-delim-arg str) args))
2014 (let ((n (or nth (1- count)))
2015 (m (if mth (1- (- count mth)) 0)))
2017 (function (lambda (a) a)) (nthcdr n (nreverse (nthcdr m args))) " "))))
2020 ;;; Input processing stuff [line mode]
2023 (defun term-send-input ()
2024 "Send input to process.
2025 After the process output mark, sends all text from the process mark to
2026 point as input to the process. Before the process output mark, calls value
2027 of variable `term-get-old-input' to retrieve old input, copies it to the
2028 process mark, and sends it. A terminal newline is also inserted into the
2029 buffer and sent to the process. The list of function names contained in the
2030 value of `term-input-filter-functions' is called on the input before sending
2031 it. The input is entered into the input history ring, if the value of variable
2032 `term-input-filter' returns non-nil when called on the input.
2034 Any history reference may be expanded depending on the value of the variable
2035 `term-input-autoexpand'. The list of function names contained in the value
2036 of `term-input-filter-functions' is called on the input before sending it.
2037 The input is entered into the input history ring, if the value of variable
2038 `term-input-filter' returns non-nil when called on the input.
2040 If variable `term-eol-on-send' is non-nil, then point is moved to the
2041 end of line before sending the input.
2043 The values of `term-get-old-input', `term-input-filter-functions', and
2044 `term-input-filter' are chosen according to the command interpreter running
2045 in the buffer. E.g.,
2047 If the interpreter is the csh,
2048 term-get-old-input is the default: take the current line, discard any
2049 initial string matching regexp term-prompt-regexp.
2050 term-input-filter-functions monitors input for \"cd\", \"pushd\", and
2051 \"popd\" commands. When it sees one, it cd's the buffer.
2052 term-input-filter is the default: returns t if the input isn't all white
2055 If the term is Lucid Common Lisp,
2056 term-get-old-input snarfs the sexp ending at point.
2057 term-input-filter-functions does nothing.
2058 term-input-filter returns nil if the input matches input-filter-regexp,
2059 which matches (1) all whitespace (2) :a, :c, etc.
2061 Similarly for Soar, Scheme, etc."
2063 ;; Note that the input string does not include its terminal newline.
2064 (let ((proc (get-buffer-process (current-buffer))))
2065 (if (not proc) (error "Current buffer has no process")
2066 (let* ((pmark (process-mark proc))
2067 (pmark-val (marker-position pmark))
2068 (input-is-new (>= (point) pmark-val))
2069 (intxt (if input-is-new
2070 (progn (if term-eol-on-send (end-of-line))
2071 (buffer-substring pmark (point)))
2072 (funcall term-get-old-input)))
2073 (input (if (not (eq term-input-autoexpand 'input))
2074 ;; Just whatever's already there
2076 ;; Expand and leave it visible in buffer
2077 (term-replace-by-expanded-history t)
2078 (buffer-substring pmark (point))))
2079 (history (if (not (eq term-input-autoexpand 'history))
2081 ;; This is messy 'cos ultimately the original
2082 ;; functions used do insertion, rather than return
2083 ;; strings. We have to expand, then insert back.
2084 (term-replace-by-expanded-history t)
2085 (let ((copy (buffer-substring pmark (point))))
2086 (delete-region pmark (point))
2089 (when (term-pager-enabled)
2091 (goto-char (process-mark proc))
2092 (setq term-pager-count (term-current-row))))
2093 (when (and (funcall term-input-filter history)
2094 (or (null term-input-ignoredups)
2095 (not (ring-p term-input-ring))
2096 (ring-empty-p term-input-ring)
2097 (not (string-equal (ring-ref term-input-ring 0)
2099 (ring-insert term-input-ring history))
2100 (let ((functions term-input-filter-functions))
2102 (funcall (car functions) (concat input "\n"))
2103 (setq functions (cdr functions))))
2104 (setq term-input-ring-index nil)
2106 ;; Update the markers before we send the input
2107 ;; in case we get output amidst sending the input.
2108 (set-marker term-last-input-start pmark)
2109 (set-marker term-last-input-end (point))
2111 ;; Set up to delete, because inferior should echo.
2112 (when (marker-buffer term-pending-delete-marker)
2113 (delete-region term-pending-delete-marker pmark))
2114 (set-marker term-pending-delete-marker pmark-val)
2115 (set-marker (process-mark proc) (point)))
2117 (funcall term-input-sender proc input)))))
2119 (defun term-get-old-input-default ()
2120 "Default for `term-get-old-input'.
2121 Take the current line, and discard any initial text matching
2122 `term-prompt-regexp'."
2126 (let ((beg (point)))
2128 (buffer-substring beg (point)))))
2130 (defun term-copy-old-input ()
2131 "Insert after prompt old input at point as new input to be edited.
2132 Calls `term-get-old-input' to get old input."
2134 (let ((input (funcall term-get-old-input))
2135 (process (get-buffer-process (current-buffer))))
2137 (error "Current buffer has no process")
2138 (goto-char (process-mark process))
2141 (defun term-skip-prompt ()
2142 "Skip past the text matching regexp `term-prompt-regexp'.
2143 If this takes us past the end of the current line, don't skip at all."
2144 (let ((eol (line-end-position)))
2145 (when (and (looking-at term-prompt-regexp)
2146 (<= (match-end 0) eol))
2147 (goto-char (match-end 0)))))
2150 (defun term-after-pmark-p ()
2151 "Is point after the process output marker?"
2152 ;; Since output could come into the buffer after we looked at the point
2153 ;; but before we looked at the process marker's value, we explicitly
2154 ;; serialize. This is just because I don't know whether or not Emacs
2155 ;; services input during execution of lisp commands.
2156 (let ((proc-pos (marker-position
2157 (process-mark (get-buffer-process (current-buffer))))))
2158 (<= proc-pos (point))))
2160 (defun term-simple-send (proc string)
2161 "Default function for sending to PROC input STRING.
2162 This just sends STRING plus a newline. To override this,
2163 set the hook `term-input-sender'."
2164 (term-send-string proc string)
2165 (term-send-string proc "\n"))
2167 (defun term-bol (arg)
2168 "Go to the beginning of line, then skip past the prompt, if any.
2169 If a prefix argument is given (\\[universal-argument]), then no prompt skip
2170 -- go straight to column 0.
2172 The prompt skip is done by skipping text matching the regular expression
2173 `term-prompt-regexp', a buffer local variable."
2176 (when (null arg) (term-skip-prompt)))
2178 ;; These two functions are for entering text you don't want echoed or
2179 ;; saved -- typically passwords to ftp, telnet, or somesuch.
2180 ;; Just enter m-x term-send-invisible and type in your line.
2182 (defun term-read-noecho (prompt &optional stars)
2183 "Read a single line of text from user without echoing, and return it.
2184 Prompt with argument PROMPT, a string. Optional argument STARS causes
2185 input to be echoed with '*' characters on the prompt line. Input ends with
2186 RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line. C-g aborts (if
2187 `inhibit-quit' is set because e.g. this function was called from a process
2188 filter and C-g is pressed, this function returns nil rather than a string).
2190 Note that the keystrokes comprising the text can still be recovered
2191 \(temporarily) with \\[view-lossage]. This may be a security bug for some
2196 (cursor-in-echo-area t)
2200 (message "%s%s" prompt (make-string (length ans) ?*))
2201 (message "%s" prompt))
2202 (setq c (read-char))
2204 ;; This function may get called from a process filter, where
2205 ;; inhibit-quit is set. In later versions of Emacs read-char
2206 ;; may clear quit-flag itself and return C-g. That would make
2207 ;; it impossible to quit this loop in a simple way, so
2208 ;; re-enable it here (for backward-compatibility the check for
2209 ;; quit-flag below would still be necessary, so this seems
2210 ;; like the simplest way to do things).
2213 ((or (= c ?\r) (= c ?\n) (= c ?\e))
2217 ((and (/= c ?\b) (/= c ?\177))
2218 (setq ans (concat ans (char-to-string c))))
2220 (setq ans (substring ans 0 -1)))))
2222 ;; Emulate a true quit, except that we have to return a value.
2224 (setq quit-flag nil)
2230 (defun term-send-invisible (str &optional proc)
2231 "Read a string without echoing.
2232 Then send it to the process running in the current buffer. A new-line
2233 is additionally sent. String is not saved on term input history list.
2234 Security bug: your string can still be temporarily recovered with
2236 (interactive "P") ; Defeat snooping via C-x esc
2237 (when (not (stringp str))
2238 (setq str (term-read-noecho "Non-echoed text: " t)))
2240 (setq proc (get-buffer-process (current-buffer))))
2241 (if (not proc) (error "Current buffer has no process")
2242 (setq term-kill-echo-list (nconc term-kill-echo-list
2244 (term-send-string proc str)
2245 (term-send-string proc "\n")))
2248 ;;; Low-level process communication
2250 (defcustom term-input-chunk-size 512
2251 "Long inputs send to term processes are broken up into chunks of this size.
2252 If your process is choking on big inputs, try lowering the value."
2256 (defun term-send-string (proc str)
2257 "Send to PROC the contents of STR as input.
2258 This is equivalent to `process-send-string', except that long input strings
2259 are broken up into chunks of size `term-input-chunk-size'. Processes
2260 are given a chance to output between chunks. This can help prevent processes
2261 from hanging when you send them long inputs on some OS's."
2262 (let* ((len (length str))
2263 (i (min len term-input-chunk-size)))
2264 (process-send-string proc (substring str 0 i))
2266 (let ((next-i (+ i term-input-chunk-size)))
2267 (accept-process-output)
2268 (process-send-string proc (substring str i (min len next-i)))
2271 (defun term-send-region (proc start end)
2272 "Send to PROC the region delimited by START and END.
2273 This is a replacement for `process-send-region' that tries to keep
2274 your process from hanging on long inputs. See `term-send-string'."
2275 (term-send-string proc (buffer-substring start end)))
2278 ;;; Random input hackage
2280 (defun term-kill-output ()
2281 "Kill all output from interpreter since last input."
2283 (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
2284 (kill-region term-last-input-end pmark)
2286 (insert "*** output flushed ***\n")
2287 (set-marker pmark (point))))
2289 (defun term-show-output ()
2290 "Display start of this batch of interpreter output at top of window.
2291 Sets mark to the value of point when this command is run."
2293 (goto-char term-last-input-end)
2296 (set-window-start (selected-window) (point))
2299 (defun term-interrupt-subjob ()
2300 "Interrupt the current subjob."
2302 (interrupt-process nil term-ptyp))
2304 (defun term-kill-subjob ()
2305 "Send kill signal to the current subjob."
2307 (kill-process nil term-ptyp))
2309 (defun term-quit-subjob ()
2310 "Send quit signal to the current subjob."
2312 (quit-process nil term-ptyp))
2314 (defun term-stop-subjob ()
2315 "Stop the current subjob.
2316 WARNING: if there is no current subjob, you can end up suspending
2317 the top-level process running in the buffer. If you accidentally do
2318 this, use \\[term-continue-subjob] to resume the process. (This
2319 is not a problem with most shells, since they ignore this signal.)"
2321 (stop-process nil term-ptyp))
2323 (defun term-continue-subjob ()
2324 "Send CONT signal to process buffer's process group.
2325 Useful if you accidentally suspend the top-level process."
2327 (continue-process nil term-ptyp))
2329 (defun term-kill-input ()
2330 "Kill all text from last stuff output by interpreter to point."
2332 (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
2333 (p-pos (marker-position pmark)))
2334 (when (> (point) p-pos)
2335 (kill-region pmark (point)))))
2337 (defun term-delchar-or-maybe-eof (arg)
2338 "Delete ARG characters forward, or send an EOF to process if at end of
2345 (defun term-send-eof ()
2346 "Send an EOF to the current buffer's process."
2350 (defun term-backward-matching-input (regexp n)
2351 "Search backward through buffer for match for REGEXP.
2352 Matches are searched for on lines that match `term-prompt-regexp'.
2353 With prefix argument N, search for Nth previous match.
2354 If N is negative, find the next or Nth next match."
2355 (interactive (term-regexp-arg "Backward input matching (regexp): "))
2356 (let* ((re (concat term-prompt-regexp ".*" regexp))
2357 (pos (save-excursion (end-of-line (if (> n 0) 0 1))
2358 (when (re-search-backward re nil t n)
2361 (progn (message "Not found")
2366 (defun term-forward-matching-input (regexp n)
2367 "Search forward through buffer for match for REGEXP.
2368 Matches are searched for on lines that match `term-prompt-regexp'.
2369 With prefix argument N, search for Nth following match.
2370 If N is negative, find the previous or Nth previous match."
2371 (interactive (term-regexp-arg "Forward input matching (regexp): "))
2372 (term-backward-matching-input regexp (- n)))
2375 (defun term-next-prompt (n)
2376 "Move to end of Nth next prompt in the buffer.
2377 See `term-prompt-regexp'."
2379 (let ((paragraph-start term-prompt-regexp))
2380 (end-of-line (if (> n 0) 1 0))
2381 (forward-paragraph n)
2382 (term-skip-prompt)))
2384 (defun term-previous-prompt (n)
2385 "Move to end of Nth previous prompt in the buffer.
2386 See `term-prompt-regexp'."
2388 (term-next-prompt (- n)))
2390 ;;; Support for source-file processing commands.
2391 ;;============================================================================
2392 ;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
2393 ;; commands that process files of source text (e.g. loading or compiling
2394 ;; files). So the corresponding process-in-a-buffer modes have commands
2395 ;; for doing this (e.g., lisp-load-file). The functions below are useful
2396 ;; for defining these commands.
2398 ;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
2399 ;; and Soar, in that they don't know anything about file extensions.
2400 ;; So the compile/load interface gets the wrong default occasionally.
2401 ;; The load-file/compile-file default mechanism could be smarter -- it
2402 ;; doesn't know about the relationship between filename extensions and
2403 ;; whether the file is source or executable. If you compile foo.lisp
2404 ;; with compile-file, then the next load-file should use foo.bin for
2405 ;; the default, not foo.lisp. This is tricky to do right, particularly
2406 ;; because the extension for executable files varies so much (.o, .bin,
2407 ;; .lbin, .mo, .vo, .ao, ...).
2410 ;; TERM-SOURCE-DEFAULT -- determines defaults for source-file processing
2413 ;; TERM-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
2414 ;; want to save the buffer before issuing any process requests to the command
2417 ;; TERM-GET-SOURCE -- used by the source-file processing commands to prompt
2418 ;; for the file to process.
2420 ;; (TERM-SOURCE-DEFAULT previous-dir/file source-modes)
2421 ;;============================================================================
2422 ;; This function computes the defaults for the load-file and compile-file
2423 ;; commands for tea, soar, cmulisp, and cmuscheme modes.
2425 ;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
2426 ;; source-file processing command, or nil if there hasn't been one yet.
2427 ;; - SOURCE-MODES is a list used to determine what buffers contain source
2428 ;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
2429 ;; Typically, (lisp-mode) or (scheme-mode).
2431 ;; If the command is given while the cursor is inside a string, *and*
2432 ;; the string is an existing filename, *and* the filename is not a directory,
2433 ;; then the string is taken as default. This allows you to just position
2434 ;; your cursor over a string that's a filename and have it taken as default.
2436 ;; If the command is given in a file buffer whose major mode is in
2437 ;; SOURCE-MODES, then the filename is the default file, and the
2438 ;; file's directory is the default directory.
2440 ;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
2441 ;; then the default directory & file are what was used in the last source-file
2442 ;; processing command (i.e., PREVIOUS-DIR/FILE). If this is the first time
2443 ;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
2444 ;; is the cwd, with no default file. (\"no default file\" = nil)
2446 ;; SOURCE-REGEXP is typically going to be something like (tea-mode)
2447 ;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
2448 ;; for Soar programs, etc.
2450 ;; The function returns a pair: (default-directory . default-file).
2452 (defun term-source-default (previous-dir/file source-modes)
2453 (cond ((and buffer-file-name (memq major-mode source-modes))
2454 (cons (file-name-directory buffer-file-name)
2455 (file-name-nondirectory buffer-file-name)))
2458 (cons default-directory nil))))
2461 ;; (TERM-CHECK-SOURCE fname)
2462 ;;============================================================================
2463 ;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
2464 ;; process-in-a-buffer modes), this function can be called on the filename.
2465 ;; If the file is loaded into a buffer, and the buffer is modified, the user
2466 ;; is queried to see if he wants to save the buffer before proceeding with
2467 ;; the load or compile.
2469 (defun term-check-source (fname)
2470 (let ((buff (get-file-buffer fname)))
2472 (buffer-modified-p buff)
2473 (y-or-n-p (format "Save buffer %s first? "
2474 (buffer-name buff))))
2476 (with-current-buffer buff
2480 ;; (TERM-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
2481 ;;============================================================================
2482 ;; TERM-GET-SOURCE is used to prompt for filenames in command-interpreter
2483 ;; commands that process source files (like loading or compiling a file).
2484 ;; It prompts for the filename, provides a default, if there is one,
2485 ;; and returns the result filename.
2487 ;; See TERM-SOURCE-DEFAULT for more on determining defaults.
2489 ;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
2490 ;; from the last source processing command. SOURCE-MODES is a list of major
2491 ;; modes used to determine what file buffers contain source files. (These
2492 ;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
2493 ;; then the filename reader will only accept a file that exists.
2496 ;; (interactive (term-get-source "Compile file: " prev-lisp-dir/file
2499 ;; This is pretty stupid about strings. It decides we're in a string
2500 ;; if there's a quote on both sides of point on the current line.
2501 (defun term-extract-string ()
2502 "Return string around `point' that starts the current line or nil."
2504 (let* ((point (point))
2505 (bol (line-beginning-position))
2506 (eol (line-end-position))
2507 (start (and (search-backward "\"" bol t)
2509 (end (progn (goto-char point)
2510 (and (search-forward "\"" eol t)
2513 (buffer-substring start end)))))
2515 (defun term-get-source (prompt prev-dir/file source-modes mustmatch-p)
2516 (let* ((def (term-source-default prev-dir/file source-modes))
2517 (stringfile (term-extract-string))
2518 (sfile-p (and stringfile
2520 (file-exists-p stringfile)
2522 (not (file-directory-p stringfile))))
2523 (defdir (if sfile-p (file-name-directory stringfile)
2525 (deffile (if sfile-p (file-name-nondirectory stringfile)
2527 (ans (read-file-name (if deffile (format "%s(default %s) "
2531 (concat defdir deffile)
2533 (list (expand-file-name (substitute-in-file-name ans)))))
2535 ;; I am somewhat divided on this string-default feature. It seems
2536 ;; to violate the principle-of-least-astonishment, in that it makes
2537 ;; the default harder to predict, so you actually have to look and see
2538 ;; what the default really is before choosing it. This can trip you up.
2539 ;; On the other hand, it can be useful, I guess. I would appreciate feedback
2544 ;;; Simple process query facility.
2545 ;; ===========================================================================
2546 ;; This function is for commands that want to send a query to the process
2547 ;; and show the response to the user. For example, a command to get the
2548 ;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
2549 ;; to an inferior Common Lisp process.
2551 ;; This simple facility just sends strings to the inferior process and pops
2552 ;; up a window for the process buffer so you can see what the process
2553 ;; responds with. We don't do anything fancy like try to intercept what the
2554 ;; process responds with and put it in a pop-up window or on the message
2555 ;; line. We just display the buffer. Low tech. Simple. Works good.
2557 ;; Send to the inferior process PROC the string STR. Pop-up but do not select
2558 ;; a window for the inferior process so that its response can be seen.
2559 (defun term-proc-query (proc str)
2560 (let* ((proc-buf (process-buffer proc))
2561 (proc-mark (process-mark proc)))
2562 (display-buffer proc-buf)
2563 (set-buffer proc-buf) ; but it's not the selected *window*
2564 (let ((proc-win (get-buffer-window proc-buf))
2565 (proc-pt (marker-position proc-mark)))
2566 (term-send-string proc str) ; send the query
2567 (accept-process-output proc) ; wait for some output
2568 ;; Try to position the proc window so you can see the answer.
2569 ;; This is bogus code. If you delete the (sit-for 0), it breaks.
2570 ;; I don't know why. Wizards invited to improve it.
2571 (when (not (pos-visible-in-window-p proc-pt proc-win))
2572 (let ((opoint (window-point proc-win)))
2573 (set-window-point proc-win proc-mark) (sit-for 0)
2574 (if (not (pos-visible-in-window-p opoint proc-win))
2576 (set-window-point proc-win opoint)))))))
2578 ;; Returns the current column in the current screen line.
2579 ;; Note: (current-column) yields column in buffer line.
2581 (defun term-horizontal-column ()
2582 (- (term-current-column) (term-start-line-column)))
2584 ;; Calls either vertical-motion or term-buffer-vertical-motion
2585 (defmacro term-vertical-motion (count)
2586 (list 'funcall 'term-vertical-motion count))
2588 ; An emulation of vertical-motion that is independent of having a window.
2589 ; Instead, it uses the term-width variable as the logical window width.
2591 (defun term-buffer-vertical-motion (count)
2593 (move-to-column (* term-width (/ (current-column) term-width)))
2597 (todo (+ count (/ (current-column) term-width))))
2599 ;; The loop iterates over buffer lines;
2600 ;; H is the number of screen lines in the current line, i.e.
2601 ;; the ceiling of dividing the buffer line width by term-width.
2602 (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2607 (setq todo (- todo H))
2608 (forward-char) ;; Move past the ?\n
2609 (end-of-line)) ;; and on to the end of the next line.
2610 (if (and (>= todo H) (> todo 0))
2611 (+ (- count todo) H -1) ;; Hit end of buffer.
2612 (move-to-column (* todo term-width))
2614 (t ;; (< count 0) ;; Similar algorithm, but for upward motion.
2617 (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
2621 (progn (beginning-of-line)
2623 (setq todo (- todo H))
2624 (backward-char)) ;; Move to end of previous line.
2625 (if (and (>= todo H) (> todo 0))
2626 (+ count todo (- 1 H)) ;; Hit beginning of buffer.
2627 (move-to-column (* (- H todo 1) term-width))
2630 ;; The term-start-line-column variable is used as a cache.
2631 (defun term-start-line-column ()
2632 (cond (term-start-line-column)
2633 ((let ((save-pos (point)))
2634 (term-vertical-motion 0)
2635 (setq term-start-line-column (current-column))
2636 (goto-char save-pos)
2637 term-start-line-column))))
2639 ;; Same as (current-column), but uses term-current-column as a cache.
2640 (defun term-current-column ()
2641 (cond (term-current-column)
2642 ((setq term-current-column (current-column)))))
2644 ;; Move DELTA column right (or left if delta < 0 limiting at column 0).
2646 (defun term-move-columns (delta)
2647 (setq term-current-column (max 0 (+ (term-current-column) delta)))
2648 (let ((point-at-eol (line-end-position)))
2649 (move-to-column term-current-column t)
2650 ;; If move-to-column extends the current line it will use the face
2651 ;; from the last character on the line, set the face for the chars
2653 (when (> (point) point-at-eol)
2654 (put-text-property point-at-eol (point) 'font-lock-face 'default))))
2656 ;; Insert COUNT copies of CHAR in the default face.
2657 (defun term-insert-char (char count)
2658 (let ((old-point (point)))
2659 (insert-char char count)
2660 (put-text-property old-point (point) 'font-lock-face 'default)))
2662 (defun term-current-row ()
2663 (cond (term-current-row)
2664 ((setq term-current-row
2667 (narrow-to-region term-home-marker (point-max))
2668 (- (term-vertical-motion -9999))))))))
2670 (defun term-adjust-current-row-cache (delta)
2671 (when term-current-row
2672 (setq term-current-row
2673 (max 0 (+ term-current-row delta)))))
2675 (defun term-terminal-pos ()
2676 (save-excursion ; save-restriction
2677 (let ((save-col (term-current-column))
2679 (term-vertical-motion 0)
2680 (setq x (- save-col (current-column)))
2681 (setq y (term-vertical-motion term-height))
2684 ;;Function that handles term messages: code by rms (and you can see the
2685 ;;difference ;-) -mm
2687 (defun term-handle-ansi-terminal-messages (message)
2688 ;; Is there a command here?
2689 (while (string-match "\eAnSiT.+\n" message)
2690 ;; Extract the command code and the argument.
2691 (let* ((start (match-beginning 0))
2692 (command-code (aref message (+ start 6)))
2697 (string-match "\r?\n" message
2700 ;; Delete this command from MESSAGE.
2701 (setq message (replace-match "" t t message))
2703 ;; If we recognize the type of command, set the appropriate variable.
2704 (cond ((= command-code ?c)
2705 (setq term-ansi-at-dir argument))
2706 ((= command-code ?h)
2707 (setq term-ansi-at-host argument))
2708 ((= command-code ?u)
2709 (setq term-ansi-at-user argument))
2710 ;; Otherwise ignore this one.
2714 ;; Update default-directory based on the changes this command made.
2717 (setq default-directory
2718 (file-name-as-directory
2719 (if (and (string= term-ansi-at-host (system-name))
2720 (string= term-ansi-at-user (user-real-login-name)))
2721 (expand-file-name term-ansi-at-dir)
2722 (if (string= term-ansi-at-user (user-real-login-name))
2723 (concat "/" term-ansi-at-host ":" term-ansi-at-dir)
2724 (concat "/" term-ansi-at-user "@" term-ansi-at-host ":"
2725 term-ansi-at-dir)))))
2727 ;; I'm not sure this is necessary,
2728 ;; but it's best to be on the safe side.
2729 (if (string= term-ansi-at-host (system-name))
2731 (setq ange-ftp-default-user term-ansi-at-save-user)
2732 (setq ange-ftp-default-password term-ansi-at-save-pwd)
2733 (setq ange-ftp-generate-anonymous-password term-ansi-at-save-anon))
2734 (setq term-ansi-at-save-user ange-ftp-default-user)
2735 (setq term-ansi-at-save-pwd ange-ftp-default-password)
2736 (setq term-ansi-at-save-anon ange-ftp-generate-anonymous-password)
2737 (setq ange-ftp-default-user nil)
2738 (setq ange-ftp-default-password nil)
2739 (setq ange-ftp-generate-anonymous-password nil)))))
2743 ;; Terminal emulation
2744 ;; This is the standard process filter for term buffers.
2745 ;; It emulates (most of the features of) a VT100/ANSI-style terminal.
2747 (defun term-emulate-terminal (proc str)
2748 (with-current-buffer (process-buffer proc)
2749 (let* ((i 0) char funny
2750 count ; number of decoded chars in substring
2751 count-bytes ; number of bytes
2753 save-point save-marker old-point temp win
2754 (buffer-undo-list t)
2755 (selected (selected-window))
2757 handled-ansi-message
2758 (str-length (length str)))
2759 (save-selected-window
2761 (let ((newstr (term-handle-ansi-terminal-messages str)))
2762 (unless (eq str newstr)
2763 (setq handled-ansi-message t
2765 (setq str-length (length str))
2767 (when (marker-buffer term-pending-delete-marker)
2768 ;; Delete text following term-pending-delete-marker.
2769 (delete-region term-pending-delete-marker (process-mark proc))
2770 (set-marker term-pending-delete-marker nil))
2772 (when (/= (point) (process-mark proc))
2773 (setq save-point (point-marker)))
2775 ;; Note if the window size has changed. We used to reset
2776 ;; point too, but that gives incorrect results (Bug#4635).
2777 (if (eq (window-buffer) (current-buffer))
2779 (setq term-vertical-motion (symbol-function 'vertical-motion))
2780 (term-check-size proc))
2781 (setq term-vertical-motion
2782 (symbol-function 'term-buffer-vertical-motion)))
2783 (setq save-marker (copy-marker (process-mark proc)))
2784 (goto-char (process-mark proc))
2787 ;; If the buffer is in line mode, and there is a partial
2788 ;; input line, save the line (by narrowing to leave it
2789 ;; outside the restriction ) until we're done with output.
2790 (when (and (> (point-max) (process-mark proc))
2791 (term-in-line-mode))
2792 (narrow-to-region (point-min) (process-mark proc)))
2794 (when term-log-buffer
2795 (princ str term-log-buffer))
2796 (cond ((eq term-terminal-state 4) ;; Have saved pending output.
2797 (setq str (concat term-terminal-parameter str))
2798 (setq term-terminal-parameter nil)
2799 (setq str-length (length str))
2800 (setq term-terminal-state 0)))
2802 (while (< i str-length)
2803 (setq char (aref str i))
2804 (cond ((< term-terminal-state 2)
2805 ;; Look for prefix of regular chars
2807 (string-match "[\r\n\000\007\033\t\b\032\016\017]"
2809 (when (not funny) (setq funny str-length))
2811 ;; Decode the string before counting
2812 ;; characters, to avoid garbling of certain
2813 ;; multibyte characters (bug#1006).
2814 (setq decoded-substring
2815 (decode-coding-string
2816 (substring str i funny)
2817 locale-coding-system))
2818 (cond ((eq term-terminal-state 1)
2819 ;; We are in state 1, we need to wrap
2820 ;; around. Go to the beginning of
2821 ;; the next line and switch to state
2824 (term-move-columns (- (term-current-column)))
2825 (setq term-terminal-state 0)))
2826 (setq count (length decoded-substring))
2827 (setq temp (- (+ (term-horizontal-column) count)
2829 (cond ((or term-suppress-hard-newline (<= temp 0)))
2830 ;; All count chars fit in line.
2831 ((> count temp) ;; Some chars fit.
2832 ;; This iteration, handle only what fits.
2833 (setq count (- count temp))
2836 (encode-coding-string
2837 (substring decoded-substring 0 count)
2840 (setq funny (+ count-bytes i)))
2841 ((or (not (or term-pager-count
2842 term-scroll-with-delete))
2843 (> (term-handle-scroll 1) 0))
2844 (term-adjust-current-row-cache 1)
2845 (setq count (min count term-width))
2848 (encode-coding-string
2849 (substring decoded-substring 0 count)
2851 (setq funny (+ count-bytes i))
2852 (setq term-start-line-column
2853 term-current-column))
2854 (t ;; Doing PAGER processing.
2855 (setq count 0 funny i)
2856 (setq term-current-column nil)
2857 (setq term-start-line-column nil)))
2858 (setq old-point (point))
2860 ;; Insert a string, check how many columns
2861 ;; we moved, then delete that many columns
2862 ;; following point if not eob nor insert-mode.
2863 (let ((old-column (current-column))
2865 (insert (decode-coding-string (substring str i funny) locale-coding-system))
2866 (setq term-current-column (current-column)
2867 columns (- term-current-column old-column))
2868 (when (not (or (eobp) term-insert-mode))
2870 (term-move-columns columns)
2871 (delete-region pos (point)))
2872 ;; In insert mode if the current line
2873 ;; has become too long it needs to be
2875 (when term-insert-mode
2878 (when (> (current-column) term-width)
2879 (delete-region (- (point) (- (current-column) term-width))
2882 (setq term-current-column nil)
2884 (put-text-property old-point (point)
2885 'font-lock-face term-current-face)
2886 ;; If the last char was written in last column,
2887 ;; back up one column, but remember we did so.
2888 ;; Thus we emulate xterm/vt100-style line-wrapping.
2890 (term-move-columns -1)
2891 (setq term-terminal-state 1)))
2892 (setq i (1- funny)))
2893 ((and (setq term-terminal-state 0)
2894 (eq char ?\^I)) ; TAB (terminfo: ht)
2895 (setq count (term-current-column))
2896 ;; The line cannot exceed term-width. TAB at
2897 ;; the end of a line should not cause wrapping.
2898 (setq count (min term-width
2899 (+ count 8 (- (mod count 8)))))
2900 (if (> term-width count)
2903 (- count (term-current-column)))
2904 (setq term-current-column count))
2905 (when (> term-width (term-current-column))
2907 (1- (- term-width (term-current-column)))))
2908 (when (= term-width (term-current-column))
2909 (term-move-columns -1))))
2910 ((eq char ?\r) ;; (terminfo: cr)
2911 (term-vertical-motion 0)
2912 (setq term-current-column term-start-line-column))
2913 ((eq char ?\n) ;; (terminfo: cud1, ind)
2914 (unless (and term-kill-echo-list
2915 (term-check-kill-echo-list))
2917 ((eq char ?\b) ;; (terminfo: cub1)
2918 (term-move-columns -1))
2919 ((eq char ?\033) ; Escape
2920 (setq term-terminal-state 2))
2921 ((eq char 0)) ; NUL: Do nothing
2922 ((eq char ?\016)) ; Shift Out - ignored
2923 ((eq char ?\017)) ; Shift In - ignored
2924 ((eq char ?\^G) ;; (terminfo: bel)
2926 ((and (eq char ?\032)
2927 (not handled-ansi-message))
2928 (let ((end (string-match "\r?$" str i)))
2930 (funcall term-command-hook
2931 (decode-coding-string
2932 (prog1 (substring str (1+ i) end)
2933 (setq i (match-end 0)))
2934 locale-coding-system))
2935 (setq term-terminal-parameter (substring str i))
2936 (setq term-terminal-state 4)
2937 (setq i str-length))))
2938 (t ; insert char FIXME: Should never happen
2939 (term-move-columns 1)
2940 (backward-delete-char 1)
2942 ((eq term-terminal-state 2) ; Seen Esc
2943 (cond ((eq char ?\133) ;; ?\133 = ?[
2945 ;; Some modifications to cope with multiple
2946 ;; settings like ^[[01;32;43m -mm
2947 ;; Note that now the init value of
2948 ;; term-terminal-previous-parameter has been
2951 (setq term-terminal-parameter 0)
2952 (setq term-terminal-previous-parameter -1)
2953 (setq term-terminal-previous-parameter-2 -1)
2954 (setq term-terminal-previous-parameter-3 -1)
2955 (setq term-terminal-previous-parameter-4 -1)
2956 (setq term-terminal-more-parameters 0)
2957 (setq term-terminal-state 3))
2958 ((eq char ?D) ;; scroll forward
2959 (term-handle-deferred-scroll)
2961 (setq term-terminal-state 0))
2962 ;; ((eq char ?E) ;; (terminfo: nw), not used for
2963 ;; ;; now, but this is a working
2964 ;; ;; implementation
2966 ;; (term-goto term-current-row 0)
2967 ;; (setq term-terminal-state 0))
2968 ((eq char ?M) ;; scroll reversed (terminfo: ri)
2969 (if (or (< (term-current-row) term-scroll-start)
2970 (>= (1- (term-current-row))
2972 ;; Scrolling up will not move outside
2973 ;; the scroll region.
2975 ;; Scrolling the scroll region is needed.
2977 (setq term-terminal-state 0))
2978 ((eq char ?7) ;; Save cursor (terminfo: sc)
2979 (term-handle-deferred-scroll)
2980 (setq term-saved-cursor
2981 (list (term-current-row)
2982 (term-horizontal-column)
2983 term-ansi-current-bg-color
2984 term-ansi-current-bold
2985 term-ansi-current-color
2986 term-ansi-current-invisible
2987 term-ansi-current-reverse
2988 term-ansi-current-underline
2991 (setq term-terminal-state 0))
2992 ((eq char ?8) ;; Restore cursor (terminfo: rc)
2993 (when term-saved-cursor
2994 (term-goto (nth 0 term-saved-cursor)
2995 (nth 1 term-saved-cursor))
2996 (setq term-ansi-current-bg-color
2997 (nth 2 term-saved-cursor)
2998 term-ansi-current-bold
2999 (nth 3 term-saved-cursor)
3000 term-ansi-current-color
3001 (nth 4 term-saved-cursor)
3002 term-ansi-current-invisible
3003 (nth 5 term-saved-cursor)
3004 term-ansi-current-reverse
3005 (nth 6 term-saved-cursor)
3006 term-ansi-current-underline
3007 (nth 7 term-saved-cursor)
3009 (nth 8 term-saved-cursor)))
3010 (setq term-terminal-state 0))
3011 ((eq char ?c) ;; \Ec - Reset (terminfo: rs1)
3012 ;; This is used by the "clear" program.
3013 (setq term-terminal-state 0)
3014 (term-reset-terminal))
3015 ;; The \E#8 reset sequence for xterm. We
3016 ;; probably don't need to handle it, but this
3017 ;; is the code to parse it.
3019 ;; (when (eq (aref str (1+ i)) ?8)
3021 ;; (setq term-scroll-start 0)
3022 ;; (setq term-scroll-end term-height)
3023 ;; (setq term-terminal-state 0)))
3024 ((setq term-terminal-state 0))))
3025 ((eq term-terminal-state 3) ; Seen Esc [
3026 (cond ((and (>= char ?0) (<= char ?9))
3027 (setq term-terminal-parameter
3028 (+ (* 10 term-terminal-parameter) (- char ?0))))
3030 ;; Some modifications to cope with multiple
3031 ;; settings like ^[[01;32;43m -mm
3032 (setq term-terminal-more-parameters 1)
3033 (setq term-terminal-previous-parameter-4
3034 term-terminal-previous-parameter-3)
3035 (setq term-terminal-previous-parameter-3
3036 term-terminal-previous-parameter-2)
3037 (setq term-terminal-previous-parameter-2
3038 term-terminal-previous-parameter)
3039 (setq term-terminal-previous-parameter
3040 term-terminal-parameter)
3041 (setq term-terminal-parameter 0))
3042 ((eq char ??)) ; Ignore ?
3044 (term-handle-ansi-escape proc char)
3045 (setq term-terminal-more-parameters 0)
3046 (setq term-terminal-previous-parameter-4 -1)
3047 (setq term-terminal-previous-parameter-3 -1)
3048 (setq term-terminal-previous-parameter-2 -1)
3049 (setq term-terminal-previous-parameter -1)
3050 (setq term-terminal-state 0)))))
3051 (when (term-handling-pager)
3052 ;; Finish stuff to get ready to handle PAGER.
3053 (if (> (% (current-column) term-width) 0)
3054 (setq term-terminal-parameter
3056 ;; We're at column 0. Goto end of buffer; to compensate,
3057 ;; prepend a ?\r for later. This looks more consistent.
3059 (setq term-terminal-parameter
3060 (concat "\r" (substring str i)))
3061 (setq term-terminal-parameter (substring str (1- i)))
3062 (aset term-terminal-parameter 0 ?\r))
3063 (goto-char (point-max)))
3064 (setq term-terminal-state 4)
3065 (make-local-variable 'term-pager-old-filter)
3066 (setq term-pager-old-filter (process-filter proc))
3067 (set-process-filter proc term-pager-filter)
3068 (setq i str-length))
3071 (when (>= (term-current-row) term-height)
3072 (term-handle-deferred-scroll))
3074 (set-marker (process-mark proc) (point))
3076 (goto-char save-point)
3077 (set-marker save-point nil))
3079 ;; Check for a pending filename-and-line number to display.
3080 ;; We do this before scrolling, because we might create a new window.
3081 (when (and term-pending-frame
3082 (eq (window-buffer selected) (current-buffer)))
3083 (term-display-line (car term-pending-frame)
3084 (cdr term-pending-frame))
3085 (setq term-pending-frame nil)
3086 ;; We have created a new window, so check the window size.
3087 (term-check-size proc))
3089 ;; Scroll each window displaying the buffer but (by default)
3090 ;; only if the point matches the process-mark we started with.
3092 ;; Avoid infinite loop in strange case where minibuffer window
3093 ;; is selected but not active.
3094 (while (window-minibuffer-p win)
3095 (setq win (next-window win nil t)))
3098 (setq win (next-window win nil t))
3099 (when (eq (window-buffer win) (process-buffer proc))
3100 (let ((scroll term-scroll-to-bottom-on-output))
3102 (when (or (= (point) save-marker)
3103 (eq scroll t) (eq scroll 'all)
3104 ;; Maybe user wants point to jump to the end.
3105 (and (eq selected win)
3106 (or (eq scroll 'this) (not save-point)))
3107 (and (eq scroll 'others)
3108 (not (eq selected win))))
3109 (goto-char term-home-marker)
3111 (goto-char (process-mark proc))
3112 (if (not (pos-visible-in-window-p (point) win))
3114 ;; Optionally scroll so that the text
3115 ;; ends at the bottom of the window.
3116 (when (and term-scroll-show-maximum-output
3117 (>= (point) (process-mark proc)))
3119 (goto-char (point-max))
3121 (not (eq win last-win))))
3123 ;; Stolen from comint.el and adapted -mm
3124 (when (> term-buffer-maximum-size 0)
3126 (goto-char (process-mark (get-buffer-process (current-buffer))))
3127 (forward-line (- term-buffer-maximum-size))
3129 (delete-region (point-min) (point))))
3130 (set-marker save-marker nil)))
3131 ;; This might be expensive, but we need it to handle something
3132 ;; like `sleep 5 | less -c' in more-or-less real time.
3133 (when (get-buffer-window (current-buffer))
3136 (defun term-handle-deferred-scroll ()
3137 (let ((count (- (term-current-row) term-height)))
3140 (goto-char term-home-marker)
3141 (term-vertical-motion (1+ count))
3142 (set-marker term-home-marker (point))
3143 (setq term-current-row (1- term-height))))))
3145 (defun term-reset-terminal ()
3146 "Reset the terminal, delete all the content and set the face to the default one."
3149 (setq term-current-row 0)
3150 (setq term-current-column 1)
3151 (setq term-scroll-start 0)
3152 (setq term-scroll-end term-height)
3153 (setq term-insert-mode nil)
3154 ;; FIXME: No idea why this is here, it looks wrong. --Stef
3155 (setq term-ansi-face-already-done nil))
3157 ;; New function to deal with ansi colorized output, as you can see you can
3158 ;; have any bold/underline/fg/bg/reverse combination. -mm
3160 (defun term-handle-colors-array (parameter)
3163 ;; Bold (terminfo: bold)
3165 (setq term-ansi-current-bold t))
3169 (setq term-ansi-current-underline t))
3171 ;; Blink (unsupported by Emacs), will be translated to bold.
3172 ;; This may change in the future though.
3174 (setq term-ansi-current-bold t))
3176 ;; Reverse (terminfo: smso)
3178 (setq term-ansi-current-reverse t))
3182 (setq term-ansi-current-invisible t))
3184 ;; Reset underline (terminfo: rmul)
3186 (setq term-ansi-current-underline nil))
3188 ;; Reset reverse (terminfo: rmso)
3190 (setq term-ansi-current-reverse nil))
3193 ((and (>= parameter 30) (<= parameter 37))
3194 (setq term-ansi-current-color (- parameter 29)))
3198 (setq term-ansi-current-color 0))
3201 ((and (>= parameter 40) (<= parameter 47))
3202 (setq term-ansi-current-bg-color (- parameter 39)))
3206 (setq term-ansi-current-bg-color 0))
3208 ;; 0 (Reset) or unknown (reset anyway)
3212 ;; (message "Debug: U-%d R-%d B-%d I-%d D-%d F-%d B-%d"
3213 ;; term-ansi-current-underline
3214 ;; term-ansi-current-reverse
3215 ;; term-ansi-current-bold
3216 ;; term-ansi-current-invisible
3217 ;; term-ansi-face-already-done
3218 ;; term-ansi-current-color
3219 ;; term-ansi-current-bg-color)
3221 (unless term-ansi-face-already-done
3222 (if term-ansi-current-invisible
3224 (if term-ansi-current-reverse
3226 (elt ansi-term-color-vector term-ansi-current-color)
3229 (elt ansi-term-color-vector term-ansi-current-bg-color)
3231 (setq term-current-face
3232 (list :background color
3234 ) ;; No need to bother with anything else if it's invisible.
3235 (setq term-current-face
3238 (elt ansi-term-color-vector term-ansi-current-color)
3242 (elt ansi-term-color-vector term-ansi-current-bg-color)
3244 :inverse-video term-ansi-current-reverse))
3246 (when term-ansi-current-bold
3247 (setq term-current-face
3248 `(,term-current-face :inherit term-bold)))
3250 (when term-ansi-current-underline
3251 (setq term-current-face
3252 `(,term-current-face :inherit term-underline)))))
3254 ;; (message "Debug %S" term-current-face)
3255 ;; FIXME: shouldn't we set term-ansi-face-already-done to t here? --Stef
3256 (setq term-ansi-face-already-done nil))
3259 ;; Handle a character assuming (eq terminal-state 2) -
3260 ;; i.e. we have previously seen Escape followed by ?[.
3262 (defun term-handle-ansi-escape (proc char)
3264 ((or (eq char ?H) ;; cursor motion (terminfo: cup,home)
3265 ;; (eq char ?f) ;; xterm seems to handle this sequence too, not
3268 (when (<= term-terminal-parameter 0)
3269 (setq term-terminal-parameter 1))
3270 (when (<= term-terminal-previous-parameter 0)
3271 (setq term-terminal-previous-parameter 1))
3272 (when (> term-terminal-previous-parameter term-height)
3273 (setq term-terminal-previous-parameter term-height))
3274 (when (> term-terminal-parameter term-width)
3275 (setq term-terminal-parameter term-width))
3277 (1- term-terminal-previous-parameter)
3278 (1- term-terminal-parameter)))
3279 ;; \E[A - cursor up (terminfo: cuu, cuu1)
3281 (term-handle-deferred-scroll)
3282 (let ((tcr (term-current-row)))
3284 (if (< (- tcr term-terminal-parameter) term-scroll-start)
3285 ;; If the amount to move is before scroll start, move
3287 (- term-scroll-start tcr)
3288 (if (>= term-terminal-parameter tcr)
3290 (- (max 1 term-terminal-parameter)))) t)))
3291 ;; \E[B - cursor down (terminfo: cud)
3293 (let ((tcr (term-current-row)))
3294 (unless (= tcr (1- term-scroll-end))
3296 (if (> (+ tcr term-terminal-parameter) term-scroll-end)
3297 (- term-scroll-end 1 tcr)
3298 (max 1 term-terminal-parameter)) t))))
3299 ;; \E[C - cursor right (terminfo: cuf, cuf1)
3303 (if (>= (+ term-terminal-parameter (term-current-column)) term-width)
3304 (- term-width (term-current-column) 1)
3305 term-terminal-parameter))))
3306 ;; \E[D - cursor left (terminfo: cub)
3308 (term-move-columns (- (max 1 term-terminal-parameter))))
3309 ;; \E[J - clear to end of screen (terminfo: ed, clear)
3311 (term-erase-in-display term-terminal-parameter))
3312 ;; \E[K - clear to end of line (terminfo: el, el1)
3314 (term-erase-in-line term-terminal-parameter))
3315 ;; \E[L - insert lines (terminfo: il, il1)
3317 (term-insert-lines (max 1 term-terminal-parameter)))
3318 ;; \E[M - delete lines (terminfo: dl, dl1)
3320 (term-delete-lines (max 1 term-terminal-parameter)))
3321 ;; \E[P - delete chars (terminfo: dch, dch1)
3323 (term-delete-chars (max 1 term-terminal-parameter)))
3324 ;; \E[@ - insert spaces (terminfo: ich)
3326 (term-insert-spaces (max 1 term-terminal-parameter)))
3327 ;; \E[?h - DEC Private Mode Set
3329 (cond ((eq term-terminal-parameter 4) ;; (terminfo: smir)
3330 (setq term-insert-mode t))
3331 ;; ((eq term-terminal-parameter 47) ;; (terminfo: smcup)
3332 ;; (term-switch-to-alternate-sub-buffer t))
3334 ;; \E[?l - DEC Private Mode Reset
3336 (cond ((eq term-terminal-parameter 4) ;; (terminfo: rmir)
3337 (setq term-insert-mode nil))
3338 ;; ((eq term-terminal-parameter 47) ;; (terminfo: rmcup)
3339 ;; (term-switch-to-alternate-sub-buffer nil))
3342 ;; Modified to allow ansi coloring -mm
3343 ;; \E[m - Set/reset modes, set bg/fg
3344 ;;(terminfo: smso,rmso,smul,rmul,rev,bold,sgr0,invis,op,setab,setaf)
3346 (when (= term-terminal-more-parameters 1)
3347 (when (>= term-terminal-previous-parameter-4 0)
3348 (term-handle-colors-array term-terminal-previous-parameter-4))
3349 (when (>= term-terminal-previous-parameter-3 0)
3350 (term-handle-colors-array term-terminal-previous-parameter-3))
3351 (when (>= term-terminal-previous-parameter-2 0)
3352 (term-handle-colors-array term-terminal-previous-parameter-2))
3353 (term-handle-colors-array term-terminal-previous-parameter))
3354 (term-handle-colors-array term-terminal-parameter))
3356 ;; \E[6n - Report cursor position (terminfo: u7)
3358 (term-handle-deferred-scroll)
3359 (process-send-string proc
3362 (1+ (term-current-row))
3363 (1+ (term-horizontal-column)))))
3364 ;; \E[r - Set scrolling region (terminfo: csr)
3366 (term-set-scroll-region
3367 (1- term-terminal-previous-parameter)
3368 (1- term-terminal-parameter)))
3371 (defun term-set-scroll-region (top bottom)
3372 "Set scrolling region.
3373 TOP is the top-most line (inclusive) of the new scrolling region,
3374 while BOTTOM is the line following the new scrolling region (e.g. exclusive).
3375 The top-most line is line 0."
3376 (setq term-scroll-start
3377 (if (or (< top 0) (>= top term-height))
3380 (setq term-scroll-end
3381 (if (or (<= bottom term-scroll-start) (> bottom term-height))
3384 (setq term-scroll-with-delete
3385 (or (term-using-alternate-sub-buffer)
3386 (not (and (= term-scroll-start 0)
3387 (= term-scroll-end term-height)))))
3388 (term-move-columns (- (term-current-column)))
3391 ;; (defun term-switch-to-alternate-sub-buffer (set)
3392 ;; ;; If asked to switch to (from) the alternate sub-buffer, and already (not)
3393 ;; ;; using it, do nothing. This test is needed for some programs (including
3394 ;; ;; Emacs) that emit the ti termcap string twice, for unknown reason.
3395 ;; (term-handle-deferred-scroll)
3396 ;; (if (eq set (not (term-using-alternate-sub-buffer)))
3397 ;; (let ((row (term-current-row))
3398 ;; (col (term-horizontal-column)))
3400 ;; (goto-char (point-max))
3401 ;; (if (not (eq (preceding-char) ?\n))
3402 ;; (term-insert-char ?\n 1))
3403 ;; (setq term-scroll-with-delete t)
3404 ;; (setq term-saved-home-marker (copy-marker term-home-marker))
3405 ;; (set-marker term-home-marker (point)))
3407 ;; (setq term-scroll-with-delete
3408 ;; (not (and (= term-scroll-start 0)
3409 ;; (= term-scroll-end term-height))))
3410 ;; (set-marker term-home-marker term-saved-home-marker)
3411 ;; (set-marker term-saved-home-marker nil)
3412 ;; (setq term-saved-home-marker nil)
3413 ;; (goto-char term-home-marker)))
3414 ;; (setq term-current-column nil)
3415 ;; (setq term-current-row 0)
3416 ;; (term-goto row col))))
3418 ;; Default value for the symbol term-command-hook.
3420 (defun term-command-hook (string)
3421 (cond ((equal string "")
3423 ((= (aref string 0) ?\032)
3424 ;; gdb (when invoked with -fullname) prints:
3425 ;; \032\032FULLFILENAME:LINENUMBER:CHARPOS:BEG_OR_MIDDLE:PC\n
3426 (let* ((first-colon (string-match ":" string 1))
3428 (string-match ":" string (1+ first-colon)))
3429 (filename (substring string 1 first-colon))
3430 (fileline (string-to-number
3431 (substring string (1+ first-colon) second-colon))))
3432 (setq term-pending-frame (cons filename fileline))))
3433 ((= (aref string 0) ?/)
3434 (cd (substring string 1)))
3435 ;; Allowing the inferior to call functions in Emacs is
3436 ;; probably too big a security hole.
3437 ;; ((= (aref string 0) ?!)
3438 ;; (eval (car (read-from-string string 1))))
3439 (t)));; Otherwise ignore it
3441 ;; Make sure the file named TRUE-FILE is in a buffer that appears on the screen
3442 ;; and that its line LINE is visible.
3443 ;; Put the overlay-arrow on the line LINE in that buffer.
3444 ;; This is mainly used by gdb.
3446 (defun term-display-line (true-file line)
3447 (term-display-buffer-line (find-file-noselect true-file) line))
3449 (defun term-display-buffer-line (buffer line)
3450 (let* ((window (display-buffer buffer t))
3452 (with-current-buffer buffer
3455 (goto-char (point-min))
3456 (forward-line (1- line))
3458 (setq overlay-arrow-string "=>")
3459 (or overlay-arrow-position
3460 (setq overlay-arrow-position (make-marker)))
3461 (set-marker overlay-arrow-position (point) (current-buffer)))
3462 (cond ((or (< pos (point-min)) (> pos (point-max)))
3465 (set-window-point window overlay-arrow-position)))
3467 ;; The buffer-local marker term-home-marker defines the "home position"
3468 ;; (in terms of cursor motion). However, we move the term-home-marker
3469 ;; "down" as needed so that is no more that a window-full above (point-max).
3471 (defun term-goto-home ()
3472 (term-handle-deferred-scroll)
3473 (goto-char term-home-marker)
3474 (setq term-current-row 0)
3475 (setq term-current-column (current-column))
3476 (setq term-start-line-column term-current-column))
3478 (defun term-goto (row col)
3479 (term-handle-deferred-scroll)
3480 (cond ((and term-current-row (>= row term-current-row))
3481 ;; I assume this is a worthwhile optimization.
3482 (term-vertical-motion 0)
3483 (setq term-current-column term-start-line-column)
3484 (setq row (- row term-current-row)))
3488 (term-move-columns col))
3490 ;; The page is full, so enter "pager" mode, and wait for input.
3492 (defun term-process-pager ()
3493 ;; (let ((process (get-buffer-process (current-buffer))))
3494 ;; (stop-process process))
3495 (setq term-pager-old-local-map (current-local-map))
3496 (use-local-map term-pager-break-map)
3497 (easy-menu-add term-terminal-menu)
3498 (easy-menu-add term-signals-menu)
3499 (easy-menu-add term-pager-menu)
3500 (make-local-variable 'term-old-mode-line-format)
3501 (setq term-old-mode-line-format mode-line-format)
3502 (setq mode-line-format
3503 (list "-- **MORE** "
3504 mode-line-buffer-identification
3505 " [Type ? for help] "
3507 (force-mode-line-update))
3509 (defun term-pager-line (lines)
3511 (let* ((moved (vertical-motion (1+ lines)))
3512 (deficit (- lines moved)))
3513 (when (> moved lines)
3515 (cond ((<= deficit 0) ;; OK, had enough in the buffer for request.
3516 (recenter (1- term-height)))
3517 ((term-pager-continue deficit)))))
3519 (defun term-pager-page (arg)
3520 "Proceed past the **MORE** break, allowing the next page of output to appear."
3522 (term-pager-line (* arg term-height)))
3524 ;; Pager mode command to go to beginning of buffer.
3525 (defun term-pager-bob ()
3527 (goto-char (point-min))
3528 (when (= (vertical-motion term-height) term-height)
3530 (recenter (1- term-height)))
3532 ;; Pager mode command to go to end of buffer.
3533 (defun term-pager-eob ()
3535 (goto-char term-home-marker)
3537 (goto-char (process-mark (get-buffer-process (current-buffer)))))
3539 (defun term-pager-back-line (lines)
3541 (vertical-motion (- 1 lines))
3545 ;; Move cursor to end of window.
3546 (vertical-motion term-height)
3548 (recenter (1- term-height)))
3550 (defun term-pager-back-page (arg)
3552 (term-pager-back-line (* arg term-height)))
3554 (defun term-pager-discard ()
3556 (setq term-terminal-parameter "")
3557 (interrupt-process nil t)
3558 (term-pager-continue term-height))
3560 ;; Disable pager processing.
3561 ;; Only callable while in pager mode. (Contrast term-disable-pager.)
3562 (defun term-pager-disable ()
3564 (if (term-handling-pager)
3565 (term-pager-continue nil)
3566 (setq term-pager-count nil))
3567 (term-update-mode-line))
3569 ;; Enable pager processing.
3570 (defun term-pager-enable ()
3572 (or (term-pager-enabled)
3573 (setq term-pager-count 0)) ;; Or maybe set to (term-current-row) ??
3574 (term-update-mode-line))
3576 (defun term-pager-toggle ()
3578 (if (term-pager-enabled) (term-pager-disable) (term-pager-enable)))
3580 (defun term-pager-help ()
3581 "Provide help on commands available in a terminal-emulator **MORE** break."
3583 (message "Terminal-emulator pager break help...")
3586 (function (lambda ()
3587 (princ (substitute-command-keys
3588 "\\<term-pager-break-map>\
3589 Terminal-emulator MORE break.\n\
3590 Type one of the following keys:\n\n\
3591 \\[term-pager-page]\t\tMove forward one page.\n\
3592 \\[term-pager-line]\t\tMove forward one line.\n\
3593 \\[universal-argument] N \\[term-pager-page]\tMove N pages forward.\n\
3594 \\[universal-argument] N \\[term-pager-line]\tMove N lines forward.\n\
3595 \\[universal-argument] N \\[term-pager-back-line]\tMove N lines back.\n\
3596 \\[universal-argument] N \\[term-pager-back-page]\t\tMove N pages back.\n\
3597 \\[term-pager-bob]\t\tMove to the beginning of the buffer.\n\
3598 \\[term-pager-eob]\t\tMove to the end of the buffer.\n\
3599 \\[term-pager-discard]\t\tKill pending output and kill process.\n\
3600 \\[term-pager-disable]\t\tDisable PAGER handling.\n\n\
3601 \\{term-pager-break-map}\n\
3602 Any other key is passed through to the program
3603 running under the terminal emulator and disables pager processing until
3604 all pending output has been dealt with."))
3607 (defun term-pager-continue (new-count)
3608 (let ((process (get-buffer-process (current-buffer))))
3609 (use-local-map term-pager-old-local-map)
3610 (setq term-pager-old-local-map nil)
3611 (setq mode-line-format term-old-mode-line-format)
3612 (force-mode-line-update)
3613 (setq term-pager-count new-count)
3614 (set-process-filter process term-pager-old-filter)
3615 (funcall term-pager-old-filter process "")
3616 (continue-process process)))
3618 ;; Make sure there are DOWN blank lines below the current one.
3619 ;; Return 0 if we're unable (because of PAGER handling), else return DOWN.
3621 (defun term-handle-scroll (down)
3622 (let ((scroll-needed
3623 (- (+ (term-current-row) down)
3624 (if (< down 0) term-scroll-start term-scroll-end))))
3625 (when (or (and (< down 0) (< scroll-needed 0))
3626 (and (> down 0) (> scroll-needed 0)))
3627 (let ((save-point (point-marker)) (save-top))
3628 (goto-char term-home-marker)
3629 (cond (term-scroll-with-delete
3632 ;; Delete scroll-needed lines at term-scroll-end,
3633 ;; then insert scroll-needed lines.
3634 (term-vertical-motion term-scroll-end)
3636 (setq save-top (point))
3637 (term-vertical-motion scroll-needed)
3639 (delete-region save-top (point))
3640 (goto-char save-point)
3641 (setq down (- scroll-needed down))
3642 (term-vertical-motion down))
3643 ;; Delete scroll-needed lines at term-scroll-start.
3644 (term-vertical-motion term-scroll-start)
3645 (setq save-top (point))
3646 (term-vertical-motion scroll-needed)
3647 (delete-region save-top (point))
3648 (goto-char save-point)
3649 (term-vertical-motion down)
3650 (term-adjust-current-row-cache (- scroll-needed)))
3651 (setq term-current-column nil)
3652 (term-insert-char ?\n (abs scroll-needed)))
3653 ((and (numberp term-pager-count)
3654 (< (setq term-pager-count (- term-pager-count down))
3657 (term-process-pager))
3659 (term-adjust-current-row-cache (- scroll-needed))
3660 (term-vertical-motion scroll-needed)
3661 (set-marker term-home-marker (point))))
3662 (goto-char save-point)
3663 (set-marker save-point nil))))
3666 (defun term-down (down &optional check-for-scroll)
3667 "Move down DOWN screen lines vertically."
3668 (let ((start-column (term-horizontal-column)))
3669 (when (and check-for-scroll (or term-scroll-with-delete term-pager-count))
3670 (setq down (term-handle-scroll down)))
3671 (unless (and (= term-current-row 0) (< down 0))
3672 (term-adjust-current-row-cache down)
3673 (when (or (/= (point) (point-max)) (< down 0))
3674 (setq down (- down (term-vertical-motion down)))))
3676 ;; Extend buffer with extra blank lines if needed.
3677 (term-insert-char ?\n down)
3678 (setq term-current-column 0)
3679 (setq term-start-line-column 0))
3681 (when (= term-current-row 0)
3682 ;; Insert lines if at the beginning.
3683 (save-excursion (term-insert-char ?\n (- down)))
3686 ;; Delete lines from the end.
3687 (forward-line term-height)
3689 (forward-line (- down))
3690 (delete-region p (point)))))
3691 (setq term-current-column 0)
3692 (setq term-start-line-column (current-column))))
3694 (term-move-columns start-column))))
3696 ;; Assuming point is at the beginning of a screen line,
3697 ;; if the line above point wraps around, add a ?\n to undo the wrapping.
3698 ;; FIXME: Probably should be called more than it is.
3699 (defun term-unwrap-line ()
3700 (when (not (bolp)) (insert-before-markers ?\n)))
3702 (defun term-erase-in-line (kind)
3703 (when (= kind 1) ;; erase left of point
3704 (let ((cols (term-horizontal-column)) (saved-point (point)))
3705 (term-vertical-motion 0)
3706 (delete-region (point) saved-point)
3707 (term-insert-char ? cols)))
3708 (when (not (eq kind 1)) ;; erase right of point
3709 (let ((saved-point (point))
3710 (wrapped (and (zerop (term-horizontal-column))
3711 (not (zerop (term-current-column))))))
3712 (term-vertical-motion 1)
3713 (delete-region saved-point (point))
3714 ;; wrapped is true if we're at the beginning of screen line,
3715 ;; but not a buffer line. If we delete the current screen line
3716 ;; that will make the previous line no longer wrap, and (because
3717 ;; of the way Emacs display works) point will be at the end of
3718 ;; the previous screen line rather then the beginning of the
3719 ;; current one. To avoid that, we make sure that current line
3720 ;; contain a space, to force the previous line to continue to wrap.
3721 ;; We could do this always, but it seems preferable to not add the
3722 ;; extra space when wrapped is false.
3726 (put-text-property saved-point (point) 'font-lock-face 'default)
3727 (goto-char saved-point))))
3729 (defun term-erase-in-display (kind)
3730 "Erase (that is blank out) part of the window.
3731 If KIND is 0, erase from (point) to (point-max);
3732 if KIND is 1, erase from home to point; else erase from home to point-max."
3733 (term-handle-deferred-scroll)
3734 (cond ((eq term-terminal-parameter 0)
3735 (let ((need-unwrap (bolp)))
3736 (delete-region (point) (point-max))
3737 (when need-unwrap (term-unwrap-line))))
3738 ((let ((row (term-current-row))
3739 (col (term-horizontal-column))
3740 (start-region term-home-marker)
3741 (end-region (if (eq kind 1) (point) (point-max))))
3742 (delete-region start-region end-region)
3745 (term-insert-char ?\n row))
3746 (setq term-current-column nil)
3747 (setq term-current-row nil)
3748 (term-goto row col)))))
3750 (defun term-delete-chars (count)
3751 (let ((save-point (point)))
3752 (term-vertical-motion 1)
3754 (goto-char save-point)
3755 (move-to-column (+ (term-current-column) count) t)
3756 (delete-region save-point (point))))
3758 ;; Insert COUNT spaces after point, but do not change any of
3759 ;; following screen lines. Hence we may have to delete characters
3760 ;; at the end of this screen line to make room.
3762 (defun term-insert-spaces (count)
3763 (let ((save-point (point)) (save-eol) (pnt-at-eol))
3764 (term-vertical-motion 1)
3767 (setq save-eol (point)
3768 pnt-at-eol (line-end-position))
3769 (move-to-column (+ (term-start-line-column) (- term-width count)) t)
3770 ;; If move-to-column extends the current line it will use the face
3771 ;; from the last character on the line, set the face for the chars
3773 (when (>= (point) pnt-at-eol)
3774 (put-text-property pnt-at-eol (point) 'font-lock-face 'default))
3775 (when (> save-eol (point))
3776 (delete-region (point) save-eol))
3777 (goto-char save-point)
3778 (term-insert-char ? count)
3779 (goto-char save-point)))
3781 (defun term-delete-lines (lines)
3782 (let ((start (point))
3783 (save-current-column term-current-column)
3784 (save-start-line-column term-start-line-column)
3785 (save-current-row (term-current-row)))
3786 ;; The number of inserted lines shouldn't exceed the scroll region end.
3787 ;; The `term-scroll-end' line is part of the scrolling region, so
3788 ;; we need to go one line past it in order to ensure correct
3790 (when (> (+ save-current-row lines) (1+ term-scroll-end))
3791 (setq lines (- lines (- (+ save-current-row lines) (1+ term-scroll-end)))))
3793 (delete-region start (point))
3794 (term-down (- (1+ term-scroll-end) save-current-row lines))
3795 (term-insert-char ?\n lines)
3796 (setq term-current-column save-current-column)
3797 (setq term-start-line-column save-start-line-column)
3798 (setq term-current-row save-current-row)
3801 (defun term-insert-lines (lines)
3802 (let ((start (point))
3804 (save-current-column term-current-column)
3805 (save-start-line-column term-start-line-column)
3806 (save-current-row (term-current-row)))
3807 ;; Inserting lines should take into account the scroll region.
3808 ;; The `term-scroll-end' line is part of the scrolling region, so
3809 ;; we need to go one line past it in order to ensure correct
3811 (if (< save-current-row term-scroll-start)
3812 ;; If point is before scroll start,
3814 (setq lines (- lines (- term-scroll-start save-current-row)))
3815 (term-down (- term-scroll-start save-current-row))
3816 (setq start (point)))
3817 ;; The number of inserted lines shouldn't exceed the scroll region end.
3818 (when (> (+ save-current-row lines) (1+ term-scroll-end))
3819 (setq lines (- lines (- (+ save-current-row lines)(1+ term-scroll-end)))))
3820 (term-down (- (1+ term-scroll-end) save-current-row lines)))
3821 (setq start-deleted (point))
3823 (delete-region start-deleted (point))
3825 (setq term-current-column save-current-column)
3826 (setq term-start-line-column save-start-line-column)
3827 (setq term-current-row save-current-row)
3828 (term-insert-char ?\n lines)
3831 (defun term-start-output-log (name)
3832 "Record raw inferior process output in a buffer."
3833 (interactive (list (if term-log-buffer
3835 (read-buffer "Record output in buffer: "
3836 (format "%s output-log"
3837 (buffer-name (current-buffer)))
3839 (if (or (null name) (equal name ""))
3840 (progn (setq term-log-buffer nil)
3841 (message "Output logging off."))
3842 (if (get-buffer name)
3844 (with-current-buffer (get-buffer-create name)
3846 (buffer-disable-undo (current-buffer))
3848 (setq term-log-buffer (get-buffer name))
3849 (message "Recording terminal emulator output into buffer \"%s\""
3850 (buffer-name term-log-buffer))))
3852 (defun term-stop-output-log ()
3853 "Discontinue raw inferior process logging."
3855 (term-start-output-log nil))
3857 (defun term-show-maximum-output ()
3858 "Put the end of the buffer at the bottom of the window."
3860 (goto-char (point-max))
3863 ;;; Do the user's customization...
3865 (defvar term-load-hook nil
3866 "This hook is run when term is loaded in.
3867 This is a good place to put keybindings.")
3869 (run-hooks 'term-load-hook)
3872 ;;; Filename/command/history completion in a buffer
3873 ;; ===========================================================================
3874 ;; Useful completion functions, courtesy of the Ergo group.
3877 ;; term-dynamic-complete Complete or expand command, filename,
3878 ;; history at point.
3879 ;; term-dynamic-complete-filename Complete filename at point.
3880 ;; term-dynamic-list-filename-completions List completions in help buffer.
3881 ;; term-replace-by-expanded-filename Expand and complete filename at point;
3882 ;; replace with expanded/completed name.
3884 ;; These are not installed in the term-mode keymap. But they are
3885 ;; available for people who want them. Shell-mode installs them:
3886 ;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
3887 ;; (define-key shell-mode-map "\M-?"
3888 ;; 'term-dynamic-list-filename-completions)))
3890 ;; Commands like this are fine things to put in load hooks if you
3891 ;; want them present in specific modes.
3893 (defcustom term-completion-autolist nil
3894 "If non-nil, automatically list possibilities on partial completion.
3895 This mirrors the optional behavior of tcsh."
3899 (defcustom term-completion-addsuffix t
3900 "If non-nil, add a `/' to completed directories, ` ' to file names.
3901 If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
3902 DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact
3903 completion. This mirrors the optional behavior of tcsh."
3905 :type '(choice (const :tag "No suffix" nil)
3906 (cons (string :tag "dirsuffix") (string :tag "filesuffix"))
3907 (other :tag "Suffix" t)))
3909 (defcustom term-completion-recexact nil
3910 "If non-nil, use shortest completion if characters cannot be added.
3911 This mirrors the optional behavior of tcsh.
3913 A non-nil value is useful if `term-completion-autolist' is non-nil too."
3917 (defcustom term-completion-fignore nil
3918 "List of suffixes to be disregarded during file completion.
3919 This mirrors the optional behavior of bash and tcsh.
3921 Note that this applies to `term-dynamic-complete-filename' only."
3923 :type '(choice (const nil)
3924 (repeat :tag "List of suffixes" string)))
3926 (defvar term-file-name-prefix ""
3927 "Prefix prepended to absolute file names taken from process input.
3928 This is used by term's and shell's completion functions, and by shell's
3929 directory tracking functions.")
3932 (defun term-directory (directory)
3933 ;; Return expanded DIRECTORY, with `term-file-name-prefix' if absolute.
3934 (expand-file-name (if (file-name-absolute-p directory)
3935 (concat term-file-name-prefix directory)
3939 (defun term-word (word-chars)
3940 "Return the word of WORD-CHARS at point, or nil if none is found.
3941 Word constituents are considered to be those in WORD-CHARS, which is like the
3942 inside of a \"[...]\" (see `skip-chars-forward')."
3944 (let ((limit (point))
3945 (word (concat "[" word-chars "]"))
3946 (non-word (concat "[^" word-chars "]")))
3947 (when (re-search-backward non-word nil 'move)
3949 ;; Anchor the search forwards.
3950 (if (or (eolp) (looking-at non-word))
3952 (re-search-forward (concat word "+") limit)
3953 (buffer-substring (match-beginning 0) (match-end 0))))))
3956 (defun term-match-partial-filename ()
3957 "Return the filename at point, or nil if none is found.
3958 Environment variables are substituted. See `term-word'."
3959 (let ((filename (term-word "~/A-Za-z0-9+@:_.$#,={}-")))
3960 (and filename (substitute-in-file-name filename))))
3963 (defun term-dynamic-complete ()
3964 "Dynamically perform completion at point.
3965 Calls the functions in `term-dynamic-complete-functions' to perform
3966 completion until a function returns non-nil, at which point completion is
3967 assumed to have occurred."
3969 (let ((functions term-dynamic-complete-functions))
3970 (while (and functions (null (funcall (car functions))))
3971 (setq functions (cdr functions)))))
3974 (defun term-dynamic-complete-filename ()
3975 "Dynamically complete the filename at point.
3976 Completes if after a filename. See `term-match-partial-filename' and
3977 `term-dynamic-complete-as-filename'.
3978 This function is similar to `term-replace-by-expanded-filename', except that
3979 it won't change parts of the filename already entered in the buffer; it just
3980 adds completion characters to the end of the filename. A completions listing
3981 may be shown in a help buffer if completion is ambiguous.
3983 Completion is dependent on the value of `term-completion-addsuffix',
3984 `term-completion-recexact' and `term-completion-fignore', and the timing of
3985 completions listing is dependent on the value of `term-completion-autolist'.
3987 Returns t if successful."
3989 (when (term-match-partial-filename)
3990 (prog2 (or (eq (selected-window) (minibuffer-window))
3991 (message "Completing file name..."))
3992 (term-dynamic-complete-as-filename))))
3994 (defun term-dynamic-complete-as-filename ()
3995 "Dynamically complete at point as a filename.
3996 See `term-dynamic-complete-filename'. Returns t if successful."
3997 (let* ((completion-ignore-case nil)
3998 (completion-ignored-extensions term-completion-fignore)
4000 (dirsuffix (cond ((not term-completion-addsuffix) "")
4001 ((not (consp term-completion-addsuffix)) "/")
4002 (t (car term-completion-addsuffix))))
4003 (filesuffix (cond ((not term-completion-addsuffix) "")
4004 ((not (consp term-completion-addsuffix)) " ")
4005 (t (cdr term-completion-addsuffix))))
4006 (filename (or (term-match-partial-filename) ""))
4007 (pathdir (file-name-directory filename))
4008 (pathnondir (file-name-nondirectory filename))
4009 (directory (if pathdir (term-directory pathdir) default-directory))
4010 (completion (file-name-completion pathnondir directory))
4011 (mini-flag (eq (selected-window) (minibuffer-window))))
4012 (cond ((null completion)
4013 (message "No completions of %s" filename)
4015 ((eq completion t) ; Means already completed "file".
4016 (when term-completion-addsuffix (insert " "))
4017 (or mini-flag (message "Sole completion")))
4018 ((string-equal completion "") ; Means completion on "directory/".
4019 (term-dynamic-list-filename-completions))
4020 (t ; Completion string returned.
4021 (let ((file (concat (file-name-as-directory directory) completion)))
4022 (insert (substring (directory-file-name completion)
4023 (length pathnondir)))
4024 (cond ((symbolp (file-name-completion completion directory))
4025 ;; We inserted a unique completion.
4026 (insert (if (file-directory-p file) dirsuffix filesuffix))
4027 (or mini-flag (message "Completed")))
4028 ((and term-completion-recexact term-completion-addsuffix
4029 (string-equal pathnondir completion)
4030 (file-exists-p file))
4031 ;; It's not unique, but user wants shortest match.
4032 (insert (if (file-directory-p file) dirsuffix filesuffix))
4033 (or mini-flag (message "Completed shortest")))
4034 ((or term-completion-autolist
4035 (string-equal pathnondir completion))
4036 ;; It's not unique, list possible completions.
4037 (term-dynamic-list-filename-completions))
4039 (or mini-flag (message "Partially completed")))))))
4043 (defun term-replace-by-expanded-filename ()
4044 "Dynamically expand and complete the filename at point.
4045 Replace the filename with an expanded, canonicalized and completed replacement.
4046 \"Expanded\" means environment variables (e.g., $HOME) and `~'s are replaced
4047 with the corresponding directories. \"Canonicalized\" means `..' and `.' are
4048 removed, and the filename is made absolute instead of relative. For expansion
4049 see `expand-file-name' and `substitute-in-file-name'. For completion see
4050 `term-dynamic-complete-filename'."
4052 (replace-match (expand-file-name (term-match-partial-filename)) t t)
4053 (term-dynamic-complete-filename))
4056 (defun term-dynamic-simple-complete (stub candidates)
4057 "Dynamically complete STUB from CANDIDATES list.
4058 This function inserts completion characters at point by completing STUB from
4059 the strings in CANDIDATES. A completions listing may be shown in a help buffer
4060 if completion is ambiguous.
4062 Returns nil if no completion was inserted.
4063 Returns `sole' if completed with the only completion match.
4064 Returns `shortest' if completed with the shortest of the completion matches.
4065 Returns `partial' if completed as far as possible with the completion matches.
4066 Returns `listed' if a completion listing was shown.
4068 See also `term-dynamic-complete-filename'."
4069 (declare (obsolete completion-in-region "23.2"))
4070 (let* ((completion-ignore-case nil)
4071 (candidates (mapcar (function (lambda (x) (list x))) candidates))
4072 (completions (all-completions stub candidates)))
4073 (cond ((null completions)
4074 (message "No completions of %s" stub)
4076 ((= 1 (length completions)) ; Gotcha!
4077 (let ((completion (car completions)))
4078 (if (string-equal completion stub)
4079 (message "Sole completion")
4080 (insert (substring completion (length stub)))
4081 (message "Completed"))
4082 (when term-completion-addsuffix (insert " "))
4084 (t ; There's no unique completion.
4085 (let ((completion (try-completion stub candidates)))
4086 ;; Insert the longest substring.
4087 (insert (substring completion (length stub)))
4088 (cond ((and term-completion-recexact term-completion-addsuffix
4089 (string-equal stub completion)
4090 (member completion completions))
4091 ;; It's not unique, but user wants shortest match.
4093 (message "Completed shortest")
4095 ((or term-completion-autolist
4096 (string-equal stub completion))
4097 ;; It's not unique, list possible completions.
4098 (term-dynamic-list-completions completions)
4101 (message "Partially completed")
4104 (defun term-dynamic-list-filename-completions ()
4105 "List in help buffer possible completions of the filename at point."
4107 (let* ((completion-ignore-case nil)
4108 (filename (or (term-match-partial-filename) ""))
4109 (pathdir (file-name-directory filename))
4110 (pathnondir (file-name-nondirectory filename))
4111 (directory (if pathdir (term-directory pathdir) default-directory))
4112 (completions (file-name-all-completions pathnondir directory)))
4114 (term-dynamic-list-completions completions)
4115 (message "No completions of %s" filename))))
4118 (defun term-dynamic-list-completions (completions)
4119 "List in help buffer sorted COMPLETIONS.
4120 Typing SPC flushes the help buffer."
4121 (let ((conf (current-window-configuration)))
4122 (with-output-to-temp-buffer "*Completions*"
4123 (display-completion-list (sort completions 'string-lessp)))
4124 (message "Hit space to flush")
4126 (if (with-current-buffer (get-buffer "*Completions*")
4127 (setq key (read-key-sequence nil)
4130 (eq (window-buffer (posn-window (event-start first)))
4131 (get-buffer "*Completions*"))
4132 (memq (key-binding key)
4133 '(mouse-choose-completion choose-completion))))
4134 ;; If the user does choose-completion with the mouse,
4135 ;; execute the command, then delete the completion window.
4137 (choose-completion first)
4138 (set-window-configuration conf))
4140 (set-window-configuration conf)
4141 (setq unread-command-events (listify-key-sequence key)))))))
4143 ;; I need a make-term that doesn't surround with *s -mm
4144 (defun term-ansi-make-term (name program &optional startfile &rest switches)
4145 "Make a term process NAME in a buffer, running PROGRAM.
4146 The name of the buffer is NAME.
4147 If there is already a running process in that buffer, it is not restarted.
4148 Optional third arg STARTFILE is the name of a file to send the contents of to
4149 the process. Any more args are arguments to PROGRAM."
4150 (let ((buffer (get-buffer-create name )))
4151 ;; If no process, or nuked process, crank up a new one and put buffer in
4152 ;; term mode. Otherwise, leave buffer and existing process alone.
4153 (cond ((not (term-check-proc buffer))
4154 (with-current-buffer buffer
4155 (term-mode)) ; Install local vars, mode, keymap, ...
4156 (term-exec buffer name program startfile switches)))
4159 (defvar term-ansi-buffer-name nil)
4160 (defvar term-ansi-default-program nil)
4161 (defvar term-ansi-buffer-base-name nil)
4164 (defun ansi-term (program &optional new-buffer-name)
4165 "Start a terminal-emulator in a new buffer."
4166 (interactive (list (read-from-minibuffer "Run program: "
4167 (or explicit-shell-file-name
4172 ;; Pick the name of the new buffer.
4173 (setq term-ansi-buffer-name
4176 (if term-ansi-buffer-base-name
4177 (if (eq term-ansi-buffer-base-name t)
4178 (file-name-nondirectory program)
4179 term-ansi-buffer-base-name)
4182 (setq term-ansi-buffer-name (concat "*" term-ansi-buffer-name "*"))
4184 ;; In order to have more than one term active at a time
4185 ;; I'd like to have the term names have the *term-ansi-term<?>* form,
4186 ;; for now they have the *term-ansi-term*<?> form but we'll see...
4188 (setq term-ansi-buffer-name (generate-new-buffer-name term-ansi-buffer-name))
4189 (setq term-ansi-buffer-name (term-ansi-make-term term-ansi-buffer-name program))
4191 (set-buffer term-ansi-buffer-name)
4195 ;; Historical baggage. A call to term-set-escape-char used to not
4196 ;; undo any previous call to t-s-e-c. Because of this, ansi-term
4197 ;; ended up with both C-x and C-c as escape chars. Who knows what
4198 ;; the original intention was, but people could have become used to
4199 ;; either. (Bug#12842)
4200 (let (term-escape-char)
4201 ;; I wanna have find-file on C-x C-f -mm
4202 ;; your mileage may definitely vary, maybe it's better to put this in your
4204 (term-set-escape-char ?\C-x))
4206 (switch-to-buffer term-ansi-buffer-name))
4209 ;;; Serial terminals
4210 ;; ===========================================================================
4211 (defun serial-port-is-file-p ()
4212 "Guess whether serial ports are files on this system.
4213 Return t if this is a Unix-based system, where serial ports are
4214 files, such as /dev/ttyS0.
4215 Return nil if this is Windows or DOS, where serial ports have
4216 special identifiers such as COM1."
4217 (not (memq system-type '(windows-nt cygwin ms-dos))))
4219 (defvar serial-name-history
4220 (if (serial-port-is-file-p)
4221 (or (when (file-exists-p "/dev/ttys0") (list "/dev/ttys0"))
4222 (when (file-exists-p "/dev/ttyS0") (list "/dev/ttyS0")))
4224 "History of serial ports used by `serial-read-name'.")
4226 (defvar serial-speed-history
4227 ;; Initialized with reasonable values for newbies.
4228 (list "9600" ;; Given twice because 9600 b/s is the most common speed
4229 "1200" "2400" "4800" "9600" "14400" "19200"
4230 "28800" "38400" "57600" "115200")
4231 "History of serial port speeds used by `serial-read-speed'.")
4233 (defun serial-nice-speed-history ()
4234 "Return `serial-speed-history' cleaned up for a mouse-menu."
4238 (copy-sequence serial-speed-history)
4239 (lambda (a b) (when (and (stringp a) (stringp b))
4240 (> (string-to-number a) (string-to-number b))))))
4241 (dolist (i x) (when (not (equal i (car y))) (push i y)))
4244 (defconst serial-no-speed "nil"
4245 "String for `serial-read-speed' for special serial ports.
4246 If `serial-read-speed' reads this string from the user, it
4247 returns nil, which is recognized by `serial-process-configure'
4248 for special serial ports that cannot be configured.")
4250 (defun serial-supported-or-barf ()
4251 "Signal an error if serial processes are not supported."
4252 (unless (fboundp 'make-serial-process)
4253 (error "Serial processes are not supported on this system")))
4255 (defun serial-read-name ()
4256 "Read a serial port name from the user.
4257 Try to be nice by providing useful defaults and history.
4258 On Windows, prepend \\.\ to the port name unless it already
4259 contains a backslash. This handles the legacy ports COM1-COM9 as
4260 well as the newer ports COM10 and higher."
4261 (serial-supported-or-barf)
4262 (let* ((file-name-history serial-name-history)
4263 (h (car file-name-history))
4264 (x (if (serial-port-is-file-p)
4266 ;; `prompt': The most recently used port is provided as
4267 ;; the default value, which is used when the user
4268 ;; simply presses return.
4269 (if (stringp h) (format "Serial port (default %s): " h)
4271 ;; `directory': Most systems have their serial ports
4272 ;; in the same directory, so start in the directory
4273 ;; of the most recently used port, or in a reasonable
4274 ;; default directory.
4275 (or (and h (file-name-directory h))
4276 (and (file-exists-p "/dev/") "/dev/")
4277 (and (file-exists-p "/") "/"))
4278 ;; `default': This causes (read-file-name) to return
4279 ;; the empty string if he user simply presses return.
4280 ;; Using nil here may result in a default directory
4281 ;; of the current buffer, which is not useful for
4284 (read-from-minibuffer
4285 (if (stringp h) (format "Serial port (default %s): " h)
4287 nil nil nil '(file-name-history . 1) nil nil))))
4288 (if (or (null x) (and (stringp x) (zerop (length x))))
4290 (setq serial-name-history file-name-history))
4291 (when (or (null x) (and (stringp x) (zerop (length x))))
4292 (error "No serial port selected"))
4293 (when (and (not (serial-port-is-file-p))
4294 (not (string-match "\\\\" x)))
4295 (set 'x (concat "\\\\.\\" x)))
4298 (defun serial-read-speed ()
4299 "Read a serial port speed (in bits per second) from the user.
4300 Try to be nice by providing useful defaults and history."
4301 (serial-supported-or-barf)
4302 (let* ((history serial-speed-history)
4304 (x (read-from-minibuffer
4305 (cond ((string= h serial-no-speed)
4306 "Speed (default nil = set by port): ")
4308 (format "Speed (default %s b/s): " h))
4310 (format "Speed (b/s): ")))
4311 nil nil nil '(history . 1) nil nil)))
4312 (when (or (null x) (and (stringp x) (zerop (length x))))
4314 (when (or (null x) (not (stringp x)) (zerop (length x)))
4315 (error "Invalid speed"))
4316 (if (string= x serial-no-speed)
4318 (setq x (string-to-number x))
4319 (when (or (null x) (not (integerp x)) (<= x 0))
4320 (error "Invalid speed")))
4321 (setq serial-speed-history history)
4325 (defun serial-term (port speed)
4326 "Start a terminal-emulator for a serial port in a new buffer.
4327 PORT is the path or name of the serial port. For example, this
4328 could be \"/dev/ttyS0\" on Unix. On Windows, this could be
4329 \"COM1\" or \"\\\\.\\COM10\".
4330 SPEED is the speed of the serial port in bits per second. 9600
4331 is a common value. SPEED can be nil, see
4332 `serial-process-configure' for details.
4333 The buffer is in Term mode; see `term-mode' for the commands to
4335 \\<term-raw-map>Type \\[switch-to-buffer] to switch to another buffer."
4336 (interactive (list (serial-read-name) (serial-read-speed)))
4337 (serial-supported-or-barf)
4338 (let* ((process (make-serial-process
4341 :coding 'no-conversion
4343 (buffer (process-buffer process)))
4344 (with-current-buffer buffer
4347 (goto-char (point-max))
4348 (set-marker (process-mark process) (point))
4349 (set-process-filter process 'term-emulate-terminal)
4350 (set-process-sentinel process 'term-sentinel))
4351 (switch-to-buffer buffer)
4354 (defvar serial-mode-line-speed-menu nil)
4355 (defvar serial-mode-line-config-menu nil)
4357 (defun serial-speed ()
4358 "Return the speed of the serial port of the current buffer's process.
4359 The return value may be nil for a special serial port."
4360 (process-contact (get-buffer-process (current-buffer)) :speed))
4362 (defun serial-mode-line-speed-menu-1 (event)
4364 (save-selected-window
4365 (select-window (posn-window (event-start event)))
4366 (serial-update-speed-menu)
4367 (let* ((selection (serial-mode-line-speed-menu event))
4368 (binding (and selection (lookup-key serial-mode-line-speed-menu
4369 (vector (car selection))))))
4370 (when binding (call-interactively binding)))))
4372 (defun serial-mode-line-speed-menu (event)
4373 (x-popup-menu event serial-mode-line-speed-menu))
4375 (defun serial-update-speed-menu ()
4376 (setq serial-mode-line-speed-menu (make-sparse-keymap "Speed (b/s)"))
4377 (define-key serial-mode-line-speed-menu [serial-mode-line-speed-menu-other]
4378 '(menu-item "Other..."
4379 (lambda (event) (interactive "e")
4380 (let ((speed (serial-read-speed)))
4381 (serial-process-configure :speed speed)
4382 (term-update-mode-line)
4383 (message "Speed set to %d b/s" speed)))))
4384 (dolist (str (serial-nice-speed-history))
4385 (let ((num (or (and (stringp str) (string-to-number str)) 0)))
4387 serial-mode-line-speed-menu
4388 (vector (make-symbol (format "serial-mode-line-speed-menu-%s" str)))
4391 (lambda (event) (interactive "e")
4392 (serial-process-configure :speed ,num)
4393 (term-update-mode-line)
4394 (message "Speed set to %d b/s" ,num))
4395 :button (:toggle . (= (serial-speed) ,num)))))))
4397 (defun serial-mode-line-config-menu-1 (event)
4399 (save-selected-window
4400 (select-window (posn-window (event-start event)))
4401 (serial-update-config-menu)
4402 (let* ((selection (serial-mode-line-config-menu event))
4403 (binding (and selection (lookup-key serial-mode-line-config-menu
4404 (vector (car selection))))))
4405 (when binding (call-interactively binding)))))
4407 (defun serial-mode-line-config-menu (event)
4408 (x-popup-menu event serial-mode-line-config-menu))
4410 (defun serial-update-config-menu ()
4411 (setq serial-mode-line-config-menu (make-sparse-keymap "Configuration"))
4412 (let ((config (process-contact
4413 (get-buffer-process (current-buffer)) t)))
4414 (dolist (y '((:flowcontrol hw "Hardware flowcontrol (RTS/CTS)")
4415 (:flowcontrol sw "Software flowcontrol (XON/XOFF)")
4416 (:flowcontrol nil "No flowcontrol")
4417 (:stopbits 2 "2 stopbits")
4418 (:stopbits 1 "1 stopbit")
4419 (:parity odd "Odd parity")
4420 (:parity even "Even parity")
4421 (:parity nil "No parity")
4422 (:bytesize 7 "7 bits per byte")
4423 (:bytesize 8 "8 bits per byte")))
4424 (define-key serial-mode-line-config-menu
4425 (vector (make-symbol (format "%s-%s" (nth 0 y) (nth 1 y))))
4428 (lambda (event) (interactive "e")
4429 (serial-process-configure ,(nth 0 y) ',(nth 1 y))
4430 (term-update-mode-line)
4431 (message "%s" ,(nth 2 y)))
4432 ;; Use :toggle instead of :radio because a non-standard port
4433 ;; configuration may not match any menu items.
4434 :button (:toggle . ,(equal (plist-get config (nth 0 y))
4438 ;;; Converting process modes to use term mode
4439 ;; ===========================================================================
4440 ;; Renaming variables
4441 ;; Most of the work is renaming variables and functions. These are the common
4444 ;; last-input-start term-last-input-start
4445 ;; last-input-end term-last-input-end
4446 ;; shell-prompt-pattern term-prompt-regexp
4447 ;; shell-set-directory-error-hook <no equivalent>
4449 ;; shell-set-directory <unnecessary>
4450 ;; shell-mode-map term-mode-map
4452 ;; shell-send-input term-send-input
4453 ;; shell-send-eof term-delchar-or-maybe-eof
4454 ;; kill-shell-input term-kill-input
4455 ;; interrupt-shell-subjob term-interrupt-subjob
4456 ;; stop-shell-subjob term-stop-subjob
4457 ;; quit-shell-subjob term-quit-subjob
4458 ;; kill-shell-subjob term-kill-subjob
4459 ;; kill-output-from-shell term-kill-output
4460 ;; show-output-from-shell term-show-output
4461 ;; copy-last-shell-input Use term-previous-input/term-next-input
4463 ;; SHELL-SET-DIRECTORY is gone, its functionality taken over by
4464 ;; SHELL-DIRECTORY-TRACKER, the shell mode's term-input-filter-functions.
4465 ;; Term mode does not provide functionality equivalent to
4466 ;; shell-set-directory-error-hook; it is gone.
4468 ;; term-last-input-start is provided for modes which want to munge
4469 ;; the buffer after input is sent, perhaps because the inferior
4470 ;; insists on echoing the input. The LAST-INPUT-START variable in
4471 ;; the old shell package was used to implement a history mechanism,
4472 ;; but you should think twice before using term-last-input-start
4473 ;; for this; the input history ring often does the job better.
4475 ;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
4476 ;; *not* create the term-mode local variables in your foo-mode function.
4477 ;; This is not modular. Instead, call term-mode, and let *it* create the
4478 ;; necessary term-specific local variables. Then create the
4479 ;; foo-mode-specific local variables in foo-mode. Set the buffer's keymap to
4480 ;; be foo-mode-map, and its mode to be foo-mode. Set the term-mode hooks
4481 ;; (term-{prompt-regexp, input-filter, input-filter-functions,
4482 ;; get-old-input) that need to be different from the defaults. Call
4483 ;; foo-mode-hook, and you're done. Don't run the term-mode hook yourself;
4484 ;; term-mode will take care of it. The following example, from shell.el,
4487 ;; (defvar shell-mode-map '())
4488 ;; (cond ((not shell-mode-map)
4489 ;; (setq shell-mode-map (copy-keymap term-mode-map))
4490 ;; (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
4491 ;; (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
4492 ;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
4493 ;; (define-key shell-mode-map "\M-?"
4494 ;; 'term-dynamic-list-filename-completions)))
4496 ;; (defun shell-mode ()
4499 ;; (setq term-prompt-regexp shell-prompt-pattern)
4500 ;; (setq major-mode 'shell-mode)
4501 ;; (setq mode-name "Shell")
4502 ;; (use-local-map shell-mode-map)
4503 ;; (make-local-variable 'shell-directory-stack)
4504 ;; (setq shell-directory-stack nil)
4505 ;; (add-hook 'term-input-filter-functions 'shell-directory-tracker)
4506 ;; (run-mode-hooks 'shell-mode-hook))
4509 ;; Completion for term-mode users
4511 ;; For modes that use term-mode, term-dynamic-complete-functions is the
4512 ;; hook to add completion functions to. Functions on this list should return
4513 ;; non-nil if completion occurs (i.e., further completion should not occur).
4514 ;; You could use completion-in-region to do the bulk of the
4519 ;;; term.el ends here