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