]> code.delx.au - gnu-emacs/blobdiff - lisp/ediff-util.el
(sgml-tag-alist): Doc fix.
[gnu-emacs] / lisp / ediff-util.el
index e87cd821e321893442ddc94b83119f53d724bdf0..99d013616246b25de2c72f7861bef805cf6eb901 100644 (file)
@@ -1,8 +1,8 @@
 ;;; ediff-util.el --- the core commands and utilities of ediff
 
-;; Copyright (C) 1994, 1995, 1996, 1997 Free Software Foundation, Inc.
+;; Copyright (C) 1994, 95, 96, 97, 98, 99, 2000, 01, 02 Free Software Foundation, Inc.
 
-;; Author: Michael Kifer <kifer@cs.sunysb.edu>
+;; Author: Michael Kifer <kifer@cs.stonybrook.edu>
 
 ;; This file is part of GNU Emacs.
 
@@ -21,6 +21,8 @@
 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 ;; Boston, MA 02111-1307, USA.
 
+;;; Commentary:
+
 ;;; Code:
         
 (provide 'ediff-util)
 ;; Compiler pacifier
 (defvar ediff-patch-diagnostics)
 (defvar ediff-patchbufer)
+(defvar ediff-use-toolbar-p)
+(defvar ediff-toolbar-height)
 (defvar ediff-toolbar)
 (defvar ediff-toolbar-3way)
 (defvar bottom-toolbar)
 (defvar bottom-toolbar-visible-p)
 (defvar bottom-toolbar-height)
 (defvar mark-active)
+(defvar ediff-emacs-p)
+
+(defvar ediff-after-quit-hook-internal nil)
 
 (eval-when-compile
   (let ((load-path (cons (expand-file-name ".") load-path)))
@@ -190,7 +197,9 @@ to invocation.")
         (define-key ediff-mode-map "r" 'ediff-restore-diff-in-merge-buffer)
         (define-key ediff-mode-map "s" 'ediff-shrink-window-C)
         (define-key ediff-mode-map "+" 'ediff-combine-diffs)
-        (define-key ediff-mode-map "$" 'ediff-toggle-show-clashes-only)
+        (define-key ediff-mode-map "$"  nil)
+        (define-key ediff-mode-map "$$" 'ediff-toggle-show-clashes-only)
+        (define-key ediff-mode-map "$*" 'ediff-toggle-skip-changed-regions)
         (define-key ediff-mode-map "&" 'ediff-re-merge))
        (ediff-3way-comparison-job
         (define-key ediff-mode-map "ab" 'ediff-copy-A-to-B)
@@ -224,7 +233,7 @@ to invocation.")
   (define-key ediff-mode-map "wb"  'ediff-save-buffer)
   (define-key ediff-mode-map "wd"  'ediff-save-buffer)
   (define-key ediff-mode-map "="   'ediff-inferior-compare-regions)
-  (if (fboundp 'ediff-show-patch-diagnostics)
+  (if (and (fboundp 'ediff-show-patch-diagnostics) (ediff-patch-job))
       (define-key ediff-mode-map "P"  'ediff-show-patch-diagnostics))
   (if ediff-3way-job
       (progn
@@ -249,6 +258,7 @@ to invocation.")
 (defun ediff-setup (buffer-A file-A buffer-B file-B buffer-C file-C
                             startup-hooks setup-parameters
                             &optional merge-buffer-file)
+  (run-hooks 'ediff-before-setup-hook)
   ;; ediff-convert-standard-filename puts file names in the form appropriate
   ;; for the OS at hand.
   (setq file-A (ediff-convert-standard-filename (expand-file-name file-A)))
@@ -263,7 +273,7 @@ to invocation.")
               (expand-file-name merge-buffer-file)))
        ;; check the directory exists
        (or (file-exists-p (file-name-directory merge-buffer-file))
-           (error "Directory %s given as place to save the merge doesn't exist."
+           (error "Directory %s given as place to save the merge doesn't exist"
                   (abbreviate-file-name 
                    (file-name-directory merge-buffer-file))))
        (if (and (file-exists-p merge-buffer-file)
@@ -285,7 +295,12 @@ to invocation.")
       (make-local-variable 'ediff-merge-window-share)
       (make-local-variable 'ediff-window-setup-function)
       (make-local-variable 'ediff-keep-variants)
-      
+
+      (ediff-cond-compile-for-xemacs-or-emacs
+       (make-local-hook 'ediff-after-quit-hook-internal) ; xemacs form
+       nil ; emacs form
+       )
+
       ;; unwrap set up parameters passed as argument
       (while setup-parameters
        (set (car (car setup-parameters)) (cdr (car setup-parameters)))
@@ -307,9 +322,13 @@ to invocation.")
       (if (string-match "buffer" (symbol-name ediff-job-name))
          (setq ediff-keep-variants t))
 
-      (make-local-hook 'pre-command-hook)
+      (ediff-cond-compile-for-xemacs-or-emacs
+       (make-local-hook 'pre-command-hook) ; xemacs form
+       nil                                 ; emacs form
+       )
+
       (if (ediff-window-display-p)
-         (add-hook 'pre-command-hook 'ediff-spy-after-mouse nil t))
+         (add-hook 'pre-command-hook 'ediff-spy-after-mouse nil 'local))
       (setq ediff-mouse-pixel-position (mouse-pixel-position))
       
       ;; adjust for merge jobs
@@ -318,7 +337,7 @@ to invocation.")
                 ;; If default variant is `combined', the right stuff is
                 ;; inserted by ediff-do-merge
                 ;; Note: at some point, we tried to put ancestor buffer here
-                ;; (which is currently buffer C. This didn't work right
+                ;; (which is currently buffer C.  This didn't work right
                 ;; because the merge buffer will contain lossage: diff regions
                 ;; in the ancestor, which correspond to revisions that agree
                 ;; in both buf A and B.
@@ -339,6 +358,7 @@ to invocation.")
              (set-buffer buffer-C)
              (insert-buffer buf)
              (funcall (ediff-with-current-buffer buf major-mode))
+             (widen) ; merge buffer is always widened
              (add-hook 'local-write-file-hooks 'ediff-set-merge-mode nil t)
              )))
       (setq buffer-read-only nil    
@@ -346,6 +366,8 @@ to invocation.")
            ediff-buffer-B buffer-B
            ediff-buffer-C buffer-C
            ediff-control-buffer control-buffer)
+
+      (ediff-choose-syntax-table)
           
       (setq ediff-control-buffer-suffix
            (if (string-match "<[0-9]*>" control-buffer-name)
@@ -437,6 +459,10 @@ to invocation.")
       (if ediff-3way-job
          (ediff-with-current-buffer ediff-buffer-C
            (ediff-nuke-selective-display)
+           ;; the merge bufer should never be narrowed
+           ;; (it can happen if it is on rmail-mode or similar)
+           (if (ediff-with-current-buffer control-buffer ediff-merge-job)
+               (widen))
            (run-hooks 'ediff-prepare-buffer-hook)
            ;; add control-buffer to the list of sessions
            (or (memq control-buffer ediff-this-buffer-ediff-sessions)
@@ -444,7 +470,8 @@ to invocation.")
                      (cons control-buffer
                            ediff-this-buffer-ediff-sessions))) 
            (if ediff-make-buffers-readonly-at-startup
-               (setq buffer-read-only t))
+               (setq buffer-read-only t)
+             (setq buffer-read-only nil))
            ))
 
       (if (ediff-buffer-live-p ediff-ancestor-buffer)
@@ -458,7 +485,7 @@ to invocation.")
                            ediff-this-buffer-ediff-sessions)))
            ))
       
-      ;; must come after setting up  ediff-narrow-bounds AND after
+      ;; the following must be after setting up  ediff-narrow-bounds AND after
       ;; nuking selective display
       (funcall ediff-setup-diff-regions-function file-A file-B file-C)
       (setq ediff-number-of-differences (length ediff-difference-vector-A))
@@ -500,7 +527,7 @@ to invocation.")
       (ediff-visible-region)
       
       (run-hooks 'startup-hooks)
-      (ediff-arrange-auto-save-in-merge-jobs merge-buffer-file)
+      (ediff-arrange-autosave-in-merge-jobs merge-buffer-file)
 
       (ediff-refresh-mode-lines)
       (setq buffer-read-only t)
@@ -552,7 +579,7 @@ to invocation.")
     
 ;; This executes in control buffer and sets auto-save, visited file name, etc,
 ;; in the merge buffer
-(defun ediff-arrange-auto-save-in-merge-jobs (merge-buffer-file)
+(defun ediff-arrange-autosave-in-merge-jobs (merge-buffer-file)
   (if (not ediff-merge-job)
       ()
     (if (stringp merge-buffer-file)
@@ -561,6 +588,7 @@ to invocation.")
     (if (stringp ediff-merge-store-file)
        (progn
          ;; save before leaving ctl buffer
+         (ediff-verify-file-merge-buffer ediff-merge-store-file)
          (setq merge-buffer-file ediff-merge-store-file) 
          (ediff-with-current-buffer ediff-buffer-C
            (set-visited-file-name merge-buffer-file))))
@@ -583,7 +611,7 @@ if necessary."
   (if (and (ediff-buffer-live-p ediff-ancestor-buffer)
           (not
            (y-or-n-p
-            "Ancestor buffer will not be used. Recompute diffs anyway? ")))
+            "Ancestor buffer will not be used.  Recompute diffs anyway? ")))
       (error "Recomputation of differences canceled"))
       
   (let ((point-A (ediff-with-current-buffer ediff-buffer-A (point)))
@@ -642,7 +670,7 @@ if necessary."
     (ediff-clear-diff-vector 'ediff-difference-vector-C 'fine-diffs-also)
     (ediff-clear-diff-vector
      'ediff-difference-vector-Ancestor 'fine-diffs-also)
-    ;; let them garbage collect. we can't use the ancestor after recomputing
+    ;; let them garbage collect.  we can't use the ancestor after recomputing
     ;; the diffs.
     (setq ediff-difference-vector-Ancestor nil
          ediff-ancestor-buffer nil
@@ -678,9 +706,9 @@ if necessary."
     (message "")
     ))
     
-;; Not bound to any key---to dangerous. A user can do it if necessary.
+;; Not bound to any key---to dangerous.  A user can do it if necessary.
 (defun ediff-revert-buffers-then-recompute-diffs (noconfirm)
-  "Revert buffers A, B and C. Then rerun Ediff on file A and file B."
+  "Revert buffers A, B and C.  Then rerun Ediff on file A and file B."
   (interactive "P")
   (ediff-barf-if-not-control-buffer)
   (let ((bufA ediff-buffer-A)
@@ -882,36 +910,40 @@ Does nothing if file-A and file-B are in different frames."
 On a dumb terminal, switches between ASCII highlighting and no highlighting." 
   (interactive)
   (ediff-barf-if-not-control-buffer)
-  (if (not (ediff-has-face-support-p))
-      (if (eq ediff-highlighting-style 'ascii)
-         (progn
-           (message "ASCII highlighting flags removed")
-           (ediff-unselect-and-select-difference ediff-current-difference
-                                                 'unselect-only)
-           (setq ediff-highlighting-style 'off))
-       (ediff-unselect-and-select-difference ediff-current-difference
-                                             'select-only))
-    (ediff-unselect-and-select-difference ediff-current-difference
-                                         'unselect-only)
-    ;; cycle through highlighting
-    (cond ((and ediff-use-faces ediff-highlight-all-diffs)
-          (message "Unhighlighting unselected difference regions")
-          (setq ediff-highlight-all-diffs nil))
-         (ediff-use-faces
-          (message "Highlighting with ASCII flags")
-          (setq ediff-use-faces nil))
-         (t
-          (message "Re-highlighting all difference regions")
-          (setq ediff-use-faces t
-                ediff-highlight-all-diffs t)))
-                
-    (if (and ediff-use-faces ediff-highlight-all-diffs)
-       (ediff-paint-background-regions)
-      (ediff-paint-background-regions 'unhighlight))
-    
-    (ediff-unselect-and-select-difference
-     ediff-current-difference 'select-only))
-  )
+
+  (ediff-unselect-and-select-difference
+   ediff-current-difference 'unselect-only)
+  ;; cycle through highlighting
+  (cond ((and ediff-use-faces
+             (ediff-has-face-support-p)
+             ediff-highlight-all-diffs)
+        (message "Unhighlighting unselected difference regions")
+        (setq ediff-highlight-all-diffs  nil
+              ediff-highlighting-style  'face))
+       ((or (and ediff-use-faces  (ediff-has-face-support-p)
+                 (eq ediff-highlighting-style 'face))       ; has face support
+            (and (not (ediff-has-face-support-p))           ; no face support
+                 (eq ediff-highlighting-style 'off)))
+        (message "Highlighting with ASCII flags")
+        (setq ediff-highlighting-style  'ascii
+              ediff-highlight-all-diffs  nil
+              ediff-use-faces            nil))
+       ((eq ediff-highlighting-style 'ascii)
+        (message "ASCII highlighting flags removed")
+        (setq ediff-highlighting-style  'off
+              ediff-highlight-all-diffs  nil))
+       ((ediff-has-face-support-p)   ; catch-all for cases with face support
+        (message "Re-highlighting all difference regions")
+        (setq ediff-use-faces            t
+              ediff-highlighting-style  'face
+              ediff-highlight-all-diffs  t)))
+  
+  (if (and ediff-use-faces ediff-highlight-all-diffs)
+      (ediff-paint-background-regions)
+    (ediff-paint-background-regions 'unhighlight))
+  
+  (ediff-unselect-and-select-difference
+   ediff-current-difference 'select-only))
 
   
 (defun ediff-toggle-autorefine ()
@@ -947,8 +979,8 @@ On a dumb terminal, switches between ASCII highlighting and no highlighting."
          (t (set-window-buffer ediff-window-C ediff-ancestor-buffer)))))
        
 (defun ediff-make-or-kill-fine-diffs (arg)
-  "Compute fine diffs. With negative prefix arg, kill fine diffs.
-In both cases, operates on the currrent difference region." 
+  "Compute fine diffs.  With negative prefix arg, kill fine diffs.
+In both cases, operates on the current difference region." 
   (interactive "P")
   (ediff-barf-if-not-control-buffer)
   (cond ((eq arg '-)
@@ -1001,8 +1033,8 @@ of the current buffer."
                                  (file-writable 'toggle-read-only)
                                  (t (key-binding "\C-x\C-q")))))
        ;; If the file is checked in, make sure we don't make buffer modifiable
-       ;; without warning the user. The user can fool our checks by making the
-       ;; buffer non-RO without checking the file out. We regard this as a
+       ;; without warning the user.  The user can fool our checks by making the
+       ;; buffer non-RO without checking the file out.  We regard this as a
        ;; user problem.
        (if (and (ediff-file-checked-in-p file)
                 ;; If ctl-buf is null, this means we called this
@@ -1013,7 +1045,7 @@ of the current buffer."
                  ((and (or (beep 1) t) ; always beep
                        (y-or-n-p
                         (format
-                         "File %s is under version control. Check it out? "
+                         "File %s is under version control.  Check it out? "
                          (ediff-abbreviate-file-name file))))
                   ;; if we checked the file out, we should also change the
                   ;; original state of buffer-read-only to nil.  If we don't
@@ -1055,7 +1087,7 @@ of the current buffer."
             (or (beep 1) t)
             (y-or-n-p
              (format
-              "File %s is under version control. Check it out? "
+              "File %s is under version control.  Check it out? "
               (ediff-abbreviate-file-name file))))
        (ediff-with-current-buffer buf
          (command-execute checkout-function)))))
@@ -1089,11 +1121,24 @@ of the current buffer."
 (defsubst ediff-file-checked-out-p (file)
   (or (not (featurep 'vc-hooks))
       (and (vc-backend file)
-          (vc-locking-user file))))
+          (if (fboundp 'vc-state)
+              (or (memq (vc-state file) '(edited needs-merge))
+                  (stringp (vc-state file)))
+            ;; XEmacs has no vc-state
+            (vc-locking-user file))
+          )))
+  
 (defsubst ediff-file-checked-in-p (file)
   (and (featurep 'vc-hooks)
-       (vc-backend file)
-       (not (vc-locking-user file))))
+       ;; CVS files are considered not checked in
+       (not (memq (vc-backend file) '(nil CVS)))
+       (if (fboundp 'vc-state)
+          (progn
+            (not (memq (vc-state file) '(edited needs-merge)))
+            (not (stringp (vc-state file))))
+        ;; XEmacs has no vc-state
+        (not (vc-locking-user file)))
+       ))
 
 (defun ediff-file-compressed-p (file)
   (condition-case nil
@@ -1162,7 +1207,7 @@ of the current buffer."
                ediff-regexp-focus-B focus-regexp))
        
        ;; The following is needed for XEmacs, since there one can't move
-       ;; overlay to another buffer. In Emacs, this swap is redundant.
+       ;; overlay to another buffer.  In Emacs, this swap is redundant.
        (if (ediff-has-face-support-p)
            (if ediff-3way-comparison-job
                (setq ediff-current-diff-overlay-A ediff-current-diff-overlay-C
@@ -1256,10 +1301,9 @@ which see."
   ;; change default
   (setq-default ediff-window-setup-function window-setup-func)
   ;; change in all active ediff sessions
-  (mapcar (function (lambda(buf)
-                     (ediff-with-current-buffer buf
-                       (setq ediff-window-setup-function window-setup-func
-                             ediff-window-B nil))))
+  (mapcar (lambda(buf) (ediff-with-current-buffer buf
+                        (setq ediff-window-setup-function window-setup-func
+                              ediff-window-B nil)))
          ediff-session-registry)
   (if (ediff-in-control-buffer-p)
       (ediff-recenter 'no-rehighlight))))
@@ -1281,11 +1325,11 @@ To change the default, set the variable `ediff-use-toolbar-p', which see."
        ;; do this only after killing the toolbar
        (setq ediff-use-toolbar-p (not ediff-use-toolbar-p))
        
-       (mapcar (function (lambda(buf)
-                           (ediff-with-current-buffer buf
-                             ;; force redisplay
-                             (setq ediff-window-config-saved "")
-                             )))
+       (mapcar (lambda(buf)
+                 (ediff-with-current-buffer buf
+                   ;; force redisplay
+                   (setq ediff-window-config-saved "")
+                   ))
                ediff-session-registry)
        (if (ediff-in-control-buffer-p)
            (ediff-recenter 'no-rehighlight)))))
@@ -1300,9 +1344,13 @@ To change the default, set the variable `ediff-use-toolbar-p', which see."
   ;; will not re-appear after our cleanup here.  Is there a way
   ;; to do "push" and "pop" toolbars ?  --marcpa  
   (if (ediff-use-toolbar-p)
-      (progn
-       (set-specifier bottom-toolbar (list (selected-frame) nil))
-       (set-specifier bottom-toolbar-visible-p (list (selected-frame) nil)))))
+      (ediff-cond-compile-for-xemacs-or-emacs
+       (progn ; xemacs
+        (set-specifier bottom-toolbar (list (selected-frame) nil))
+        (set-specifier bottom-toolbar-visible-p (list (selected-frame) nil)))
+       nil  ; emacs
+       )
+    ))
 
 ;; If wants to use toolbar, make it.
 ;; If not, zero the toolbar for XEmacs.
@@ -1312,22 +1360,31 @@ To change the default, set the variable `ediff-use-toolbar-p', which see."
       (progn
        (setq frame (or frame (selected-frame)))
        (cond ((ediff-use-toolbar-p) ; this checks for XEmacs
-              (set-specifier
-               bottom-toolbar
-               (list frame (if (ediff-3way-comparison-job)
-                               ediff-toolbar-3way ediff-toolbar)))
-              (set-specifier bottom-toolbar-visible-p (list frame t)) 
-              (set-specifier bottom-toolbar-height
-                             (list frame ediff-toolbar-height)))
+              (ediff-cond-compile-for-xemacs-or-emacs
+               (progn ; xemacs
+                 (set-specifier
+                  bottom-toolbar
+                  (list frame (if (ediff-3way-comparison-job)
+                                  ediff-toolbar-3way ediff-toolbar)))
+                 (set-specifier bottom-toolbar-visible-p (list frame t)) 
+                 (set-specifier bottom-toolbar-height
+                                (list frame ediff-toolbar-height)))
+               nil ; emacs
+               )
+              )
              ((ediff-has-toolbar-support-p)
-              (set-specifier bottom-toolbar-height (list frame 0)))
+              (ediff-cond-compile-for-xemacs-or-emacs
+               (set-specifier bottom-toolbar-height (list frame 0)) ; xemacs
+               nil                                                  ; emacs
+               )
+              )
              ))
     ))
               
 ;; Merging
 
 (defun ediff-toggle-show-clashes-only ()
-  "Toggle the mode where only the regions where both buffers differ with the ancestor are shown."
+  "Toggle the mode that shows only the merge regions where both variants differ from the ancestor."
   (interactive)
   (ediff-barf-if-not-control-buffer)
   (if (not ediff-merge-with-ancestor-job)
@@ -1336,6 +1393,18 @@ To change the default, set the variable `ediff-use-toolbar-p', which see."
   (if ediff-show-clashes-only
       (message "Focus on regions where both buffers differ from the ancestor")
     (message "Canceling focus on regions where changes clash")))
+
+(defun ediff-toggle-skip-changed-regions ()
+  "Toggle the mode that skips the merge regions that differ from the default."
+  (interactive)
+  (ediff-barf-if-not-control-buffer)
+  (setq ediff-skip-merge-regions-that-differ-from-default
+       (not ediff-skip-merge-regions-that-differ-from-default))
+  (if ediff-skip-merge-regions-that-differ-from-default
+      (message "Skipping regions that differ from default setting")
+    (message "Showing regions that differ from default setting")))
+
+
               
 ;; Widening/narrowing
 
@@ -1350,7 +1419,7 @@ Used in ediff-windows/regions only."
     (setq ediff-visible-bounds ediff-wide-bounds))
   (ediff-recenter 'no-rehighlight))
   
-;; Narrow bufs A/B/C to ediff-visible-bounds. If this is currently set to
+;; Narrow bufs A/B/C to ediff-visible-bounds.  If this is currently set to
 ;; ediff-wide-bounds, then this actually widens.
 ;; This function does nothing if job-name is not
 ;; ediff-regions-wordwise/linewise or ediff-windows-wordwise/linewise. 
@@ -1493,9 +1562,17 @@ the width of the A/B/C windows."
       (error ediff-KILLED-VITAL-BUFFER))
     
   (ediff-operate-on-windows
+   ;; Arrange for scroll-left and scroll-right being called
+   ;; interactively so that they set the window's min_hscroll.
+   ;; Otherwise, automatic hscrolling will undo the effect of
+   ;; hscrolling.
    (if (= last-command-char ?<)
-       'scroll-left
-     'scroll-right)
+       (lambda (arg) 
+        (let ((prefix-arg arg))
+          (call-interactively 'scroll-left)))
+     (lambda (arg)
+       (let ((prefix-arg arg))
+        (call-interactively 'scroll-right))))
    ;; calculate argument to scroll-left/right
    ;; if there is an explicit argument
    (if (and arg (not (equal arg '-)))
@@ -1524,7 +1601,7 @@ the width of the A/B/C windows."
 
 
 ;;BEG, END show the region to be positioned.
-;;JOB-NAME holds ediff-job-name. The ediff-windows job positions regions
+;;JOB-NAME holds ediff-job-name.  The ediff-windows job positions regions
 ;;differently. 
 (defun ediff-position-region (beg end pos job-name)
   (if (> end (point-max))
@@ -1632,30 +1709,40 @@ With a prefix argument, go forward that many differences."
   (if (< ediff-current-difference ediff-number-of-differences)
       (let ((n (min ediff-number-of-differences
                    (+ ediff-current-difference (or arg 1))))
-           non-clash-skip regexp-skip)
+           non-clash-skip skip-changed regexp-skip)
            
        (ediff-visible-region)
        (or (>= n ediff-number-of-differences)
            (setq regexp-skip (funcall ediff-skip-diff-region-function n))
            ;; this won't exec if regexp-skip is t
-           (setq non-clash-skip (ediff-merge-region-is-non-clash n))
+           (setq non-clash-skip (ediff-merge-region-is-non-clash n)
+                 skip-changed 
+                 (ediff-skip-merge-region-if-changed-from-default-p n))
            (ediff-install-fine-diff-if-necessary n))
+       ;; Skip loop
        (while (and (< n ediff-number-of-differences)
                    (or
                     ;; regexp skip
                     regexp-skip
                     ;; skip clashes, if necessary
                     non-clash-skip
+                    ;; skip processed regions
+                    skip-changed
                     ;; skip difference regions that differ in white space
                     (and ediff-ignore-similar-regions
-                         (eq (ediff-no-fine-diffs-p n) t))))
+                         (or (eq (ediff-no-fine-diffs-p n) t)
+                             (and (ediff-merge-job)
+                                  (eq (ediff-no-fine-diffs-p n) 'C)))
+                         )))
          (setq n (1+ n))
          (if (= 0 (mod n 20))
              (message "Skipped over region %d and counting ..."  n))
          (or (>= n ediff-number-of-differences)
              (setq regexp-skip (funcall ediff-skip-diff-region-function n))
              ;; this won't exec if regexp-skip is t
-             (setq non-clash-skip (ediff-merge-region-is-non-clash n))
+             (setq non-clash-skip (ediff-merge-region-is-non-clash n)
+                   skip-changed
+                   (ediff-skip-merge-region-if-changed-from-default-p n))
              (ediff-install-fine-diff-if-necessary n))
          )
        (message "")
@@ -1671,13 +1758,15 @@ With a prefix argument, go back that many differences."
   (ediff-barf-if-not-control-buffer)
   (if (> ediff-current-difference -1)
       (let ((n (max -1 (- ediff-current-difference (or arg 1))))
-           non-clash-skip regexp-skip)
+           non-clash-skip skip-changed regexp-skip)
            
        (ediff-visible-region)
        (or (< n 0)
            (setq regexp-skip (funcall ediff-skip-diff-region-function n))
            ;; this won't exec if regexp-skip is t
-           (setq non-clash-skip (ediff-merge-region-is-non-clash n))
+           (setq non-clash-skip (ediff-merge-region-is-non-clash n)
+                 skip-changed 
+                 (ediff-skip-merge-region-if-changed-from-default-p n))
            (ediff-install-fine-diff-if-necessary n))
        (while (and (> n -1)
                    (or
@@ -1685,16 +1774,23 @@ With a prefix argument, go back that many differences."
                     regexp-skip
                     ;; skip clashes, if necessary
                     non-clash-skip
+                    ;; skipp changed regions
+                    skip-changed
                     ;; skip difference regions that differ in white space
                     (and ediff-ignore-similar-regions
-                         (eq (ediff-no-fine-diffs-p n) t))))
+                         (or (eq (ediff-no-fine-diffs-p n) t)
+                             (and (ediff-merge-job)
+                                  (eq (ediff-no-fine-diffs-p n) 'C)))
+                         )))
          (if (= 0 (mod (1+ n) 20))
              (message "Skipped over region %d and counting ..."  (1+ n)))
          (setq n (1- n))
          (or (< n 0)
              (setq regexp-skip (funcall ediff-skip-diff-region-function n))
              ;; this won't exec if regexp-skip is t
-             (setq non-clash-skip (ediff-merge-region-is-non-clash n))
+             (setq non-clash-skip (ediff-merge-region-is-non-clash n)
+                   skip-changed
+                   (ediff-skip-merge-region-if-changed-from-default-p n))
              (ediff-install-fine-diff-if-necessary n))
          )
        (message "")
@@ -1726,8 +1822,8 @@ If the prefix is negative, count differences from the end."
 (defun ediff-jump-to-difference-at-point (arg)
   "Go to difference closest to the point in buffer A, B, or C.
 The buffer depends on last command character \(a, b, or c\) that invoked this
-command. For instance, if the command was `ga' then the point value in buffer A
-is used.
+command.  For instance, if the command was `ga' then the point value in buffer
+is used.
 With a prefix argument, synchronize all files around the current point position
 in the specified buffer."
   (interactive "P")
@@ -1782,9 +1878,9 @@ in the specified buffer."
 ;; find region most related to the current point position (or POS, if given)
 ;; returns diff number as seen by the user (i.e., 1+ the internal
 ;; representation) 
-;; The optional argument WHICH-DIFF can be `after' or `before'. If `after',
-;; find the diff after the point. If `before', find the diff before the
-;; point. If the point is inside a diff, return that diff.
+;; The optional argument WHICH-DIFF can be `after' or `before'.  If `after',
+;; find the diff after the point.  If `before', find the diff before the
+;; point.  If the point is inside a diff, return that diff.
 (defun ediff-diff-at-point (buf-type &optional pos which-diff)
   (let ((buffer (ediff-get-buffer buf-type))
        (ctl-buffer ediff-control-buffer)
@@ -1829,7 +1925,7 @@ If numerical prefix argument, copy the difference specified in the arg.
 Otherwise, copy the difference given by `ediff-current-difference'.
 This command assumes it is bound to a 2-character key sequence, `ab', `ba',
 `ac', etc., which is used to determine the types of buffers to be used for
-copying difference regions. The first character in the sequence specifies
+copying difference regions.  The first character in the sequence specifies
 the source buffer and the second specifies the target.
 
 If the second optional argument, a 2-character string, is given, use it to
@@ -1842,8 +1938,8 @@ determine the source and the target buffers instead of the command keys."
 
   (let* ((key1 (aref keys 0))
         (key2 (aref keys 1))
-        (char1 (if (and ediff-xemacs-p (eventp key1)) (event-key key1) key1))
-        (char2 (if (and ediff-xemacs-p (eventp key1)) (event-key key2) key2))
+        (char1 (ediff-event-key key1))
+        (char2 (ediff-event-key key2))
         ediff-verbose-p)
     (ediff-copy-diff ediff-current-difference
                     (ediff-char-to-buftype char1)
@@ -1853,37 +1949,37 @@ determine the source and the target buffers instead of the command keys."
 
 (defun ediff-copy-A-to-B (arg)
   "Copy ARGth difference region from buffer A to B.
-ARG is a prefix argument. If nil, copy the current difference region."
+ARG is a prefix argument.  If nil, copy the current difference region."
   (interactive "P")
   (ediff-diff-to-diff arg "ab"))
 
 (defun ediff-copy-B-to-A (arg)
   "Copy ARGth difference region from buffer B to A.
-ARG is a prefix argument. If nil, copy the current difference region."
+ARG is a prefix argument.  If nil, copy the current difference region."
   (interactive "P")
   (ediff-diff-to-diff arg "ba"))
 
 (defun ediff-copy-A-to-C (arg)
   "Copy ARGth difference region from buffer A to buffer C.
-ARG is a prefix argument. If nil, copy the current difference region."
+ARG is a prefix argument.  If nil, copy the current difference region."
   (interactive "P")
   (ediff-diff-to-diff arg "ac"))
 
 (defun ediff-copy-B-to-C (arg)
   "Copy ARGth difference region from buffer B to buffer C.
-ARG is a prefix argument. If nil, copy the current difference region."
+ARG is a prefix argument.  If nil, copy the current difference region."
   (interactive "P")
   (ediff-diff-to-diff arg "bc"))
 
 (defun ediff-copy-C-to-B (arg)
   "Copy ARGth difference region from buffer C to B.
-ARG is a prefix argument. If nil, copy the current difference region."
+ARG is a prefix argument.  If nil, copy the current difference region."
   (interactive "P")
   (ediff-diff-to-diff arg "cb"))
 
 (defun ediff-copy-C-to-A (arg)
   "Copy ARGth difference region from buffer C to A.
-ARG is a prefix argument. If nil, copy the current difference region."
+ARG is a prefix argument.  If nil, copy the current difference region."
   (interactive "P")
   (ediff-diff-to-diff arg "ca"))
 
@@ -1891,7 +1987,7 @@ ARG is a prefix argument. If nil, copy the current difference region."
 
 ;; Copy diff N from FROM-BUF-TYPE \(given as A, B or C\) to TO-BUF-TYPE.
 ;; If optional DO-NOT-SAVE is non-nil, do not save the old value of the
-;; target diff. This is used in merging, when constructing the merged
+;; target diff.  This is used in merging, when constructing the merged
 ;; version.
 (defun ediff-copy-diff (n from-buf-type to-buf-type
                          &optional batch-invocation reg-to-copy)
@@ -1960,7 +2056,7 @@ ARG is a prefix argument. If nil, copy the current difference region."
       (ediff-refresh-mode-lines)
       
       ;; For diff2 jobs, don't recompute fine diffs, since we know there
-      ;; aren't any. So we clear diffs after ediff-recenter.
+      ;; aren't any.  So we clear diffs after ediff-recenter.
       (if (and saved-p (not three-way))
          (ediff-clear-fine-differences n))
       ;; Make sure that the message about saving and how to restore is seen
@@ -1986,7 +2082,7 @@ ARG is a prefix argument. If nil, copy the current difference region."
        (setq ediff-killed-diffs-alist  ;; create record for n-th diff
              (cons (list n (cons buf reg))
                    ediff-killed-diffs-alist))))
-    (message "Saving old diff region #%d of buffer %S. To recover, type `r%s'"
+    (message "Saving old diff region #%d of buffer %S.  To recover, type `r%s'"
             (1+ n) buf-type
             (if ediff-merge-job
                 "" (downcase (symbol-name buf-type))))
@@ -2001,7 +2097,7 @@ ARG is a prefix argument. If nil, copy the current difference region."
     (if this-buf-n-th-diff-saved
        (if (yes-or-no-p
             (format 
-             "You've previously copied diff region %d to buffer %S. Confirm "
+             "You've previously copied diff region %d to buffer %S.  Confirm "
              (1+ n) buf-type))
            t
          (error "Quit"))
@@ -2044,7 +2140,7 @@ ARG is a prefix argument. If nil, copy the current difference region."
             (beep 1)))
     
     ;; Clearing fine diffs is necessary for
-    ;; ediff-unselect-and-select-difference to properly recompute them. We
+    ;; ediff-unselect-and-select-difference to properly recompute them.  We
     ;; can't rely on ediff-copy-diff to clear this vector, as the user might
     ;; have modified diff regions after copying and, thus, may have recomputed
     ;; fine diffs.
@@ -2081,7 +2177,7 @@ determine the target buffer instead of last-command-char"
 
 (defun ediff-restore-diff-in-merge-buffer (arg)
   "Restore ARGth diff in the merge buffer.
-ARG is a prefix argument. If nil, restore the current diff."
+ARG is a prefix argument.  If nil, restore the current diff."
   (interactive "P")
   (ediff-restore-diff arg ?c))
   
@@ -2202,7 +2298,7 @@ doesn't match `ediff-regexp-focus-B'.
 This function returns nil if the region number N (specified as
 an argument) is not to be ignored and t if region N is to be ignored.
 
-N is a region number used by Ediff internally. It is 1 less
+N is a region number used by Ediff internally.  It is 1 less
 the number seen by the user."
   (if (ediff-valid-difference-p n)
       (let* ((ctl-buf ediff-control-buffer)
@@ -2243,7 +2339,7 @@ Regions to be ignored are those where buf A region matches
 This function returns nil if the region number N (specified as
 an argument) is not to be ignored and t if region N is to be ignored.
 
-N is a region number used by Ediff internally. It is 1 less
+N is a region number used by Ediff internally.  It is 1 less
 the number seen by the user."
   (if (ediff-valid-difference-p n)
       (let* ((ctl-buf ediff-control-buffer)
@@ -2290,7 +2386,7 @@ flags of the compared file buffers, kills Ediff buffers for this session
 
 If `ediff-keep-variants' is nil, the user will be asked whether the buffers
 containing the variants should be removed \(if they haven't been modified\). 
-If it is t, they will be preserved unconditionally. A prefix argument, 
+If it is t, they will be preserved unconditionally.  A prefix argument, 
 temporarily reverses the meaning of this variable."
   (interactive "P")
   (ediff-barf-if-not-control-buffer)
@@ -2315,7 +2411,7 @@ temporarily reverses the meaning of this variable."
 
   (ediff-delete-temp-files)
                                  
-  ;; Restore visibility range. This affects only ediff-*-regions/windows.
+  ;; Restore the visibility range.  This affects only ediff-*-regions/windows.
   ;; Since for other job names ediff-visible-region sets
   ;; ediff-visible-bounds to ediff-wide-bounds, the settings below are
   ;; ignored for such jobs.
@@ -2325,18 +2421,19 @@ temporarily reverses the meaning of this variable."
   
   ;; Apply selective display to narrow or widen
   (ediff-visible-region)
-  (mapcar (function (lambda (overl)
-                     (if (ediff-overlayp overl)
-                         (ediff-delete-overlay overl))))
+  (mapcar (lambda (overl)
+           (if (ediff-overlayp overl)
+               (ediff-delete-overlay overl)))
          ediff-wide-bounds)
-  (mapcar (function (lambda (overl)
-                     (if (ediff-overlayp overl)
-                         (ediff-delete-overlay overl))))
+  (mapcar (lambda (overl)
+           (if (ediff-overlayp overl)
+               (ediff-delete-overlay overl)))
          ediff-narrow-bounds)
 
   ;; restore buffer mode line id's in buffer-A/B/C
   (let ((control-buffer ediff-control-buffer)
        (meta-buffer ediff-meta-buffer)
+       (after-quit-hook-internal ediff-after-quit-hook-internal)
        (session-number ediff-meta-session-number)
        ;; suitable working frame
        (warp-frame (if (and (ediff-window-display-p) (eq ediff-grab-mouse t))
@@ -2394,13 +2491,18 @@ temporarily reverses the meaning of this variable."
          (run-hooks 'ediff-quit-merge-hook))
     (quit))
 
-  ;; good place to kill buffers A/B/C
   (run-hooks 'ediff-cleanup-hook)
-  (let ((ediff-keep-variants ediff-keep-variants))
-    (if reverse-default-keep-variants
-       (setq ediff-keep-variants (not ediff-keep-variants)))
-    (or ediff-keep-variants (ediff-janitor 'ask)))
 
+  (ediff-janitor
+   'ask
+   ;; reverse-default-keep-variants is t if the user quits with a prefix arg
+   (if reverse-default-keep-variants
+       (not ediff-keep-variants)
+     ediff-keep-variants))
+
+  ;; one hook here is ediff-cleanup-mess, which kills the control buffer and
+  ;; other auxiliary buffers. we made it into a hook to let the users do their
+  ;; own cleanup, if needed.
   (run-hooks 'ediff-quit-hook)
   (ediff-update-meta-buffer meta-buffer nil session-number)
 
@@ -2408,18 +2510,17 @@ temporarily reverses the meaning of this variable."
   (setq warp-frame  ; if mouse is over a reasonable frame, use it
        (cond ((ediff-good-frame-under-mouse))
              (t warp-frame)))
-  (if (frame-live-p warp-frame)
+  (if (and (ediff-window-display-p) (frame-live-p warp-frame) ediff-grab-mouse)
       (set-mouse-position (if ediff-emacs-p
                              warp-frame
                            (frame-selected-window warp-frame))
                          2 1))
 
-  (if (ediff-buffer-live-p meta-buffer)
-      (ediff-show-meta-buffer meta-buffer session-number))
+  (run-hooks 'after-quit-hook-internal)
   ))
 
 ;; Returns frame under mouse, if this frame is not a minibuffer
-;; frame. Otherwise: nil
+;; frame.  Otherwise: nil
 (defun ediff-good-frame-under-mouse ()
   (let ((frame-or-win (car (mouse-position)))
        (buf-name "")
@@ -2449,13 +2550,17 @@ temporarily reverses the meaning of this variable."
 ;; Kill control buffer, other auxiliary Ediff buffers.
 ;; Leave one of the frames split between buffers A/B/C
 (defun ediff-cleanup-mess ()
-  (let ((buff-A ediff-buffer-A)
-       (buff-B ediff-buffer-B)
-       (buff-C ediff-buffer-C)
-       (ctl-buf  ediff-control-buffer)
-       (ctl-frame ediff-control-frame)
-       (three-way-job ediff-3way-job))
-       
+  (let* ((buff-A ediff-buffer-A)
+        (buff-B ediff-buffer-B)
+        (buff-C ediff-buffer-C)
+        (ctl-buf  ediff-control-buffer)
+        (ctl-frame ediff-control-frame)
+        (three-way-job ediff-3way-job)
+        (main-frame (cond ((window-live-p ediff-window-A) 
+                           (window-frame ediff-window-A))
+                          ((window-live-p ediff-window-B) 
+                           (window-frame ediff-window-B)))))
+    
     (ediff-kill-buffer-carefully ediff-diff-buffer)
     (ediff-kill-buffer-carefully ediff-custom-diff-buffer)
     (ediff-kill-buffer-carefully ediff-fine-diff-buffer)
@@ -2474,7 +2579,8 @@ temporarily reverses the meaning of this variable."
 
     (ediff-kill-buffer-carefully ctl-buf)
       
-    (delete-other-windows)
+    (if (frame-live-p main-frame)
+       (select-frame main-frame))
     
     ;; display only if not visible
     (condition-case nil
@@ -2484,7 +2590,8 @@ temporarily reverses the meaning of this variable."
     (condition-case nil
        (or (ediff-get-visible-buffer-window buff-A)
            (progn
-             (if (ediff-get-visible-buffer-window buff-B)
+             (if (and (ediff-get-visible-buffer-window buff-B)
+                      (ediff-buffer-live-p buff-A))
                  (funcall ediff-split-window-function))
              (switch-to-buffer buff-A)))
       (error))
@@ -2492,8 +2599,9 @@ temporarily reverses the meaning of this variable."
        (condition-case nil
            (or (ediff-get-visible-buffer-window buff-C)
                (progn
-                 (if (or (ediff-get-visible-buffer-window buff-A)
-                         (ediff-get-visible-buffer-window buff-B))
+                 (if (and (or (ediff-get-visible-buffer-window buff-A)
+                              (ediff-get-visible-buffer-window buff-B))
+                          (ediff-buffer-live-p buff-C))
                      (funcall ediff-split-window-function))
                  (switch-to-buffer buff-C)
                  (balance-windows)))
@@ -2501,46 +2609,63 @@ temporarily reverses the meaning of this variable."
     (message "")
     ))
 
-(defun ediff-janitor (&optional ask)
+(defun ediff-janitor (ask keep-variants)
   "Kill buffers A, B, and, possibly, C, if these buffers aren't modified.
-In merge jobs, buffer C is never deleted.
-However, the side effect of cleaning up may be that you cannot compare the same
-buffer in two separate Ediff sessions: quitting one of them will delete this
-buffer in another session as well."
-  (or (not (ediff-buffer-live-p ediff-buffer-A))
-      (buffer-modified-p ediff-buffer-A)
-      (and ask
-          (not (y-or-n-p (format "Kill buffer A [%s]? "
-                                 (buffer-name ediff-buffer-A)))))
-      (ediff-kill-buffer-carefully ediff-buffer-A))
-  (or (not (ediff-buffer-live-p ediff-buffer-B))
-      (buffer-modified-p ediff-buffer-B)
-      (and ask
-          (not (y-or-n-p (format "Kill buffer B [%s]? "
-                                 (buffer-name ediff-buffer-B)))))
-      (ediff-kill-buffer-carefully ediff-buffer-B))
+In merge jobs, buffer C is not deleted here, but rather according to
+ediff-quit-merge-hook.
+A side effect of cleaning up may be that you should be careful when comparing
+the same buffer in two separate Ediff sessions: quitting one of them might
+delete this buffer in another session as well."
+  (ediff-dispose-of-variant-according-to-user
+   ediff-buffer-A 'A ask keep-variants)
+  (ediff-dispose-of-variant-according-to-user
+   ediff-buffer-B 'B ask keep-variants)
   (if ediff-merge-job  ; don't del buf C if merging--del ancestor buf instead
-      (or (not (ediff-buffer-live-p ediff-ancestor-buffer))
-         (buffer-modified-p ediff-ancestor-buffer)
-         (and ask
-              (not (y-or-n-p (format "Kill the ancestor buffer [%s]? "
-                                     (buffer-name ediff-ancestor-buffer)))))
-         (ediff-kill-buffer-carefully ediff-ancestor-buffer))
-    (or (not (ediff-buffer-live-p ediff-buffer-C))
-       (buffer-modified-p ediff-buffer-C)
-       (and ask (not (y-or-n-p (format "Kill buffer C [%s]? "
-                                       (buffer-name ediff-buffer-C)))))
-       (ediff-kill-buffer-carefully ediff-buffer-C))))
+      (ediff-dispose-of-variant-according-to-user
+       ediff-ancestor-buffer 'Ancestor ask keep-variants)
+    (ediff-dispose-of-variant-according-to-user
+     ediff-buffer-C 'C ask keep-variants)
+    ))
+
+;; Kill the variant buffer, according to user directives (ask, kill
+;; unconditionaly, keep)
+;; BUFF is the buffer, BUFF-TYPE is either 'A, or 'B, 'C, 'Ancestor
+(defun ediff-dispose-of-variant-according-to-user (buff bufftype ask keep-variants)
+  ;; if this is indirect buffer, kill it and substitute with direct buf
+  (if (and (ediff-buffer-live-p buff)
+          (ediff-with-current-buffer buff ediff-temp-indirect-buffer))
+      (let ((wind (ediff-get-visible-buffer-window buff))
+           (base (buffer-base-buffer buff))
+           (modified-p (buffer-modified-p buff)))
+       (if (and (window-live-p wind) (ediff-buffer-live-p base))
+           (set-window-buffer wind base))
+       ;; Kill indirect buffer even if it is modified, because the base buffer
+       ;; is still there. Note that if the base buffer is dead then so will be
+       ;; the indirect buffer
+       (ediff-with-current-buffer buff 
+         (set-buffer-modified-p nil))
+       (ediff-kill-buffer-carefully buff)
+       (ediff-with-current-buffer base
+         (set-buffer-modified-p modified-p)))
+    ;; otherwise, ask or use the value of keep-variants
+    (or (not (ediff-buffer-live-p buff))
+       keep-variants
+       (buffer-modified-p buff)
+       (and ask
+            (not (y-or-n-p (format "Kill buffer %S [%s]? "
+                                   bufftype (buffer-name buff)))))
+       (ediff-kill-buffer-carefully buff))
+    ))
 
 (defun ediff-maybe-save-and-delete-merge (&optional save-and-continue)
   "Default hook to run on quitting a merge job.
 This can also be used to save merge buffer in the middle of an Ediff session.
 
 If the optional SAVE-AND-CONTINUE argument is non-nil, save merge buffer and
-continue. Otherwise:
+continue.  Otherwise:
 If `ediff-autostore-merges' is nil, this does nothing.
 If it is t, it saves the merge buffer in the file `ediff-merge-store-file'
-or asks the user, if the latter is nil. It then asks the user whether to
+or asks the user, if the latter is nil.  It then asks the user whether to
 delete the merge buffer.
 If `ediff-autostore-merges' is neither nil nor t, the merge buffer is saved
 only if this merge job is part of a group, i.e., was invoked from within
@@ -2549,7 +2674,7 @@ only if this merge job is part of a group, i.e., was invoked from within
        (ediff-autostore-merges ; fake ediff-autostore-merges, if necessary
         (if save-and-continue t ediff-autostore-merges)))
     (if ediff-autostore-merges
-       (cond ((stringp ediff-merge-store-file)
+       (cond ((stringp merge-store-file)
               ;; store, ask to delete
               (ediff-write-merge-buffer-and-maybe-kill
                ediff-buffer-C merge-store-file 'show-file save-and-continue))
@@ -2562,35 +2687,45 @@ only if this merge job is part of a group, i.e., was invoked from within
              ((and (ediff-buffer-live-p ediff-meta-buffer)
                    (ediff-with-current-buffer ediff-meta-buffer
                      (ediff-merge-metajob)))
-              ;; This case shouldn't occur, as the parent metajob must pass on
-              ;; a file name, ediff-merge-store-file, where to save the result
-              ;; of the merge.
-              ;; Ask where to save anyway--will decide what to do here later.
-              (setq merge-store-file
-                    (read-file-name "Save the merge buffer in file: "))
-              (ediff-write-merge-buffer-and-maybe-kill
-               ediff-buffer-C merge-store-file nil save-and-continue))))
+              ;; The parent metajob passed nil as the autostore file.
+              nil)))
     ))
 
-;; write merge buffer. If the optional argument save-and-continue is non-nil,
+;; write merge buffer.  If the optional argument save-and-continue is non-nil,
 ;; then don't kill the merge buffer
 (defun ediff-write-merge-buffer-and-maybe-kill (buf file
                                               &optional
                                               show-file save-and-continue)
-  (ediff-with-current-buffer buf
-    (if (or (not (file-exists-p file))
-           (y-or-n-p (format "File %s exists, overwrite? " file)))
-       (progn
-         (write-region (point-min) (point-max) file)
-         (if show-file
-             (progn
-               (message "Merge buffer saved in: %s" file)
-               (set-buffer-modified-p nil)
-               (sit-for 2)))
-         (if (and
-              (not save-and-continue)
-              (y-or-n-p "Merge buffer saved in file. Now kill the buffer? "))
-             (ediff-kill-buffer-carefully buf))))))
+  (if (not (eq (find-buffer-visiting file) buf))
+      (let ((warn-message
+            (format "Another buffer is visiting file %s. Too dangerous to save the merge buffer"
+                    file)))
+       (beep)
+       (message warn-message)
+       (with-output-to-temp-buffer ediff-msg-buffer
+         (princ "\n\n")
+         (princ warn-message)
+         (princ "\n\n")
+         )
+       (sit-for 2))
+    (ediff-with-current-buffer buf
+      (if (or (not (file-exists-p file))
+             (y-or-n-p (format "File %s exists, overwrite? " file)))
+         (progn
+           ;;(write-region (point-min) (point-max) file)
+           (ediff-with-current-buffer buf
+             (set-visited-file-name file)
+             (save-buffer))
+           (if show-file
+               (progn
+                 (message "Merge buffer saved in: %s" file)
+                 (set-buffer-modified-p nil)
+                 (sit-for 3)))
+           (if (and
+                (not save-and-continue)
+                (y-or-n-p "Merge buffer saved.  Now kill the buffer? "))
+               (ediff-kill-buffer-carefully buf)))))
+    ))
 
 ;; The default way of suspending Ediff.
 ;; Buries Ediff buffers, kills all windows.
@@ -2669,6 +2804,8 @@ Hit \\[ediff-recenter] to reset the windows afterward."
   (save-excursion
     (ediff-skip-unsuitable-frames))
   (with-output-to-temp-buffer ediff-msg-buffer
+    (ediff-with-current-buffer standard-output
+      (fundamental-mode))
     (raise-frame (selected-frame))
     (princ (ediff-version))
     (princ "\n\n")
@@ -2728,6 +2865,9 @@ Hit \\[ediff-recenter] to reset the windows afterward."
     (if (and ediff-merge-job ediff-show-clashes-only)
        (princ
         "\nFocusing on regions where both buffers differ from the ancestor"))
+    (if (and ediff-skip-merge-regions-that-differ-from-default ediff-merge-job)
+       (princ
+        "\nSkipping merge regions that differ from default setting"))
     
     (cond ((eq ediff-skip-diff-region-function 'ediff-show-all-diffs)
           (princ "\nSelective browsing by regexp is off\n"))
@@ -2773,23 +2913,22 @@ Hit \\[ediff-recenter] to reset the windows afterward."
           (ediff-buffer-live-p ediff-buffer-B)
           (ediff-valid-difference-p n))
       (progn
-       (if (and (ediff-has-face-support-p) ediff-use-faces)
-           (progn
-             (ediff-highlight-diff n)
-             (setq ediff-highlighting-style 'face))
-         (setq ediff-highlighting-style 'ascii)
-         (ediff-place-flags-in-buffer
-          'A ediff-buffer-A ediff-control-buffer n)
-         (ediff-place-flags-in-buffer
-          'B ediff-buffer-B ediff-control-buffer n)
-         (if ediff-3way-job
-             (ediff-place-flags-in-buffer
-              'C ediff-buffer-C ediff-control-buffer n))
-         (if (ediff-buffer-live-p ediff-ancestor-buffer)
-             (ediff-place-flags-in-buffer
-              'Ancestor ediff-ancestor-buffer
-              ediff-control-buffer n))
-         ) 
+       (cond
+           ((and (ediff-has-face-support-p) ediff-use-faces)
+              (ediff-highlight-diff n))
+           ((eq ediff-highlighting-style 'ascii)
+            (ediff-place-flags-in-buffer
+             'A ediff-buffer-A ediff-control-buffer n)
+            (ediff-place-flags-in-buffer
+             'B ediff-buffer-B ediff-control-buffer n)
+            (if ediff-3way-job
+                (ediff-place-flags-in-buffer
+                 'C ediff-buffer-C ediff-control-buffer n))
+            (if (ediff-buffer-live-p ediff-ancestor-buffer)
+                (ediff-place-flags-in-buffer
+                 'Ancestor ediff-ancestor-buffer
+                 ediff-control-buffer n))
+            )) 
                                       
        (ediff-install-fine-diff-if-necessary n)
        (run-hooks 'ediff-select-hook))))
@@ -2818,7 +2957,6 @@ Hit \\[ediff-recenter] to reset the windows afterward."
                    ediff-ancestor-buffer
                    (ediff-get-diff-overlay n 'Ancestor)))
               ))
-       (setq ediff-highlighting-style nil)
        
        ;; unhighlight fine diffs
        (ediff-set-fine-diff-properties ediff-current-difference 'default)
@@ -2847,18 +2985,106 @@ Hit \\[ediff-recenter] to reset the windows afterward."
          (setq ediff-current-difference n)
          ) ; end protected section
       
-      (ediff-with-current-buffer control-buf (ediff-refresh-mode-lines))
-      )))
+      (ediff-with-current-buffer control-buf (ediff-refresh-mode-lines)))
+    ))
+
 
 
-(defun ediff-read-file-name (prompt default-dir default-file)
-; This is a modified version of a similar function in `emerge.el'.
-; PROMPT should not have trailing ': ', so that it can be modified
-; according to context.
-; If default-file is set, it should be used as the default value.
-; If default-dir is non-nil, use it as the default directory.
-; Otherwise, use the value of Emacs' variable `default-directory.'
+(defun ediff-highlight-diff-in-one-buffer (n buf-type)
+  (if (ediff-buffer-live-p (ediff-get-buffer buf-type))
+      (let* ((buff (ediff-get-buffer buf-type))
+            (last (ediff-with-current-buffer buff (point-max)))
+            (begin (ediff-get-diff-posn buf-type 'beg n))
+            (end (ediff-get-diff-posn buf-type 'end n))
+            (xtra (if (equal begin end) 1 0))
+            (end-hilit (min last (+ end xtra)))
+            (current-diff-overlay
+             (symbol-value
+              (ediff-get-symbol-from-alist
+               buf-type ediff-current-diff-overlay-alist))))
+
+       (if ediff-xemacs-p
+           (ediff-move-overlay current-diff-overlay begin end-hilit)
+         (ediff-move-overlay current-diff-overlay begin end-hilit buff))
+       (ediff-overlay-put current-diff-overlay 'priority
+                          (ediff-highest-priority begin end-hilit buff))
+       (ediff-overlay-put current-diff-overlay 'ediff-diff-num n)
+
+       ;; unhighlight the background overlay for diff n so it won't
+       ;; interfere with the current diff overlay
+       (ediff-set-overlay-face (ediff-get-diff-overlay n buf-type) nil)
+       )))
+
+
+(defun ediff-unhighlight-diff-in-one-buffer (buf-type)
+  (if (ediff-buffer-live-p (ediff-get-buffer buf-type))
+      (let ((current-diff-overlay
+            (symbol-value
+             (ediff-get-symbol-from-alist
+              buf-type ediff-current-diff-overlay-alist)))
+           (overlay
+            (ediff-get-diff-overlay ediff-current-difference buf-type))
+           )
+
+       (ediff-move-overlay current-diff-overlay 1 1)
+
+       ;; rehighlight the overlay in the background of the
+       ;; current difference region
+       (ediff-set-overlay-face
+        overlay
+        (if (and (ediff-has-face-support-p)
+                 ediff-use-faces ediff-highlight-all-diffs)
+            (ediff-background-face buf-type ediff-current-difference)))
+       )))
+
+(defun ediff-unhighlight-diffs-totally-in-one-buffer (buf-type)
+  (ediff-unselect-and-select-difference -1)
+  (if (and (ediff-has-face-support-p) ediff-use-faces)
+      (let* ((inhibit-quit t)
+            (current-diff-overlay-var
+             (ediff-get-symbol-from-alist
+              buf-type ediff-current-diff-overlay-alist))
+            (current-diff-overlay (symbol-value current-diff-overlay-var)))
+       (ediff-paint-background-regions 'unhighlight)
+       (if (ediff-overlayp current-diff-overlay)
+           (ediff-delete-overlay current-diff-overlay))
+       (set current-diff-overlay-var nil)
+       )))
+
+
+(defsubst ediff-highlight-diff (n)
+  "Put face on diff N.  Invoked for X displays only."
+  (ediff-highlight-diff-in-one-buffer n 'A)
+  (ediff-highlight-diff-in-one-buffer n 'B)
+  (ediff-highlight-diff-in-one-buffer n 'C)
+  (ediff-highlight-diff-in-one-buffer n 'Ancestor)
+  )
+
+
+(defsubst ediff-unhighlight-diff ()
+  "Remove overlays from buffers A, B, and C."
+  (ediff-unhighlight-diff-in-one-buffer 'A)
+  (ediff-unhighlight-diff-in-one-buffer 'B)
+  (ediff-unhighlight-diff-in-one-buffer 'C)
+  (ediff-unhighlight-diff-in-one-buffer 'Ancestor)
+  )
+
+;; delete highlighting overlays, restore faces to their original form
+(defsubst ediff-unhighlight-diffs-totally ()
+  (ediff-unhighlight-diffs-totally-in-one-buffer 'A)
+  (ediff-unhighlight-diffs-totally-in-one-buffer 'B)
+  (ediff-unhighlight-diffs-totally-in-one-buffer 'C)
+  (ediff-unhighlight-diffs-totally-in-one-buffer 'Ancestor)
+  )
 
+
+;; This is adapted from a similar function in `emerge.el'.
+;; PROMPT should not have a trailing ': ', so that it can be modified
+;; according to context.
+;; If DEFAULT-FILE is set, it should be used as the default value.
+;; If DEFAULT-DIR is non-nil, use it as the default directory.
+;; Otherwise, use the value of Emacs' variable `default-directory.'
+(defun ediff-read-file-name (prompt default-dir default-file &optional no-dirs)
   ;; hack default-dir if it is not set
   (setq default-dir
        (file-name-as-directory
@@ -2889,43 +3115,52 @@ Hit \\[ediff-recenter] to reset the windows afterward."
              )
             default-dir
             ))
-    ;; If user enters a directory name, expand the default file in that
+    ;; If user entered a directory name, expand the default file in that
     ;; directory.  This allows the user to enter a directory name for the
     ;; B-file and diff against the default-file in that directory instead
     ;; of a DIRED listing!
     (if (and (file-directory-p f) default-file)
        (setq f (expand-file-name
                 (file-name-nondirectory default-file) f)))
+    (if (and no-dirs (file-directory-p f))
+       (error "File %s is a directory" f))
     f)) 
   
 ;; If PREFIX is given, then it is used as a prefix for the temp file
-;; name. Otherwise, `ediff_' is used. If FILE is given, use this
+;; name.  Otherwise, `ediff' is used.  If FILE is given, use this
 ;; file and don't create a new one.
-;; On MS-DOS, make sure the prefix isn't longer than 7 characters, or
-;; else `make-temp-name' isn't guaranteed to return a unique filename.
+;; In MS-DOS, make sure the prefix isn't too long, or else
+;; `make-temp-name' isn't guaranteed to return a unique filename.
 ;; Also, save buffer from START to END in the file.
 ;; START defaults to (point-min), END to (point-max)
 (defun ediff-make-temp-file (buff &optional prefix given-file start end)
-  (let ((p (or prefix "ediff"))
-       f)
-    (if (and (eq system-type 'ms-dos) (> (length p) 7))
-       (setq p (substring p 0 7)))
-
+  (let* ((p (ediff-convert-standard-filename (or prefix "ediff")))
+        (short-p p)
+        (coding-system-for-write ediff-coding-system-for-write)
+        f short-f)
+    (if (and (fboundp 'msdos-long-file-names)
+            (not (msdos-long-file-names))
+            (> (length p) 2))
+       (setq short-p (substring p 0 2)))
+    
     (setq f (concat ediff-temp-file-prefix p)
-         f (cond (given-file)
+         short-f (concat ediff-temp-file-prefix short-p)
+         f (cond (given-file)
                  ((find-file-name-handler f 'find-file-noselect)
                   ;; to thwart file handlers in write-region, e.g., if file
                   ;; name ends with .Z or .gz
                   ;; This is needed so that patches produced by ediff will
                   ;; have more meaningful names
-                  (make-temp-name f))
-                 ;; Prefix is most often the same as the file name for the
-                 ;; variant. Here we are trying to use the original file name
-                 ;; but in the temp directory.
-                 ((and prefix (not (file-exists-p f))) f)
-                 ;; If a file with the orig name exists, add some random stuff
-                 ;; to it.
-                 (t (make-temp-name f))))
+                  (ediff-make-empty-tmp-file short-f))
+                 (prefix 
+                  ;; Prefix is most often the same as the file name for the
+                  ;; variant.  Here we are trying to use the original file
+                  ;; name but in the temp directory.
+                  (ediff-make-empty-tmp-file f 'keep-name))
+                 (t
+                  ;; If don't care about name, add some random stuff
+                  ;; to proposed file name.
+                  (ediff-make-empty-tmp-file short-f))))
     
     ;; create the file
     (ediff-with-current-buffer buff
@@ -2935,7 +3170,35 @@ Hit \\[ediff-recenter] to reset the windows afterward."
                    nil          ; don't append---erase
                    'no-message) 
       (set-file-modes f ediff-temp-file-mode)
-      (ediff-convert-standard-filename (expand-file-name f)))))
+      (expand-file-name f))))
+
+;; Create a temporary file.
+;; The returned file name (created by appending some random characters at the
+;; end of PROPOSED-NAME is guaranteed to point to a newly created empty file.
+;; This is a replacement for make-temp-name, which eliminates a security hole.
+;; If KEEP-PROPOSED-NAME isn't nil, try to keep PROPOSED-NAME, unless such file
+;; already exists.
+;; It is a modified version of make-temp-file in emacs 20.5
+(defun ediff-make-empty-tmp-file (proposed-name &optional keep-proposed-name)
+  (let ((file proposed-name))
+    (while (condition-case ()
+               (progn
+                (if (or (file-exists-p file) (not keep-proposed-name))
+                    (setq file (make-temp-name proposed-name)))
+                ;; the with-temp-buffer thing is a workaround for an XEmacs
+                ;; bug: write-region complains that we are trying to visit a
+                ;; file in an indirect buffer, failing to notice that the
+                ;; VISIT flag is unset and that we are actually writing from a
+                ;; string and not from any buffer.
+                (with-temp-buffer
+                  (write-region "" nil file nil 'silent nil 'excl))
+                 nil)
+            (file-already-exists t))
+      ;; the file was somehow created by someone else between
+      ;; `make-temp-name' and `write-region', let's try again.
+      nil)
+    file))
+
 
 ;; Quote metacharacters (using \) when executing diff in Unix, but not in
 ;; EMX OS/2
@@ -2961,7 +3224,8 @@ Hit \\[ediff-recenter] to reset the windows afterward."
       (if (buffer-modified-p)
          ;; If buffer is not obsolete and is modified, offer to save
          (if (yes-or-no-p 
-              (format "Buffer out of sync with visited file. Save file %s? "
+              (format "Buffer %s has been modified. Save it in file %s? "
+                      (buffer-name)
                       buffer-file-name))
              (condition-case nil
                  (save-buffer)
@@ -2973,7 +3237,9 @@ Hit \\[ediff-recenter] to reset the windows afterward."
        nil)
     ;; If buffer is obsolete, offer to revert
     (if (yes-or-no-p
-        (format "Buffer is out of sync with visited file. REVERT file %s? "
+        (format "File %s was modified since visited by buffer %s.  REVERT file %s? "
+                buffer-file-name
+                (buffer-name)
                 buffer-file-name))
        (progn
          (if file-magic
@@ -2981,6 +3247,29 @@ Hit \\[ediff-recenter] to reset the windows afterward."
          (revert-buffer t t))
       (error "Buffer out of sync for file %s" buffer-file-name))))
 
+;; if there is another buffer visiting the file of the merge buffer, offer to
+;; save and delete the buffer; else bark
+(defun ediff-verify-file-merge-buffer (file)
+  (let ((buff (if (stringp file) (find-buffer-visiting file)))
+       warn-message)
+    (or (null buff)
+       (progn
+         (setq warn-message
+               (format "Buffer %s is visiting %s. Save and kill the buffer? "
+                       (buffer-name buff) file))
+         (with-output-to-temp-buffer ediff-msg-buffer
+           (princ "\n\n")
+           (princ warn-message)
+           (princ "\n\n"))
+         (if (y-or-n-p
+              (message warn-message))
+             (with-current-buffer buff
+               (save-buffer)
+               (kill-buffer (current-buffer)))
+           (error "Too dangerous to merge versions of a file visited by another buffer"))))
+    ))
+
+
 
 (defun ediff-filename-magic-p (file)
   (or (ediff-file-compressed-p file)
@@ -3015,6 +3304,78 @@ Without an argument, it saves customized diff argument, if available
            )
     (save-buffer)))
 
+
+;; idea suggested by Hannu Koivisto <azure@iki.fi>
+(defun ediff-clone-buffer-for-region-comparison (buff region-name)
+  (let ((cloned-buff (ediff-make-cloned-buffer buff region-name))
+       (wind (ediff-get-visible-buffer-window buff))
+       (pop-up-windows t)
+       other-wind
+       msg-buf)
+    (ediff-with-current-buffer cloned-buff
+      (setq ediff-temp-indirect-buffer t))
+    (if (window-live-p wind)
+       (set-window-buffer wind cloned-buff))
+    (pop-to-buffer cloned-buff)
+    (with-temp-buffer
+      (erase-buffer)
+      (insert
+       (format "\n   *******  Mark a region in buffer %s  *******\n"
+              (buffer-name cloned-buff)))
+      (insert
+       (format "\n\t      When done, type %s       Use %s to abort\n    "
+              (ediff-format-bindings-of 'exit-recursive-edit)
+              (ediff-format-bindings-of 'abort-recursive-edit)))
+      (goto-char (point-min))
+      (setq msg-buf (current-buffer))
+      (other-window 1)
+      (set-window-buffer (selected-window) msg-buf)
+      (shrink-window-if-larger-than-buffer)
+      (if (window-live-p wind)
+         (select-window wind))
+      (condition-case nil
+         (recursive-edit)
+       (quit
+        (ediff-kill-buffer-carefully cloned-buff)))
+      )
+    cloned-buff))
+
+
+(defun ediff-clone-buffer-for-window-comparison (buff wind region-name)
+  (let ((cloned-buff (ediff-make-cloned-buffer buff region-name)))
+    (ediff-with-current-buffer cloned-buff
+      (setq ediff-temp-indirect-buffer t))
+    (set-window-buffer wind cloned-buff)
+    cloned-buff))
+
+(defun ediff-clone-buffer-for-current-diff-comparison (buff buf-type reg-name)
+  (let ((cloned-buff (ediff-make-cloned-buffer buff reg-name))
+       (reg-start (ediff-get-diff-posn buf-type 'beg))
+       (reg-end (ediff-get-diff-posn buf-type 'end)))
+    (ediff-with-current-buffer cloned-buff
+      ;; set region to be the current diff region
+      (goto-char reg-start)
+      (set-mark reg-end)
+      (setq ediff-temp-indirect-buffer t))
+    cloned-buff))
+  
+
+
+(defun ediff-make-cloned-buffer (buff region-name)
+  (ediff-make-indirect-buffer
+   buff (concat
+        (if (stringp buff) buff (buffer-name buff))
+        region-name (symbol-name (gensym)))))
+
+
+(defun ediff-make-indirect-buffer (base-buf indirect-buf-name)
+  (ediff-cond-compile-for-xemacs-or-emacs
+   (make-indirect-buffer base-buf indirect-buf-name) ; xemacs
+   (make-indirect-buffer base-buf indirect-buf-name 'clone) ; emacs
+   ))
+
+
+;; This function operates only from an ediff control buffer
 (defun ediff-compute-custom-diffs-maybe ()
   (let ((buf-A-file-name (buffer-file-name ediff-buffer-A))
        (buf-B-file-name (buffer-file-name ediff-buffer-B))
@@ -3030,9 +3391,16 @@ Without an argument, it saves customized diff argument, if available
        (setq ediff-custom-diff-buffer
              (get-buffer-create
               (ediff-unique-buffer-name "*ediff-custom-diff" "*"))))
+    (ediff-with-current-buffer ediff-custom-diff-buffer
+      (setq buffer-read-only nil)
+      (erase-buffer))
     (ediff-exec-process
      ediff-custom-diff-program ediff-custom-diff-buffer 'synchronize
      ediff-custom-diff-options file-A file-B)
+    ;; put the diff file in diff-mode, if it is available
+    (if (fboundp 'diff-mode)
+       (with-current-buffer ediff-custom-diff-buffer
+         (diff-mode)))
     (delete-file file-A)
     (delete-file file-B)
     ))
@@ -3078,10 +3446,18 @@ Ediff Control Panel to restore highlighting."
        (zmacs-regions t)
        (ctl-buf (current-buffer))
        quit-now
+       use-current-diff-p
        begA begB endA endB bufA bufB)
 
+    (if (ediff-valid-difference-p ediff-current-difference)
+       (progn
+         (ediff-set-fine-diff-properties ediff-current-difference 'default)
+         (ediff-unhighlight-diff)))
+    (ediff-paint-background-regions 'unhighlight)
+
     (cond ((ediff-merge-job)
           (setq bufB ediff-buffer-C)
+          ;; ask which buffer to compare to the merge buffer
           (while (cond ((eq answer ?A)
                         (setq bufA ediff-buffer-A
                               possibilities '(?B))
@@ -3096,10 +3472,12 @@ Ediff Control Panel to restore highlighting."
                           (sit-for 2)
                           t))
             (let ((cursor-in-echo-area t))
-              (message "Which buffer to compare to the merge buffer (A/B)? ")
+              (message
+               "Which buffer to compare to the merge buffer (A or B)? ")
               (setq answer (capitalize (read-char-exclusive))))))
 
          ((ediff-3way-comparison-job)
+          ;; ask which two buffers to compare
           (while (cond ((memq answer possibilities)
                         (setq possibilities (delq answer possibilities))
                         (setq bufA
@@ -3116,7 +3494,7 @@ Ediff Control Panel to restore highlighting."
                           t))
             (let ((cursor-in-echo-area t))
               (message "Enter the 1st buffer you want to compare (%s): "
-                       (mapconcat 'char-to-string possibilities "/"))
+                       (mapconcat 'char-to-string possibilities " or "))
               (setq answer (capitalize (read-char-exclusive)))))
           (setq answer "") ; silence error msg
           (while (cond ((memq answer possibilities)
@@ -3142,9 +3520,15 @@ Ediff Control Panel to restore highlighting."
                 bufB ediff-buffer-B
                 possibilities nil)))
 
+    (if (and (ediff-valid-difference-p ediff-current-difference)
+            (y-or-n-p "Compare currently highlighted difference regions? "))
+       (setq use-current-diff-p t))
+
+    (setq bufA (if use-current-diff-p
+                  (ediff-clone-buffer-for-current-diff-comparison
+                   bufA 'A "-Region.A-")
+                (ediff-clone-buffer-for-region-comparison bufA "-Region.A-")))
     (ediff-with-current-buffer bufA
-      (or (mark t)
-         (error "You forgot to specify a region in buffer %s" (buffer-name)))
       (setq begA (region-beginning)
            endA (region-end))
       (goto-char begA)
@@ -3154,9 +3538,12 @@ Ediff Control Panel to restore highlighting."
       (end-of-line)
       (or (eobp) (forward-char)) ; include the newline char
       (setq endA (point)))
+
+    (setq bufB (if use-current-diff-p
+                  (ediff-clone-buffer-for-current-diff-comparison
+                   bufB 'B "-Region.B-")
+                (ediff-clone-buffer-for-region-comparison bufB "-Region.B-")))
     (ediff-with-current-buffer bufB
-      (or (mark t)
-         (error "You forgot to specify a region in buffer %s" (buffer-name)))
       (setq begB (region-beginning)
            endB (region-end))
       (goto-char begB)
@@ -3167,57 +3554,15 @@ Ediff Control Panel to restore highlighting."
       (or (eobp) (forward-char)) ; include the newline char
       (setq endB (point)))
 
-    (ediff-unselect-and-select-difference
-     ediff-current-difference 'unselect-only)
-    (ediff-paint-background-regions 'unhighlight)
-
-    (ediff-with-current-buffer bufA
-      (goto-char begA)
-      (set-mark endA)
-      (narrow-to-region begA endA)
-      ;; (ediff-activate-mark)
-      )
-    ;; (sit-for 0)
-    (ediff-with-current-buffer bufB
-      (goto-char begB)
-      (set-mark endB)
-      (narrow-to-region begB endB)
-      ;; (ediff-activate-mark)
-      )
-    ;; (sit-for 0)
-    
-    ;; At this point, possibilities contains either the window char A/B/C
-    ;; that was not selected, or it is nil. We delete the window that is not
-    ;; selected.
-    (if possibilities
-       (ediff-with-current-buffer ctl-buf
-         (let* ((wind-to-delete (eval
-                                 (ediff-get-symbol-from-alist
-                                  (car possibilities)
-                                   ediff-window-alist)))
-                (frame (window-frame wind-to-delete)))
-           (delete-window wind-to-delete)
-           (select-frame frame)
-           (balance-windows))))
-    (or (y-or-n-p 
-        "Please check regions selected for comparison. Continue? ")
-       (setq quit-now t))
-    
-    (ediff-with-current-buffer bufA
-      (widen))
-    (ediff-with-current-buffer bufB
-      (widen))
-    (if quit-now
-       (ediff-with-current-buffer ctl-buf
-         (ediff-recenter)
-         (sit-for 0)
-         (error "All right. Make up your mind and come back...")))
 
     (ediff-regions-internal
      bufA begA endA bufB begB endB
-     nil                       ; setup-hook
-     'ediff-regions-linewise   ; job name
-     nil                       ; no word mode
+     nil                       ; setup-hook
+     (if use-current-diff-p    ; job name
+        'ediff-regions-wordwise
+       'ediff-regions-linewise)
+     (if use-current-diff-p    ; word mode, if diffing current diff
+        t nil)
      ;; setup param to pass to ediff-setup
      (list (cons 'ediff-split-window-function ediff-split-window-function)))
     ))
@@ -3280,6 +3625,40 @@ Ediff Control Panel to restore highlighting."
       (ediff-overlay-put curr-overl 'after-string flag))
     ))
 
+
+;;; Some diff region tests
+
+;; t if diff region is empty.
+;; In case of buffer C, t also if it is not a 3way
+;; comparison job (merging jobs return t as well).
+(defun ediff-empty-diff-region-p (n buf-type)
+  (if (eq buf-type 'C)
+      (or (not ediff-3way-comparison-job)
+         (= (ediff-get-diff-posn 'C 'beg n)
+            (ediff-get-diff-posn 'C 'end n)))
+    (= (ediff-get-diff-posn buf-type 'beg n)
+       (ediff-get-diff-posn buf-type 'end n))))
+
+;; Test if diff region is white space only.
+;; If 2-way job and buf-type = C, then returns t.
+(defun ediff-whitespace-diff-region-p (n buf-type)
+  (or (and (eq buf-type 'C) (not ediff-3way-job))
+      (ediff-empty-diff-region-p n buf-type)
+      (let ((beg (ediff-get-diff-posn buf-type 'beg n))
+           (end (ediff-get-diff-posn buf-type 'end n)))
+       (ediff-with-current-buffer (ediff-get-buffer buf-type)
+         (save-excursion
+           (goto-char beg)
+           (skip-chars-forward ediff-whitespace)
+           (>= (point) end))))))
+
+
+(defsubst ediff-get-region-contents (n buf-type ctrl-buf &optional start end)
+  (ediff-with-current-buffer
+      (ediff-with-current-buffer ctrl-buf (ediff-get-buffer buf-type))
+    (buffer-substring
+     (or start (ediff-get-diff-posn buf-type 'beg n ctrl-buf))
+     (or end (ediff-get-diff-posn buf-type 'end n ctrl-buf)))))
   
 ;; Returns positions of difference sectors in the BUF-TYPE buffer.
 ;; BUF-TYPE should be a symbol -- `A', `B', or `C'. 
@@ -3287,7 +3666,7 @@ Ediff Control Panel to restore highlighting."
 ;; the beginning of a difference or at the end.
 ;; 
 ;; The optional argument N says which difference (default:
-;; `ediff-current-difference'). N is the internal difference number (1- what
+;; `ediff-current-difference').  N is the internal difference number (1- what
 ;; the user sees).  The optional argument CONTROL-BUF says
 ;; which control buffer is in effect in case it is not the current
 ;; buffer.
@@ -3329,13 +3708,12 @@ Ediff Control Panel to restore highlighting."
 ;; VEC is either a difference vector or a fine-diff vector
 (defun ediff-clear-diff-vector (vec-var &optional fine-diffs-also)
   (if (vectorp (symbol-value vec-var))
-      (mapcar (function
-              (lambda (elt)
-                (ediff-delete-overlay 
-                 (ediff-get-diff-overlay-from-diff-record elt))
-                (if fine-diffs-also
-                    (ediff-clear-fine-diff-vector elt))
-                ))
+      (mapcar (lambda (elt)
+               (ediff-delete-overlay 
+                (ediff-get-diff-overlay-from-diff-record elt))
+               (if fine-diffs-also
+                   (ediff-clear-fine-diff-vector elt))
+               )
              (symbol-value vec-var)))
   ;; allow them to be garbage collected
   (set vec-var nil))
@@ -3344,10 +3722,10 @@ Ediff Control Panel to restore highlighting."
 \f
 ;;; Misc
 
-;; In Emacs, this just makes overlay. In the future, when Emacs will start
+;; In Emacs, this just makes overlay.  In the future, when Emacs will start
 ;; supporting sticky overlays, this function will make a sticky overlay.
 ;; BEG and END are expressions telling where overlay starts.
-;; If they are numbers or buffers, then all is well. Otherwise, they must
+;; If they are numbers or buffers, then all is well.  Otherwise, they must
 ;; be expressions to be evaluated in buffer BUF in order to get the overlay
 ;; bounds.
 ;; If BUFF is not a live buffer, then return nil; otherwise, return the
@@ -3361,15 +3739,16 @@ Ediff Control Panel to restore highlighting."
          (or (number-or-marker-p end)
              (setq end (eval end)))
          (setq overl 
-               (if ediff-xemacs-p
-                   (make-extent beg end buff)
-                 ;; advance front and rear of the overlay
-                 (make-overlay beg end buff nil 'rear-advance)))
+               (ediff-cond-compile-for-xemacs-or-emacs
+                (make-extent beg end buff)                     ; xemacs
+                ;; advance front and rear of the overlay
+                (make-overlay beg end buff nil 'rear-advance)  ; emacs
+                ))
          
          ;; never detach
          (ediff-overlay-put
           overl (if ediff-emacs-p 'evaporate 'detachable) nil)
-         ;; make vip-minibuffer-overlay open-ended
+         ;; make overlay open-ended
          ;; In emacs, it is made open ended at creation time
          (if ediff-xemacs-p
              (progn
@@ -3377,54 +3756,141 @@ Ediff Control Panel to restore highlighting."
                (ediff-overlay-put overl 'end-open nil)))
          (ediff-overlay-put overl 'ediff-diff-num 0)
          overl))))
+
+
+(defun ediff-make-current-diff-overlay (type)
+  (if (ediff-has-face-support-p)
+      (let ((overlay (ediff-get-symbol-from-alist
+                     type ediff-current-diff-overlay-alist))
+           (buffer (ediff-get-buffer type))
+           (face (face-name
+                  (symbol-value
+                   (ediff-get-symbol-from-alist
+                    type ediff-current-diff-face-alist)))))
+       (set overlay
+            (ediff-make-bullet-proof-overlay (point-max) (point-max) buffer))
+       (ediff-set-overlay-face (symbol-value overlay) face)
+       (ediff-overlay-put (symbol-value overlay) 'ediff ediff-control-buffer))
+    ))
          
   
 ;; Like other-buffer, but prefers visible buffers and ignores temporary or
 ;; other insignificant buffers (those beginning with "^[ *]").
 ;; Gets one arg--buffer name or a list of buffer names (it won't return
 ;; these buffers).
-(defun ediff-other-buffer (buff-lst)
-  (or (listp buff-lst) (setq buff-lst (list buff-lst)))
-  (let* ((frame-buffers (buffer-list))
-        (buff-name-list 
+;; EXCL-BUFF-LIST is an exclusion list. 
+(defun ediff-other-buffer (excl-buff-lst)
+  (or (listp excl-buff-lst) (setq excl-buff-lst (list excl-buff-lst)))
+  (let* ((all-buffers (nconc (ediff-get-selected-buffers) (buffer-list)))
+        ;; we compute this the second time because we need to do memq on it
+        ;; later, and nconc above will break it. Either this or use slow
+        ;; append instead of nconc
+        (selected-buffers (ediff-get-selected-buffers))
+        (prefered-buffer (car all-buffers))
+        visible-dired-buffers
+        (excl-buff-name-list 
          (mapcar 
-          (function (lambda (b)
-                      (cond ((stringp b) b)
-                            ((bufferp b) (buffer-name b)))))
-          buff-lst))
+          (lambda (b) (cond ((stringp b) b)
+                            ((bufferp b) (buffer-name b))))
+          excl-buff-lst))
+        ;; if at least one buffer on the exclusion list is dired, then force
+        ;; all others to be dired. This is because this means that the user
+        ;; has already chosen a dired buffer before
+        (use-dired-major-mode
+         (cond ((null (ediff-buffer-live-p (car excl-buff-lst))) 'unknown)
+               ((eq (ediff-with-current-buffer (car excl-buff-lst) major-mode)
+                    'dired-mode)
+                'yes)
+               (t 'no)))
+        ;; significant-buffers must be visible and not belong
+        ;; to the exclusion list `buff-list'
+        ;; We also exclude temporary buffers, but keep mail and gnus buffers
+        ;; Furthermore, we exclude dired buffers, unless they are the only
+        ;; ones visible (and there are at least two of them).
+        ;; Also, any visible window not on the exclusion list that is first in
+        ;; the buffer list is chosen regardless. (This is because the user
+        ;; clicked on it or did something to distinguish it).
         (significant-buffers
          (mapcar
-          (function (lambda (x)
-                      (cond ((member (buffer-name x) buff-name-list) nil)
-                            ((not (ediff-get-visible-buffer-window x)) nil)
-                            ((string-match "^[ *]" (buffer-name x)) nil)
-                            ((memq (ediff-with-current-buffer x major-mode)
-                                   '(dired-mode))
-                             nil)
-                            (t x))))
-          frame-buffers))
-        (buffers (delq nil significant-buffers))
+          (lambda (x)
+            (cond ((member (buffer-name x) excl-buff-name-list) nil)
+                  ((memq x selected-buffers) x)
+                  ((not (ediff-get-visible-buffer-window x)) nil)
+                  ((eq x prefered-buffer) x)
+                  ;; if prev selected buffer is dired, look only at
+                  ;; dired.
+                  ((eq use-dired-major-mode 'yes)
+                   (if (eq (ediff-with-current-buffer x major-mode)
+                           'dired-mode)
+                       x nil))
+                  ((eq (ediff-with-current-buffer x major-mode)
+                       'dired-mode)
+                   (if (null use-dired-major-mode)
+                       ;; don't know if we must enforce dired.
+                       ;; Remember this buffer in case
+                       ;; dired buffs are the only ones visible.
+                       (setq visible-dired-buffers
+                             (cons x visible-dired-buffers)))
+                   ;; skip, if dired is not forced
+                   nil)
+                  ((memq (ediff-with-current-buffer x major-mode)
+                         '(rmail-mode
+                           vm-mode
+                           gnus-article-mode
+                           mh-show-mode))
+                   x)
+                  ((string-match "^[ *]" (buffer-name x)) nil)
+                  ((string= "*scratch*" (buffer-name x)) nil)
+                  (t x)))
+          all-buffers))
+        (clean-significant-buffers (delq nil significant-buffers))
         less-significant-buffers)
+
+    (if (and (null clean-significant-buffers) 
+            (> (length visible-dired-buffers) 0))
+       (setq clean-significant-buffers visible-dired-buffers))
         
-    (cond (buffers (car buffers))
+    (cond (clean-significant-buffers (car clean-significant-buffers))
          ;; try also buffers that are not displayed in windows
          ((setq less-significant-buffers
                 (delq nil
                       (mapcar
-                       (function
-                        (lambda (x)
-                          (cond ((member (buffer-name x) buff-name-list) nil)
-                                ((string-match "^[ *]" (buffer-name x)) nil)
-                                ((memq
-                                  (ediff-with-current-buffer x major-mode)
-                                  '(dired-mode))
-                                 nil)
-                                (t x))))
-                       frame-buffers)))
+                       (lambda (x)
+                         (cond ((member (buffer-name x) excl-buff-name-list)
+                                nil)
+                               ((eq use-dired-major-mode 'yes)
+                                (if (eq (ediff-with-current-buffer
+                                            x major-mode)
+                                        'dired-mode)
+                                    x nil))
+                               ((eq (ediff-with-current-buffer x major-mode)
+                                    'dired-mode)
+                                nil)
+                               ((string-match "^[ *]" (buffer-name x)) nil)
+                               ((string= "*scratch*" (buffer-name x)) nil)
+                               (t x)))
+                       all-buffers)))
           (car less-significant-buffers))
-         (t (other-buffer (current-buffer))))
+         (t "*scratch*"))
     ))
       
+
+;; If current buffer is a Buffer-menu buffer, then take the selected buffers
+;; and append the buffer at the cursor to the end.
+;; This list would be the preferred list.
+(defun ediff-get-selected-buffers ()
+  (if (eq major-mode 'Buffer-menu-mode)
+      (let ((lis (condition-case nil
+                    (list (Buffer-menu-buffer t))
+                  (error))
+                ))
+       (save-excursion
+         (goto-char (point-max))
+         (while (search-backward "\n>" nil t)
+           (forward-char 1)
+           (setq lis (cons (Buffer-menu-buffer t) lis)))
+         lis))
+    ))
       
 ;; Construct a unique buffer name.
 ;; The first one tried is prefixsuffix, then prefix<2>suffix, 
@@ -3465,7 +3931,7 @@ Ediff Control Panel to restore highlighting."
                    ediff-device-type
                    ))
     (setq salutation "
-Congratulations! You may have unearthed a bug in Ediff!
+Congratulations!  You may have unearthed a bug in Ediff!
 
 Please make a concise and accurate summary of what happened
 and mail it to the address above.
@@ -3482,16 +3948,16 @@ and mail it to the address above.
 Please read this first:
 ----------------------
 
-Some ``bugs'' may actually be no bugs at all. For instance, if you are
+Some ``bugs'' may actually be no bugs at all.  For instance, if you are
 reporting that certain difference regions are not matched as you think they
 should, this is most likely due to the way Unix diff program decides what
-constitutes a difference region. Ediff is an Emacs interface to diff, and
+constitutes a difference region.  Ediff is an Emacs interface to diff, and
 it has nothing to do with those decisions---it only takes the output from
 diff and presents it in a way that is better suited for human browsing and
 manipulation.
 
 If Emacs happens to dump core, this is NOT an Ediff problem---it is
-an Emacs bug. Report this to Emacs maintainers.
+an Emacs bug.  Report this to Emacs maintainers.
 
 Another popular topic for reports is compilation messages.  Because Ediff
 interfaces to several other packages and runs under Emacs and XEmacs,
@@ -3518,7 +3984,7 @@ Mail anyway? (y or n) ")
              (set-buffer ctl-buf))
          (setq buffer-name (buffer-name))
          (require 'reporter)
-         (reporter-submit-bug-report "kifer@cs.sunysb.edu"
+         (reporter-submit-bug-report "kifer@cs.stonybrook.edu"
                                      (ediff-version)
                                      varlist
                                      nil 
@@ -3530,16 +3996,37 @@ Mail anyway? (y or n) ")
          (ediff-with-current-buffer ctl-buf
            (ediff-recenter 'no-rehighlight))))
     ))
-                            
+
+
+;; Find an appropriate syntax table for everyone to use
+;; If buffer B is not fundamental or text mode, use its syntax table
+;; Otherwise, use buffer B's.
+;; The syntax mode is used in ediff-forward-word-function
+;; The important thing is that every buffer should use the same syntax table
+;; during the refinement operation
+(defun ediff-choose-syntax-table ()
+  (setq ediff-syntax-table
+       (ediff-with-current-buffer ediff-buffer-A
+         (if (not (memq major-mode 
+                        '(fundamental-mode text-mode indented-text-mode)))
+             (syntax-table))))
+  (if (not ediff-syntax-table)
+      (setq ediff-syntax-table 
+           (ediff-with-current-buffer ediff-buffer-B
+             (syntax-table))))
+  )
+
        
 (defun ediff-deactivate-mark ()
-  (if ediff-xemacs-p
-         (zmacs-deactivate-region)
-       (deactivate-mark)))
+  (ediff-cond-compile-for-xemacs-or-emacs
+   (zmacs-deactivate-region) ; xemacs
+   (deactivate-mark) ; emacs
+   ))
 (defun ediff-activate-mark ()
-  (if ediff-emacs-p
-      (setq mark-active t)
-    (zmacs-activate-region)))
+  (ediff-cond-compile-for-xemacs-or-emacs
+   (zmacs-activate-region) ; xemacs
+   (setq mark-active t) ; emacs
+   ))
 
 (cond ((fboundp 'nuke-selective-display)
        ;; XEmacs 19.12 has nuke-selective-display
@@ -3569,7 +4056,7 @@ Mail anyway? (y or n) ")
 ;; VARS must be a list of symbols
 ;; ediff-save-variables returns an association list: ((var . val) ...)
 (defsubst ediff-save-variables (vars)
-  (mapcar (function (lambda (v) (cons v (symbol-value v))))
+  (mapcar (lambda (v) (cons v (symbol-value v)))
          vars))
 ;; VARS is a list of variable symbols.
 (defun ediff-restore-variables (vars assoc-list)
@@ -3622,7 +4109,7 @@ Mail anyway? (y or n) ")
          (ediff-restore-variables ediff-protected-variables values-Ancestor)))
     ))
 
-;; save BUFFER in FILE. used in hooks.
+;; save BUFFER in FILE.  used in hooks.
 (defun ediff-save-buffer-in-file (buffer file)
   (ediff-with-current-buffer buffer
     (write-file file)))
@@ -3651,7 +4138,12 @@ Mail anyway? (y or n) ")
   "Toggle profiling Ediff commands."
   (interactive)
   (ediff-barf-if-not-control-buffer)
-  (make-local-hook 'post-command-hook)
+
+  (ediff-cond-compile-for-xemacs-or-emacs
+   (make-local-hook 'post-command-hook) ; xemacs form
+   nil                                  ; emacs form
+   )
+
   (let ((pre-hook 'pre-command-hook)
        (post-hook 'post-command-hook))
     (if (not (equal ediff-command-begin-time '(0 0 0)))
@@ -3659,33 +4151,32 @@ Mail anyway? (y or n) ")
               (remove-hook post-hook 'ediff-calc-command-time)
               (setq ediff-command-begin-time '(0 0 0))
               (message "Ediff profiling disabled"))
-      (add-hook pre-hook 'ediff-save-time t t)
-      (add-hook post-hook 'ediff-calc-command-time nil t)
+      (add-hook pre-hook 'ediff-save-time t 'local)
+      (add-hook post-hook 'ediff-calc-command-time nil 'local)
       (message "Ediff profiling enabled"))))
     
 (defun ediff-print-diff-vector (diff-vector-var)
   (princ (format "\n*** %S ***\n" diff-vector-var))
-  (mapcar (function
-          (lambda (overl-vec)
-            (princ
-             (format
-              "Diff %d: \tOverlay:    %S
+  (mapcar (lambda (overl-vec)
+           (princ
+            (format
+             "Diff %d: \tOverlay:    %S
 \t\tFine diffs: %s
 \t\tNo-fine-diff-flag: %S
 \t\tState-of-diff:\t   %S
 \t\tState-of-merge:\t   %S
 " 
-              (1+ (ediff-overlay-get (aref overl-vec 0) 'ediff-diff-num))
-              (aref overl-vec 0)
-              ;; fine-diff-vector
-              (if (= (length (aref overl-vec 1)) 0)
-                  "none\n"
-                (mapconcat 'prin1-to-string
-                           (aref overl-vec 1) "\n\t\t\t    "))
-              (aref overl-vec 2) ; no fine diff flag
-              (aref overl-vec 3) ; state-of-diff
-              (aref overl-vec 4) ; state-of-merge
-              ))))
+             (1+ (ediff-overlay-get (aref overl-vec 0) 'ediff-diff-num))
+             (aref overl-vec 0)
+             ;; fine-diff-vector
+             (if (= (length (aref overl-vec 1)) 0)
+                 "none\n"
+               (mapconcat 'prin1-to-string
+                          (aref overl-vec 1) "\n\t\t\t    "))
+             (aref overl-vec 2) ; no fine diff flag
+             (aref overl-vec 3) ; state-of-diff
+             (aref overl-vec 4) ; state-of-merge
+             )))
          (eval diff-vector-var)))
 
   
@@ -3694,6 +4185,8 @@ Mail anyway? (y or n) ")
   (interactive)
   (ediff-barf-if-not-control-buffer)
   (with-output-to-temp-buffer ediff-debug-buffer
+    (ediff-with-current-buffer standard-output
+      (fundamental-mode))
     (princ (format "\nCtl buffer: %S\n" ediff-control-buffer))
     (ediff-print-diff-vector (intern "ediff-difference-vector-A"))
     (ediff-print-diff-vector (intern "ediff-difference-vector-B"))
@@ -3710,6 +4203,16 @@ Mail anyway? (y or n) ")
     (setq lis (cdr lis)))
   lis)
 
+;; Make a readable representation of the invocation sequence for FUNC-DEF.
+;; It would either be a key or M-x something.
+(defun ediff-format-bindings-of (func-def)
+  (let ((desc (car (where-is-internal func-def
+                                     overriding-local-map
+                                     nil nil))))
+    (if desc
+       (key-description desc)
+      (format "M-x %s" func-def))))
+
 ;; this uses comparison-func to decide who is a member, and this determines how
 ;; intersection looks like
 (defun ediff-intersection (lis1 lis2 comparison-func)
@@ -3744,19 +4247,21 @@ Mail anyway? (y or n) ")
       (setq lis1 (cdr lis1)))
     (cdr result)))
 
-(defun ediff-copy-list (list)
-  (if (consp list)
+(if (fboundp 'copy-sequence)
+    (fset 'ediff-copy-list (symbol-function 'copy-sequence))
+  (defun ediff-copy-list (list)
+    (if (consp list)
       ;;;(let ((res nil))
       ;;;  (while (consp list) (push (pop list) res))
       ;;;  (prog1 (nreverse res) (setcdr res list)))
-      (let (res elt)
-       (while (consp list)
-         (setq elt (car list)
-               res (cons elt res)
-               list (cdr list)))
-       (nreverse res))
-    (car list)))
-    
+       (let (res elt)
+         (while (consp list)
+           (setq elt (car list)
+                 res (cons elt res)
+                 list (cdr list)))
+         (nreverse res))
+      (car list))))
+
 
 ;; don't report error if version control package wasn't found
 ;;(ediff-load-version-control 'silent)