(vc-fetch-master-properties): Count cvs status "Needs Patch" as
[bpt/emacs.git] / lisp / term.el
index c672fca..1d34088 100644 (file)
@@ -1,5 +1,5 @@
 ;; term.el --- general command interpreter in a window stuff
-;; Copyright (C) 1988, 1990, 1992, 1992, 1994 Free Software Foundation, Inc.
+;; Copyright (C) 1988, 1990, 1992, 1994, 1995 Free Software Foundation, Inc.
 
 ;; Author: Per Bothner <bothner@cygnus.com>
 ;; Based on comint mode written by: Olin Shivers <shivers@cs.cmu.edu>
@@ -82,7 +82,7 @@
 
 ;;; 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.93")
+(defconst term-protocol-version "0.95")
 
 (require 'ring)
 (require 'ehelp)
 ;;;     term-delimiter-argument-list - list  For delimiters and arguments
 ;;;     term-last-input-start - marker       Handy if inferior always echoes
 ;;;     term-last-input-end   - marker       For term-kill-output command
-;;;     term-input-ring-size  - integer      For the input history
-;;;     term-input-ring       - ring             mechanism
+;; For the input history mechanism:
+(defvar term-input-ring-size 32 "Size of input history ring.")
+;;;     term-input-ring-size  - integer
+;;;     term-input-ring       - ring
 ;;;     term-input-ring-index - number           ...
 ;;;     term-input-autoexpand - symbol           ...
 ;;;     term-input-ignoredups - boolean          ...
 ;;;     term-input-send        - function
 ;;;     term-scroll-to-bottom-on-output - symbol ...
 ;;;     term-scroll-show-maximum-output - boolean...
+(defvar term-height) ;; Number of lines in window.
+(defvar term-width) ;; Number of columns in window.
+(defvar term-home-marker) ;; Marks the "home" position for cursor addressing.
+(defvar term-saved-home-marker nil) ;; When using alternate sub-buffer,
+;;             contains saved term-home-marker from original sub-buffer .
+(defvar term-start-line-column 0) ;; (current-column) at start of screen line,
+;;             or nil if unknown.
+(defvar term-current-column 0) ;; If non-nil, is cache for (current-column).
+(defvar term-current-row 0) ;; Current vertical row (relative to home-marker)
+;;             or nil if unknown.
+(defvar term-insert-mode nil)
+(defvar term-vertical-motion)
+(defvar term-terminal-state 0) ;; State of the terminal emulator:
+;;             state 0: Normal state
+;;             state 1: Last character was a graphic in the last column.
+;;             If next char is graphic, first move one column right
+;;             (and line warp) before displaying it.
+;;             This emulates (more or less) the behavior of xterm.
+;;             state 2: seen ESC
+;;             state 3: seen ESC [ (or ESC [ ?)
+;;             state 4: term-terminal-parameter contains pending output.
+(defvar term-kill-echo-list nil) ;; A queue of strings whose echo
+;;             we want suppressed.
+(defvar term-terminal-parameter)
+(defvar term-terminal-previous-parameter)
+(defvar term-current-face 'default)
+(defvar term-scroll-start 0) ;; Top-most line (inclusive) of scrolling region.
+(defvar term-scroll-end) ;; Number of line (zero-based) after scrolling region.
+(defvar term-pager-count nil) ;; If nil, paging is disabled.
+;;             Otherwise, number of lines before we need to page.
+(defvar term-saved-cursor nil)
+(defvar term-command-hook)
+(defvar term-log-buffer nil)
+(defvar term-scroll-with-delete nil) ;; term-scroll-with-delete is t if
+;;             forward scrolling should be implemented by delete to
+;;             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) ;; 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.")
@@ -178,9 +225,6 @@ 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.")
 
-(defvar term-input-ring-size 32
-  "Size of input history ring.")
-
 ;; Where gud-display-frame should put the debugging arrow.  This is
 ;; set by the marker-filter, which scans the debugger's output for
 ;; indications of the current pc.
@@ -221,6 +265,10 @@ 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-eol-on-send t
+  "*Non-nil means go to the end of the line before sending input.
+See `term-send-input'.")
+
 (defvar term-mode-hook '()
   "Called upon entry into term-mode
 This is run before the process is cranked up.")
@@ -235,7 +283,9 @@ executed once when the buffer is created.")
 (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)
@@ -268,26 +318,35 @@ Buffer local variable.")
 (put 'term-scroll-show-maximum-output 'permanent-local t)
 (put 'term-ptyp 'permanent-local t)
 
-(defmacro term-is-emacs19 ()  '(string-match "^19" emacs-version))
-;; True if running under XEmacs (perviously Lucid emacs).
+;; 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).
+(defmacro term-if-xemacs (&rest forms)
+  (if (term-is-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)))
 
 (defmacro term-in-char-mode () '(eq (current-local-map) term-raw-map))
 (defmacro term-in-line-mode () '(not (term-in-char-mode)))
+;; True if currently doing PAGER handling.
+(defmacro term-pager-enabled () 'term-pager-count)
+(defmacro term-handling-pager () 'term-pager-old-local-map)
+(defmacro term-using-alternate-sub-buffer () 'term-saved-home-marker)
 
-(if (term-is-xemacs)
-  (defvar term-terminal-menu
-    '("Terminal"
-      [ "Character mode" term-char-mode (term-in-line-mode)]
-      [ "Line mode" term-line-mode (term-in-char-mode)]
-      [ "Enable paging" term-pager-enable (not term-pager-count)]
-      [ "Disable paging" term-pager-disable term-pager-count]))
-)
+(defvar term-signals-menu)
+(defvar term-terminal-menu)
 
-(put 'term-char-mode 'menu-enable '(term-in-line-mode))
-(put 'term-line-mode 'menu-enable '(term-in-char-mode))
-(put 'term-pager-enable 'menu-enable '(not term-pager-count))
-(put 'term-pager-disable 'menu-enable 'term-pager-count)
+(term-if-xemacs
+ (defvar term-terminal-menu
+   '("Terminal"
+     [ "Character mode" term-char-mode (term-in-line-mode)]
+     [ "Line mode" term-line-mode (term-in-char-mode)]
+     [ "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.
@@ -325,19 +384,16 @@ Entry to this mode runs the hooks on term-mode-hook"
     (kill-all-local-variables)
     (setq major-mode 'term-mode)
     (setq mode-name "Term")
-    (setq mode-line-process '(": line %s"))
     (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)
-    (setq term-saved-home-marker nil)
     (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)
-    (setq term-saved-cursor nil)
     (make-local-variable 'term-last-input-start)
     (setq term-last-input-start (make-marker))
     (make-local-variable 'term-last-input-end)
@@ -357,54 +413,20 @@ Entry to this mode runs the hooks on term-mode-hook"
     (make-local-variable 'term-command-hook)
     (setq term-command-hook (symbol-function 'term-command-hook))
 
-    ;; state 0: Normal state
-    ;; state 1: Last character was a graphic in the last column.
-    ;;          If next char is graphic, first move one column right
-    ;;          (and line warp) before displaying it.
-    ;;          This emulates (more or less) the behavior of xterm.
-    ;; state 2: seen ESC
-    ;; state 3: seen ESC [ (or ESC [ ?)
-    ;; state 4: term-terminal-parameter contains pending output.
     (make-local-variable 'term-terminal-state)
-    (setq term-terminal-state 0)
-
-    ;; A queue of strings whose echo we want suppressed.
     (make-local-variable 'term-kill-echo-list)
-    (setq term-kill-echo-list nil)
-
-    ;; (current-column) at start of screen line, or nil if unknown.
     (make-local-variable 'term-start-line-column)
-    (setq term-start-line-column 0)
-    ;; Cache for (current-column), or nil if unknown.
     (make-local-variable 'term-current-column)
-    (setq term-current-column 0)
-    ;; Current vertical row (from home-marker) or nil if unknown.
     (make-local-variable 'term-current-row)
-    (setq term-current-row 0)
     (make-local-variable 'term-log-buffer)
-    (setq term-log-buffer nil)
     (make-local-variable 'term-scroll-start)
-    (setq term-scroll-start 0)
     (make-local-variable 'term-scroll-end)
     (setq term-scroll-end term-height)
-    ;; term-scroll-with-delete is t if forward scrolling should
-    ;; be implemented by delete to 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.
     (make-local-variable 'term-scroll-with-delete)
-    (setq term-scroll-with-delete nil)
     (make-local-variable 'term-pager-count)
-    ;;(setq term-pager-count 0)
-    (setq term-pager-count nil)
-    ;; Used to save the old keymap when doing PAGER processing.
     (make-local-variable 'term-pager-old-local-map)
-    (setq term-pager-old-local-map nil)
-    ;; Used to save the old keymap when in char mode.
     (make-local-variable 'term-old-mode-map)
-    (setq term-old-mode-map nil)
     (make-local-variable 'term-insert-mode)
-    (setq term-insert-mode nil)
     (make-local-variable 'term-dynamic-complete-functions)
     (make-local-variable 'term-completion-fignore)
     (make-local-variable 'term-get-old-input)
@@ -415,6 +437,7 @@ Entry to this mode runs the hooks on term-mode-hook"
     (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)
@@ -423,17 +446,15 @@ Entry to this mode runs the hooks on term-mode-hook"
     (make-local-variable 'term-pending-delete-marker)
     (setq term-pending-delete-marker (make-marker))
     (make-local-variable 'term-current-face)
-    (setq term-current-face 'default)
     (make-local-variable 'term-pending-frame)
     (setq term-pending-frame nil)
-    (make-local-variable 'term-chars-mode)
-    (setq term-chars-mode nil)
     (run-hooks 'term-mode-hook)
-    (if (term-is-xemacs)
-       (set-buffer-menubar
-        (append current-menubar (list term-terminal-menu))))
+    (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))))
+       (setq term-input-ring (make-ring term-input-ring-size)))
+    (term-update-mode-line))
 
 (if term-mode-map
     nil
@@ -442,10 +463,9 @@ Entry to this mode runs the hooks on term-mode-hook"
   (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)
-  (if (term-is-xemacs)
-      t
-    (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))
+  (term-ifnot-xemacs
+   (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)
   (define-key term-mode-map "\C-d" 'term-delchar-or-maybe-eof)
@@ -463,9 +483,9 @@ Entry to this mode runs the hooks on term-mode-hook"
   (define-key term-mode-map "\C-c\C-n" 'term-next-prompt)
   (define-key term-mode-map "\C-c\C-p" 'term-previous-prompt)
   (define-key term-mode-map "\C-c\C-d" 'term-send-eof)
-  (define-key term-mode-map "\C-cc" 'term-char-mode)
-  (define-key term-mode-map "\C-cp" 'term-pager-enable)
-  (define-key term-mode-map "\C-cD" 'term-pager-disable)
+  (define-key term-mode-map "\C-c\C-k" 'term-char-mode)
+  (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)
@@ -487,85 +507,86 @@ Entry to this mode runs the hooks on term-mode-hook"
   )
 
 ;; Menu bars:
-(if (and (not (boundp 'term-terminal-menu))
-        (term-is-emacs19) (not (term-is-xemacs)))
-    (progn
-      ;; terminal:
-      (defvar term-terminal-menu (make-sparse-keymap "Terminal"))
-      (define-key term-mode-map [menu-bar terminal] 
-       (cons "Terminal" term-terminal-menu))
-      (define-key term-terminal-menu [terminal-char-mode]
-       '("Character mode" . term-char-mode))
-      (define-key term-terminal-menu [terminal-line-mode]
-       '("Line mode" . term-line-mode))
-      (define-key term-terminal-menu [terminal-pager-enable]
-       '("Enable paging" . term-pager-enable))
-      (define-key term-terminal-menu [terminal-pager-disable]
-       '("Disable paging" . term-pager-disable))
-
-      ;; completion:  (line mode only)
-      (defvar term-completion-menu (make-sparse-keymap "Complete"))
-      (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))
-      (define-key term-completion-menu [complete-listing]
-       '("File Completion Listing" . term-dynamic-list-filename-completions))
-      (define-key term-completion-menu [menu-bar completion complete-file]
-       '("Complete File Name" . term-dynamic-complete-filename))
-      (define-key term-completion-menu [menu-bar completion complete]
-       '("Complete Before Point" . term-dynamic-complete))
-
-      ;; Input history: (line mode only)
-      (defvar term-inout-menu (make-sparse-keymap "In/Out"))
-      (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))
-      (define-key term-inout-menu [next-prompt]
-       '("Forward Output Group" . term-next-prompt))
-      (define-key term-inout-menu [previous-prompt]
-       '("Backward Output Group" . term-previous-prompt))
-      (define-key term-inout-menu [show-maximum-output]
-       '("Show Maximum Output" . term-show-maximum-output))
-      (define-key term-inout-menu [show-output]
-       '("Show Current Output Group" . term-show-output))
-      (define-key term-inout-menu [kill-input]
-       '("Kill Current Input" . term-kill-input))
-      (define-key term-inout-menu [copy-input]
-       '("Copy Old Input" . term-copy-old-input))
-      (define-key term-inout-menu [forward-matching-history]
-       '("Forward Matching Input..." . term-forward-matching-input))
-      (define-key term-inout-menu [backward-matching-history]
-       '("Backward Matching Input..." . term-backward-matching-input))
-      (define-key term-inout-menu [next-matching-history]
-       '("Next Matching Input..." . term-next-matching-input))
-      (define-key term-inout-menu [previous-matching-history]
-       '("Previous Matching Input..." . term-previous-matching-input))
-      (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))
-      (define-key term-inout-menu [next-history]
-       '("Next Input" . term-next-input))
-      (define-key term-inout-menu [previous-history]
-       '("Previous Input" . term-previous-input))
-      (define-key term-inout-menu [list-history]
-       '("List Input History" . term-dynamic-list-input-ring))
-      (define-key term-inout-menu [expand-history]
-       '("Expand History Before Point" . term-replace-by-expanded-history))
-
-      ;; Signals
-      (defvar term-signals-menu (make-sparse-keymap "Signals"))
-      (define-key term-mode-map [menu-bar signals]
-       (cons "Signals" term-signals-menu))
-      (define-key term-signals-menu [eof] '("EOF" . term-send-eof))
-      (define-key term-signals-menu [kill] '("KILL" . term-kill-subjob))
-      (define-key term-signals-menu [quit] '("QUIT" . term-quit-subjob))
-      (define-key term-signals-menu [cont] '("CONT" . term-continue-subjob))
-      (define-key term-signals-menu [stop] '("STOP" . term-stop-subjob))
-      (define-key term-signals-menu [] '("BREAK" . term-interrupt-subjob))
-      ))
+(term-ifnot-xemacs
+ (term-if-emacs19
+
+  ;; terminal:
+  (let (newmap)
+    (setq newmap (make-sparse-keymap "Terminal"))
+    (define-key newmap [terminal-pager-enable]
+      '("Enable paging" . term-fake-pager-enable))
+    (define-key newmap [terminal-pager-disable]
+      '("Disable paging" . term-fake-pager-disable))
+    (define-key newmap [terminal-char-mode]
+      '("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)))
+
+    ;; completion:  (line mode only)
+    (defvar term-completion-menu (make-sparse-keymap "Complete"))
+    (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))
+    (define-key term-completion-menu [complete-listing]
+      '("File Completion Listing" . term-dynamic-list-filename-completions))
+    (define-key term-completion-menu [menu-bar completion complete-file]
+      '("Complete File Name" . term-dynamic-complete-filename))
+    (define-key term-completion-menu [menu-bar completion complete]
+      '("Complete Before Point" . term-dynamic-complete))
+
+    ;; Input history: (line mode only)
+    (defvar term-inout-menu (make-sparse-keymap "In/Out"))
+    (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))
+    (define-key term-inout-menu [next-prompt]
+      '("Forward Output Group" . term-next-prompt))
+    (define-key term-inout-menu [previous-prompt]
+      '("Backward Output Group" . term-previous-prompt))
+    (define-key term-inout-menu [show-maximum-output]
+      '("Show Maximum Output" . term-show-maximum-output))
+    (define-key term-inout-menu [show-output]
+      '("Show Current Output Group" . term-show-output))
+    (define-key term-inout-menu [kill-input]
+      '("Kill Current Input" . term-kill-input))
+    (define-key term-inout-menu [copy-input]
+      '("Copy Old Input" . term-copy-old-input))
+    (define-key term-inout-menu [forward-matching-history]
+      '("Forward Matching Input..." . term-forward-matching-input))
+    (define-key term-inout-menu [backward-matching-history]
+      '("Backward Matching Input..." . term-backward-matching-input))
+    (define-key term-inout-menu [next-matching-history]
+      '("Next Matching Input..." . term-next-matching-input))
+    (define-key term-inout-menu [previous-matching-history]
+      '("Previous Matching Input..." . term-previous-matching-input))
+    (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))
+    (define-key term-inout-menu [next-history]
+      '("Next Input" . term-next-input))
+    (define-key term-inout-menu [previous-history]
+      '("Previous Input" . term-previous-input))
+    (define-key term-inout-menu [list-history]
+      '("List Input History" . term-dynamic-list-input-ring))
+    (define-key term-inout-menu [expand-history]
+      '("Expand History Before Point" . term-replace-by-expanded-history))
+
+    ;; Signals
+    (setq newmap (make-sparse-keymap "Signals"))
+    (define-key newmap [eof] '("EOF" . term-send-eof))
+    (define-key newmap [kill] '("KILL" . term-kill-subjob))
+    (define-key newmap [quit] '("QUIT" . term-quit-subjob))
+    (define-key newmap [cont] '("CONT" . term-continue-subjob))
+    (define-key newmap [stop] '("STOP" . term-stop-subjob))
+    (define-key newmap [] '("BREAK" . term-interrupt-subjob))
+    (define-key term-mode-map [menu-bar signals]
+      (setq term-signals-menu (cons "Signals" newmap)))
+    )))
 
 (defun term-reset-size (height width)
   (setq term-height height)
@@ -617,7 +638,7 @@ Entry to this mode runs the hooks on term-mode-hook"
       ;; Note that (term-current-row) must be called *after*
       ;; (point) has been updated to (process-mark proc).
       (goto-char (process-mark proc))
-      (if term-pager-count
+      (if (term-pager-enabled)
          (setq term-pager-count (term-current-row)))
       (send-string proc chars))))
 
@@ -633,23 +654,36 @@ without any interpretation."
 
 (defun term-send-raw-meta ()
   (interactive)
-  ;; Convert `return' to C-m, etc.
-  (if (and (symbolp last-input-char)
-          (get last-input-char 'ascii-character))
-      (setq last-input-char (get last-input-char 'ascii-character)))
-  (term-send-raw-string (if (> last-input-char 127)
+  (if (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))))
 
 (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)
+   (term-send-raw-string (current-kill (cond
+                                       ((listp arg) 0)
+                                       ((eq arg '-) -1)
+                                       (t (1- arg)))))))
 
 ;; Which would be better:  "\e[A" or "\eOA"? readline accepts either.
 (defun term-send-up    () (interactive) (term-send-raw-string "\e[A"))
@@ -658,6 +692,7 @@ without any interpretation."
 (defun term-send-left  () (interactive) (term-send-raw-string "\e[D"))
 
 (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))
@@ -670,13 +705,15 @@ without any interpretation."
   (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 "p" 'term-pager-enable)
-  (define-key term-raw-escape-map "D" 'term-pager-disable)
-  (define-key term-raw-escape-map "l" 'term-line-mode))
+  (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))
     
 (defun term-char-mode ()
-  "Start using raw keyboard mode to send each character
-to inferior process until a key bound to term-line-mode is encountered."
+  "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)."
   (interactive)
   (if (not term-raw-map)
       (let* ((map (make-keymap))
@@ -690,44 +727,53 @@ to inferior process until a key bound to term-line-mode is encountered."
        (setq term-raw-map map)
        (setq term-raw-escape-map
              (copy-keymap (lookup-key (current-global-map) "\C-x")))
-       (if (term-is-emacs19)
-           (progn
-             (if (term-is-xemacs)
-                 (define-key term-raw-map [(button2)] 'term-mouse-paste)
-               (progn
-                 (define-key term-raw-map [mouse-2] 'term-mouse-paste)
-                 (define-key term-raw-map [menu-bar terminal] 
-                   (cons "Terminal" term-terminal-menu))
-                 (define-key term-raw-map [menu-bar signals]
-                   (cons "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-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
-  (setq term-old-mode-map (current-local-map))
-  (use-local-map term-raw-map)
-
-  ;; Send existing partial line to inferior (without newline).
-  (let ((pmark (process-mark (get-buffer-process (current-buffer))))
-       (save-input-sender term-input-sender))
-    (if (> (point) pmark)
-       (unwind-protect
-           (progn
-             (setq term-input-sender (symbol-function 'term-send-string))
-             (end-of-line)
-             (term-send-input))
-         (setq term-input-sender save-input-sender))))
-
-  (setq mode-line-process '(": char %s"))
-  (set-buffer-modified-p (buffer-modified-p))) ;;No-op, but updates mode line.
+  (if (term-in-line-mode)
+      (progn
+       (setq term-old-mode-map (current-local-map))
+       (use-local-map term-raw-map)
+
+       ;; Send existing partial line to inferior (without newline).
+       (let ((pmark (process-mark (get-buffer-process (current-buffer))))
+             (save-input-sender term-input-sender))
+         (if (> (point) pmark)
+             (unwind-protect
+                 (progn
+                   (setq term-input-sender
+                         (symbol-function 'term-send-string))
+                   (end-of-line)
+                   (term-send-input))
+               (setq term-input-sender save-input-sender))))
+       (term-update-mode-line))))
 
 (defun term-line-mode  ()
+  "Switch to line (\"cooked\") sub-mode of term mode.
+This means that emacs editing commands work as normally, until
+you type \\[term-send-input] which sends the current line to the inferior."
   (interactive)
-  (use-local-map term-old-mode-map)
-  (setq mode-line-process '(": line %s"))
-  (set-buffer-modified-p (buffer-modified-p))) ;;No-op, but updates mode line.
+  (if (term-in-char-mode)
+      (progn
+       (use-local-map term-old-mode-map)
+       (term-update-mode-line))))
+
+(defun term-update-mode-line ()
+  (setq mode-line-process
+       (if (term-in-char-mode)
+           (if (term-pager-enabled) '(": char page %s") '(": char %s"))
+         (if (term-pager-enabled) '(": line page %s") '(": line %s"))))
+  (force-mode-line-update))
 
 (defun term-check-proc (buffer)
   "True if there is a process associated w/buffer BUFFER, and
@@ -833,7 +879,7 @@ buffer. The hook term-exec-hook is run after each exec."
               (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 "EMACS=%s (term:%s)" emacs-version term-protocol-version)
           (format "LINES=%d" term-height)
           (format "COLUMNS=%d" term-width))
          process-environment)))
@@ -1377,6 +1423,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.,
@@ -1402,14 +1451,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
@@ -1427,7 +1472,7 @@ Similarly for Soar, Scheme, etc."
                          (delete-region pmark (point))
                          (insert input)
                          copy))))
-       (if term-pager-count
+       (if (term-pager-enabled)
            (save-excursion
              (goto-char (process-mark proc))
              (setq term-pager-count (term-current-row))))
@@ -1443,11 +1488,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 ()
@@ -1567,7 +1620,6 @@ 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 (list (term-read-noecho "Enter non-echoed text")))
   (interactive "P") ; Defeat snooping via C-x esc
   (if (not (stringp str))
       (setq str (term-read-noecho "Non-echoed text: " t)))
@@ -2000,15 +2052,10 @@ See `term-prompt-regexp'."
   (if term-current-row
       (setq term-current-row (+ term-current-row delta))))
 
-;; True if currently doing PAGER handling.
-(defmacro term-handling-pager () 'term-pager-old-local-map)
-
-(defmacro term-using-alternate-sub-buffer () 'term-saved-home-marker)
-
 (defun term-terminal-pos ()
   (save-excursion ;    save-restriction
     (let ((save-col (term-current-column))
-         (x))
+         x y)
       (term-vertical-motion 0)
       (setq x (- save-col (current-column)))
       (setq y (term-vertical-motion term-height))
@@ -2082,24 +2129,31 @@ See `term-prompt-regexp'."
                                   ;; This iteration, handle only what fits.
                                   (setq count (- count temp))
                                   (setq funny (+ count i)))
-                                 ((>  (term-handle-scroll 1) 0)
+                                 ((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))
-                                  (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))
+                           ;; In the common case that we're at the end of
+                           ;; the buffer, we can save a little work.
+                           (cond ((/= (point) (point-max))
+                                  (if term-insert-mode
+                                      ;; Inserting spaces, then deleting them,
+                                      ;; then inserting the actual text is
+                                      ;; inefficient, but it is simple, and
+                                      ;; the actual overhead is miniscule.
+                                      (term-insert-spaces count))
+                                  (term-move-columns count)
+                                  (delete-region old-point (point)))
+       (t (setq term-current-column (+ (term-current-column) count))))
                            (insert (substring str i funny))
                            (put-text-property old-point (point)
                                               'face term-current-face)
@@ -2117,17 +2171,29 @@ See `term-prompt-regexp'."
                            (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))
+                           (setq term-current-column count))
                           ((eq char ?\r)
-                           (term-vertical-motion 0)
-                           (setq term-current-column nil))
+                           ;; 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 0))))
                           ((eq char ?\n)
                            (if (not (and term-kill-echo-list
                                          (term-check-kill-echo-list)))
-                               (term-down 1 0 t)))
+                               (term-down 1 t)))
+                          ((eq char ?\b)
+                           (term-move-columns -1))
                           ((eq char ?\033) ; Escape
                            (setq term-terminal-state 2))
                           ((eq char 0)) ; NUL: Do nothing
@@ -2157,12 +2223,14 @@ See `term-prompt-regexp'."
                            (setq term-terminal-previous-parameter 0)
                            (setq term-terminal-state 3))
                           ((eq char ?D) ;; scroll forward
-                           (term-down 1 0 t)
+                           (term-handle-deferred-scroll)
+                           (term-down 1 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
+                           (term-handle-deferred-scroll)
                            (setq term-saved-cursor
                                  (cons (term-current-row)
                                        (term-horizontal-column)))
@@ -2183,7 +2251,7 @@ See `term-prompt-regexp'."
                            (setq term-terminal-parameter 0))
                           ((eq char ??)) ; Ignore ? 
                           (t
-                           (term-handle-ansi-escape char)
+                           (term-handle-ansi-escape proc char)
                            (setq term-terminal-state 0)))))
              (if (term-handling-pager)
                  ;; Finish stuff to get ready to handle PAGER.
@@ -2206,6 +2274,9 @@ See `term-prompt-regexp'."
                    (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)
@@ -2256,25 +2327,39 @@ See `term-prompt-regexp'."
       (set-buffer previous-buffer)
       (select-window selected))))
 
+(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 count)
+         (set-marker term-home-marker (point))
+         (setq term-current-row (1- term-height))))))
+
 ;;; Handle a character assuming (eq terminal-state 2) -
 ;;; i.e. we have previousely seen Escape followed by ?[.
 
-(defun term-handle-ansi-escape (char)
+(defun term-handle-ansi-escape (proc char)
   (cond
    ((eq char ?H) ; cursor motion
     (if (<= term-terminal-parameter 0)
        (setq term-terminal-parameter 1))
     (if (<= term-terminal-previous-parameter 0)
        (setq term-terminal-previous-parameter 1))
+    (if (> term-terminal-previous-parameter term-height)
+       (setq term-terminal-previous-parameter term-height))
+    (if (> term-terminal-parameter term-width)
+       (setq term-terminal-parameter term-width))
     (term-goto
      (1- term-terminal-previous-parameter)
      (1- term-terminal-parameter)))
    ;; \E[A - cursor up
    ((eq char ?A)
-    (term-down (- (max 1 term-terminal-parameter)) 0 t))
+    (term-handle-deferred-scroll)
+    (term-down (- (max 1 term-terminal-parameter)) t))
    ;; \E[B - cursor down
    ((eq char ?B)
-    (term-down (max 1 term-terminal-parameter) t))
+    (term-down (max 1 term-terminal-parameter) t))
    ;; \E[C - cursor right
    ((eq char ?C)
     (term-move-columns (max 1 term-terminal-parameter)))
@@ -2320,6 +2405,13 @@ See `term-prompt-regexp'."
          ((eq term-terminal-parameter 1)
           (setq term-current-face 'bold))
          (t (setq term-current-face 'default))))
+   ;; \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)
     (term-scroll-region
@@ -2337,7 +2429,7 @@ The top-most line is line 0."
            0
          top))
   (setq term-scroll-end
-       (if (or (< bottom term-scroll-start) (> bottom term-height))
+       (if (or (<= bottom term-scroll-start) (> bottom term-height))
            term-height
          bottom))
   (setq term-scroll-with-delete
@@ -2349,6 +2441,7 @@ The top-most line is line 0."
   ;; 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)))
@@ -2368,7 +2461,6 @@ The top-most line is line 0."
               (setq term-saved-home-marker nil)
               (goto-char term-home-marker)))
        (setq term-current-column nil)
-       (setq term-line-start-column nil)
        (setq term-current-row 0)
        (term-goto row col))))
 
@@ -2387,8 +2479,10 @@ The top-most line is line 0."
           (setq term-pending-frame (cons filename fileline))))
        ((= (aref string 0) ?/)
         (cd (substring string 1)))
-       ((= (aref string 0) ?!)
-           (eval (car (read-from-string string 1))))
+       ;; 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))))
        (t)));; Otherwise ignore it
 
 ;; Make sure the file named TRUE-FILE is in a buffer that appears on the screen
@@ -2422,22 +2516,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))
+            (i 0) tmp)
 ;      (while (< i 128)
 ;        (define-key map (make-string 1 i) 'term-send-raw)
 ;        (setq i (1+ i)))
@@ -2457,6 +2559,27 @@ The top-most line is line 0."
        (define-key map "D" 'term-pager-disable)
        (define-key map "<" 'term-pager-bob)
        (define-key map ">" 'term-pager-eob)
+
+       ;; Add menu bar.
+       (term-if-emacs19
+        (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))
+         (define-key tmp [discard]
+           '("Discard remaining output" . term-pager-discard))
+         (define-key tmp [eob] '("Goto to end" . term-pager-eob))
+         (define-key tmp [bob] '("Goto to beginning" . term-pager-bob))
+         (define-key tmp [line] '("1 line forwards" . term-pager-line))
+         (define-key tmp [bline] '("1 line backwards" . term-pager-back-line))
+         (define-key tmp [back] '("1 page backwards" . term-pager-back-page))
+         (define-key tmp [page] '("1 page forwards" . term-pager-page))
+         (define-key map [menu-bar page] (cons "More pages?" tmp))
+         ))
+
        (setq term-pager-break-map map)))
 ;  (let ((process (get-buffer-process (current-buffer))))
 ;    (stop-process process))  
@@ -2468,7 +2591,8 @@ The top-most line is line 0."
        (list "--  **MORE**  "
              mode-line-buffer-identification
              " [Type ? for help] "
-             "%-")))
+             "%-"))
+  (force-mode-line-update))
 
 (defun term-pager-line (lines)
   (interactive "p")
@@ -2527,13 +2651,27 @@ The top-most line is line 0."
   (interactive)
   (if (term-handling-pager)
       (term-pager-continue nil)
-    (setq term-pager-count nil)))
+    (setq term-pager-count nil))
+  (term-update-mode-line))
     
 ; Enable pager processing.
 (defun term-pager-enable ()
   (interactive)
-  (or term-pager-count
-      (setq term-pager-count 0))) ;; Or maybe set to (term-current-row) ??
+  (or (term-pager-enabled)
+      (setq term-pager-count 0)) ;; Or maybe set to (term-current-row) ??
+  (term-update-mode-line))
+
+(defun term-pager-toggle ()
+  (interactive)
+  (if (term-pager-enabled) (term-pager-disable) (term-pager-enable)))
+
+(term-ifnot-xemacs
+ (defalias 'term-fake-pager-enable 'term-pager-toggle)
+ (defalias 'term-fake-pager-disable 'term-pager-toggle)
+ (put 'term-char-mode 'menu-enable '(term-in-line-mode))
+ (put 'term-line-mode 'menu-enable '(term-in-char-mode))
+ (put 'term-fake-pager-enable 'menu-enable '(not term-pager-count))
+ (put 'term-fake-pager-disable 'menu-enable 'term-pager-count))
 
 (defun term-pager-help ()
   "Provide help on commands available in a terminal-emulator **MORE** break"
@@ -2567,6 +2705,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)
+    (force-mode-line-update)
     (setq term-pager-count new-count)
     (set-process-filter process term-pager-old-filter)
     (funcall term-pager-old-filter process "")
@@ -2589,6 +2728,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))
@@ -2596,27 +2737,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-line-start-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 (/= (point) (point-max))
+       (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.
@@ -2626,10 +2771,10 @@ all pending output has been dealt with."))
 
 (defun term-erase-in-line (kind)
   (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))))
+      (let ((cols (term-horizontal-column)) (saved-point (point)))
+       (term-vertical-motion 0)
+       (delete-region (point) saved-point)
+       (term-insert-char ?\n cols)))
   (if (not (eq kind 1)) ;; erase right of point
       (let ((saved-point (point))
            (wrapped (and (zerop (term-horizontal-column))
@@ -2656,6 +2801,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))
@@ -2666,9 +2812,8 @@ Should only be called when point is at the start of a screen line."
           (delete-region start-region end-region)
           (term-unwrap-line)
           (if (eq kind 1)
-              (term-insert-char \?n row))
+              (term-insert-char ?\n row))
           (setq term-current-column nil)
-          (setq term-line-start-column nil)
           (setq term-current-row nil)
           (term-goto row col)))))
 
@@ -2680,6 +2825,10 @@ 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))
     (term-vertical-motion 1)
@@ -2698,9 +2847,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)
@@ -2713,9 +2862,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)