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