]> code.delx.au - gnu-emacs/blobdiff - lisp/term.el
(Top): Add some nodes from the chapter "Major and Minor Modes" to the
[gnu-emacs] / lisp / term.el
index e4d1e87abd2ea4f7d549bcb9fb82393bf97c3758..473fafd558a2ebdee61581913b39de8cc2820ba8 100644 (file)
@@ -1,9 +1,11 @@
-;; term.el --- general command interpreter in a window stuff
-;; Copyright (C) 1988, 1990, 1992, 1994, 1995 Free Software Foundation, Inc.
+;;; term.el --- general command interpreter in a window stuff
 
-;; Author: Per Bothner <bothner@cygnus.com>
+;;; Copyright (C) 1988, 1990, 1992, 1994, 1995, 2004 Free Software Foundation, Inc.
+
+;; Author: Per Bothner <per@bothner.com>
+;; Maintainer: Dan Nicolaescu <dann@ics.uci.edu>, Per Bothner <per@bothner.com>
 ;; Based on comint mode written by: Olin Shivers <shivers@cs.cmu.edu>
-;; Keyword: processes
+;; Keywords: processes
 
 ;; This file is part of GNU Emacs.
 
 ;; GNU General Public License for more details.
 
 ;; You should have received a copy of the GNU General Public License
-;; along with GNU Emacs; see the file COPYING.  If not, write to
-;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+;; along with GNU Emacs; see the file COPYING.  If not, write to the
+;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Marck 13 2001
+;;; Fixes for CJK support by Yong Lu <lyongu@yahoo.com>.
+
+;;; Dir/Hostname tracking and ANSI colorization by
+;;; Marco Melgazzi <marco@techie.com>.
+
+;;; To see what I've modified and where it came from search for '-mm'
 
 ;;; Commentary:
 
