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