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