-;;; The changelog is at the end of this file.
+;;; Speed considerations and a few caveats
+;;; --------------------------------------
+;;;
+;;; While the message passing and the colorization surely introduce some
+;;; overhead this has became so small that IMHO is surely outweighted by
+;;; the benefits you get but, as usual, YMMV
+;;;
+;;; Important caveat, when deciding the cursor/'grey keys' keycodes I had to
+;;; make a choice: on my Linux box this choice allows me to run all the
+;;; ncurses applications without problems but make these keys
+;;; uncomprehensible to all the cursesX programs.  Your mileage may vary so
+;;; you may consider changing the default 'emulation'.  Just search for this
+;;; piece of code and modify it as you like:
+;;;
+;;; ;; Which would be better:  "\e[A" or "\eOA"? readline accepts either.
+;;; ;; For my configuration it's definitely better \eOA but YMMV.  -mm
+;;; ;; For example: vi works with \eOA while elm wants \e[A ...
+;;; (defun term-send-up    () (interactive) (term-send-raw-string "\eOA"))
+;;; (defun term-send-down  () (interactive) (term-send-raw-string "\eOB"))
+;;; (defun term-send-right () (interactive) (term-send-raw-string "\eOC"))
+;;; (defun term-send-left  () (interactive) (term-send-raw-string "\eOD"))
+;;;
+;;;
+;;; IMPORTANT: additions & changes
+;;; ------------------------------
+;;;
+;;;  With this enhanced ansi-term.el you will get a reliable mechanism of
+;;; directory/username/host tracking: the only drawback is that you will
+;;; have to modify your shell start-up script.  It's worth it, believe me :).
+;;;
+;;; When you rlogin/su/telnet and the account you access has a modified
+;;; startup script, you will be able to access the remote files as usual
+;;; with C-x C-f, if it's needed you will have to enter a password,
+;;; otherwise the file should get loaded straight away.
+;;;
+;;; This is useful even if you work only on one host: it often happens that,
+;;; for maintenance reasons, you have to edit files 'as root': before
+;;; patching term.el, I su-ed in a term.el buffer and used vi :), now I
+;;; simply do a C-x C-f and, via ange-ftp, the file is automatically loaded
+;;; 'as-root'.  ( If you don't want to enter the root password every time you
+;;; can put it in your .netrc: note that this is -not- advisable if you're
+;;; connected to the internet or if somebody else works on your workstation!)
+;;;
+;;; If you use wu-ftpd you can use some of its features to avoid root ftp
+;;; access to the rest of the world: just put in /etc/ftphosts something like
+;;;
+;;; # Local access
+;;; allow      root            127.0.0.1
+;;;
+;;; # By default nobody can't do anything
+;;; deny       root            *
+;;;
+;;;
+;;;             ----------------------------------------
+;;;
+;;;  If, instead of 'term', you call 'ansi-term', you get multiple term
+;;; buffers, after every new call ansi-term opens a new *ansi-term*<xx> window,
+;;; where <xx> is, as usual, a number...
+;;;
+;;;             ----------------------------------------
+;;;
+;;;  With the term-buffer-maximum-size you can finally decide how many
+;;; scrollback lines to keep: its default is 2048 but you can change it as
+;;; usual.
+;;;
+;;;             ----------------------------------------
+;;;
+;;;
+;;;  ANSI colorization should work well, I've decided to limit the interpreter
+;;; to five outstanding commands (like ESC [ 01;04;32;41;07m.
+;;;  You shouldn't need more, if you do, tell me and I'll increase it.  It's
+;;; so easy you could do it yourself...
+;;;
+;;;  Blink, is not supported.  Currently it's mapped as bold.
+;;;
+;;; Important caveat:
+;;; -----------------
+;;;   if you want custom colors in term.el redefine term-default-fg-color
+;;;  and term-default-bg-color BEFORE loading it.
+;;;
+;;;             ----------------------------------------
+;;;
+;;;  If you'd like to check out my complete configuration, you can download
+;;; it from http://www.polito.it/~s64912/things.html, it's ~500k in size and
+;;; contains my .cshrc, .emacs and my whole site-lisp subdirectory.  (notice
+;;; that this term.el may be newer/older than the one in there, please
+;;; check!)
+;;;
+;;;  This complete configuration contains, among other things, a complete
+;;; rectangular marking solution (based on rect-mark.el and
+;;; pc-bindings.el) and should be a good example of how extensively Emacs
+;;; can be configured on a ppp-connected ws.
+;;;
+;;;             ----------------------------------------
+;;;
+;;;  TODO:
+;;;
+;;;  - Add hooks to allow raw-mode keys to be configurable
+;;;  - Which keys are better ? \eOA or \e[A ?
+;;;
+;;;
+;;;  Changes:
+;;;
+;;; V4.0 January 1997
+;;;
+;;;   - Huge reworking of the faces code: now we only have roughly 20-30
+;;;     faces for everything so we're even faster than the old md-term.el !
+;;;   - Finished removing all the J-Shell code.
+;;;
+;;;  V3.0 January 1997
+;;;
+;;;  - Now all the supportable ANSI commands work well.
+;;;  - Reworked a little the code: much less jsh-inspired stuff
+;;;
+;;;  V2.3 November
+;;;
+;;;  - Now all the faces are accessed through an array: much cleaner code.
+;;;
+;;;  V2.2 November 4 1996
+;;;
+;;;  - Implemented ANSI output colorization ( a bit rough but enough for
+;;;    color_ls )
+;;;
+;;;  - Implemented a maximum limit for the scroll buffer (stolen from
+;;;    comint.el)
+;;;
+;;;  v2.1 October 28 1996, first public release
+;;;
+;;;  - Some new keybindings for term-char mode ( notably home/end/...)
+;;;  - Directory, hostname and username tracking via ange-ftp
+;;;  - Multi-term capability via the ansi-term call
+;;;
+;;;  ----------------------------------------------------------------
+;;;  You should/could have something like this in your .emacs to take
+;;;  full advantage of this package
+;;;
+;;;  (add-hook 'term-mode-hook
+;;;              (function
+;;;               (lambda ()
+;;;                     (setq term-prompt-regexp "^[^#$%>\n]*[#$%>] *")
+;;;                     (make-local-variable 'mouse-yank-at-point)
+;;;                     (make-local-variable 'transient-mark-mode)
+;;;                     (setq mouse-yank-at-point t)
+;;;                     (setq transient-mark-mode nil)
+;;;                     (auto-fill-mode -1)
+;;;                     (setq tab-width 8 ))))
+;;;
+;;;
+;;;             ----------------------------------------
+;;;
+;;;  If you want to use color ls the best setup is to have a different file
+;;; when you use eterm ( see above, mine is named .emacs_dircolors ).  This
+;;; is necessary because some terminals, rxvt for example, need non-ansi
+;;; hacks to work ( for example on my rxvt white is wired to fg, and to
+;;; obtain normal white I have to do bold-white :)
+;;;
+;;;             ----------------------------------------
+;;;
+;;;
+;;;  # Configuration file for the color ls utility
+;;;  # This file goes in the /etc directory, and must be world readable.
+;;;  # You can copy this file to .dir_colors in your $HOME directory to
+;;;  # override the system defaults.
+;;;
+;;;  # COLOR needs one of these arguments: 'tty' colorizes output to ttys, but
+;;;  # not pipes.  'all' adds color characters to all output.  'none' shuts
+;;;  # colorization off.
+;;;  COLOR tty
+;;;  OPTIONS -F
+;;;
+;;;  # Below, there should be one TERM entry for each termtype that is
+;;;  # colorizable
+;;;  TERM eterm
+;;;
+;;;  # EIGHTBIT, followed by '1' for on, '0' for off.  (8-bit output)
+;;;  EIGHTBIT 1
+;;;
+;;;  # Below are the color init strings for the basic file types.  A color init
+;;;  # string consists of one or more of the following numeric codes:
+;;;  # Attribute codes:
+;;;  # 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
+;;;  # Text color codes:
+;;;  # 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
+;;;  # Background color codes:
+;;;  # 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
+;;;  NORMAL 00 # global default, although everything should be something.
+;;;  FILE 00           # normal file
+;;;  DIR 00;37         # directory
+;;;  LINK 00;36        # symbolic link
+;;;  FIFO 00;37        # pipe
+;;;  SOCK 40;35        # socket
+;;;  BLK 33;01 # block device driver
+;;;  CHR 33;01         # character device driver
+;;;
+;;;  # This is for files with execute permission:
+;;;  EXEC 00;32
+;;;
+;;;  # List any file extensions like '.gz' or '.tar' that you would like ls
+;;;  # to colorize below.  Put the extension, a space, and the color init
+;;;  # string.  (and any comments you want to add after a '#')
+;;;  .tar 01;33 # archives or compressed
+;;;  .tgz 01;33
+;;;  .arj 01;33
+;;;  .taz 01;33
+;;;  .lzh 01;33
+;;;  .zip 01;33
+;;;  .z   01;33
+;;;  .Z   01;33
+;;;  .gz  01;33
+;;;  .jpg 01;35 # image formats
+;;;  .gif 01;35
+;;;  .bmp 01;35
+;;;  .xbm 01;35
+;;;  .xpm 01;35
+;;;
+;;;
+;;;             ----------------------------------------
+;;;
+;;;  Notice: for directory/host/user tracking you need to have something
+;;; like this in your shell startup script ( this is for tcsh but should
+;;; be quite easy to port to other shells )
+;;;
+;;;             ----------------------------------------
+;;;
+;;;
+;;;     set os = `uname`
+;;;     set host = `hostname`
+;;;     set date = `date`
+;;;
+;;;  # su does not change this but I'd like it to
+;;;
+;;;     set user = `whoami`
+;;;
+;;;  # ...
+;;;
+;;;     if ( eterm =~ $TERM ) then
+;;;
+;;;            echo --------------------------------------------------------------
+;;;            echo Hello $user
+;;;            echo Today is $date
+;;;            echo We are on $host running $os under Emacs term mode
+;;;            echo --------------------------------------------------------------
+;;;
+;;;            setenv EDITOR emacsclient
+;;;
+;;;   # Notice: $host and $user have been set before to 'hostname' and 'whoami'
+;;;   # this is necessary because, f.e., certain versions of 'su' do not change
+;;;   # $user, YMMV: if you don't want to fiddle with them define a couple
+;;;   # of new variables and use these instead.
+;;;   # NOTICE that there is a space between "AnSiT?" and $whatever NOTICE
+;;;
+;;;   # These are because we want the real cwd in the messages, not the login
+;;;   # time one !
+;;;
+;;;            set cwd_hack='$cwd'
+;;;            set host_hack='$host'
+;;;            set user_hack='$user'
+;;;
+;;;   # Notice that the ^[ character is an ESC, not two chars.  You can
+;;;   # get it in various ways, for example by typing
+;;;   # echo -e '\033' > escape.file
+;;;   # or by using your favourite editor
+;;;
+;;;            foreach temp (cd pushd)
+;;;                    alias $temp "$temp \!* ; echo '\eAnSiTc' $cwd_hack"
+;;;            end
+;;;            alias popd 'popd ;echo "\eAnSiTc" $cwd'
+;;;
+;;;   # Every command that can modify the user/host/directory should be aliased
+;;;   # as follows for the tracking mechanism to work.
+;;;
+;;;            foreach temp ( rlogin telnet rsh sh ksh csh tcsh zsh bash tcl su )
+;;;                    alias $temp "$temp \!* ; echo '\eAnSiTh' $host_hack ; \
+;;;                                    echo '\eAnSiTu' $user_hack ;echo '\eAnSiTc' $cwd_hack"
+;;;            end
+;;;
+;;;   # Start up & use color ls
+;;;
+;;;            echo "\eAnSiTh" $host
+;;;            echo "\eAnSiTu" $user
+;;;            echo "\eAnSiTc" $cwd
+;;;
+;;;   # some housekeeping
+;;;
+;;;            unset cwd_hack
+;;;            unset host_hack
+;;;            unset user_hack
+;;;            unset temp
+;;;
+;;;            eval `/bin/dircolors /home/marco/.emacs_dircolors`
+;;;    endif
+;;;
+;;;  # ...
+;;;
+;;;  # Let's not clutter user space
+;;;
+;;;     unset os
+;;;     unset date
+;;;
+;;;
+
+;;; Original Commentary:
+;;; --------------------
 
-;;; Please send me bug reports, bug fixes, and extensions, so that I can
-;;; merge them into the master source.
-;;;     - Per Bothner (bothner@cygnus.com)
+;; The changelog is at the end of this file.
 
-;;; This file defines a general command-interpreter-in-a-buffer package
-;;; (term mode). The idea is that you can build specific process-in-a-buffer
-;;; modes on top of term mode -- e.g., lisp, shell, scheme, T, soar, ....
-;;; This way, all these specific packages share a common base functionality, 
-;;; and a common set of bindings, which makes them easier to use (and
-;;; saves code, implementation time, etc., etc.).
+;; Please send me bug reports, bug fixes, and extensions, so that I can
+;; merge them into the master source.
+;;     - Per Bothner (bothner@cygnus.com)
 
-;;; For hints on converting existing process modes (e.g., tex-mode,
-;;; background, dbx, gdb, kermit, prolog, telnet) to use term-mode
-;;; instead of shell-mode, see the notes at the end of this file.
+;; This file defines a general command-interpreter-in-a-buffer package
+;; (term mode).  The idea is that you can build specific process-in-a-buffer
+;; modes on top of term mode -- e.g., lisp, shell, scheme, T, soar, ....
+;; This way, all these specific packages share a common base functionality,
+;; and a common set of bindings, which makes them easier to use (and
+;; saves code, implementation time, etc., etc.).
 
-\f
-;;; Brief Command Documentation:
-;;;============================================================================
-;;; Term Mode Commands: (common to all derived modes, like cmushell & cmulisp
-;;; mode)
-;;;
-;;; m-p            term-previous-input           Cycle backwards in input history
-;;; m-n            term-next-input               Cycle forwards
-;;; m-r     term-previous-matching-input  Previous input matching a regexp
-;;; m-s     comint-next-matching-input      Next input that matches
-;;; return  term-send-input
-;;; c-c c-a term-bol                      Beginning of line; skip prompt.
-;;; c-d            term-delchar-or-maybe-eof     Delete char unless at end of buff.
-;;; c-c c-u term-kill-input                ^u
-;;; c-c c-w backward-kill-word             ^w
-;;; c-c c-c term-interrupt-subjob          ^c
-;;; c-c c-z term-stop-subjob               ^z
-;;; c-c c-\ term-quit-subjob               ^\
-;;; c-c c-o term-kill-output               Delete last batch of process output
-;;; c-c c-r term-show-output               Show last batch of process output
-;;; c-c c-h term-dynamic-list-input-ring  List input history
-;;;
-;;; Not bound by default in term-mode
-;;; term-send-invisible                        Read a line w/o echo, and send to proc
-;;; (These are bound in shell-mode)
-;;; term-dynamic-complete              Complete filename at point.
-;;; term-dynamic-list-completions      List completions in help buffer.
-;;; term-replace-by-expanded-filename  Expand and complete filename at point;
-;;;                                    replace with expanded/completed name.
-;;; term-kill-subjob                   No mercy.
-;;; term-show-maximum-output            Show as much output as possible.
-;;; term-continue-subjob               Send CONT signal to buffer's process
-;;;                                    group. Useful if you accidentally
-;;;                                    suspend your process (with C-c C-z).
+;; For hints on converting existing process modes (e.g., tex-mode,
+;; background, dbx, gdb, kermit, prolog, telnet) to use term-mode
+;; instead of shell-mode, see the notes at the end of this file.
 
-;;; term-mode-hook is the term mode hook. Basically for your keybindings.
-;;; term-load-hook is run after loading in this package.
+\f
+;; Brief Command Documentation:
+;;============================================================================
+;; Term Mode Commands: (common to all derived modes, like cmushell & cmulisp
+;; mode)
+;;
+;; m-p     term-previous-input           Cycle backwards in input history
+;; m-n     term-next-input               Cycle forwards
+;; m-r     term-previous-matching-input  Previous input matching a regexp
+;; m-s     comint-next-matching-input      Next input that matches
+;; return  term-send-input
+;; c-c c-a term-bol                      Beginning of line; skip prompt.
+;; c-d     term-delchar-or-maybe-eof     Delete char unless at end of buff.
+;; c-c c-u term-kill-input                 ^u
+;; c-c c-w backward-kill-word              ^w
+;; c-c c-c term-interrupt-subjob           ^c
+;; c-c c-z term-stop-subjob                ^z
+;; c-c c-\ term-quit-subjob                ^\
+;; c-c c-o term-kill-output                Delete last batch of process output
+;; c-c c-r term-show-output                Show last batch of process output
+;; c-c c-h term-dynamic-list-input-ring  List input history
+;;
+;; Not bound by default in term-mode
+;; term-send-invisible                 Read a line w/o echo, and send to proc
+;; (These are bound in shell-mode)
+;; term-dynamic-complete               Complete filename at point.
+;; term-dynamic-list-completions       List completions in help buffer.
+;; term-replace-by-expanded-filename   Expand and complete filename at point;
+;;                                     replace with expanded/completed name.
+;; term-kill-subjob                    No mercy.
+;; term-show-maximum-output            Show as much output as possible.
+;; term-continue-subjob                Send CONT signal to buffer's process
+;;                                     group.  Useful if you accidentally
+;;                                     suspend your process (with C-c C-z).
+
+;; term-mode-hook is the term mode hook.  Basically for your keybindings.
+;; term-load-hook is run after loading in this package.
 
 ;;; Code:
 
-;;; This is passed to the inferior in the EMACS environment variable,
-;;; so it is important to increase it if there are protocol-relevant changes.
-(defconst term-version "0.95")
+;; This is passed to the inferior in the EMACS environment variable,
+;; so it is important to increase it if there are protocol-relevant changes.
+(defconst term-protocol-version "0.96")
 
+(eval-when-compile
+  (require 'ange-ftp))
 (require 'ring)
 (require 'ehelp)
+
+(defgroup term nil
+  "General command interpreter in a window"
+  :group 'processes
+  :group 'unix)
+
 \f
 ;;; Buffer Local Variables:
 ;;;============================================================================
 ;;;     term-last-input-match - string           ...
 ;;;     term-dynamic-complete-functions - hook   For the completion mechanism
 ;;;     term-completion-fignore - list           ...
-;;;     term-get-old-input    - function     Hooks for specific 
+;;;     term-get-old-input    - function     Hooks for specific
 ;;;     term-input-filter-functions - hook     process-in-a-buffer
 ;;;     term-input-filter     - function         modes.
 ;;;     term-input-send        - function
 ;;             top-most line(s); and nil if scrolling should be implemented
 ;;             by moving term-home-marker.  It is set to t iff there is a
 ;;             (non-default) scroll-region OR the alternate buffer is used.
-(defvar term-pending-delete-marker)
+(defvar term-pending-delete-marker) ;; New user input in line mode needs to
+;;             be deleted, because it gets echoed by the inferior.
+;;             To reduce flicker, we defer the delete until the next output.
 (defvar term-old-mode-map nil) ;; Saves the old keymap when in char mode.
 (defvar term-old-mode-line-format) ;; Saves old mode-line-format while paging.
 (defvar term-pager-old-local-map nil) ;; Saves old keymap while paging.
 (defvar term-pager-old-filter) ;; Saved process-filter while paging.
 
-(defvar explicit-shell-file-name nil
-  "*If non-nil, is file name to use for explicitly requested inferior shell.")
+(defcustom explicit-shell-file-name nil
+  "*If non-nil, is file name to use for explicitly requested inferior shell."
+  :type '(choice (const nil) file)
+  :group 'term)
 
 (defvar term-prompt-regexp "^"
   "Regexp to recognise prompts in the inferior process.
@@ -178,11 +505,11 @@ surrounding them, and also be regarded as arguments in their own right (unlike
 whitespace).  See `term-arguments'.
 Defaults to the empty list.
 
-For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?;).
+For shells, a good value is (?\\| ?& ?< ?> ?\\( ?\\) ?\\;).
 
 This is a good thing to set in mode hooks.")
 
-(defvar term-input-autoexpand nil
+(defcustom term-input-autoexpand nil
   "*If non-nil, expand input command history references on completion.
 This mirrors the optional behavior of tcsh (its autoexpand and histlit).
 
@@ -191,21 +518,27 @@ If the value is `history', then the expansion is only when inserting
 into the buffer's input ring.  See also `term-magic-space' and
 `term-dynamic-complete'.
 
-This variable is buffer-local.")
+This variable is buffer-local."
+  :type '(choice (const nil) (const t) (const input) (const history))
+  :group 'term)
 
-(defvar term-input-ignoredups nil
+(defcustom term-input-ignoredups nil
   "*If non-nil, don't add input matching the last on the input ring.
 This mirrors the optional behavior of bash.
 
-This variable is buffer-local.")
+This variable is buffer-local."
+  :type 'boolean
+  :group 'term)
 
-(defvar term-input-ring-file-name nil
+(defcustom term-input-ring-file-name nil
   "*If non-nil, name of the file to read/write input history.
 See also `term-read-input-ring' and `term-write-input-ring'.
 
-This variable is buffer-local, and is a good thing to set in mode hooks.")
+This variable is buffer-local, and is a good thing to set in mode hooks."
+  :type 'boolean
+  :group 'term)
 
-(defvar term-scroll-to-bottom-on-output nil
+(defcustom term-scroll-to-bottom-on-output nil
   "*Controls whether interpreter output causes window to scroll.
 If nil, then do not scroll.  If t or `all', scroll all windows showing buffer.
 If `this', scroll only the selected window.
@@ -214,14 +547,18 @@ If `others', scroll only those that are not the selected window.
 The default is nil.
 
 See variable `term-scroll-show-maximum-output'.
-This variable is buffer-local.")
+This variable is buffer-local."
+  :type 'boolean
+  :group 'term)
 
-(defvar term-scroll-show-maximum-output nil
+(defcustom term-scroll-show-maximum-output nil
   "*Controls how interpreter output causes window to scroll.
 If non-nil, then show the maximum output when the window is scrolled.
 
 See variable `term-scroll-to-bottom-on-output'.
-This variable is buffer-local.")
+This variable is buffer-local."
+  :type 'boolean
+  :group 'term)
 
 ;; Where gud-display-frame should put the debugging arrow.  This is
 ;; set by the marker-filter, which scans the debugger's output for
@@ -248,7 +585,7 @@ This is a good thing to set in mode hooks.")
   (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
   "Predicate for filtering additions to input history.
 Only inputs answering true to this function are saved on the input
-history list. Default is to save anything that isn't all whitespace")
+history list.  Default is to save anything that isn't all whitespace")
 
 (defvar term-input-filter-functions '()
   "Functions to call before input is sent to the process.
@@ -258,37 +595,49 @@ This variable is buffer-local.")
 
 (defvar term-input-sender (function term-simple-send)
   "Function to actually send to PROCESS the STRING submitted by user.
-Usually this is just 'term-simple-send, but if your mode needs to 
-massage the input string, this is your hook. This is called from
-the user command term-send-input. term-simple-send just sends
+Usually this is just 'term-simple-send, but if your mode needs to
+massage the input string, this is your hook.  This is called from
+the user command term-send-input.  term-simple-send just sends
 the string plus a newline.")
 
-(defvar term-mode-hook '()
+(defcustom term-eol-on-send t
+  "*Non-nil means go to the end of the line before sending input.
+See `term-send-input'."
+  :type 'boolean
+  :group 'term)
+
+(defcustom term-mode-hook '()
   "Called upon entry into term-mode
-This is run before the process is cranked up.")
+This is run before the process is cranked up."
+  :type 'hook
+  :group 'term)
 
-(defvar term-exec-hook '()
+(defcustom term-exec-hook '()
   "Called each time a process is exec'd by term-exec.
 This is called after the process is cranked up.  It is useful for things that
 must be done each time a process is executed in a term-mode buffer (e.g.,
-(process-kill-without-query)). In contrast, the term-mode-hook is only
-executed once when the buffer is created.")
+\(process-kill-without-query)).  In contrast, the term-mode-hook is only
+executed once when the buffer is created."
+  :type 'hook
+  :group 'term)
 
 (defvar term-mode-map nil)
 (defvar term-raw-map nil
   "Keyboard map for sending characters directly to the inferior process.")
-(defvar term-escape-char nil)
+(defvar term-escape-char nil
+  "Escape character for char-sub-mode of term mode.
+Do not change it directly;  use `term-set-escape-char' instead.")
 (defvar term-raw-escape-map nil)
 
 (defvar term-pager-break-map nil)
 
 (defvar term-ptyp t
   "True if communications via pty; false if by pipe.  Buffer local.
-This is to work around a bug in emacs process signalling.")
+This is to work around a bug in Emacs process signaling.")
 
 (defvar term-last-input-match ""
   "Last string searched for by term input history search, for defaulting.
-Buffer local variable.") 
+Buffer local variable.")
 
 (defvar term-input-ring nil)
 (defvar term-last-input-start)
@@ -298,7 +647,7 @@ Buffer local variable.")
 (defvar term-matching-input-from-input-string ""
   "Input previously used to match input history.")
 ; This argument to set-process-filter disables reading from the process,
-; assuming this is emacs-19.20 or newer.
+; assuming this is Emacs 19.20 or newer.
 (defvar term-pager-filter t)
 
 (put 'term-replace-by-expanded-history 'menu-enable 'term-input-autoexpand)
@@ -310,17 +659,12 @@ Buffer local variable.")
 (put 'term-scroll-show-maximum-output 'permanent-local t)
 (put 'term-ptyp 'permanent-local t)
 
-;; Do FORMS if running under Emacs-19.
-(defmacro term-if-emacs19 (&rest forms)
-  (if (string-match "^19" emacs-version) (cons 'progn forms)))
-;; True if running under XEmacs (previously Lucid emacs).
-(defmacro term-is-xemacs ()  '(string-match "Lucid" emacs-version))
-;; Do FORM if running under XEmacs (previously Lucid emacs).
+;; Do FORM if running under XEmacs (previously Lucid Emacs).
 (defmacro term-if-xemacs (&rest forms)
-  (if (term-is-xemacs) (cons 'progn forms)))
-;; Do FORM if NOT running under XEmacs (previously Lucid emacs).
+  (if (featurep 'xemacs) (cons 'progn forms)))
+;; Do FORM if NOT running under XEmacs (previously Lucid Emacs).
 (defmacro term-ifnot-xemacs (&rest forms)
-  (if (not (term-is-xemacs)) (cons 'progn forms)))
+  (if (not (featurep 'xemacs)) (cons 'progn forms)))
 
 (defmacro term-in-char-mode () '(eq (current-local-map) term-raw-map))
 (defmacro term-in-line-mode () '(not (term-in-char-mode)))
@@ -332,6 +676,54 @@ Buffer local variable.")
 (defvar term-signals-menu)
 (defvar term-terminal-menu)
 
+;;; Let's silence the byte-compiler -mm
+(defvar term-ansi-at-host nil)
+(defvar term-ansi-at-dir nil)
+(defvar term-ansi-at-user nil)
+(defvar term-ansi-at-message nil)
+(defvar term-ansi-at-save-user nil)
+(defvar term-ansi-at-save-pwd nil)
+(defvar term-ansi-at-save-anon nil)
+(defvar term-ansi-current-bold nil)
+(defvar term-ansi-current-color 0)
+(defvar term-ansi-face-already-done nil)
+(defvar term-ansi-current-bg-color 0)
+(defvar term-ansi-current-underline nil)
+(defvar term-ansi-current-reverse nil)
+(defvar term-ansi-current-invisible nil)
+
+;;; Four should be enough, if you want more, just add. -mm
+(defvar term-terminal-more-parameters 0)
+(defvar term-terminal-previous-parameter-2 -1)
+(defvar term-terminal-previous-parameter-3 -1)
+(defvar term-terminal-previous-parameter-4 -1)
+;;;
+
+;;; faces -mm
+
+(defcustom term-default-fg-color 'unspecified
+  "Default color for foreground in `term'."
+  :group 'term
+  :type 'string)
+
+(defcustom term-default-bg-color 'unspecified
+  "Default color for background in `term'."
+  :group 'term
+  :type 'string)
+
+;;; Use the same colors that xterm uses, see `xterm-standard-colors'.
+(defvar ansi-term-color-vector
+  [unspecified "black" "red3" "green3" "yellow3" "blue2"
+   "magenta3" "cyan3" "white"])
+
+;;; Inspiration came from comint.el -mm
+(defvar term-buffer-maximum-size 2048
+  "*The maximum size in lines for term buffers.
+Term buffers are truncated from the top to be no greater than this number.
+Notice that a setting of 0 means 'don't truncate anything'.  This variable
+is buffer-local.")
+;;;
+\f
 (term-if-xemacs
  (defvar term-terminal-menu
    '("Terminal"
@@ -340,122 +732,15 @@ Buffer local variable.")
      [ "Enable paging" term-pager-toggle (not term-pager-count)]
      [ "Disable paging" term-pager-toggle term-pager-count])))
 
-(defun term-mode ()
-  "Major mode for interacting with an inferior interpreter.
-Interpreter name is same as buffer name, sans the asterisks.
-In line sub-mode, return at end of buffer sends line as input,
-while return not at end copies rest of line to end and sends it.
-In char sub-mode, each character (except `term-escape-char`) is
-set immediately.
-
-This mode is typically customised to create inferior-lisp-mode,
-shell-mode, etc.. This can be done by setting the hooks
-term-input-filter-functions, term-input-filter, term-input-sender and
-term-get-old-input to appropriate functions, and the variable
-term-prompt-regexp to the appropriate regular expression.
-
-An input history is maintained of size `term-input-ring-size', and
-can be accessed with the commands \\[term-next-input], \\[term-previous-input], and \\[term-dynamic-list-input-ring].
-Input ring history expansion can be achieved with the commands
-\\[term-replace-by-expanded-history] or \\[term-magic-space].
-Input ring expansion is controlled by the variable `term-input-autoexpand',
-and addition is controlled by the variable `term-input-ignoredups'.
-
-Input to, and output from, the subprocess can cause the window to scroll to
-the end of the buffer.  See variables `term-scroll-to-bottom-on-input',
-and `term-scroll-to-bottom-on-output'.
-
-If you accidentally suspend your process, use \\[term-continue-subjob]
-to continue it.
-
-\\{term-mode-map}
-
-Entry to this mode runs the hooks on term-mode-hook"
-  (interactive)
-    ;; Do not remove this.  All major modes must do this.
-    (kill-all-local-variables)
-    (setq major-mode 'term-mode)
-    (setq mode-name "Term")
-    (use-local-map term-mode-map)
-    (make-local-variable 'term-home-marker)
-    (setq term-home-marker (copy-marker 0))
-    (make-local-variable 'term-saved-home-marker)
-    (make-local-variable 'term-height)
-    (make-local-variable 'term-width)
-    (setq term-width (1- (window-width)))
-    (setq term-height (1- (window-height)))
-    (make-local-variable 'term-terminal-parameter)
-    (make-local-variable 'term-saved-cursor)
-    (make-local-variable 'term-last-input-start)
-    (setq term-last-input-start (make-marker))
-    (make-local-variable 'term-last-input-end)
-    (setq term-last-input-end (make-marker))
-    (make-local-variable 'term-last-input-match)
-    (setq term-last-input-match "")
-    (make-local-variable 'term-prompt-regexp)        ; Don't set; default
-    (make-local-variable 'term-input-ring-size)      ; ...to global val.
-    (make-local-variable 'term-input-ring)
-    (make-local-variable 'term-input-ring-file-name)
-    (or (and (boundp 'term-input-ring) term-input-ring)
-       (setq term-input-ring (make-ring term-input-ring-size)))
-    (make-local-variable 'term-input-ring-index)
-    (or (and (boundp 'term-input-ring-index) term-input-ring-index)
-       (setq term-input-ring-index nil))
-
-    (make-local-variable 'term-command-hook)
-    (setq term-command-hook (symbol-function 'term-command-hook))
-
-    (make-local-variable 'term-terminal-state)
-    (make-local-variable 'term-kill-echo-list)
-    (make-local-variable 'term-start-line-column)
-    (make-local-variable 'term-current-column)
-    (make-local-variable 'term-current-row)
-    (make-local-variable 'term-log-buffer)
-    (make-local-variable 'term-scroll-start)
-    (make-local-variable 'term-scroll-end)
-    (setq term-scroll-end term-height)
-    (make-local-variable 'term-scroll-with-delete)
-    (make-local-variable 'term-pager-count)
-    (make-local-variable 'term-pager-old-local-map)
-    (make-local-variable 'term-old-mode-map)
-    (make-local-variable 'term-insert-mode)
-    (make-local-variable 'term-dynamic-complete-functions)
-    (make-local-variable 'term-completion-fignore)
-    (make-local-variable 'term-get-old-input)
-    (make-local-variable 'term-matching-input-from-input-string)
-    (make-local-variable 'term-input-autoexpand)
-    (make-local-variable 'term-input-ignoredups)
-    (make-local-variable 'term-delimiter-argument-list)
-    (make-local-variable 'term-input-filter-functions)
-    (make-local-variable 'term-input-filter)  
-    (make-local-variable 'term-input-sender)
-    (make-local-variable 'term-scroll-to-bottom-on-output)
-    (make-local-variable 'term-scroll-show-maximum-output)
-    (make-local-variable 'term-ptyp)
-    (make-local-variable 'term-exec-hook)
-    (make-local-variable 'term-vertical-motion)
-    (make-local-variable 'term-pending-delete-marker)
-    (setq term-pending-delete-marker (make-marker))
-    (make-local-variable 'term-current-face)
-    (make-local-variable 'term-pending-frame)
-    (setq term-pending-frame nil)
-    (run-hooks 'term-mode-hook)
-    (term-if-xemacs
-     (set-buffer-menubar
-      (append current-menubar (list term-terminal-menu))))
-    (or term-input-ring
-       (setq term-input-ring (make-ring term-input-ring-size)))
-    (term-update-mode-line))
-
-(if term-mode-map
-    nil
+(unless term-mode-map
   (setq term-mode-map (make-sparse-keymap))
   (define-key term-mode-map "\ep" 'term-previous-input)
   (define-key term-mode-map "\en" 'term-next-input)
   (define-key term-mode-map "\er" 'term-previous-matching-input)
   (define-key term-mode-map "\es" 'term-next-matching-input)
   (term-ifnot-xemacs
-   (define-key term-mode-map [?\A-\M-r] 'term-previous-matching-input-from-input)
+   (define-key term-mode-map [?\A-\M-r]
+        'term-previous-matching-input-from-input)
    (define-key term-mode-map [?\A-\M-s] 'term-next-matching-input-from-input))
   (define-key term-mode-map "\e\C-l" 'term-show-output)
   (define-key term-mode-map "\C-m" 'term-send-input)
@@ -478,11 +763,8 @@ Entry to this mode runs the hooks on term-mode-hook"
   (define-key term-mode-map "\C-c\C-j" 'term-line-mode)
   (define-key term-mode-map "\C-c\C-q" 'term-pager-toggle)
 
-  (copy-face 'default 'term-underline-face)
-  (set-face-underline-p 'term-underline-face t)
-
 ;  ;; completion:
-;  (define-key term-mode-map [menu-bar completion] 
+;  (define-key term-mode-map [menu-bar completion]
 ;    (cons "Complete" (make-sparse-keymap "Complete")))
 ;  (define-key term-mode-map [menu-bar completion complete-expand]
 ;    '("Expand File Name" . term-replace-by-expanded-filename))
@@ -499,7 +781,7 @@ Entry to this mode runs the hooks on term-mode-hook"
 
 ;; Menu bars:
 (term-ifnot-xemacs
- (term-if-emacs19
+ (progn
 
   ;; terminal:
   (let (newmap)
@@ -512,12 +794,11 @@ Entry to this mode runs the hooks on term-mode-hook"
       '("Character mode" . term-char-mode))
     (define-key newmap [terminal-line-mode]
       '("Line mode" . term-line-mode))
-    (define-key newmap [menu-bar terminal] 
-      (setq term-terminal-menu (cons "Terminal" newmap)))
+    (setq term-terminal-menu (cons "Terminal" newmap))
 
     ;; completion:  (line mode only)
     (defvar term-completion-menu (make-sparse-keymap "Complete"))
-    (define-key term-mode-map [menu-bar completion] 
+    (define-key term-mode-map [menu-bar completion]
       (cons "Complete" term-completion-menu))
     (define-key term-completion-menu [complete-expand]
       '("Expand File Name" . term-replace-by-expanded-filename))
@@ -530,7 +811,7 @@ Entry to this mode runs the hooks on term-mode-hook"
 
     ;; Input history: (line mode only)
     (defvar term-inout-menu (make-sparse-keymap "In/Out"))
-    (define-key term-mode-map [menu-bar inout] 
+    (define-key term-mode-map [menu-bar inout]
       (cons "In/Out" term-inout-menu))
     (define-key term-inout-menu [kill-output]
       '("Kill Current Output Group" . term-kill-output))
@@ -557,7 +838,8 @@ Entry to this mode runs the hooks on term-mode-hook"
     (define-key term-inout-menu [next-matching-history-from-input]
       '("Next Matching Current Input" . term-next-matching-input-from-input))
     (define-key term-inout-menu [previous-matching-history-from-input]
-      '("Previous Matching Current Input" . term-previous-matching-input-from-input))
+      '("Previous Matching Current Input" .
+               term-previous-matching-input-from-input))
     (define-key term-inout-menu [next-history]
       '("Next Input" . term-next-input))
     (define-key term-inout-menu [previous-history]
@@ -578,7 +860,256 @@ Entry to this mode runs the hooks on term-mode-hook"
     (define-key term-mode-map [menu-bar signals]
       (setq term-signals-menu (cons "Signals" newmap)))
     )))
+\f
+;; Set up term-raw-map, etc.
+
+(defun term-set-escape-char (c)
+  "Change term-escape-char and keymaps that depend on it."
+  (if term-escape-char
+      (define-key term-raw-map term-escape-char 'term-send-raw))
+  (setq c (make-string 1 c))
+  (define-key term-raw-map c term-raw-escape-map)
+  ;; Define standard bindings in term-raw-escape-map
+  (define-key term-raw-escape-map "\C-v"
+    (lookup-key (current-global-map) "\C-v"))
+  (define-key term-raw-escape-map "\C-u"
+    (lookup-key (current-global-map) "\C-u"))
+  (define-key term-raw-escape-map c 'term-send-raw)
+  (define-key term-raw-escape-map "\C-q" 'term-pager-toggle)
+  ;; The keybinding for term-char-mode is needed by the menubar code.
+  (define-key term-raw-escape-map "\C-k" 'term-char-mode)
+  (define-key term-raw-escape-map "\C-j" 'term-line-mode)
+  ;; It's convenient to have execute-extended-command here.
+  (define-key term-raw-escape-map [?\M-x] 'execute-extended-command))
+
+(let* ((map (make-keymap))
+       (esc-map (make-keymap))
+       (i 0))
+  (while (< i 128)
+    (define-key map (make-string 1 i) 'term-send-raw)
+    ;; Avoid O and [. They are used in escape sequences for various keys.
+    (unless (or (eq i ?O) (eq i 91)) 
+               (define-key esc-map (make-string 1 i) 'term-send-raw-meta))
+    (setq i (1+ i)))
+  (dolist (elm (generic-character-list))
+    (define-key map (vector elm) 'term-send-raw))
+  (define-key map "\e" esc-map)
+  (setq term-raw-map map)
+  (setq term-raw-escape-map
+       (copy-keymap (lookup-key (current-global-map) "\C-x")))
+
+;;; Added nearly all the 'grey keys' -mm
+
+  (progn
+    (term-if-xemacs
+     (define-key term-raw-map [button2] 'term-mouse-paste))
+    (term-ifnot-xemacs
+     (define-key term-raw-map [mouse-2] 'term-mouse-paste)
+     (define-key term-raw-map [menu-bar terminal] term-terminal-menu)
+     (define-key term-raw-map [menu-bar signals] term-signals-menu))
+    (define-key term-raw-map [up] 'term-send-up)
+    (define-key term-raw-map [down] 'term-send-down)
+    (define-key term-raw-map [right] 'term-send-right)
+    (define-key term-raw-map [left] 'term-send-left)
+    (define-key term-raw-map [delete] 'term-send-del)
+    (define-key term-raw-map [deletechar] 'term-send-del)
+    (define-key term-raw-map [backspace] 'term-send-backspace)
+    (define-key term-raw-map [home] 'term-send-home)
+    (define-key term-raw-map [end] 'term-send-end)
+    (define-key term-raw-map [S-prior] 'scroll-down)
+    (define-key term-raw-map [S-next] 'scroll-up)
+    (define-key term-raw-map [S-insert] 'term-paste)
+    (define-key term-raw-map [prior] 'term-send-prior)
+    (define-key term-raw-map [next] 'term-send-next)))
+
+(term-set-escape-char ?\C-c)
+
+(defun term-window-width ()
+  (if (featurep 'xemacs)
+      (1- (window-width))
+    (if (and window-system overflow-newline-into-fringe)
+       (window-width)
+      (1- (window-width)))))
+
+\f
+(put 'term-mode 'mode-class 'special)
+
+
+;;; Use this variable as a display table for `term-mode'.
+(defvar term-display-table
+  (let ((dt (or (copy-sequence standard-display-table)
+               (make-display-table)))
+        i)
+    ;; avoid changing the display table for ^J
+    (setq i 0) 
+    (while (< i 10)
+      (aset dt i (vector i))
+      (setq i (1+ i)))
+    (setq i 11) 
+    (while (< i 32)
+      (aset dt i (vector i))
+      (setq i (1+ i)))
+    (setq i 128)
+    (while (< i 256)
+      (aset dt i (vector i))
+      (setq i (1+ i)))
+    dt))
+
+(defun term-mode ()
+  "Major mode for interacting with an inferior interpreter.
+The interpreter name is same as buffer name, sans the asterisks.
+
+There are two submodes: line mode and char mode.  By default, you are
+in char mode.  In char sub-mode, each character (except
+`term-escape-char') is sent immediately to the subprocess.
+The escape character is equivalent to the usual meaning of C-x.
+
+In line mode, you send a line of input at a time; use
+\\[term-send-input] to send.
+
+In line mode, this maintains an input history of size
+`term-input-ring-size', and you can access it with the commands
+\\[term-next-input], \\[term-previous-input], and
+\\[term-dynamic-list-input-ring].  Input ring history expansion can be
+achieved with the commands \\[term-replace-by-expanded-history] or
+\\[term-magic-space].  Input ring expansion is controlled by the
+variable `term-input-autoexpand', and addition is controlled by the
+variable `term-input-ignoredups'.
+
+Input to, and output from, the subprocess can cause the window to scroll to
+the end of the buffer.  See variables `term-scroll-to-bottom-on-input',
+and `term-scroll-to-bottom-on-output'.
+
+If you accidentally suspend your process, use \\[term-continue-subjob]
+to continue it.
+
+This mode can be customised to create specific modes for running
+particular subprocesses.  This can be done by setting the hooks
+`term-input-filter-functions', `term-input-filter',
+`term-input-sender' and `term-get-old-input' to appropriate functions,
+and the variable `term-prompt-regexp' to the appropriate regular
+expression.
+
+Commands in raw mode:
+
+\\{term-raw-map}
+
+Commands in line mode:
+
+\\{term-mode-map}
 
+Entry to this mode runs the hooks on `term-mode-hook'."
+  (interactive)
+  ;; Do not remove this.  All major modes must do this.
+  (kill-all-local-variables)
+  (setq major-mode 'term-mode)
+  (setq mode-name "Term")
+  (use-local-map term-mode-map)
+  ;; we do not want indent to sneak in any tabs
+  (setq indent-tabs-mode nil)
+  (setq buffer-display-table term-display-table)
+  (make-local-variable 'term-home-marker)
+  (setq term-home-marker (copy-marker 0))
+  (make-local-variable 'term-saved-home-marker)
+  (make-local-variable 'term-height)
+  (make-local-variable 'term-width)
+  (setq term-width (term-window-width))
+  (setq term-height (1- (window-height)))
+  (make-local-variable 'term-terminal-parameter)
+  (make-local-variable 'term-saved-cursor)
+  (make-local-variable 'term-last-input-start)
+  (setq term-last-input-start (make-marker))
+  (make-local-variable 'term-last-input-end)
+  (setq term-last-input-end (make-marker))
+  (make-local-variable 'term-last-input-match)
+  (setq term-last-input-match "")
+  (make-local-variable 'term-prompt-regexp) ; Don't set; default
+  (make-local-variable 'term-input-ring-size) ; ...to global val.
+  (make-local-variable 'term-input-ring)
+  (make-local-variable 'term-input-ring-file-name)
+  (or (and (boundp 'term-input-ring) term-input-ring)
+      (setq term-input-ring (make-ring term-input-ring-size)))
+  (make-local-variable 'term-input-ring-index)
+  (or (and (boundp 'term-input-ring-index) term-input-ring-index)
+      (setq term-input-ring-index nil))
+
+  (make-local-variable 'term-command-hook)
+  (setq term-command-hook (symbol-function 'term-command-hook))
+
+;;; I'm not sure these saves are necessary but, since I
+;;; haven't tested the whole thing on a net connected machine with
+;;; a properly configured ange-ftp, I've decided to be conservative
+;;; and put them in. -mm
+
+  (make-local-variable 'term-ansi-at-host)
+  (setq term-ansi-at-host (system-name))
+
+  (make-local-variable 'term-ansi-at-dir)
+  (setq term-ansi-at-dir default-directory)
+
+  (make-local-variable 'term-ansi-at-message)
+  (setq term-ansi-at-message nil)
+
+;;; For user tracking purposes -mm
+  (make-local-variable 'ange-ftp-default-user)
+  (make-local-variable 'ange-ftp-default-password)
+  (make-local-variable 'ange-ftp-generate-anonymous-password)
+
+;;; You may want to have different scroll-back sizes -mm
+  (make-local-variable 'term-buffer-maximum-size)
+
+;;; Of course these have to be buffer-local -mm
+  (make-local-variable 'term-ansi-current-bold)
+  (make-local-variable 'term-ansi-current-color)
+  (make-local-variable 'term-ansi-face-already-done)
+  (make-local-variable 'term-ansi-current-bg-color)
+  (make-local-variable 'term-ansi-current-underline)
+  (make-local-variable 'term-ansi-current-reverse)
+  (make-local-variable 'term-ansi-current-invisible)
+
+  (make-local-variable 'term-terminal-state)
+  (make-local-variable 'term-kill-echo-list)
+  (make-local-variable 'term-start-line-column)
+  (make-local-variable 'term-current-column)
+  (make-local-variable 'term-current-row)
+  (make-local-variable 'term-log-buffer)
+  (make-local-variable 'term-scroll-start)
+  (make-local-variable 'term-scroll-end)
+  (setq term-scroll-end term-height)
+  (make-local-variable 'term-scroll-with-delete)
+  (make-local-variable 'term-pager-count)
+  (make-local-variable 'term-pager-old-local-map)
+  (make-local-variable 'term-old-mode-map)
+  (make-local-variable 'term-insert-mode)
+  (make-local-variable 'term-dynamic-complete-functions)
+  (make-local-variable 'term-completion-fignore)
+  (make-local-variable 'term-get-old-input)
+  (make-local-variable 'term-matching-input-from-input-string)
+  (make-local-variable 'term-input-autoexpand)
+  (make-local-variable 'term-input-ignoredups)
+  (make-local-variable 'term-delimiter-argument-list)
+  (make-local-variable 'term-input-filter-functions)
+  (make-local-variable 'term-input-filter)
+  (make-local-variable 'term-input-sender)
+  (make-local-variable 'term-eol-on-send)
+  (make-local-variable 'term-scroll-to-bottom-on-output)
+  (make-local-variable 'term-scroll-show-maximum-output)
+  (make-local-variable 'term-ptyp)
+  (make-local-variable 'term-exec-hook)
+  (make-local-variable 'term-vertical-motion)
+  (make-local-variable 'term-pending-delete-marker)
+  (setq term-pending-delete-marker (make-marker))
+  (make-local-variable 'term-current-face)
+  (make-local-variable 'term-pending-frame)
+  (setq term-pending-frame nil)
+  (run-hooks 'term-mode-hook)
+  (term-if-xemacs
+   (set-buffer-menubar
+    (append current-menubar (list term-terminal-menu))))
+  (or term-input-ring
+      (setq term-input-ring (make-ring term-input-ring-size)))
+  (term-update-mode-line))
+\f
 (defun term-reset-size (height width)
   (setq term-height height)
   (setq term-width width)
@@ -617,9 +1148,9 @@ Entry to this mode runs the hooks on term-mode-hook"
 
 (defun term-check-size (process)
   (if (or (/= term-height (1- (window-height)))
-         (/= term-width (1- (window-width))))
+         (/= term-width (term-window-width)))
       (progn
-       (term-reset-size (1- (window-height)) (1- (window-width)))
+       (term-reset-size (1- (window-height)) (term-window-width))
        (set-process-window-size process term-height term-width))))
 
 (defun term-send-raw-string (chars)
@@ -631,11 +1162,11 @@ Entry to this mode runs the hooks on term-mode-hook"
       (goto-char (process-mark proc))
       (if (term-pager-enabled)
          (setq term-pager-count (term-current-row)))
-      (send-string proc chars))))
+      (process-send-string proc chars))))
 
 (defun term-send-raw ()
   "Send the last character typed through the terminal-emulator
-without any interpretation." 
+without any interpretation."
   (interactive)
  ;; Convert `return' to C-m, etc.
   (if (and (symbolp last-input-char)
@@ -645,84 +1176,64 @@ without any interpretation."
 
 (defun term-send-raw-meta ()
   (interactive)
-  (if (symbolp last-input-char)
+  (let ((char last-input-char))
+    (when (symbolp last-input-char)
       ;; Convert `return' to C-m, etc.
-      (let ((tmp (get last-input-char 'event-symbol-elements)))
-       (if tmp
-           (setq last-input-char (car tmp)))
-       (if (symbolp last-input-char)
-           (progn
-             (setq tmp (get last-input-char 'ascii-character))
-             (if tmp (setq last-input-char tmp))))))
-  (term-send-raw-string (if (and (numberp last-input-char)
-                                (> last-input-char 127)
-                                (< last-input-char 256))
-                           (make-string 1 last-input-char)
-                         (format "\e%c" last-input-char))))
+      (let ((tmp (get char 'event-symbol-elements)))
+       (when tmp
+         (setq char (car tmp)))
+       (when (symbolp char)
+         (setq tmp (get char 'ascii-character))
+         (when tmp
+           (setq char tmp)))))
+    (setq char (event-basic-type char))
+    (term-send-raw-string (if (and (numberp char)
+                                  (> char 127)
+                                  (< char 256))
+                             (make-string 1 char)
+                           (format "\e%c" char)))))
 
 (defun term-mouse-paste (click arg)
   "Insert the last stretch of killed text at the position clicked on."
   (interactive "e\nP")
-  (mouse-set-point click)
-  (setq this-command 'yank)
-  (term-send-raw-string (current-kill (cond
-                                      ((listp arg) 0)
-                                      ((eq arg '-) -1)
-                                      (t (1- arg))))))
+  (term-if-xemacs
+   (term-send-raw-string (or (condition-case () (x-get-selection) (error ()))
+                            (x-get-cutbuffer)
+                            (error "No selection or cut buffer available"))))
+  (term-ifnot-xemacs
+   ;; Give temporary modes such as isearch a chance to turn off.
+   (run-hooks 'mouse-leave-buffer-hook)
+   (setq this-command 'yank)
+   (mouse-set-point click)
+   (term-send-raw-string (current-kill (cond
+                                       ((listp arg) 0)
+                                       ((eq arg '-) -1)
+                                       (t (1- arg)))))))
+
+(defun term-paste ()
+  "Insert the last stretch of killed text at point."
+  (interactive)
+   (term-send-raw-string (current-kill 0)))
 
 ;; Which would be better:  "\e[A" or "\eOA"? readline accepts either.
-(defun term-send-up    () (interactive) (term-send-raw-string "\e[A"))
-(defun term-send-down  () (interactive) (term-send-raw-string "\e[B"))
-(defun term-send-right () (interactive) (term-send-raw-string "\e[C"))
-(defun term-send-left  () (interactive) (term-send-raw-string "\e[D"))
-
-(defun term-set-escape-char (c)
-  (if term-escape-char
-      (define-key term-raw-map term-escape-char 'term-send-raw))
-  (setq c (make-string 1 c))
-  (define-key term-raw-map c term-raw-escape-map)
-  ;; Define standard binings in term-raw-escape-map
-  (define-key term-raw-escape-map "\C-x"
-    (lookup-key (current-global-map) "\C-x"))
-  (define-key term-raw-escape-map "\C-v"
-    (lookup-key (current-global-map) "\C-v"))
-  (define-key term-raw-escape-map "\C-u"
-    (lookup-key (current-global-map) "\C-u"))
-  (define-key term-raw-escape-map c 'term-send-raw)
-  (define-key term-raw-escape-map "\C-q" 'term-pager-toggle)
-  ;; The keybinding for term-char-mode is needed by the menubar code.
-  (define-key term-raw-escape-map "\C-k" 'term-char-mode)
-  (define-key term-raw-escape-map "\C-j" 'term-line-mode))
-    
+;; For my configuration it's definitely better \eOA but YMMV. -mm
+;; For example: vi works with \eOA while elm wants \e[A ...
+(defun term-send-up    () (interactive) (term-send-raw-string "\eOA"))
+(defun term-send-down  () (interactive) (term-send-raw-string "\eOB"))
+(defun term-send-right () (interactive) (term-send-raw-string "\eOC"))
+(defun term-send-left  () (interactive) (term-send-raw-string "\eOD"))
+(defun term-send-home  () (interactive) (term-send-raw-string "\e[1~"))
+(defun term-send-end   () (interactive) (term-send-raw-string "\e[4~"))
+(defun term-send-prior () (interactive) (term-send-raw-string "\e[5~"))
+(defun term-send-next  () (interactive) (term-send-raw-string "\e[6~"))
+(defun term-send-del   () (interactive) (term-send-raw-string "\e[3~"))
+(defun term-send-backspace  () (interactive) (term-send-raw-string "\C-?"))
+\f
 (defun term-char-mode ()
   "Switch to char (\"raw\") sub-mode of term mode.
 Each character you type is sent directly to the inferior without
-intervention from emacs, except for the escape character (usually C-c)."
+intervention from Emacs, except for the escape character (usually C-c)."
   (interactive)
-  (if (not term-raw-map)
-      (let* ((map (make-keymap))
-            (esc-map (make-keymap))
-            (i 0))
-       (while (< i 128)
-         (define-key map (make-string 1 i) 'term-send-raw)
-         (define-key esc-map (make-string 1 i) 'term-send-raw-meta)
-         (setq i (1+ i)))
-       (define-key map "\e" esc-map)
-       (setq term-raw-map map)
-       (setq term-raw-escape-map
-             (copy-keymap (lookup-key (current-global-map) "\C-x")))
-       (term-if-emacs19
-        (term-if-xemacs
-         (define-key term-raw-map [(button2)] 'term-mouse-paste))
-        (term-ifnot-xemacs
-         (define-key term-raw-map [mouse-2] 'term-mouse-paste)
-         (define-key term-raw-map [menu-bar terminal] term-terminal-menu)
-         (define-key term-raw-map [menu-bar signals] term-signals-menu)
-        (define-key term-raw-map [up] 'term-send-up)
-        (define-key term-raw-map [down] 'term-send-down)
-        (define-key term-raw-map [right] 'term-send-right)
-        (define-key term-raw-map [left] 'term-send-left))
-       (term-set-escape-char ?\C-c))))
   ;; FIXME: Emit message? Cfr ilisp-raw-message
   (if (term-in-line-mode)
       (progn
@@ -744,7 +1255,7 @@ intervention from emacs, except for the escape character (usually C-c)."
 
 (defun term-line-mode  ()
   "Switch to line (\"cooked\") sub-mode of term mode.
-This means that emacs editing commands work as normally, until
+This means that Emacs editing commands work as normally, until
 you type \\[term-send-input] which sends the current line to the inferior."
   (interactive)
   (if (term-in-char-mode)
@@ -757,27 +1268,25 @@ you type \\[term-send-input] which sends the current line to the inferior."
        (if (term-in-char-mode)
            (if (term-pager-enabled) '(": char page %s") '(": char %s"))
          (if (term-pager-enabled) '(": line page %s") '(": line %s"))))
-  (set-buffer-modified-p (buffer-modified-p))) ;; Force mode line update.
+  (force-mode-line-update))
 
 (defun term-check-proc (buffer)
   "True if there is a process associated w/buffer BUFFER, and
-it is alive (status RUN or STOP). BUFFER can be either a buffer or the
+it is alive (status RUN or STOP).  BUFFER can be either a buffer or the
 name of one"
   (let ((proc (get-buffer-process buffer)))
     (and proc (memq (process-status proc) '(run stop)))))
 
-;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
-;;; for the second argument (program).
 ;;;###autoload
 (defun make-term (name program &optional startfile &rest switches)
 "Make a term process NAME in a buffer, running PROGRAM.
 The name of the buffer is made by surrounding NAME with `*'s.
 If there is already a running process in that buffer, it is not restarted.
-Optional third arg STARTFILE is the name of a file to send the contents of to 
+Optional third arg STARTFILE is the name of a file to send the contents of to
 the process.  Any more args are arguments to PROGRAM."
   (let ((buffer (get-buffer-create (concat "*" name "*"))))
     ;; If no process, or nuked process, crank up a new one and put buffer in
-    ;; term mode. Otherwise, leave buffer and existing process alone.
+    ;; term mode.  Otherwise, leave buffer and existing process alone.
     (cond ((not (term-check-proc buffer))
           (save-excursion
             (set-buffer buffer)
@@ -787,7 +1296,11 @@ the process.  Any more args are arguments to PROGRAM."
 
 ;;;###autoload
 (defun term (program)
-  "Start a terminal-emulator in a new buffer."
+  "Start a terminal-emulator in a new buffer.
+The buffer is in Term mode; see `term-mode' for the
+commands to use in that buffer.
+
+\\<term-raw-map>Type \\[switch-to-buffer] to switch to another buffer."
   (interactive (list (read-from-minibuffer "Run program: "
                                           (or explicit-shell-file-name
                                               (getenv "ESHELL")
@@ -800,9 +1313,9 @@ the process.  Any more args are arguments to PROGRAM."
 
 (defun term-exec (buffer name command startfile switches)
   "Start up a process in buffer for term modes.
-Blasts any old process running in the buffer. Doesn't set the buffer mode.
+Blasts any old process running in the buffer.  Doesn't set the buffer mode.
 You can use this to cheaply run a series of processes in the same term
-buffer. The hook term-exec-hook is run after each exec."
+buffer.  The hook term-exec-hook is run after each exec."
   (save-excursion
     (set-buffer buffer)
     (let ((proc (get-buffer-process buffer)))  ; Blast any old process.
@@ -810,11 +1323,12 @@ buffer. The hook term-exec-hook is run after each exec."
     ;; Crank up a new process
     (let ((proc (term-exec-1 name buffer command switches)))
       (make-local-variable 'term-ptyp)
-      (setq term-ptyp process-connection-type) ; T if pty, NIL if pipe.
+      (setq term-ptyp process-connection-type) ; t if pty, nil if pipe.
       ;; Jump to the end, and set the process mark.
       (goto-char (point-max))
       (set-marker (process-mark proc) (point))
       (set-process-filter proc 'term-emulate-terminal)
+      (set-process-sentinel proc 'term-sentinel)
       ;; Feed it the startfile.
       (cond (startfile
             ;;This is guaranteed to wait long enough
@@ -831,27 +1345,75 @@ buffer. The hook term-exec-hook is run after each exec."
     (run-hooks 'term-exec-hook)
     buffer)))
 
+(defun term-sentinel  (proc msg)
+  "Sentinel for term buffers.
+The main purpose is to get rid of the local keymap."
+  (let ((buffer (process-buffer proc)))
+    (if (memq (process-status proc) '(signal exit))
+       (progn
+         (if (null (buffer-name buffer))
+             ;; buffer killed
+             (set-process-buffer proc nil)
+           (let ((obuf (current-buffer)))
+             ;; save-excursion isn't the right thing if
+             ;; process-buffer is current-buffer
+             (unwind-protect
+                 (progn
+                   ;; Write something in the compilation buffer
+                   ;; and hack its mode line.
+                   (set-buffer buffer)
+                   ;; Get rid of local keymap.
+                   (use-local-map nil)
+                   (term-handle-exit (process-name proc)
+                                     msg)
+                   ;; Since the buffer and mode line will show that the
+                   ;; process is dead, we can delete it now.  Otherwise it
+                   ;; will stay around until M-x list-processes.
+                   (delete-process proc))
+               (set-buffer obuf))))
+         ))))
+
+(defun term-handle-exit (process-name msg)
+  "Write process exit (or other change) message MSG in the current buffer."
+  (let ((buffer-read-only nil)
+       (omax (point-max))
+       (opoint (point)))
+    ;; Record where we put the message, so we can ignore it
+    ;; later on.
+    (goto-char omax)
+    (insert ?\n "Process " process-name " " msg)
+    ;; Force mode line redisplay soon.
+    (force-mode-line-update)
+    (if (and opoint (< opoint omax))
+       (goto-char opoint))))
+
+
 ;;; Name to use for TERM.
 ;;; Using "emacs" loses, because bash disables editing if TERM == emacs.
 (defvar term-term-name "eterm")
-; Format string, usage: (format term-termcap-string emacs-term-name "TERMCAP=" 24 80)
+; Format string, usage:
+; (format term-termcap-string emacs-term-name "TERMCAP=" 24 80)
 (defvar term-termcap-format
   "%s%s:li#%d:co#%d:cl=\\E[H\\E[J:cd=\\E[J:bs:am:xn:cm=\\E[%%i%%d;%%dH\
 :nd=\\E[C:up=\\E[A:ce=\\E[K:ho=\\E[H:pt\
-:al=\\E[L:dl=\\E[M:DL=\\E[%%dM:AL=\\E[%%dL:cs=\\E[%%i%%d;%%dr:sf=\\n\
-:te=\\E[2J\\E[?47l\\E8:ti=\\E7\\E[?47h\
+:al=\\E[L:dl=\\E[M:DL=\\E[%%dM:AL=\\E[%%dL:cs=\\E[%%i%%d;%%dr:sf=^J\
 :dc=\\E[P:DC=\\E[%%dP:IC=\\E[%%d@:im=\\E[4h:ei=\\E[4l:mi:\
 :so=\\E[7m:se=\\E[m:us=\\E[4m:ue=\\E[m:md=\\E[1m:mr=\\E[7m:me=\\E[m\
-:UP=\\E[%%dA:DO=\\E[%%dB:LE=\\E[%%dD:RI=\\E[%%dC"
+:UP=\\E[%%dA:DO=\\E[%%dB:LE=\\E[%%dD:RI=\\E[%%dC\
+:kl=\\EOD:kd=\\EOB:kr=\\EOC:ku=\\EOA:kN=\\E[6~:kP=\\E[5~:@7=\\E[4~:kh=\\E[1~\
+:mk=\\E[8m:cb=\\E[1K:op=\\E[39;49m:Co#8:pa#64:AB=\\E[4%%dm:AF=\\E[3%%dm:cr=^M\
+:bl=^G:do=^J:le=^H:ta=^I:se=\E[27m:ue=\E24m\
+:kb=^?:kD=^[[3~:sc=\E7:rc=\E8:r1=\Ec:"
 ;;; : -undefine ic
-  "termcap capabilties supported")
+;;; don't define :te=\\E[2J\\E[?47l\\E8:ti=\\E7\\E[?47h\
+  "termcap capabilities supported")
 
 ;;; This auxiliary function cranks up the process for term-exec in
 ;;; the appropriate environment.
 
 (defun term-exec-1 (name buffer command switches)
   ;; We need to do an extra (fork-less) exec to run stty.
-  ;; (This would not be needed if we had suitable emacs primitives.)
+  ;; (This would not be needed if we had suitable Emacs primitives.)
   ;; The 'if ...; then shift; fi' hack is because Bourne shell
   ;; loses one arg when called with -c, and newer shells (bash,  ksh) don't.
   ;; Thus we add an extra dummy argument "..", and then remove it.
@@ -859,14 +1421,21 @@ buffer. The hook term-exec-hook is run after each exec."
         (nconc
          (list
           (format "TERM=%s" term-term-name)
-          (if (and (boundp 'system-uses-terminfo) system-uses-terminfo)
-              (format "TERMINFO=%s" data-directory)
-           (format term-termcap-format "TERMCAP="
-                   term-term-name term-height term-width))
-          (format "EMACS=%s (term:%s)" emacs-version term-version)
+          (format "TERMINFO=%s" data-directory)
+          (format term-termcap-format "TERMCAP="
+                  term-term-name term-height term-width)
+          ;; Breaks `./configure' of w3 and url which try to run $EMACS.
+          (format "EMACS=%s (term:%s)" emacs-version term-protocol-version)
           (format "LINES=%d" term-height)
           (format "COLUMNS=%d" term-width))
-         process-environment)))
+         process-environment))
+       (process-connection-type t)
+       ;; We should suppress conversion of end-of-line format.
+       (inhibit-eol-conversion t)
+       ;; The process's output contains not just chars but also binary
+       ;; escape codes, so we need to see the raw output.  We will have to
+       ;; do the decoding by hand on the parts that are made of chars.
+       (coding-system-for-read 'binary))
     (apply 'start-process name buffer
           "/bin/sh" "-c"
           (format "stty -nl echo rows %d columns %d sane 2>/dev/null;\
@@ -875,18 +1444,6 @@ if [ $1 = .. ]; then shift; fi; exec \"$@\""
           ".."
           command switches)))
 
-;;; This should be in emacs, but it isn't.
-(defun term-mem (item list &optional elt=)
-  "Test to see if ITEM is equal to an item in LIST.
-Option comparison function ELT= defaults to equal."
-  (let ((elt= (or elt= (function equal)))
-       (done nil))
-    (while (and list (not done))
-      (if (funcall elt= item (car list))
-         (setq done list)
-         (setq list (cdr list))))
-    done))
-
 \f
 ;;; Input history processing in a buffer
 ;;; ===========================================================================
@@ -1024,8 +1581,7 @@ See also `term-read-input-ring'."
 
 (defun term-regexp-arg (prompt)
   ;; Return list of regexp and prefix arg using PROMPT.
-  (let* ((minibuffer-history-sexp-flag nil)
-        ;; Don't clobber this.
+  (let* (;; Don't clobber this.
         (last-command last-command)
         (regexp (read-from-minibuffer prompt nil nil nil
                                       'minibuffer-history-search-history)))
@@ -1064,7 +1620,7 @@ See also `term-read-input-ring'."
   "Return the string ARG places along the input ring.
 Moves relative to `term-input-ring-index'."
   (ring-ref term-input-ring (if term-input-ring-index
-                                 (mod (+ arg term-input-ring-index) 
+                                 (mod (+ arg term-input-ring-index)
                                       (ring-length term-input-ring))
                                arg)))
 
@@ -1084,7 +1640,8 @@ Moves relative to `term-input-ring-index'."
   (let* ((pos (term-previous-matching-input-string-position regexp arg)))
     (if pos (ring-ref term-input-ring pos))))
 
-(defun term-previous-matching-input-string-position (regexp arg &optional start)
+(defun term-previous-matching-input-string-position
+  (regexp arg &optional start)
   "Return the index matching REGEXP ARG places along the input ring.
 Moves relative to START, or `term-input-ring-index'."
   (if (or (not (ring-p term-input-ring))
@@ -1124,7 +1681,7 @@ If N is negative, find the next or Nth next match."
        (error "Not found")
       (setq term-input-ring-index pos)
       (message "History item: %d" (1+ pos))
-      (delete-region 
+      (delete-region
        ;; Can't use kill-region as it sets this-command
        (process-mark (get-buffer-process (current-buffer))) (point))
       (insert (ring-ref term-input-ring pos)))))
@@ -1147,8 +1704,8 @@ If N is negative, search forwards for the -Nth following match."
                                term-next-matching-input-from-input)))
       ;; Starting a new search
       (setq term-matching-input-from-input-string
-           (buffer-substring 
-            (process-mark (get-buffer-process (current-buffer))) 
+           (buffer-substring
+            (process-mark (get-buffer-process (current-buffer)))
             (point))
            term-input-ring-index nil))
   (term-previous-matching-input
@@ -1171,7 +1728,7 @@ Expansion is dependent on the value of `term-input-autoexpand'.
 This function depends on the buffer's idea of the input history, which may not
 match the command interpreter's idea, assuming it has one.
 
-Assumes history syntax is like typical Un*x shells'.  However, since emacs
+Assumes history syntax is like typical Un*x shells'.  However, since Emacs
 cannot know the interpreter's idea of input line numbers, assuming it has one,
 it cannot expand absolute input line number references.
 
@@ -1358,7 +1915,7 @@ Argument 0 is the command name."
   (let ((argpart "[^ \n\t\"'`]+\\|\\(\"[^\"]*\"\\|'[^']*'\\|`[^`]*`\\)")
        (args ()) (pos 0)
        (count 0)
-       beg str value quotes)
+       beg str quotes)
     ;; Build a list of all the args until we have as many as we want.
     (while (and (or (null mth) (<= count mth))
                (string-match argpart string pos))
@@ -1390,7 +1947,7 @@ Argument 0 is the command name."
 ;;; Input processing stuff [line mode]
 ;;;
 
-(defun term-send-input () 
+(defun term-send-input ()
   "Send input to process.
 After the process output mark, sends all text from the process mark to
 point as input to the process.  Before the process output mark, calls value
@@ -1407,6 +1964,9 @@ of `term-input-filter-functions' is called on the input before sending it.
 The input is entered into the input history ring, if the value of variable
 `term-input-filter' returns non-nil when called on the input.
 
+If variable `term-eol-on-send' is non-nil, then point is moved to the
+end of line before sending the input.
+
 The values of `term-get-old-input', `term-input-filter-functions', and
 `term-input-filter' are chosen according to the command interpreter running
 in the buffer.  E.g.,
@@ -1415,14 +1975,14 @@ If the interpreter is the csh,
     term-get-old-input is the default: take the current line, discard any
         initial string matching regexp term-prompt-regexp.
     term-input-filter-functions monitors input for \"cd\", \"pushd\", and
-       \"popd\" commands. When it sees one, it cd's the buffer.
-    term-input-filter is the default: returns T if the input isn't all white
+       \"popd\" commands.  When it sees one, it cd's the buffer.
+    term-input-filter is the default: returns t if the input isn't all white
        space.
 
-If the term is Lucid Common Lisp, 
+If the term is Lucid Common Lisp,
     term-get-old-input snarfs the sexp ending at point.
     term-input-filter-functions does nothing.
-    term-input-filter returns NIL if the input matches input-filter-regexp,
+    term-input-filter returns nil if the input matches input-filter-regexp,
         which matches (1) all whitespace (2) :a, :c, etc.
 
 Similarly for Soar, Scheme, etc."
@@ -1432,14 +1992,10 @@ Similarly for Soar, Scheme, etc."
     (if (not proc) (error "Current buffer has no process")
       (let* ((pmark (process-mark proc))
             (pmark-val (marker-position pmark))
-            (intxt (if (>= (point) pmark-val)
-                       (progn (end-of-line)
-                              (let ((copy (buffer-substring pmark (point))))
-                                ;; Delete, because inferior should echo.
-                                (set-marker term-pending-delete-marker
-                                            pmark-val)
-                                (set-marker (process-mark proc) (point))
-                                copy))
+            (input-is-new (>= (point) pmark-val))
+            (intxt (if input-is-new
+                       (progn (if term-eol-on-send (end-of-line))
+                              (buffer-substring pmark (point)))
                      (funcall term-get-old-input)))
             (input (if (not (eq term-input-autoexpand 'input))
                        ;; Just whatever's already there
@@ -1473,11 +2029,19 @@ Similarly for Soar, Scheme, etc."
            (funcall (car functions) (concat input "\n"))
            (setq functions (cdr functions))))
        (setq term-input-ring-index nil)
-       (goto-char pmark)
+
        ;; Update the markers before we send the input
        ;; in case we get output amidst sending the input.
        (set-marker term-last-input-start pmark)
        (set-marker term-last-input-end (point))
+       (if input-is-new
+           (progn
+             ;; Set up to delete, because inferior should echo.
+             (if (marker-buffer term-pending-delete-marker)
+                 (delete-region term-pending-delete-marker pmark))
+             (set-marker term-pending-delete-marker pmark-val)
+             (set-marker (process-mark proc) (point))))
+       (goto-char pmark)
        (funcall term-input-sender proc input)))))
 
 (defun term-get-old-input-default ()
@@ -1503,7 +2067,7 @@ Calls `term-get-old-input' to get old input."
       (insert input))))
 
 (defun term-skip-prompt ()
-  "Skip past the text matching regexp term-prompt-regexp. 
+  "Skip past the text matching regexp term-prompt-regexp.
 If this takes us past the end of the current line, don't skip at all."
   (let ((eol (save-excursion (end-of-line) (point))))
     (if (and (looking-at term-prompt-regexp)
@@ -1514,8 +2078,8 @@ If this takes us past the end of the current line, don't skip at all."
 (defun term-after-pmark-p ()
   "Is point after the process output marker?"
   ;; Since output could come into the buffer after we looked at the point
-  ;; but before we looked at the process marker's value, we explicitly 
-  ;; serialise. This is just because I don't know whether or not emacs
+  ;; but before we looked at the process marker's value, we explicitly
+  ;; serialise.  This is just because I don't know whether or not Emacs
   ;; services input during execution of lisp commands.
   (let ((proc-pos (marker-position
                   (process-mark (get-buffer-process (current-buffer))))))
@@ -1523,14 +2087,14 @@ If this takes us past the end of the current line, don't skip at all."
 
 (defun term-simple-send (proc string)
   "Default function for sending to PROC input STRING.
-This just sends STRING plus a newline. To override this,
+This just sends STRING plus a newline.  To override this,
 set the hook TERM-INPUT-SENDER."
   (term-send-string proc string)
   (term-send-string proc "\n"))
 
 (defun term-bol (arg)
   "Goes to the beginning of line, then skips past the prompt, if any.
-If a prefix argument is given (\\[universal-argument]), then no prompt skip 
+If a prefix argument is given (\\[universal-argument]), then no prompt skip
 -- go straight to column 0.
 
 The prompt skip is done by skipping text matching the regular expression
@@ -1544,7 +2108,7 @@ term-prompt-regexp, a buffer local variable."
 ;;; Just enter m-x term-send-invisible and type in your line.
 
 (defun term-read-noecho (prompt &optional stars)
-  "Read a single line of text from user without echoing, and return it. 
+  "Read a single line of text from user without echoing, and return it.
 Prompt with argument PROMPT, a string.  Optional argument STARS causes
 input to be echoed with '*' characters on the prompt line.  Input ends with
 RET, LFD, or ESC.  DEL or C-h rubs out.  C-u kills line.  C-g aborts (if
@@ -1562,11 +2126,11 @@ applications."
     (while (not done)
       (if stars
           (message "%s%s" prompt (make-string (length ans) ?*))
-        (message prompt))
+        (message "%s" prompt))
       (setq c (read-char))
       (cond ((= c ?\C-g)
              ;; This function may get called from a process filter, where
-             ;; inhibit-quit is set.  In later versions of emacs read-char
+             ;; inhibit-quit is set.  In later versions of Emacs read-char
              ;; may clear quit-flag itself and return C-g.  That would make
              ;; it impossible to quit this loop in a simple way, so
              ;; re-enable it here (for backward-compatibility the check for
@@ -1593,8 +2157,8 @@ applications."
 
 (defun term-send-invisible (str &optional proc)
   "Read a string without echoing.
-Then send it to the process running in the current buffer. A new-line
-is additionally sent. String is not saved on term input history list.
+Then send it to the process running in the current buffer.  A new-line
+is additionally sent.  String is not saved on term input history list.
 Security bug: your string can still be temporarily recovered with
 \\[view-lossage]."
   (interactive "P") ; Defeat snooping via C-x esc
@@ -1618,8 +2182,8 @@ If your process is choking on big inputs, try lowering the value.")
 (defun term-send-string (proc str)
   "Send PROCESS the contents of STRING as input.
 This is equivalent to process-send-string, except that long input strings
-are broken up into chunks of size term-input-chunk-size. Processes
-are given a chance to output between chunks. This can help prevent processes
+are broken up into chunks of size term-input-chunk-size.  Processes
+are given a chance to output between chunks.  This can help prevent processes
 from hanging when you send them long inputs on some OS's."
   (let* ((len (length str))
         (i (min len term-input-chunk-size)))
@@ -1633,7 +2197,7 @@ from hanging when you send them long inputs on some OS's."
 (defun term-send-region (proc start end)
   "Sends to PROC the region delimited by START and END.
 This is a replacement for process-send-region that tries to keep
-your process from hanging on long inputs. See term-send-string."
+your process from hanging on long inputs.  See term-send-string."
   (term-send-string proc (buffer-substring start end)))
 
 \f
@@ -1644,7 +2208,7 @@ your process from hanging on long inputs. See term-send-string."
   (interactive)
   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
     (kill-region term-last-input-end pmark)
-    (goto-char pmark)    
+    (goto-char pmark)
     (insert "*** output flushed ***\n")
     (set-marker pmark (point))))
 
@@ -1676,8 +2240,8 @@ Sets mark to the value of point when this command is run."
 (defun term-stop-subjob ()
   "Stop the current subjob.
 WARNING: if there is no current subjob, you can end up suspending
-the top-level process running in the buffer. If you accidentally do
-this, use \\[term-continue-subjob] to resume the process. (This
+the top-level process running in the buffer.  If you accidentally do
+this, use \\[term-continue-subjob] to resume the process.  (This
 is not a problem with most shells, since they ignore this signal.)"
   (interactive)
   (stop-process nil term-ptyp))
@@ -1697,7 +2261,8 @@ Useful if you accidentally suspend the top-level process."
        (kill-region pmark (point)))))
 
 (defun term-delchar-or-maybe-eof (arg)
-  "Delete ARG characters forward, or send an EOF to process if at end of buffer."
+  "Delete ARG characters forward, or send an EOF to process if at end of
+buffer."
   (interactive "p")
   (if (eobp)
       (process-send-eof)
@@ -1752,8 +2317,8 @@ See `term-prompt-regexp'."
 ;;;============================================================================
 ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
 ;;; commands that process files of source text (e.g. loading or compiling
-;;; files). So the corresponding process-in-a-buffer modes have commands
-;;; for doing this (e.g., lisp-load-file). The functions below are useful
+;;; files).  So the corresponding process-in-a-buffer modes have commands
+;;; for doing this (e.g., lisp-load-file).  The functions below are useful
 ;;; for defining these commands.
 ;;;
 ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
@@ -1761,9 +2326,9 @@ See `term-prompt-regexp'."
 ;;; So the compile/load interface gets the wrong default occasionally.
 ;;; The load-file/compile-file default mechanism could be smarter -- it
 ;;; doesn't know about the relationship between filename extensions and
-;;; whether the file is source or executable. If you compile foo.lisp
+;;; whether the file is source or executable.  If you compile foo.lisp
 ;;; with compile-file, then the next load-file should use foo.bin for
-;;; the default, not foo.lisp. This is tricky to do right, particularly
+;;; the default, not foo.lisp.  This is tricky to do right, particularly
 ;;; because the extension for executable files varies so much (.o, .bin,
 ;;; .lbin, .mo, .vo, .ao, ...).
 
@@ -1781,33 +2346,33 @@ See `term-prompt-regexp'."
 ;;; (TERM-SOURCE-DEFAULT previous-dir/file source-modes)
 ;;;============================================================================
 ;;; This function computes the defaults for the load-file and compile-file
-;;; commands for tea, soar, cmulisp, and cmuscheme modes. 
-;;; 
-;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last 
-;;; source-file processing command. NIL if there hasn't been one yet.
+;;; commands for tea, soar, cmulisp, and cmuscheme modes.
+;;;
+;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last
+;;; source-file processing command, or nil if there hasn't been one yet.
 ;;; - SOURCE-MODES is a list used to determine what buffers contain source
 ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
 ;;; Typically, (lisp-mode) or (scheme-mode).
-;;; 
+;;;
 ;;; If the command is given while the cursor is inside a string, *and*
 ;;; the string is an existing filename, *and* the filename is not a directory,
-;;; then the string is taken as default. This allows you to just position
+;;; then the string is taken as default.  This allows you to just position
 ;;; your cursor over a string that's a filename and have it taken as default.
 ;;;
 ;;; If the command is given in a file buffer whose major mode is in
-;;; SOURCE-MODES, then the the filename is the default file, and the
+;;; SOURCE-MODES, then the filename is the default file, and the
 ;;; file's directory is the default directory.
-;;; 
+;;;
 ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
 ;;; then the default directory & file are what was used in the last source-file
 ;;; processing command (i.e., PREVIOUS-DIR/FILE).  If this is the first time
 ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
-;;; is the cwd, with no default file. (\"no default file\" = nil)
-;;; 
+;;; is the cwd, with no default file.  (\"no default file\" = nil)
+;;;
 ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
 ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
 ;;; for Soar programs, etc.
-;;; 
+;;;
 ;;; The function returns a pair: (default-directory . default-file).
 
 (defun term-source-default (previous-dir/file source-modes)
@@ -1846,29 +2411,29 @@ See `term-prompt-regexp'."
 ;;; commands that process source files (like loading or compiling a file).
 ;;; It prompts for the filename, provides a default, if there is one,
 ;;; and returns the result filename.
-;;; 
+;;;
 ;;; See TERM-SOURCE-DEFAULT for more on determining defaults.
-;;; 
-;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
+;;;
+;;; PROMPT is the prompt string.  PREV-DIR/FILE is the (directory . file) pair
 ;;; from the last source processing command.  SOURCE-MODES is a list of major
 ;;; modes used to determine what file buffers contain source files.  (These
-;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
+;;; two arguments are used for determining defaults).  If MUSTMATCH-P is true,
 ;;; then the filename reader will only accept a file that exists.
-;;; 
+;;;
 ;;; A typical use:
 ;;; (interactive (term-get-source "Compile file: " prev-lisp-dir/file
 ;;;                                 '(lisp-mode) t))
 
-;;; This is pretty stupid about strings. It decides we're in a string
+;;; This is pretty stupid about strings.  It decides we're in a string
 ;;; if there's a quote on both sides of point on the current line.
 (defun term-extract-string ()
-  "Returns string around POINT that starts the current line or nil." 
+  "Returns string around POINT that starts the current line or nil."
   (save-excursion
     (let* ((point (point))
           (bol (progn (beginning-of-line) (point)))
           (eol (progn (end-of-line) (point)))
-          (start (progn (goto-char point) 
-                        (and (search-backward "\"" bol t) 
+          (start (progn (goto-char point)
+                        (and (search-backward "\"" bol t)
                              (1+ (point)))))
           (end (progn (goto-char point)
                       (and (search-forward "\"" eol t)
@@ -1896,11 +2461,11 @@ See `term-prompt-regexp'."
                              mustmatch-p)))
     (list (expand-file-name (substitute-in-file-name ans)))))
 
-;;; I am somewhat divided on this string-default feature. It seems
+;;; I am somewhat divided on this string-default feature.  It seems
 ;;; to violate the principle-of-least-astonishment, in that it makes
 ;;; the default harder to predict, so you actually have to look and see
-;;; what the default really is before choosing it. This can trip you up.
-;;; On the other hand, it can be useful, I guess. I would appreciate feedback
+;;; what the default really is before choosing it.  This can trip you up.
+;;; On the other hand, it can be useful, I guess.  I would appreciate feedback
 ;;; on this.
 ;;;     -Olin
 
@@ -1908,17 +2473,17 @@ See `term-prompt-regexp'."
 ;;; Simple process query facility.
 ;;; ===========================================================================
 ;;; This function is for commands that want to send a query to the process
-;;; and show the response to the user. For example, a command to get the
+;;; and show the response to the user.  For example, a command to get the
 ;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
 ;;; to an inferior Common Lisp process.
-;;; 
+;;;
 ;;; This simple facility just sends strings to the inferior process and pops
 ;;; up a window for the process buffer so you can see what the process
 ;;; responds with.  We don't do anything fancy like try to intercept what the
 ;;; process responds with and put it in a pop-up window or on the message
-;;; line. We just display the buffer. Low tech. Simple. Works good.
+;;; line.  We just display the buffer.  Low tech.  Simple.  Works good.
 
-;;; Send to the inferior process PROC the string STR. Pop-up but do not select
+;;; Send to the inferior process PROC the string STR.  Pop-up but do not select
 ;;; a window for the inferior process so that its response can be seen.
 (defun term-proc-query (proc str)
   (let* ((proc-buf (process-buffer proc))
@@ -1930,8 +2495,8 @@ See `term-prompt-regexp'."
       (term-send-string proc str) ; send the query
       (accept-process-output proc)  ; wait for some output
       ;; Try to position the proc window so you can see the answer.
-      ;; This is bogus code. If you delete the (sit-for 0), it breaks.
-      ;; I don't know why. Wizards invited to improve it.
+      ;; This is bogus code.  If you delete the (sit-for 0), it breaks.
+      ;; I don't know why.  Wizards invited to improve it.
       (if (not (pos-visible-in-window-p proc-pt proc-win))
          (let ((opoint (window-point proc-win)))
            (set-window-point proc-win proc-mark) (sit-for 0)
@@ -1945,14 +2510,14 @@ See `term-prompt-regexp'."
 (defun term-horizontal-column ()
   (- (term-current-column) (term-start-line-column)))
 
-;; Calls either vertical-motion or buffer-vertical-motion
+;; Calls either vertical-motion or term-buffer-vertical-motion
 (defmacro term-vertical-motion (count)
   (list 'funcall 'term-vertical-motion count))
 
 ;; An emulation of vertical-motion that is independent of having a window.
 ;; Instead, it uses the term-width variable as the logical window width.
 
-(defun buffer-vertical-motion (count)
+(defun term-buffer-vertical-motion (count)
   (cond ((= count 0)
         (move-to-column (* term-width (/ (current-column) term-width)))
         0)
@@ -1960,7 +2525,7 @@ See `term-prompt-regexp'."
         (let ((H)
               (todo (+ count (/ (current-column) term-width))))
           (end-of-line)
-          ;; The loop interates over buffer lines;
+          ;; The loop iterates over buffer lines;
           ;; H is the number of screen lines in the current line, i.e.
           ;; the ceiling of dividing the buffer line width by term-width.
           (while (and (<= (setq H (max (/ (+ (current-column) term-width -1)
@@ -1985,7 +2550,7 @@ See `term-prompt-regexp'."
                       (progn (beginning-of-line)
                              (not (bobp))))
             (setq todo (- todo H))
-            (backward-char)) ;; Move to end of previos line
+            (backward-char)) ;; Move to end of previous line.
           (if (and (>= todo H) (> todo 0))
               (+ count todo (- 1 H)) ;; Hit beginning of buffer.
             (move-to-column (* (- H todo 1) term-width))
@@ -2005,11 +2570,20 @@ See `term-prompt-regexp'."
   (cond (term-current-column)
        ((setq term-current-column (current-column)))))
 
-;;; Move DELTA column right (or left if delta < 0).
+;;; Move DELTA column right (or left if delta < 0 limiting at column 0).
 
 (defun term-move-columns (delta)
-  (setq term-current-column (+ (term-current-column) delta))
-  (move-to-column term-current-column t))
+  (setq term-current-column (max 0 (+ (term-current-column) delta)))
+  (let (point-at-eol)
+    (save-excursion
+      (end-of-line)
+      (setq point-at-eol (point)))
+    (move-to-column term-current-column t)
+    ;; If move-to-column extends the current line it will use the face
+    ;; from the last character on the line, set the face for the chars
+    ;; to default.
+    (when (> (point) point-at-eol)
+      (put-text-property point-at-eol (point) 'face 'default))))
 
 ;; Insert COUNT copies of CHAR in the default face.
 (defun term-insert-char (char count)
@@ -2026,8 +2600,9 @@ See `term-prompt-regexp'."
                   (- (term-vertical-motion -9999))))))))
 
 (defun term-adjust-current-row-cache (delta)
-  (if term-current-row
-      (setq term-current-row (+ term-current-row delta))))
+  (when term-current-row
+    (setq term-current-row 
+         (max 0 (+ term-current-row delta)))))
 
 (defun term-terminal-pos ()
   (save-excursion ;    save-restriction
@@ -2038,254 +2613,583 @@ See `term-prompt-regexp'."
       (setq y (term-vertical-motion term-height))
       (cons x y))))
 
+;;;Function that handles term messages: code by rms ( and you can see the
+;;;difference ;-) -mm
+
+(defun term-handle-ansi-terminal-messages (message)
+  ;; Is there a command here?
+  (while (string-match "\eAnSiT.+\n" message)
+    ;; Extract the command code and the argument.
+    (let* ((start (match-beginning 0))
+          (end (match-end 0))
+          (command-code (aref message (+ start 6)))
+          (argument
+           (save-match-data
+             (substring message
+                        (+ start 8)
+                        (string-match "\r?\n" message
+                                      (+ start 8)))))
+          ignore)
+      ;; Delete this command from MESSAGE.
+      (setq message (replace-match "" t t message))
+
+      ;; If we recognize the type of command, set the appropriate variable.
+      (cond ((= command-code ?c)
+            (setq term-ansi-at-dir argument))
+           ((= command-code ?h)
+            (setq term-ansi-at-host argument))
+           ((= command-code ?u)
+            (setq term-ansi-at-user argument))
+           ;; Otherwise ignore this one.
+           (t
+            (setq ignore t)))
+
+      ;; Update default-directory based on the changes this command made.
+      (if ignore
+         nil
+       (setq default-directory
+             (file-name-as-directory
+              (if (and (string= term-ansi-at-host (system-name))
+                                       (string= term-ansi-at-user (user-real-login-name)))
+                  (expand-file-name term-ansi-at-dir)
+                (if (string= term-ansi-at-user (user-real-login-name))
+                    (concat "/" term-ansi-at-host ":" term-ansi-at-dir)
+                  (concat "/" term-ansi-at-user "@" term-ansi-at-host ":"
+                          term-ansi-at-dir)))))
+
+       ;; I'm not sure this is necessary,
+       ;; but it's best to be on the safe side.
+       (if (string= term-ansi-at-host (system-name))
+           (progn
+             (setq ange-ftp-default-user term-ansi-at-save-user)
+             (setq ange-ftp-default-password term-ansi-at-save-pwd)
+             (setq ange-ftp-generate-anonymous-password term-ansi-at-save-anon))
+         (setq term-ansi-at-save-user ange-ftp-default-user)
+         (setq term-ansi-at-save-pwd ange-ftp-default-password)
+         (setq term-ansi-at-save-anon ange-ftp-generate-anonymous-password)
+         (setq ange-ftp-default-user nil)
+         (setq ange-ftp-default-password nil)
+         (setq ange-ftp-generate-anonymous-password nil)))))
+  message)
+
+
 ;;; Terminal emulation
 ;;; This is the standard process filter for term buffers.
 ;;; It emulates (most of the features of) a VT100/ANSI-style terminal.
 
 (defun term-emulate-terminal (proc str)
-  (let* ((previous-buffer (current-buffer))
-        (i 0) char funny count save-point save-marker old-point temp win
-        (selected (selected-window))
-        (str-length (length str)))
-    (unwind-protect
-       (progn
-         (set-buffer (process-buffer proc))
-
-         (if (marker-buffer term-pending-delete-marker)
-             (progn
-               ;; Delete text following term-pending-delete-marker.
-               (delete-region term-pending-delete-marker (process-mark proc))
-               (set-marker term-pending-delete-marker nil)))
-
-         (if (eq (window-buffer) (current-buffer))
-             (progn
-               (setq term-vertical-motion (symbol-function 'vertical-motion))
-               (term-check-size proc))
-           (setq term-vertical-motion
-                 (symbol-function 'buffer-vertical-motion)))
-
-         (setq save-marker (copy-marker (process-mark proc)))
-
-         (if (/= (point) (process-mark proc))
-             (progn (setq save-point (point-marker))
-                    (goto-char (process-mark proc))))
-
-         (save-restriction
-           ;; If the buffer is in line mode, and there is a partial
-           ;; input line, save the line (by narrowing to leave it
-           ;; outside the restriction ) until we're done with output.
-           (if (and (> (point-max) (process-mark proc))
-                    (term-in-line-mode))
-               (narrow-to-region (point-min) (process-mark proc)))
-           
-           (if term-log-buffer
-               (princ str term-log-buffer))
-           (cond ((eq term-terminal-state 4) ;; Have saved pending output.
-                  (setq str (concat term-terminal-parameter str))
-                  (setq term-terminal-parameter nil)
-                  (setq str-length (length str))
-                  (setq term-terminal-state 0)))
-           
-           (while (< i str-length)
-             (setq char (aref str i))
-             (cond ((< term-terminal-state 2)
-                    ;; Look for prefix of regular chars
-                    (setq funny
-                          (string-match "[\r\n\000\007\033\t\b\032\016\017]"
-                                        str i))
-                    (if (not funny) (setq funny str-length))
-                    (cond ((> funny i)
-                           (cond ((eq term-terminal-state 1)
-                                  (term-move-columns 1)
-                                  (setq term-terminal-state 0)))
-                           (setq count (- funny i))
-                           (setq temp (- (+ (term-horizontal-column) count)
-                                         term-width))
-                           (cond ((<= temp 0)) ;; All count chars fit in line.
-                                 ((> count temp) ;; Some chars fit.
-                                  ;; This iteration, handle only what fits.
-                                  (setq count (- count temp))
-                                  (setq funny (+ count i)))
-                                 ((>  (term-handle-scroll 1) 0)
-                                  (setq count (min count term-width))
-                                  (setq funny (+ count i))
-                                  (term-adjust-current-row-cache 1)
-                                  (setq term-start-line-column
-                                        term-current-column))
-                                 (t ;; Doing PAGER processing.
-                                  (setq count 0 funny i)
-                                  (setq term-current-column nil)
-                                  (setq term-start-line-column nil)))
-                           (if term-insert-mode
-                               ;; Inserting spaces, then deleting them, then
-                               ;; inserting the actual text seems clumsy, but
-                               ;; it is simple, and the overhead is miniscule.
-                               (term-insert-spaces count))
-                           (setq old-point (point))
-                           (term-move-columns count)
-                           (delete-region old-point (point))
-                           (insert (substring str i funny))
-                           (put-text-property old-point (point)
-                                              'face term-current-face)
-                           ;; If the last char was written in last column,
-                           ;; back up one column, but remember we did so.
-                           ;; Thus we emulate xterm/vt100-style line-wrapping.
-                           (cond ((eq temp 0)
-                                  (term-move-columns -1)
-                                  (setq term-terminal-state 1)))
-                           (setq i (1- funny)))
-                          ((and (setq term-terminal-state 0)
-                           (eq char ?\^I)) ; TAB
-                           ;; FIXME:  Does not handle line wrap!
-                           (setq count (term-current-column))
-                           (setq count (+ count 8 (- (mod count 8))))
-                           (if (< (move-to-column count nil) count)
-                               (term-insert-char char 1))
-                           (setq term-current-column count)
-                           (setq term-start-line-column nil))
-                          ((eq char ?\b)
-                           (term-move-columns -1))
-                          ((eq char ?\r)
-                           (term-vertical-motion 0)
-                           (setq term-current-column nil))
-                          ((eq char ?\n)
-                           (if (not (and term-kill-echo-list
-                                         (term-check-kill-echo-list)))
-                               (term-down 1 0 t)))
-                          ((eq char ?\033) ; Escape
-                           (setq term-terminal-state 2))
-                          ((eq char 0)) ; NUL: Do nothing
-                          ((eq char ?\016)) ; Shift Out - ignored
-                          ((eq char ?\017)) ; Shift In - ignored
-                          ((eq char ?\^G)
-                           (beep t)) ; Bell
-                          ((eq char ?\032)
-                           (let ((end (string-match "\n" str i)))
-                             (if end
-                                 (progn (funcall term-command-hook
-                                                 (substring str (1+ i) (1- end)))
-                                        (setq i end))
-                               (setq term-terminal-parameter
-                                     (substring str i))
-                               (setq term-terminal-state 4)
-                               (setq i str-length))))
-                          (t ; insert char FIXME: Should never happen
-                           (term-move-columns 1)
-                           (backward-delete-char 1)
-                           (insert char))))
-                   ((eq term-terminal-state 2) ; Seen Esc
-                    (cond ((eq char ?\133) ;; ?\133 = ?[
-                           (make-local-variable 'term-terminal-parameter)
-                           (make-local-variable 'term-terminal-previous-parameter)
-                           (setq term-terminal-parameter 0)
-                           (setq term-terminal-previous-parameter 0)
-                           (setq term-terminal-state 3))
-                          ((eq char ?D) ;; scroll forward
-                           (term-down 1 0 t)
-                           (setq term-terminal-state 0))
-                          ((eq char ?M) ;; scroll reversed
-                           (term-insert-lines 1)
-                           (setq term-terminal-state 0))
-                          ((eq char ?7) ;; Save cursor
-                           (setq term-saved-cursor
-                                 (cons (term-current-row)
-                                       (term-horizontal-column)))
-                           (setq term-terminal-state 0))
-                          ((eq char ?8) ;; Restore cursor
-                           (if term-saved-cursor
-                               (term-goto (car term-saved-cursor)
-                                          (cdr term-saved-cursor)))
-                           (setq term-terminal-state 0))
-                          ((setq term-terminal-state 0))))
-                   ((eq term-terminal-state 3) ; Seen Esc [
-                    (cond ((and (>= char ?0) (<= char ?9))
-                           (setq term-terminal-parameter
-                                 (+ (* 10 term-terminal-parameter) (- char ?0))))
-                          ((eq char ?\073 ) ; ?;
-                           (setq term-terminal-previous-parameter
-                                 term-terminal-parameter)
-                           (setq term-terminal-parameter 0))
-                          ((eq char ??)) ; Ignore ? 
-                          (t
-                           (term-handle-ansi-escape proc char)
-                           (setq term-terminal-state 0)))))
-             (if (term-handling-pager)
-                 ;; Finish stuff to get ready to handle PAGER.
-                 (progn
-                   (if (> (% (current-column) term-width) 0)
-                       (setq term-terminal-parameter
-                             (substring str i))
-                     ;; We're at column 0.  Goto end of buffer; to compensate,
-                     ;; prepend a ?\r for later.  This looks more consistent.
-                     (if (zerop i)
+  (with-current-buffer (process-buffer proc)
+    (let* ((i 0) char funny count save-point save-marker old-point temp win
+          (buffer-undo-list t)
+          (selected (selected-window))
+          last-win
+          (str-length (length str)))
+      (save-selected-window
+
+       ;; Let's handle the messages. -mm
+
+       (setq str (term-handle-ansi-terminal-messages str))
+       (setq str-length (length str))
+
+       (if (marker-buffer term-pending-delete-marker)
+           (progn
+             ;; Delete text following term-pending-delete-marker.
+             (delete-region term-pending-delete-marker (process-mark proc))
+             (set-marker term-pending-delete-marker nil)))
+
+       (if (eq (window-buffer) (current-buffer))
+           (progn
+             (setq term-vertical-motion (symbol-function 'vertical-motion))
+             (term-check-size proc))
+         (setq term-vertical-motion
+               (symbol-function 'term-buffer-vertical-motion)))
+
+       (setq save-marker (copy-marker (process-mark proc)))
+
+       (if (/= (point) (process-mark proc))
+           (progn (setq save-point (point-marker))
+                  (goto-char (process-mark proc))))
+
+       (save-restriction
+         ;; If the buffer is in line mode, and there is a partial
+         ;; input line, save the line (by narrowing to leave it
+         ;; outside the restriction ) until we're done with output.
+         (if (and (> (point-max) (process-mark proc))
+                  (term-in-line-mode))
+             (narrow-to-region (point-min) (process-mark proc)))
+
+         (if term-log-buffer
+             (princ str term-log-buffer))
+         (cond ((eq term-terminal-state 4) ;; Have saved pending output.
+                (setq str (concat term-terminal-parameter str))
+                (setq term-terminal-parameter nil)
+                (setq str-length (length str))
+                (setq term-terminal-state 0)))
+
+         (while (< i str-length)
+           (setq char (aref str i))
+           (cond ((< term-terminal-state 2)
+                  ;; Look for prefix of regular chars
+                  (setq funny
+                        (string-match "[\r\n\000\007\033\t\b\032\016\017]"
+                                      str i))
+                  (if (not funny) (setq funny str-length))
+                  (cond ((> funny i)
+                         (cond ((eq term-terminal-state 1)
+                                ;; We are in state 1, we need to wrap
+                                ;; around.  Go to the beginning of
+                                ;; the next line and switch to state
+                                ;; 0.
+                                (term-down 1)
+                                (term-move-columns (- (term-current-column)))
+                                (setq term-terminal-state 0)))
+                         (setq count (- funny i))
+                         (setq temp (- (+ (term-horizontal-column) count)
+                                       term-width))
+                         (cond ((<= temp 0)) ;; All count chars fit in line.
+                               ((> count temp) ;; Some chars fit.
+                                ;; This iteration, handle only what fits.
+                                (setq count (- count temp))
+                                (setq temp 0)
+                                (setq funny (+ count i)))
+                               ((or (not (or term-pager-count
+                                             term-scroll-with-delete))
+                                    (>  (term-handle-scroll 1) 0))
+                                (term-adjust-current-row-cache 1)
+                                (setq count (min count term-width))
+                                (setq funny (+ count i))
+                                (setq term-start-line-column
+                                      term-current-column))
+                               (t ;; Doing PAGER processing.
+                                (setq count 0 funny i)
+                                (setq term-current-column nil)
+                                (setq term-start-line-column nil)))
+                         (setq old-point (point))
+
+                         ;; Insert a string, check how many columns
+                         ;; we moved, then delete that many columns
+                         ;; following point if not eob nor insert-mode.
+                         (let ((old-column (current-column))
+                               columns pos)
+                           (insert (decode-coding-string (substring str i funny) locale-coding-system))
+                           (setq term-current-column (current-column)
+                                 columns (- term-current-column old-column))
+                           (when (not (or (eobp) term-insert-mode))
+                             (setq pos (point))
+                             (term-move-columns columns)
+                             (delete-region pos (point)))
+                           ;; In insert if the if the current line
+                           ;; has become too long it needs to be
+                           ;; chopped off.
+                           (when term-insert-mode 
+                             (setq pos (point))
+                             (end-of-line)
+                             (when (> (current-column) term-width)
+                               (delete-region (- (point) (- (current-column) term-width)) 
+                                              (point)))
+                             (goto-char pos)))
+                         (setq term-current-column nil)
+
+                         (put-text-property old-point (point)
+                                            'face term-current-face)
+                         ;; If the last char was written in last column,
+                         ;; back up one column, but remember we did so.
+                         ;; Thus we emulate xterm/vt100-style line-wrapping.
+                         (cond ((eq temp 0)
+                                (term-move-columns -1)
+                                (setq term-terminal-state 1)))
+                         (setq i (1- funny)))
+                        ((and (setq term-terminal-state 0)
+                              (eq char ?\^I)) ; TAB (terminfo: ht)
+                         (setq count (term-current-column))
+                         ;; The line cannot exceed term-width. TAB at
+                         ;; the end of a line should not cause wrapping.
+                         (setq count (min term-width 
+                                          (+ count 8 (- (mod count 8)))))
+                         (if (> term-width count)
+                           (progn
+                             (term-move-columns 
+                              (- count (term-current-column)))
+                             (setq term-current-column count))
+                           (when (> term-width (term-current-column))
+                             (term-move-columns 
+                              (1- (- term-width (term-current-column)))))
+                           (when (= term-width (term-current-column))
+                             (term-move-columns -1))))
+                        ((eq char ?\r)
+                         ;; Optimize CRLF at end of buffer:
+                         (cond ((and (< (setq temp (1+ i)) str-length)
+                                     (eq (aref str temp) ?\n)
+                                     (= (point) (point-max))
+                                     (not (or term-pager-count
+                                              term-kill-echo-list
+                                              term-scroll-with-delete)))
+                                (insert ?\n)
+                                (term-adjust-current-row-cache 1)
+                                (setq term-start-line-column 0)
+                                (setq term-current-column 0)
+                                (setq i temp))
+                               (t ;; Not followed by LF or can't optimize:
+                                (term-vertical-motion 0)
+                                (setq term-current-column term-start-line-column))))
+                        ((eq char ?\n)
+                         (if (not (and term-kill-echo-list
+                                       (term-check-kill-echo-list)))
+                             (term-down 1 t)))
+                        ((eq char ?\b)  ;; (terminfo: cub1)
+                         (term-move-columns -1))
+                        ((eq char ?\033) ; Escape
+                         (setq term-terminal-state 2))
+                        ((eq char 0))         ; NUL: Do nothing
+                        ((eq char ?\016))     ; Shift Out - ignored
+                        ((eq char ?\017))     ; Shift In - ignored
+                        ((eq char ?\^G)
+                         (beep t))     ; Bell
+                        ((eq char ?\032)
+                         (let ((end (string-match "\r?$" str i)))
+                           (if end
+                               (funcall term-command-hook
+                                        (prog1 (substring str (1+ i) end)
+                                          (setq i (match-end 0))))
+                             (setq term-terminal-parameter
+                                   (substring str i))
+                             (setq term-terminal-state 4)
+                             (setq i str-length))))
+                        (t   ; insert char FIXME: Should never happen
+                         (term-move-columns 1)
+                         (backward-delete-char 1)
+                         (insert char))))
+                 ((eq term-terminal-state 2)     ; Seen Esc
+                  (cond ((eq char ?\133)         ;; ?\133 = ?[
+
+;;; Some modifications to cope with multiple settings like ^[[01;32;43m -mm
+;;; Note that now the init value of term-terminal-previous-parameter has
+;;; been changed to -1
+
+                         (make-local-variable 'term-terminal-parameter)
+                         (make-local-variable 'term-terminal-previous-parameter)
+                         (make-local-variable 'term-terminal-previous-parameter-2)
+                         (make-local-variable 'term-terminal-previous-parameter-3)
+                         (make-local-variable 'term-terminal-previous-parameter-4)
+                         (make-local-variable 'term-terminal-more-parameters)
+                         (setq term-terminal-parameter 0)
+                         (setq term-terminal-previous-parameter -1)
+                         (setq term-terminal-previous-parameter-2 -1)
+                         (setq term-terminal-previous-parameter-3 -1)
+                         (setq term-terminal-previous-parameter-4 -1)
+                         (setq term-terminal-more-parameters 0)
+                         (setq term-terminal-state 3))
+                        ((eq char ?D) ;; scroll forward
+                         (term-handle-deferred-scroll)
+                         (term-down 1 t)
+                         (setq term-terminal-state 0))
+                        ;; ((eq char ?E) ;; (terminfo: nw), not used for
+                        ;;            ;; now, but this is a working
+                        ;;            ;; implementation
+                        ;;  (term-down 1)
+                        ;;  (term-goto term-current-row 0)
+                        ;;  (setq term-terminal-state 0))
+                        ((eq char ?M) ;; scroll reversed (terminfo: ri)
+                         (term-down -1)
+                         (setq term-terminal-state 0))
+                        ((eq char ?7) ;; Save cursor (terminfo: sc)
+                         (term-handle-deferred-scroll)
+                         (setq term-saved-cursor
+                               (cons (term-current-row)
+                                     (term-horizontal-column)))
+                         (setq term-terminal-state 0))
+                        ((eq char ?8) ;; Restore cursor (terminfo: rc)
+                         (if term-saved-cursor
+                             (term-goto (car term-saved-cursor)
+                                        (cdr term-saved-cursor)))
+                         (setq term-terminal-state 0))
+                        ((eq char ?c) ;; \Ec - Reset (terminfo: rs1) 
+                         ;; This is used by the "clear" program.
+                         (setq term-terminal-state 0)
+                         (term-reset-terminal))
+                        ;; The \E#8 reset sequence for xterm. We
+                        ;; probably don't need to handle it, but this
+                        ;; is the code to parse it.
+                        ;; ((eq char ?#)
+                        ;;  (when (eq (aref str (1+ i)) ?8)
+                        ;;    (setq i (1+ i))
+                        ;;    (setq term-terminal-state 0)))
+                        ((setq term-terminal-state 0))))
+                 ((eq term-terminal-state 3) ; Seen Esc [
+                  (cond ((and (>= char ?0) (<= char ?9))
                          (setq term-terminal-parameter
-                               (concat "\r" (substring str i)))
-                       (setq term-terminal-parameter (substring str (1- i)))
-                       (aset term-terminal-parameter 0 ?\r))
-                     (goto-char (point-max)))
-                   (setq term-terminal-state 4)
-                   (make-local-variable 'term-pager-old-filter)
-                   (setq term-pager-old-filter (process-filter proc))
-                   (set-process-filter proc term-pager-filter)
-                   (setq i str-length)))
-             (setq i (1+ i))))
-
-         (set-marker (process-mark proc) (point))
-         (if save-point
-             (progn (goto-char save-point)
-                    (set-marker save-point nil)))
-
-         ;; Check for a pending filename-and-line number to display.
-         ;; We do this before scrolling, because we might create a new window.
-         (if (and term-pending-frame
-                  (eq (window-buffer selected) (current-buffer)))
-             (progn (term-display-line (car term-pending-frame)
-                                       (cdr term-pending-frame))
-                    (setq term-pending-frame nil)
-                ;; We have created a new window, so check the window size.
-                    (term-check-size proc)))
-
-         ;; Scroll each window displaying the buffer but (by default)
-         ;; only if the point matches the process-mark we started with.
-         (setq win selected)
-         (while (progn
-                  (setq win (next-window win nil t))
-                  (if (eq (window-buffer win) (process-buffer proc))
-                      (let ((scroll term-scroll-to-bottom-on-output))
-                        (select-window win)
-                        (if (or (= (point) save-marker)
-                                (eq scroll t) (eq scroll 'all)
-                                ;; Maybe user wants point to jump to the end.
-                                (and (eq selected win)
-                                     (or (eq scroll 'this) (not save-point)))
-                                (and (eq scroll 'others)
-                                     (not (eq selected win))))
-                            (progn
-                              (goto-char term-home-marker)
-                              (recenter 0)
-                              (goto-char (process-mark proc))
-                              (if (not (pos-visible-in-window-p (point) win))
-                                  (recenter -1))))
-                        ;; Optionally scroll so that the text
-                        ;; ends at the bottom of the window.
-                        (if (and term-scroll-show-maximum-output
-                                 (>= (point) (process-mark proc)))
-                            (save-excursion
-                              (goto-char (point-max))
-                              (recenter -1)))))
-                  (not (eq win selected))))
-
-         (set-marker save-marker nil))
-      ;; unwind-protect cleanup-forms follow:
-      (set-buffer previous-buffer)
-      (select-window selected))))
+                               (+ (* 10 term-terminal-parameter) (- char ?0))))
+                        ((eq char ?\;)
+;;; Some modifications to cope with multiple settings like ^[[01;32;43m -mm
+                         (setq term-terminal-more-parameters 1)
+                         (setq term-terminal-previous-parameter-4
+                               term-terminal-previous-parameter-3)
+                         (setq term-terminal-previous-parameter-3
+                               term-terminal-previous-parameter-2)
+                         (setq term-terminal-previous-parameter-2
+                               term-terminal-previous-parameter)
+                         (setq term-terminal-previous-parameter
+                               term-terminal-parameter)
+                         (setq term-terminal-parameter 0))
+                        ((eq char ??)) ; Ignore ?
+                        (t
+                         (term-handle-ansi-escape proc char)
+                         (setq term-terminal-more-parameters 0)
+                         (setq term-terminal-previous-parameter-4 -1)
+                         (setq term-terminal-previous-parameter-3 -1)
+                         (setq term-terminal-previous-parameter-2 -1)
+                         (setq term-terminal-previous-parameter -1)
+                         (setq term-terminal-state 0)))))
+           (if (term-handling-pager)
+               ;; Finish stuff to get ready to handle PAGER.
+               (progn
+                 (if (> (% (current-column) term-width) 0)
+                     (setq term-terminal-parameter
+                           (substring str i))
+                   ;; We're at column 0.  Goto end of buffer; to compensate,
+                   ;; prepend a ?\r for later.  This looks more consistent.
+                   (if (zerop i)
+                       (setq term-terminal-parameter
+                             (concat "\r" (substring str i)))
+                     (setq term-terminal-parameter (substring str (1- i)))
+                     (aset term-terminal-parameter 0 ?\r))
+                   (goto-char (point-max)))
+                 (setq term-terminal-state 4)
+                 (make-local-variable 'term-pager-old-filter)
+                 (setq term-pager-old-filter (process-filter proc))
+                 (set-process-filter proc term-pager-filter)
+                 (setq i str-length)))
+           (setq i (1+ i))))
+
+       (if (>= (term-current-row) term-height)
+           (term-handle-deferred-scroll))
+
+       (set-marker (process-mark proc) (point))
+       (if save-point
+           (progn (goto-char save-point)
+                  (set-marker save-point nil)))
+
+       ;; Check for a pending filename-and-line number to display.
+       ;; We do this before scrolling, because we might create a new window.
+       (if (and term-pending-frame
+                (eq (window-buffer selected) (current-buffer)))
+           (progn (term-display-line (car term-pending-frame)
+                                     (cdr term-pending-frame))
+                  (setq term-pending-frame nil)
+                  ;; We have created a new window, so check the window size.
+                  (term-check-size proc)))
+
+       ;; Scroll each window displaying the buffer but (by default)
+       ;; only if the point matches the process-mark we started with.
+       (setq win selected)
+       ;; Avoid infinite loop in strange case where minibuffer window
+       ;; is selected but not active.
+       (while (window-minibuffer-p win)
+         (setq win (next-window win nil t)))
+       (setq last-win win)
+       (while (progn
+                (setq win (next-window win nil t))
+                (if (eq (window-buffer win) (process-buffer proc))
+                    (let ((scroll term-scroll-to-bottom-on-output))
+                      (select-window win)
+                      (if (or (= (point) save-marker)
+                              (eq scroll t) (eq scroll 'all)
+                              ;; Maybe user wants point to jump to the end.
+                              (and (eq selected win)
+                                   (or (eq scroll 'this) (not save-point)))
+                              (and (eq scroll 'others)
+                                   (not (eq selected win))))
+                          (progn
+                            (goto-char term-home-marker)
+                            (recenter 0)
+                            (goto-char (process-mark proc))
+                            (if (not (pos-visible-in-window-p (point) win))
+                                (recenter -1))))
+                      ;; Optionally scroll so that the text
+                      ;; ends at the bottom of the window.
+                      (if (and term-scroll-show-maximum-output
+                               (>= (point) (process-mark proc)))
+                          (save-excursion
+                            (goto-char (point-max))
+                            (recenter -1)))))
+                (not (eq win last-win))))
+
+;;; Stolen from comint.el and adapted -mm
+       (if (> term-buffer-maximum-size 0)
+           (save-excursion
+             (goto-char (process-mark (get-buffer-process (current-buffer))))
+             (forward-line (- term-buffer-maximum-size))
+             (beginning-of-line)
+             (delete-region (point-min) (point))))
+;;;
+
+       (set-marker save-marker nil)))))
+
+(defun term-handle-deferred-scroll ()
+  (let ((count (- (term-current-row) term-height)))
+    (if (>= count 0)
+       (save-excursion
+         (goto-char term-home-marker)
+         (term-vertical-motion (1+ count))
+         (set-marker term-home-marker (point))
+         (setq term-current-row (1- term-height))))))
+
+;;; Reset the terminal, delete all the content and set the face to the
+;;; default one. 
+(defun term-reset-terminal ()
+  (erase-buffer)
+  (setq term-current-row 0)
+  (setq term-current-column 1)
+  (setq term-insert-mode nil)
+  (setq term-current-face nil)
+  (setq term-ansi-current-underline nil)
+  (setq term-ansi-current-bold nil)
+  (setq term-ansi-current-reverse nil)
+  (setq term-ansi-current-color 0)
+  (setq term-ansi-current-invisible nil)
+  (setq term-ansi-face-already-done nil)
+  (setq term-ansi-current-bg-color 0))
+
+;;; New function to deal with ansi colorized output, as you can see you can
+;;; have any bold/underline/fg/bg/reverse combination. -mm
+
+(defun term-handle-colors-array (parameter)
+  (cond
+
+;;; Bold  (terminfo: bold)
+   ((eq parameter 1)
+    (setq term-ansi-current-bold t))
+
+;;; Underline
+   ((eq parameter 4)
+    (setq term-ansi-current-underline t))
+
+;;; Blink (unsupported by Emacs), will be translated to bold.
+;;; This may change in the future though.
+   ((eq parameter 5)
+    (setq term-ansi-current-bold t))
+
+;;; Reverse
+   ((eq parameter 7)
+    (setq term-ansi-current-reverse t))
+
+;;; Invisible
+   ((eq parameter 8)
+    (setq term-ansi-current-invisible t))
+
+;;; Reset underline (i.e. terminfo rmul)
+   ((eq parameter 24)
+    (setq term-ansi-current-underline nil))
+
+;;; Reset reverse (i.e. terminfo rmso)
+   ((eq parameter 27)
+    (setq term-ansi-current-reverse nil))
+
+;;; Foreground
+   ((and (>= parameter 30) (<= parameter 37))
+    (setq term-ansi-current-color (- parameter 29)))
+
+;;; Reset foreground
+   ((eq parameter 39)
+    (setq term-ansi-current-color 0))
+
+;;; Background
+   ((and (>= parameter 40) (<= parameter 47))
+    (setq term-ansi-current-bg-color (- parameter 39)))
+
+;;; Reset background
+   ((eq parameter 49)
+    (setq term-ansi-current-bg-color 0))
+
+;;; 0 (Reset) or unknown (reset anyway)
+   (t
+    (setq term-current-face nil)
+    (setq term-ansi-current-underline nil)
+    (setq term-ansi-current-bold nil)
+    (setq term-ansi-current-reverse nil)
+    (setq term-ansi-current-color 0)
+    (setq term-ansi-current-invisible nil)
+    (setq term-ansi-face-already-done t)
+    (setq term-ansi-current-bg-color 0)))
+
+;      (message "Debug: U-%d R-%d B-%d I-%d D-%d F-%d B-%d"
+;                 term-ansi-current-underline
+;                 term-ansi-current-reverse
+;                 term-ansi-current-bold
+;                 term-ansi-current-invisible
+;                 term-ansi-face-already-done
+;                 term-ansi-current-color
+;                 term-ansi-current-bg-color)
+
+
+  (unless term-ansi-face-already-done
+      (if term-ansi-current-reverse
+         (if term-ansi-current-invisible
+             (setq term-current-face
+                   (if (= term-ansi-current-color 0)
+                       (list :background
+                             term-default-fg-color
+                             :foreground
+                             term-default-fg-color)
+                     (list :background
+                           (elt ansi-term-color-vector term-ansi-current-color)
+                           :foreground
+                           (elt ansi-term-color-vector term-ansi-current-color)))
+                   ;; No need to bother with anything else if it's invisible
+                   )
+           (setq term-current-face
+                 (list :background
+                       (if (= term-ansi-current-color 0)
+                           (face-foreground 'default)
+                           (elt ansi-term-color-vector term-ansi-current-color))
+                       :foreground
+                       (if (= term-ansi-current-bg-color 0)
+                           (face-background 'default)
+                       (elt ansi-term-color-vector term-ansi-current-bg-color))))
+           (when term-ansi-current-bold
+               (setq term-current-face
+                     (append '(:weight bold) term-current-face)))
+           (when term-ansi-current-underline
+               (setq term-current-face
+                     (append '(:underline t) term-current-face))))
+       (if term-ansi-current-invisible
+           (setq term-current-face
+                 (if (= term-ansi-current-bg-color 0)
+                     (list :background
+                           term-default-bg-color
+                           :foreground
+                           term-default-bg-color)
+                   (list :foreground
+                         (elt ansi-term-color-vector term-ansi-current-bg-color)
+                         :background
+                         (elt ansi-term-color-vector term-ansi-current-bg-color)))
+                 ;; No need to bother with anything else if it's invisible
+                 )
+         (setq term-current-face
+               (list :foreground
+                     (elt ansi-term-color-vector term-ansi-current-color)
+                     :background
+                     (elt ansi-term-color-vector term-ansi-current-bg-color)))
+         (when term-ansi-current-bold
+             (setq term-current-face
+                   (append '(:weight bold) term-current-face)))
+         (when term-ansi-current-underline
+             (setq term-current-face
+                   (append '(:underline t) term-current-face))))))
+
+;;;    (message "Debug %S" term-current-face)
+  (setq term-ansi-face-already-done nil))
+
 
 ;;; Handle a character assuming (eq terminal-state 2) -
-;;; i.e. we have previousely seen Escape followed by ?[.
+;;; i.e. we have previously seen Escape followed by ?[.
 
 (defun term-handle-ansi-escape (proc char)
   (cond
-   ((eq char ?H) ; cursor motion
+   ((or (eq char ?H)  ; cursor motion (terminfo: cup)
+       ;; (eq char ?f) ; xterm seems to handle this sequence too, not
+       ;; needed for now
+       ) 
     (if (<= term-terminal-parameter 0)
        (setq term-terminal-parameter 1))
     (if (<= term-terminal-previous-parameter 0)
@@ -2297,25 +3201,30 @@ See `term-prompt-regexp'."
     (term-goto
      (1- term-terminal-previous-parameter)
      (1- term-terminal-parameter)))
-   ;; \E[A - cursor up
+   ;; \E[A - cursor up (terminfo: cuu, cuu1)
    ((eq char ?A)
-    (term-down (- (max 1 term-terminal-parameter)) 0 t))
-   ;; \E[B - cursor down
+    (term-handle-deferred-scroll)
+    (term-down (- (max 1 term-terminal-parameter)) t))
+   ;; \E[B - cursor down (terminfo: cud)
    ((eq char ?B)
-    (term-down (max 1 term-terminal-parameter) t))
-   ;; \E[C - cursor right
+    (term-down (max 1 term-terminal-parameter) t))
+   ;; \E[C - cursor right (terminfo: cuf)
    ((eq char ?C)
-    (term-move-columns (max 1 term-terminal-parameter)))
-   ;; \E[D - cursor left
+    (term-move-columns 
+     (max 1 
+         (if (>= (+ term-terminal-parameter (term-current-column)) term-width)
+             (- term-width (term-current-column)  1)
+           term-terminal-parameter))))
+   ;; \E[D - cursor left (terminfo: cub)
    ((eq char ?D)
     (term-move-columns (- (max 1 term-terminal-parameter))))
-   ;; \E[J - clear to end of screen
+   ;; \E[J - clear to end of screen (terminfo: ed, clear)
    ((eq char ?J)
     (term-erase-in-display term-terminal-parameter))
-   ;; \E[K - clear to end of line
+   ;; \E[K - clear to end of line (terminfo: el, el1)
    ((eq char ?K)
     (term-erase-in-line term-terminal-parameter))
-   ;; \E[L - insert lines
+   ;; \E[L - insert lines (terminfo: il, il1)
    ((eq char ?L)
     (term-insert-lines (max 1 term-terminal-parameter)))
    ;; \E[M - delete lines
@@ -2325,37 +3234,46 @@ See `term-prompt-regexp'."
    ((eq char ?P)
     (term-delete-chars (max 1 term-terminal-parameter)))
    ;; \E[@ - insert spaces
-   ((eq char ?@)
+   ((eq char ?@) ;; (terminfo: ich)
     (term-insert-spaces (max 1 term-terminal-parameter)))
    ;; \E[?h - DEC Private Mode Set
    ((eq char ?h)
-    (cond ((eq term-terminal-parameter 4)
+    (cond ((eq term-terminal-parameter 4)  ;; (terminfo: smir)
           (setq term-insert-mode t))
-         ((eq term-terminal-parameter 47)
-          (term-switch-to-alternate-sub-buffer t))))
+         ;; ((eq term-terminal-parameter 47) ;; (terminfo: smcup)
+         ;; (term-switch-to-alternate-sub-buffer t))
+         ))
    ;; \E[?l - DEC Private Mode Reset
    ((eq char ?l)
-    (cond ((eq term-terminal-parameter 4)
+    (cond ((eq term-terminal-parameter 4)  ;; (terminfo: rmir)
           (setq term-insert-mode nil))
-         ((eq term-terminal-parameter 47)
-          (term-switch-to-alternate-sub-buffer nil))))
-   ;; \E[m - Set/reset standard mode
+         ;; ((eq term-terminal-parameter 47) ;; (terminfo: rmcup)
+         ;; (term-switch-to-alternate-sub-buffer nil))
+         ))
+
+;;; Modified to allow ansi coloring -mm
+   ;; \E[m - Set/reset modes, set bg/fg 
+   ;;(terminfo: smso,rmso,smul,rmul,rev,bold,sgr0,invis,op,setab,setaf)
    ((eq char ?m)
-    (cond ((eq term-terminal-parameter 7)
-          (setq term-current-face 'highlight))
-         ((eq term-terminal-parameter 4)
-          (setq term-current-face 'term-underline-face))
-         ((eq term-terminal-parameter 1)
-          (setq term-current-face 'bold))
-         (t (setq term-current-face 'default))))
+    (when (= term-terminal-more-parameters 1)
+      (if (>= term-terminal-previous-parameter-4 0)
+         (term-handle-colors-array term-terminal-previous-parameter-4))
+      (if (>= term-terminal-previous-parameter-3 0)
+         (term-handle-colors-array term-terminal-previous-parameter-3))
+      (if (>= term-terminal-previous-parameter-2 0)
+         (term-handle-colors-array term-terminal-previous-parameter-2))
+      (term-handle-colors-array term-terminal-previous-parameter))
+    (term-handle-colors-array term-terminal-parameter))
+
    ;; \E[6n - Report cursor position
    ((eq char ?n)
+    (term-handle-deferred-scroll)
     (process-send-string proc
                         (format "\e[%s;%sR"
                                 (1+ (term-current-row))
                                 (1+ (term-horizontal-column)))))
    ;; \E[r - Set scrolling region
-   ((eq char ?r)
+   ((eq char ?r) ;; (terminfo: csr)
     (term-scroll-region
      (1- term-terminal-previous-parameter)
      term-terminal-parameter))
@@ -2364,7 +3282,7 @@ See `term-prompt-regexp'."
 (defun term-scroll-region (top bottom)
   "Set scrolling region.
 TOP is the top-most line (inclusive) of the new scrolling region,
-while BOTTOM is the line folling the new scrolling region (e.g. exclusive).
+while BOTTOM is the line following the new scrolling region (e.g. exclusive).
 The top-most line is line 0."
   (setq term-scroll-start
        (if (or (< top 0) (>= top term-height))
@@ -2377,38 +3295,44 @@ The top-most line is line 0."
   (setq term-scroll-with-delete
        (or (term-using-alternate-sub-buffer)
            (not (and (= term-scroll-start 0)
-                     (= term-scroll-end term-height))))))
-
-(defun term-switch-to-alternate-sub-buffer (set)
-  ;; If asked to switch to (from) the alternate sub-buffer, and already (not)
-  ;; using it, do nothing.  This test is needed for some programs (including
-  ;; emacs) that emit the ti termcap string twice, for unknown reason.
-  (if (eq set (not (term-using-alternate-sub-buffer)))
-      (let ((row (term-current-row))
-           (col (term-horizontal-column)))
-       (cond (set
-              (goto-char (point-max))
-              (if (not (eq (preceding-char) ?\n))
-                  (term-insert-char ?\n 1))
-              (setq term-scroll-with-delete t)
-              (setq term-saved-home-marker (copy-marker term-home-marker))
-              (set-marker term-home-marker (point)))
-             (t
-              (setq term-scroll-with-delete
-                    (not (and (= term-scroll-start 0)
-                              (= term-scroll-end term-height))))
-              (set-marker term-home-marker term-saved-home-marker)
-              (set-marker term-saved-home-marker nil)
-              (setq term-saved-home-marker nil)
-              (goto-char term-home-marker)))
-       (setq term-current-column nil)
-       (setq term-current-row 0)
-       (term-goto row col))))
+                     (= term-scroll-end term-height)))))
+  (term-move-columns (- (term-current-column)))
+  (term-goto 
+   term-scroll-start (term-current-column)))
+
+;; (defun term-switch-to-alternate-sub-buffer (set)
+;;   ;; If asked to switch to (from) the alternate sub-buffer, and already (not)
+;;   ;; using it, do nothing.  This test is needed for some programs (including
+;;   ;; Emacs) that emit the ti termcap string twice, for unknown reason.
+;;   (term-handle-deferred-scroll)
+;;   (if (eq set (not (term-using-alternate-sub-buffer)))
+;;       (let ((row (term-current-row))
+;;         (col (term-horizontal-column)))
+;;     (cond (set
+;;            (goto-char (point-max))
+;;            (if (not (eq (preceding-char) ?\n))
+;;                (term-insert-char ?\n 1))
+;;            (setq term-scroll-with-delete t)
+;;            (setq term-saved-home-marker (copy-marker term-home-marker))
+;;            (set-marker term-home-marker (point)))
+;;           (t
+;;            (setq term-scroll-with-delete
+;;                  (not (and (= term-scroll-start 0)
+;;                            (= term-scroll-end term-height))))
+;;            (set-marker term-home-marker term-saved-home-marker)
+;;            (set-marker term-saved-home-marker nil)
+;;            (setq term-saved-home-marker nil)
+;;            (goto-char term-home-marker)))
+;;     (setq term-current-column nil)
+;;     (setq term-current-row 0)
+;;     (term-goto row col))))
 
 ;; Default value for the symbol term-command-hook.
 
 (defun term-command-hook (string)
-  (cond ((= (aref string 0) ?\032)
+  (cond ((equal string "")
+        t)
+       ((= (aref string 0) ?\032)
         ;; gdb (when invoked with -fullname) prints:
         ;; \032\032FULLFILENAME:LINENUMBER:CHARPOS:BEG_OR_MIDDLE:PC\n
         (let* ((first-colon (string-match ":" string 1))
@@ -2420,7 +3344,7 @@ The top-most line is line 0."
           (setq term-pending-frame (cons filename fileline))))
        ((= (aref string 0) ?/)
         (cd (substring string 1)))
-       ;; Allowing the inferior to call functions in emacs is
+       ;; Allowing the inferior to call functions in Emacs is
        ;; probably too big a security hole.
        ;; ((= (aref string 0) ?!)
        ;; (eval (car (read-from-string string 1))))
@@ -2457,22 +3381,30 @@ The top-most line is line 0."
 ;;; "down" as needed so that is no more that a window-full above (point-max).
 
 (defun term-goto-home ()
+  (term-handle-deferred-scroll)
   (goto-char term-home-marker)
   (setq term-current-row 0)
   (setq term-current-column (current-column))
   (setq term-start-line-column term-current-column))
 
-;;; FIXME:  This can be optimized some.
 (defun term-goto (row col)
-  (term-goto-home)
-  (term-down row col))
+  (term-handle-deferred-scroll)
+  (cond ((and term-current-row (>= row term-current-row))
+        ;; I assume this is a worthwhile optimization.
+        (term-vertical-motion 0)
+        (setq term-current-column term-start-line-column)
+        (setq row (- row term-current-row)))
+       (t
+        (term-goto-home)))
+  (term-down row)
+  (term-move-columns col))
 
 ; The page is full, so enter "pager" mode, and wait for input.
 
 (defun term-process-pager ()
   (if (not term-pager-break-map)
       (let* ((map (make-keymap))
-           (i 0) tmp)
+            (i 0) tmp)
 ;      (while (< i 128)
 ;        (define-key map (make-string 1 i) 'term-send-raw)
 ;        (setq i (1+ i)))
@@ -2494,14 +3426,14 @@ The top-most line is line 0."
        (define-key map ">" 'term-pager-eob)
 
        ;; Add menu bar.
-       (term-if-emacs19
+       (progn
         (term-ifnot-xemacs
          (define-key map [menu-bar terminal] term-terminal-menu)
          (define-key map [menu-bar signals] term-signals-menu)
          (setq tmp (make-sparse-keymap "More pages?"))
          (define-key tmp [help] '("Help" . term-pager-help))
          (define-key tmp [disable]
-           '("Diable paging" . term-fake-pager-disable))
+           '("Disable paging" . term-fake-pager-disable))
          (define-key tmp [discard]
            '("Discard remaining output" . term-pager-discard))
          (define-key tmp [eob] '("Goto to end" . term-pager-eob))
@@ -2515,7 +3447,7 @@ The top-most line is line 0."
 
        (setq term-pager-break-map map)))
 ;  (let ((process (get-buffer-process (current-buffer))))
-;    (stop-process process))  
+;    (stop-process process))
   (setq term-pager-old-local-map (current-local-map))
   (use-local-map term-pager-break-map)
   (make-local-variable 'term-old-mode-line-format)
@@ -2525,7 +3457,7 @@ The top-most line is line 0."
              mode-line-buffer-identification
              " [Type ? for help] "
              "%-"))
-  (set-buffer-modified-p (buffer-modified-p))) ;;No-op, but updates mode line.
+  (force-mode-line-update))
 
 (defun term-pager-line (lines)
   (interactive "p")
@@ -2586,7 +3518,7 @@ The top-most line is line 0."
       (term-pager-continue nil)
     (setq term-pager-count nil))
   (term-update-mode-line))
-    
+
 ; Enable pager processing.
 (defun term-pager-enable ()
   (interactive)
@@ -2638,7 +3570,7 @@ all pending output has been dealt with."))
     (use-local-map term-pager-old-local-map)
     (setq term-pager-old-local-map nil)
     (setq mode-line-format term-old-mode-line-format)
-    (set-buffer-modified-p (buffer-modified-p)) ;; Updates mode line.
+    (force-mode-line-update)
     (setq term-pager-count new-count)
     (set-process-filter process term-pager-old-filter)
     (funcall term-pager-old-filter process "")
@@ -2661,6 +3593,8 @@ all pending output has been dealt with."))
                 (delete-region save-top (point))
                 (goto-char save-point)
                 (term-vertical-motion down)
+                (term-adjust-current-row-cache (- scroll-needed))
+                (setq term-current-column nil)
                 (term-insert-char ?\n scroll-needed))
                ((and (numberp term-pager-count)
                      (< (setq term-pager-count (- term-pager-count down))
@@ -2668,26 +3602,31 @@ all pending output has been dealt with."))
                 (setq down 0)
                 (term-process-pager))
                (t
+                (term-adjust-current-row-cache (- scroll-needed))
                 (term-vertical-motion scroll-needed)
                 (set-marker term-home-marker (point))))
          (goto-char save-point)
-         (set-marker save-point nil)
-         (setq term-current-column nil)
-         (setq term-current-row nil))))
+         (set-marker save-point nil))))
   down)
 
-(defun term-down (down right &optional check-for-scroll)
-  "Move down DOWN screen lines vertically, and RIGHT columns horizontally."
+(defun term-down (down &optional check-for-scroll)
+  "Move down DOWN screen lines vertically."
   (let ((start-column (term-horizontal-column)))
-    (if check-for-scroll
+    (if (and check-for-scroll (or term-scroll-with-delete term-pager-count))
        (setq down (term-handle-scroll down)))
     (term-adjust-current-row-cache down)
-    (setq down (- down (term-vertical-motion down)))
-    ; Extend buffer with extra blank lines if needed.
-    (if (> down 0) (term-insert-char ?\n down))
-    (setq term-current-column nil)
-    (setq term-start-line-column (current-column))
-    (move-to-column (+ term-start-line-column start-column right) t)))
+    (if (or (/= (point) (point-max)) (< down 0))
+       (setq down (- down (term-vertical-motion down))))
+    ;; Extend buffer with extra blank lines if needed.
+    (cond ((> down 0)
+          (term-insert-char ?\n down)
+          (setq term-current-column 0)
+          (setq term-start-line-column 0))
+         (t
+          (setq term-current-column nil)
+          (setq term-start-line-column (current-column))))
+    (if start-column
+       (term-move-columns start-column))))
 
 ;; Assuming point is at the beginning of a screen line,
 ;; if the line above point wraps around, add a ?\n to undo the wrapping.
@@ -2696,11 +3635,11 @@ all pending output has been dealt with."))
   (if (not (bolp)) (insert-before-markers ?\n)))
 
 (defun term-erase-in-line (kind)
-  (if (> kind 1) ;; erase left of point
+  (if (= kind 1) ;; erase left of point
       (let ((cols (term-horizontal-column)) (saved-point (point)))
        (term-vertical-motion 0)
        (delete-region (point) saved-point)
-       (term-insert-char ?\n cols)))
+       (term-insert-char ?  cols)))
   (if (not (eq kind 1)) ;; erase right of point
       (let ((saved-point (point))
            (wrapped (and (zerop (term-horizontal-column))
@@ -2710,9 +3649,9 @@ all pending output has been dealt with."))
        ;; wrapped is true if we're at the beginning of screen line,
        ;; but not a buffer line.  If we delete the current screen line
        ;; that will make the previous line no longer wrap, and (because
-       ;; of the way emacs display works) point will be at the end of
+       ;; of the way Emacs display works) point will be at the end of
        ;; the previous screen line rather then the beginning of the
-       ;; current one. To avoid that, we make sure that current line
+       ;; current one.  To avoid that, we make sure that current line
        ;; contain a space, to force the previous line to continue to wrap.
        ;; We could do this always, but it seems preferable to not add the
        ;; extra space when wrapped is false.
@@ -2727,6 +3666,7 @@ all pending output has been dealt with."))
 If KIND is 0, erase from (point) to (point-max);
 if KIND is 1, erase from home to point; else erase from home to point-max.
 Should only be called when point is at the start of a screen line."
+  (term-handle-deferred-scroll)
   (cond ((eq term-terminal-parameter 0)
         (delete-region (point) (point-max))
         (term-unwrap-line))
@@ -2736,8 +3676,8 @@ Should only be called when point is at the start of a screen line."
              (end-region (if (eq kind 1) (point) (point-max))))
           (delete-region start-region end-region)
           (term-unwrap-line)
-          (if (eq kind 1)
-              (term-insert-char ?\n row))
+          (when (eq kind 1)
+            (term-insert-char ?\n row))
           (setq term-current-column nil)
           (setq term-current-row nil)
           (term-goto row col)))))
@@ -2750,13 +3690,25 @@ Should only be called when point is at the start of a screen line."
     (move-to-column (+ (term-current-column) count) t)
     (delete-region save-point (point))))
 
+;;; Insert COUNT spaces after point, but do not change any of
+;;; following screen lines.  Hence we may have to delete characters
+;;; at teh end of this screen line to make room.
+
 (defun term-insert-spaces (count)
-  (let ((save-point (point)) (save-eol))
+  (let ((save-point (point)) (save-eol) (point-at-eol))
     (term-vertical-motion 1)
     (if (bolp)
        (backward-char))
     (setq save-eol (point))
+    (save-excursion
+      (end-of-line)
+      (setq point-at-eol (point)))
     (move-to-column (+ (term-start-line-column) (- term-width count)) t)
+    ;; If move-to-column extends the current line it will use the face
+    ;; from the last character on the line, set the face for the chars
+    ;; to default.
+    (when (> (point) (point-at-eol))
+      (put-text-property point-at-eol (point) 'face 'default))
     (if (> save-eol (point))
        (delete-region (point) save-eol))
     (goto-char save-point)
@@ -2768,9 +3720,9 @@ Should only be called when point is at the start of a screen line."
        (save-current-column term-current-column)
        (save-start-line-column term-start-line-column)
        (save-current-row (term-current-row)))
-    (term-down lines 0)
+    (term-down lines)
     (delete-region start (point))
-    (term-down (- term-scroll-end save-current-row lines) 0)
+    (term-down (- term-scroll-end save-current-row lines))
     (term-insert-char ?\n lines)
     (setq term-current-column save-current-column)
     (setq term-start-line-column save-start-line-column)
@@ -2783,9 +3735,9 @@ Should only be called when point is at the start of a screen line."
        (save-current-column term-current-column)
        (save-start-line-column term-start-line-column)
        (save-current-row (term-current-row)))
-    (term-down (- term-scroll-end save-current-row lines) 0)
+    (term-down (- term-scroll-end save-current-row lines))
     (setq start-deleted (point))
-    (term-down lines 0)
+    (term-down lines)
     (delete-region start-deleted (point))
     (goto-char start)
     (setq term-current-column save-current-column)
@@ -2794,7 +3746,7 @@ Should only be called when point is at the start of a screen line."
     (term-insert-char ?\n lines)
     (goto-char start)))
 \f
-(defun term-set-output-log (name)
+(defun term-start-output-log (name)
   "Record raw inferior process output in a buffer."
   (interactive (list (if term-log-buffer
                         nil
@@ -2816,10 +3768,10 @@ Should only be called when point is at the start of a screen line."
     (message "Recording terminal emulator output into buffer \"%s\""
             (buffer-name term-log-buffer))))
 
-(defun term-stop-photo ()
+(defun term-stop-output-log ()
   "Discontinue raw inferior process logging."
   (interactive)
-  (term-set-output-log nil))
+  (term-start-output-log nil))
 
 (defun term-show-maximum-output ()
   "Put the end of the buffer at the bottom of the window."
@@ -2832,7 +3784,7 @@ Should only be called when point is at the start of a screen line."
 (defvar term-load-hook nil
   "This hook is run when term is loaded in.
 This is a good place to put keybindings.")
-       
+
 (run-hooks 'term-load-hook)
 
 \f
@@ -2849,8 +3801,8 @@ This is a good place to put keybindings.")
 ;;;                                    replace with expanded/completed name.
 ;;; term-dynamic-simple-complete       Complete stub given candidates.
 
-;;; These are not installed in the term-mode keymap. But they are
-;;; available for people who want them. Shell-mode installs them:
+;;; These are not installed in the term-mode keymap.  But they are
+;;; available for people who want them.  Shell-mode installs them:
 ;;; (define-key shell-mode-map "\t" 'term-dynamic-complete)
 ;;; (define-key shell-mode-map "\M-?"
 ;;;             'term-dynamic-list-filename-completions)))
@@ -2859,12 +3811,14 @@ This is a good place to put keybindings.")
 ;;; want them present in specific modes.
 
 (defvar term-completion-autolist nil
-  "*If non-nil, automatically list possiblities on partial completion.
+  "*If non-nil, automatically list possibilities on partial completion.
 This mirrors the optional behavior of tcsh.")
 
 (defvar term-completion-addsuffix t
   "*If non-nil, add a `/' to completed directories, ` ' to file names.
-This mirrors the optional behavior of tcsh.")
+If a cons pair, it should be of the form (DIRSUFFIX . FILESUFFIX) where
+DIRSUFFIX and FILESUFFIX are strings added on unambiguous or exact
+completion.  This mirrors the optional behavior of tcsh.")
 
 (defvar term-completion-recexact nil
   "*If non-nil, use shortest completion if characters cannot be added.
@@ -2952,6 +3906,12 @@ See `term-dynamic-complete-filename'.  Returns t if successful."
   (let* ((completion-ignore-case nil)
         (completion-ignored-extensions term-completion-fignore)
         (success t)
+        (dirsuffix (cond ((not term-completion-addsuffix) "")
+                         ((not (consp term-completion-addsuffix)) "/")
+                         (t (car term-completion-addsuffix))))
+        (filesuffix (cond ((not term-completion-addsuffix) "")
+                          ((not (consp term-completion-addsuffix)) " ")
+                          (t (cdr term-completion-addsuffix))))
         (filename (or (term-match-partial-filename) ""))
         (pathdir (file-name-directory filename))
         (pathnondir (file-name-nondirectory filename))
@@ -2972,14 +3932,13 @@ See `term-dynamic-complete-filename'.  Returns t if successful."
                                 (length pathnondir)))
              (cond ((symbolp (file-name-completion completion directory))
                     ;; We inserted a unique completion.
-                    (if term-completion-addsuffix
-                        (insert (if (file-directory-p file) "/" " ")))
+                   (insert (if (file-directory-p file) dirsuffix filesuffix))
                     (or mini-flag (message "Completed")))
                    ((and term-completion-recexact term-completion-addsuffix
                          (string-equal pathnondir completion)
                          (file-exists-p file))
                     ;; It's not unique, but user wants shortest match.
-                    (insert (if (file-directory-p file) "/" " "))
+                   (insert (if (file-directory-p file) dirsuffix filesuffix))
                     (or mini-flag (message "Completed shortest")))
                    ((or term-completion-autolist
                         (string-equal pathnondir completion))
@@ -3089,11 +4048,73 @@ Typing SPC flushes the help buffer."
        (if (eq first ?\ )
            (set-window-configuration conf)
          (setq unread-command-events (listify-key-sequence key)))))))
+
+;;; I need a make-term that doesn't surround with *s -mm
+(defun term-ansi-make-term (name program &optional startfile &rest switches)
+"Make a term process NAME in a buffer, running PROGRAM.
+The name of the buffer is NAME.
+If there is already a running process in that buffer, it is not restarted.
+Optional third arg STARTFILE is the name of a file to send the contents of to
+the process.  Any more args are arguments to PROGRAM."
+  (let ((buffer (get-buffer-create name )))
+    ;; If no process, or nuked process, crank up a new one and put buffer in
+    ;; term mode.  Otherwise, leave buffer and existing process alone.
+    (cond ((not (term-check-proc buffer))
+          (save-excursion
+            (set-buffer buffer)
+            (term-mode)) ; Install local vars, mode, keymap, ...
+          (term-exec buffer name program startfile switches)))
+    buffer))
+
+(defvar term-ansi-buffer-name nil)
+(defvar term-ansi-default-program nil)
+(defvar term-ansi-buffer-base-name nil)
+
+;;;###autoload
+(defun ansi-term (program &optional new-buffer-name)
+  "Start a terminal-emulator in a new buffer."
+  (interactive (list (read-from-minibuffer "Run program: "
+                                          (or explicit-shell-file-name
+                                              (getenv "ESHELL")
+                                              (getenv "SHELL")
+                                              "/bin/sh"))))
+
+  ;; Pick the name of the new buffer.
+  (setq term-ansi-buffer-name
+       (if new-buffer-name
+           new-buffer-name
+         (if term-ansi-buffer-base-name
+             (if (eq term-ansi-buffer-base-name t)
+                 (file-name-nondirectory program)
+               term-ansi-buffer-base-name)
+           "ansi-term")))
+
+  (setq term-ansi-buffer-name (concat "*" term-ansi-buffer-name "*"))
+
+  ;; In order to have more than one term active at a time
+  ;; I'd like to have the term names have the *term-ansi-term<?>* form,
+  ;; for now they have the *term-ansi-term*<?> form but we'll see...
+
+  (setq term-ansi-buffer-name (generate-new-buffer-name term-ansi-buffer-name))
+  (setq term-ansi-buffer-name (term-ansi-make-term term-ansi-buffer-name program))
+
+  (set-buffer term-ansi-buffer-name)
+  (term-mode)
+  (term-char-mode)
+
+;; I wanna have find-file on C-x C-f -mm
+;; your mileage may definitely vary, maybe it's better to put this in your
+;; .emacs ...
+
+  (term-set-escape-char ?\C-x)
+
+  (switch-to-buffer term-ansi-buffer-name))
+
 \f
 ;;; Converting process modes to use term mode
 ;;; ===========================================================================
 ;;; Renaming variables
-;;; Most of the work is renaming variables and functions. These are the common
+;;; Most of the work is renaming variables and functions.  These are the common
 ;;; ones:
 ;;; Local variables:
 ;;;    last-input-start        term-last-input-start
@@ -3126,19 +4147,19 @@ Typing SPC flushes the help buffer."
 ;;; the old shell package was used to implement a history mechanism,
 ;;; but you should think twice before using term-last-input-start
 ;;; for this; the input history ring often does the job better.
-;;; 
+;;;
 ;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
 ;;; *not* create the term-mode local variables in your foo-mode function.
 ;;; This is not modular.  Instead, call term-mode, and let *it* create the
-;;; necessary term-specific local variables. Then create the
+;;; necessary term-specific local variables.  Then create the
 ;;; foo-mode-specific local variables in foo-mode.  Set the buffer's keymap to
 ;;; be foo-mode-map, and its mode to be foo-mode.  Set the term-mode hooks
 ;;; (term-{prompt-regexp, input-filter, input-filter-functions,
 ;;; get-old-input) that need to be different from the defaults.  Call
-;;; foo-mode-hook, and you're done. Don't run the term-mode hook yourself;
-;;; term-mode will take care of it. The following example, from shell.el,
+;;; foo-mode-hook, and you're done.  Don't run the term-mode hook yourself;
+;;; term-mode will take care of it.  The following example, from shell.el,
 ;;; is typical:
-;;; 
+;;;
 ;;; (defvar shell-mode-map '())
 ;;; (cond ((not shell-mode-map)
 ;;;        (setq shell-mode-map (copy-keymap term-mode-map))
@@ -3161,14 +4182,8 @@ Typing SPC flushes the help buffer."
 ;;;   (run-hooks 'shell-mode-hook))
 ;;;
 ;;;
-;;; Note that make-term is different from make-shell in that it
-;;; doesn't have a default program argument. If you give make-shell
-;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
-;;; $ESHELL, $SHELL, or /bin/sh. If you give make-term a program argument
-;;; of NIL, it barfs. Adjust your code accordingly...
-;;;
 ;;; Completion for term-mode users
-;;; 
+;;;
 ;;; For modes that use term-mode, term-dynamic-complete-functions is the
 ;;; hook to add completion functions to.  Functions on this list should return
 ;;; non-nil if completion occurs (i.e., further completion should not occur).
@@ -3177,4 +4192,5 @@ Typing SPC flushes the help buffer."
 \f
 (provide 'term)
 
+;;; arch-tag: eee16bc8-2cd7-4147-9534-a5694752f716
 ;;; term.el ends here