Initial Commit
[packages] / xemacs-packages / prog-modes / diff-mode.el
1 ;;; diff-mode.el --- a mode for viewing/editing context diffs
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005 Free Software Foundation, Inc.
5
6 ;; Author: Stefan Monnier <monnier@cs.yale.edu>
7 ;; Keywords: convenience patch diff
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Synched up with: GNU Emacs 21.3, except for the easy-mmode-defmap stuff.
27 ;;;                  Also various trivial bits synced from Emacs CVS 2004-08-13
28 ;;;                  and 2005-12-01.
29
30 ;;; Commentary:
31
32 ;; Provides support for font-lock, outline, navigation
33 ;; commands, editing and various conversions as well as jumping
34 ;; to the corresponding source file.
35
36 ;; Inspired by Pavel Machek's patch-mode.el (<pavel@@atrey.karlin.mff.cuni.cz>)
37 ;; Some efforts were spent to have it somewhat compatible with XEmacs'
38 ;; diff-mode as well as with compilation-minor-mode
39
40 ;; Bugs:
41
42 ;; - Reverse doesn't work with normal diffs.
43
44 ;; Todo:
45
46 ;; - Improve narrowed-view support.
47 ;; - re-enable (conditionally) the `compile' support after improving it to use
48 ;;   the same code as diff-goto-source.
49 ;; - Support for # comments in context->unified.
50 ;; - Do a fuzzy search in diff-goto-source.
51 ;; - Allow diff.el to use diff-mode.
52 ;;   This mostly means ability to jump from half-hunk to half-hunk
53 ;;   in context (and normal) diffs and to jump to the corresponding
54 ;;   (i.e. new or old) file.
55 ;; - Handle `diff -b' output in context->unified.
56
57 ;; Low priority:
58 ;; - Spice up the minor-mode with font-lock support.
59 ;; - Recognize pcl-cvs' special string for `cvs-execute-single'.
60
61 ;;; Code:
62
63 ;; XEmacs change
64 (if (featurep 'diff)
65     (error 'invalid-state
66            "The diff and diff-mode packages are incompatible."))
67
68 (eval-when-compile (require 'cl))
69
70
71 (defgroup diff-mode ()
72   "Major mode for viewing/editing diffs."
73   :version "21.1"
74   :group 'tools
75   :group 'diff)
76
77 (defcustom diff-default-read-only nil
78   "If non-nil, `diff-mode' buffers default to being read-only."
79   :type 'boolean
80   :group 'diff-mode)
81
82 (defcustom diff-jump-to-old-file nil
83   "*Non-nil means `diff-goto-source' jumps to the old file.
84 Else, it jumps to the new file."
85   :type 'boolean
86   :group 'diff-mode)
87
88 (defcustom diff-update-on-the-fly t
89   "*Non-nil means hunk headers are kept up-to-date on-the-fly.
90 When editing a diff file, the line numbers in the hunk headers
91 need to be kept consistent with the actual diff.  This can
92 either be done on the fly (but this sometimes interacts poorly with the
93 undo mechanism) or whenever the file is written (can be slow
94 when editing big diffs)."
95   :type 'boolean
96   :group 'diff-mode)
97
98 (defcustom diff-advance-after-apply-hunk t
99   "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
100   :type 'boolean
101   :group 'diff-mode)
102
103
104 (defvar diff-mode-hook nil
105   "Run after setting up the `diff-mode' major mode.")
106
107 (defvar diff-outline-regexp
108   "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
109
110 ;;;;
111 ;;;; keymap, menu, ...
112 ;;;;
113
114 ;; XEmacs change: the clever keymap tricks here didn't work; fix them.
115
116 (defmacro diff-defmap (var bindings doc)
117   `(defvar ,var
118      (let ((m (make-keymap)))
119        (dolist (b ,bindings)
120          (define-key m (car b) (cdr b)))
121        m)
122      ,doc))
123
124 (defmacro diff-metify-map (var bindings doc)
125   `(defvar ,var
126      (let ((m (make-keymap)))
127        (dolist (b ,bindings)
128          (define-key m (char-to-string (+ 128 (string-to-char (car b))))
129            (cdr b)))
130        m)
131      ,doc))
132
133 (let ((bindings
134        '(;; from Pavel Machek's patch-mode
135          ("n" . diff-hunk-next)
136          ("N" . diff-file-next)
137          ("p" . diff-hunk-prev)
138          ("P" . diff-file-prev)
139          ("k" . diff-hunk-kill)
140          ("K" . diff-file-kill)
141          ;; From compilation-minor-mode.
142          ("}" . diff-file-next)
143          ("{" . diff-file-prev)
144          ("\C-m" . diff-goto-source)
145          ("W" . widen)
146          ;;("." . diff-goto-source)             ;display-buffer
147          ;;("f" . diff-goto-source)             ;find-file
148          ("o" . diff-goto-source)       ;other-window
149          ;;("w" . diff-goto-source)             ;other-frame
150          ;;("N" . diff-narrow)
151          ;;("h" . diff-show-header)
152          ;;("j" . diff-show-difference) ;jump to Nth diff
153          ;;("q" . diff-quit)
154          (" " . scroll-up)
155          ("\177" . scroll-down)
156          ;; Our very own bindings.
157          ("A" . diff-ediff-patch)
158          ("r" . diff-restrict-view)
159          ("R" . diff-reverse-direction)
160          ("U" . diff-context->unified)
161          ("C" . diff-unified->context))))
162   (diff-defmap
163    diff-mode-shared-map bindings
164    "Keymap for read-only `diff-mode'. Only active in read-only mode.")
165   (diff-metify-map
166    diff-mode-map bindings
167    "Keymap for `diff-mode'.  See also `diff-mode-shared-map'."))
168
169 ;; from compilation-minor-mode
170 (define-key diff-mode-map "\C-c\C-c" 'diff-goto-source)
171 ;; from GNU Emacs
172 (define-key diff-mode-map "\C-c\C-s" 'diff-split-hunk)
173 (define-key diff-mode-map "\C-c\C-a" 'diff-apply-hunk)
174 (define-key diff-mode-map "\C-c\C-t" 'diff-test-hunk)
175
176 (easy-menu-define diff-mode-menu diff-mode-map
177   "Menu for `diff-mode'."
178   '("Diff"
179     ["Jump to Source"           diff-goto-source        t]
180     ["Apply hunk"               diff-apply-hunk         t]
181     ["Apply diff with Ediff"    diff-ediff-patch        t]
182     ["-----" nil nil]
183     ["Reverse direction"        diff-reverse-direction  t]
184     ["Context -> Unified"       diff-context->unified   t]
185     ["Unified -> Context"       diff-unified->context   t]
186     ;;["Fixup Headers"          diff-fixup-modifs       (not buffer-read-only)]
187     ))
188
189 (defcustom diff-minor-mode-prefix "\C-c="
190   "Prefix key for `diff-minor-mode' commands."
191   :type '(choice (string "\e") (string "C-c=") string)
192   :group 'diff-mode)
193
194 (easy-mmode-defmap diff-minor-mode-map
195   `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
196   "Keymap for `diff-minor-mode'.  See also `diff-mode-shared-map'.")
197
198
199 ;;;;
200 ;;;; font-lock support
201 ;;;;
202
203 (defface diff-header-face
204   '((((type tty pc) (class color) (background light))
205      (:foreground "blue1" :bold t))
206     (((type tty pc) (class color) (background dark))
207      (:foreground "green" :bold t))
208     (((class color) (background light))
209      (:background "grey85"))
210     (((class color) (background dark))
211      (:background "grey45"))
212     (t (:bold t)))
213   "`diff-mode' face inherited by hunk and index header faces."
214   :group 'diff-mode)
215 (defvar diff-header-face 'diff-header-face)
216
217 (defface diff-file-header-face
218   '((((type tty pc) (class color) (background light))
219      (:foreground "yellow" :bold t))
220     (((type tty pc) (class color) (background dark))
221      (:foreground "cyan" :bold t))
222     (((class color) (background light))
223      (:background "grey70" :bold t))
224     (((class color) (background dark))
225      (:background "grey60" :bold t))
226     (t (:bold t)))                      ; :height 1.3
227   "`diff-mode' face used to highlight file header lines."
228   :group 'diff-mode)
229 (defvar diff-file-header-face 'diff-file-header-face)
230
231 (defface diff-index-face
232   ;; XEmacs change: no :inherit in 21.4, copy/pasted `diff-file-header-face'.
233   '((((type tty pc) (class color) (background light))
234      (:foreground "yellow" :bold t))
235     (((type tty pc) (class color) (background dark))
236      (:foreground "cyan" :bold t))
237     (((class color) (background light))
238      (:background "grey70" :bold t))
239     (((class color) (background dark))
240      (:background "grey60" :bold t))
241     (t (:bold t)))                      ; :height 1.3
242   "`diff-mode' face used to highlight index header lines."
243   :group 'diff-mode)
244 (defvar diff-index-face 'diff-index-face)
245
246 (defface diff-hunk-header-face
247   ;; XEmacs change: no :inherit in 21.4; copy/pasted `diff-header-face'.
248   '((((type tty pc) (class color) (background light))
249      (:foreground "blue1" :bold t))
250     (((type tty pc) (class color) (background dark))
251      (:foreground "green" :bold t))
252     (((class color) (background light))
253      (:background "grey85"))
254     (((class color) (background dark))
255      (:background "grey45"))
256     (t (:bold t)))
257   "`diff-mode' face used to highlight hunk header lines."
258   :group 'diff-mode)
259 (defvar diff-hunk-header-face 'diff-hunk-header-face)
260
261 (defface diff-removed-face
262   ;; XEmacs change: no :inherit in 21.4; copy/pasted `diff-changed-face'.
263   '((((type tty pc) (class color) (background light))
264      (:foreground "magenta" :bold t :italic t))
265     (((type tty pc) (class color) (background dark))
266      (:foreground "yellow" :bold t :italic t))
267     (t ()))
268   "`diff-mode' face used to highlight removed lines."
269   :group 'diff-mode)
270 (defvar diff-removed-face 'diff-removed-face)
271
272 (defface diff-added-face
273   ;; XEmacs change: no :inherit in 21.4; copy/pasted `diff-changed-face'.
274   '((((type tty pc) (class color) (background light))
275      (:foreground "magenta" :bold t :italic t))
276     (((type tty pc) (class color) (background dark))
277      (:foreground "yellow" :bold t :italic t))
278     (t ()))
279   "`diff-mode' face used to highlight added lines."
280   :group 'diff-mode)
281 (defvar diff-added-face 'diff-added-face)
282
283 (defface diff-changed-face
284   '((((type tty pc) (class color) (background light))
285      (:foreground "magenta" :bold t :italic t))
286     (((type tty pc) (class color) (background dark))
287      (:foreground "yellow" :bold t :italic t))
288     (t ()))
289   "`diff-mode' face used to highlight changed lines."
290   :group 'diff-mode)
291 (defvar diff-changed-face 'diff-changed-face)
292
293 (defface diff-function-face
294   ;; XEmacs change: no :inherit in 21.4; copy/pasted `diff-context-face'.
295   '((((class color) (background light))
296      (:foreground "grey50"))
297     (((class color) (background dark))
298      (:foreground "grey70"))
299     (t ))
300   "`diff-mode' face used to highlight function names produced by \"diff -p\"."
301   :group 'diff-mode)
302 (defvar diff-function-face 'diff-function-face)
303
304 (defface diff-context-face
305   '((((class color) (background light))
306      (:foreground "grey50"))
307     (((class color) (background dark))
308      (:foreground "grey70"))
309     (t ))
310   "`diff-mode' face used to highlight context and other side-information."
311   :group 'diff-mode)
312 (defvar diff-context-face 'diff-context-face)
313
314 (defface diff-nonexistent-face
315   ;; XEmacs change: no :inherit in 21.4; copy/pasted `diff-file-header-face'.
316   '((((type tty pc) (class color) (background light))
317      (:foreground "yellow" :bold t))
318     (((type tty pc) (class color) (background dark))
319      (:foreground "cyan" :bold t))
320     (((class color) (background light))
321      (:background "grey70" :bold t))
322     (((class color) (background dark))
323      (:background "grey60" :bold t))
324     (t (:bold t)))                      ; :height 1.3
325   "`diff-mode' face used to highlight nonexistent files in recursive diffs."
326   :group 'diff-mode)
327 (defvar diff-nonexistent-face 'diff-nonexistent-face)
328
329 (defvar diff-font-lock-keywords
330   '(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
331      (1 diff-hunk-header-face)
332      (2 diff-function-face))
333     ("^--- .+ ----$" . diff-hunk-header-face) ;context
334     ("^\\(\\*\\{15\\}\\)\\(.*\\)$"      ;context
335      (1 diff-hunk-header-face)
336      (2 diff-function-face))
337     ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
338     ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
339      (0 diff-header-face) (2 diff-file-header-face prepend))
340     ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face)
341     ("^!.*\n" . diff-changed-face)      ;context
342     ("^[+>].*\n" . diff-added-face)
343     ("^[-<].*\n" . diff-removed-face)
344     ("^Index: \\(.+\\).*\n" (0 diff-header-face) (1 diff-index-face prepend))
345     ("^Only in .*\n" . diff-nonexistent-face)
346     ("^#.*" . font-lock-string-face)
347     ("^[^-=+*!<>].*\n" . diff-context-face)))
348
349 (defconst diff-font-lock-defaults
350   '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
351
352 (defvar diff-imenu-generic-expression
353   ;; Prefer second name as first is most likely to be a backup or
354   ;; version-control name.  The [\t\n] at the end of the unidiff pattern
355   ;; catches Debian source diff files (which lack the trailing date).
356   '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
357     (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
358
359 ;; XEmacs change: we don't have combine-after-change-calls.
360 (eval-when-compile
361   (unless (fboundp 'combine-after-change-calls)
362     (defmacro combine-after-change-calls (&rest body)
363       "Execute `body'."
364       `(progn ,@body))))
365
366 ;; XEmacs change: we don't have delete-and-extract-region
367 (eval-when-compile
368   (unless (fboundp 'delete-and-extract-region)
369     (defun delete-and-extract-region (start end)
370       "Delete the text between START and END and return it."
371       (let ((str (buffer-substring start end)))
372         (delete-region start end)
373         str))))
374
375 ;;;;
376 ;;;; Compile support
377 ;;;;
378
379 (defvar diff-file-regexp-alist
380   '(("Index: \\(.+\\)" 1)))
381
382 (defvar diff-error-regexp-alist
383   '(("@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@" nil 2)
384     ("--- \\([0-9]+\\),[0-9]+ ----" nil 1)
385     ("\\([0-9]+\\)\\(,[0-9]+\\)?[adc]\\([0-9]+\\)" nil 3)))
386
387 ;;;;
388 ;;;; Movement
389 ;;;;
390
391 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
392 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
393 (defvar diff-narrowed-to nil)
394
395 (defun diff-end-of-hunk (&optional style)
396   (when (looking-at diff-hunk-header-re)
397     (unless style
398       ;; Especially important for unified (because headers are ambiguous).
399       (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
400     (goto-char (match-end 0)))
401   (let ((end (and (re-search-forward (case style
402                                        ;; A `unified' header is ambiguous.
403                                        (unified (concat "^[^-+# \\]\\|"
404                                                         diff-file-header-re))
405                                        (context "^[^-+#! \\]")
406                                        (normal "^[^<>#\\]")
407                                        (t "^[^-+#!<> \\]"))
408                                      nil t)
409                   (match-beginning 0))))
410     ;; The return value is used by easy-mmode-define-navigation.
411     (goto-char (or end (point-max)))))
412
413 (defun diff-beginning-of-hunk ()
414   (beginning-of-line)
415   (unless (looking-at diff-hunk-header-re)
416     (forward-line 1)
417     (condition-case ()
418         (re-search-backward diff-hunk-header-re)
419       (error (error "Can't find the beginning of the hunk")))))
420
421 (defun diff-beginning-of-file ()
422   (beginning-of-line)
423   (unless (looking-at diff-file-header-re)
424     (forward-line 2)
425     (condition-case ()
426         (re-search-backward diff-file-header-re)
427       (error (error "Can't find the beginning of the file")))))
428
429 (defun diff-end-of-file ()
430   (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
431   (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
432                      nil 'move)
433   (if (match-beginning 1)
434       (goto-char (match-beginning 1))
435     (beginning-of-line)))
436
437 ;; Define diff-{hunk,file}-{prev,next}
438 (easy-mmode-define-navigation
439  diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk)
440 (easy-mmode-define-navigation
441  diff-file diff-file-header-re "file" diff-end-of-hunk)
442
443 (defun diff-restrict-view (&optional arg)
444   "Restrict the view to the current hunk.
445 If the prefix ARG is given, restrict the view to the current file instead."
446   (interactive "P")
447   (save-excursion
448     (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
449     (narrow-to-region (point)
450                       (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
451                              (point)))
452     (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
453
454
455 (defun diff-hunk-kill ()
456   "Kill current hunk."
457   (interactive)
458   (diff-beginning-of-hunk)
459   (let ((start (point))
460         (firsthunk (save-excursion
461                      (ignore-errors
462                        (diff-beginning-of-file) (diff-hunk-next) (point))))
463         (nexthunk  (save-excursion
464                      (ignore-errors
465                        (diff-hunk-next) (point))))
466         (nextfile (save-excursion
467                     (ignore-errors
468                       (diff-file-next) (point)))))
469     (if (and firsthunk (= firsthunk start)
470              (or (null nexthunk)
471                  (and nextfile (> nexthunk nextfile))))
472         ;; It's the only hunk for this file, so kill the file.
473         (diff-file-kill)
474       (diff-end-of-hunk)
475       (kill-region start (point)))))
476
477 (defun diff-file-kill ()
478   "Kill current file's hunks."
479   (interactive)
480   (diff-beginning-of-file)
481   (let* ((start (point))
482          (prevhunk (save-excursion
483                      (ignore-errors
484                        (diff-hunk-prev) (point))))
485          (index (save-excursion
486                   (re-search-backward "^Index: " prevhunk t))))
487     (when index (setq start index))
488     (diff-end-of-file)
489     (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
490     (kill-region start (point))))
491
492 (defun diff-kill-junk ()
493   "Kill spurious empty diffs."
494   (interactive)
495   (save-excursion
496     (let ((inhibit-read-only t))
497       (goto-char (point-min))
498       (while (re-search-forward (concat "^\\(Index: .*\n\\)"
499                                         "\\([^-+!* <>].*\n\\)*?"
500                                         "\\(\\(Index:\\) \\|"
501                                         diff-file-header-re "\\)")
502                                 nil t)
503         (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
504                        (match-beginning 3))
505         (beginning-of-line)))))
506
507 (defun diff-count-matches (re start end)
508   (save-excursion
509     (let ((n 0))
510       (goto-char start)
511       (while (re-search-forward re end t) (incf n))
512       n)))
513
514 (defun diff-split-hunk ()
515   "Split the current (unified diff) hunk at point into two hunks."
516   (interactive)
517   (beginning-of-line)
518   (let ((pos (point))
519         (start (progn (diff-beginning-of-hunk) (point))))
520     (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
521       (error "diff-split-hunk only works on unified context diffs"))
522     (forward-line 1)
523     (let* ((start1 (string-to-number (match-string 1)))
524            (start2 (string-to-number (match-string 2)))
525            (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
526            (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos))))
527       (goto-char pos)
528       ;; Hopefully the after-change-function will not screw us over.
529       (insert "@@ -" (number-to-string newstart1) ",1 +"
530               (number-to-string newstart2) ",1 @@\n")
531       ;; Fix the original hunk-header.
532       (diff-fixup-modifs start pos))))
533
534
535 ;;;;
536 ;;;; jump to other buffers
537 ;;;;
538
539 (defvar diff-remembered-files-alist nil)
540
541 (defun diff-filename-drop-dir (file)
542   (when (string-match "/" file) (substring file (match-end 0))))
543
544 (defun diff-merge-strings (ancestor from to)
545   "Merge the diff between ANCESTOR and FROM into TO.
546 Returns the merged string if successful or nil otherwise.
547 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
548 If ANCESTOR = FROM, returns TO.
549 If ANCESTOR = TO, returns FROM.
550 The heuristic is simplistic and only really works for cases
551 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
552   ;; Ideally, we want:
553   ;;   AMB ANB CMD -> CND
554   ;; but that's ambiguous if `foo' or `bar' is empty:
555   ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
556   (let ((str (concat ancestor "\n" from "\n" to)))
557     (when (and (string-match (concat
558                               "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
559                               "\\1\\(.*\\)\\3\n"
560                               "\\(.*\\(\\2\\).*\\)\\'") str)
561                (equal to (match-string 5 str)))
562       (concat (substring str (match-beginning 5) (match-beginning 6))
563               (match-string 4 str)
564               (substring str (match-end 6) (match-end 5))))))
565
566 (defun diff-find-file-name (&optional old)
567   "Return the file corresponding to the current patch.
568 Non-nil OLD means that we want the old file."
569   (save-excursion
570     (unless (looking-at diff-file-header-re)
571       (or (ignore-errors (diff-beginning-of-file))
572           (re-search-forward diff-file-header-re nil t)))
573     (let* ((limit (save-excursion
574                    (condition-case ()
575                        (progn (diff-hunk-prev) (point))
576                      (error (point-min)))))
577            (header-files
578             (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
579                 (list (if old (match-string 1) (match-string 3))
580                       (if old (match-string 3) (match-string 1)))
581               (forward-line 1) nil))
582            (fs (append
583                 (when (save-excursion
584                         (re-search-backward "^Index: \\(.+\\)" limit t))
585                   (list (match-string 1)))
586                 header-files
587                 (when (re-search-backward "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?" nil t)
588                   (list (if old (match-string 2) (match-string 4))
589                         (if old (match-string 4) (match-string 2))))))
590            (fs (delq nil fs)))
591       (or
592        ;; use any previously used preference
593        (cdr (assoc fs diff-remembered-files-alist))
594        ;; try to be clever and use previous choices as an inspiration
595        (dolist (rf diff-remembered-files-alist)
596          (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
597            (if (and newfile (file-exists-p newfile)) (return newfile))))
598        ;; look for each file in turn.  If none found, try again but
599        ;; ignoring the first level of directory, ...
600        (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
601              (file nil nil))
602            ((or (null files)
603                 (setq file (do* ((files files (cdr files))
604                                  (file (car files) (car files)))
605                                ((or (null file) (file-exists-p file))
606                                 file))))
607             file))
608        ;; <foo>.rej patches implicitly apply to <foo>
609        (and (string-match "\\.rej\\'" (or buffer-file-name ""))
610             (let ((file (substring buffer-file-name 0 (match-beginning 0))))
611               (when (file-exists-p file) file)))
612        ;; if all else fails, ask the user
613        (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
614                                    nil (first fs) t (first fs))))
615          (set (make-local-variable 'diff-remembered-files-alist)
616               (cons (cons fs file) diff-remembered-files-alist))
617          file)))))
618
619
620 (defun diff-mouse-goto-source (event)
621   "Run `diff-goto-source' for the diff at a mouse click."
622   (interactive "e")
623   (save-excursion
624     (mouse-set-point event)
625     (diff-goto-source)))
626
627
628 (defun diff-ediff-patch ()
629   "Call `ediff-patch-file' on the current buffer."
630   (interactive)
631   (condition-case err
632       (ediff-patch-file nil (current-buffer))
633     (wrong-number-of-arguments (ediff-patch-file))))
634
635 ;;;;
636 ;;;; Conversion functions
637 ;;;;
638
639 ;;(defvar diff-inhibit-after-change nil
640 ;;  "Non-nil means inhibit `diff-mode's after-change functions.")
641
642 (defun diff-unified->context (start end)
643   "Convert unified diffs to context diffs.
644 START and END are either taken from the region (if a prefix arg is given) or
645 else cover the whole bufer."
646   (interactive (if current-prefix-arg
647                    (list (mark) (point))
648                  (list (point-min) (point-max))))
649   (unless (markerp end) (setq end (copy-marker end)))
650   (let (;;(diff-inhibit-after-change t)
651         (inhibit-read-only t))
652     (save-excursion
653       (goto-char start)
654       (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
655                   (< (point) end))
656         (combine-after-change-calls
657           (if (match-beginning 2)
658               ;; we matched a file header
659               ;; XEmacs change: don't use `replace-match'
660               ;; which has a different API there.
661               (save-excursion
662                 ;; use reverse order to make sure the indices are kept valid
663                 (delete-region (match-beginning 3) (match-end 3))
664                 (goto-char (match-beginning 3))
665                 (insert-string "---")
666                 (delete-region (match-beginning 2) (match-end 2))
667                 (goto-char (match-beginning 2))
668                 (insert-string "***"))
669             ;; we matched a hunk header
670             (let ((line1 (match-string 4))
671                   (lines1 (match-string 5))
672                   (line2 (match-string 6))
673                   (lines2 (match-string 7)))
674               (replace-match
675                (concat "***************\n*** " line1 ","
676                        (number-to-string (+ (string-to-number line1)
677                                             (string-to-number lines1)
678                                             -1)) " ****"))
679               (forward-line 1)
680               (save-restriction
681                 (narrow-to-region (point)
682                                   (progn (diff-end-of-hunk 'unified) (point)))
683                 (let ((hunk (buffer-string)))
684                   (goto-char (point-min))
685                   (if (not (save-excursion (re-search-forward "^-" nil t)))
686                       (delete-region (point) (point-max))
687                     (goto-char (point-max))
688                     (let ((modif nil) last-pt)
689                       (while (progn (setq last-pt (point))
690                                     (= (forward-line -1) 0))
691                         (case (char-after)
692                           (?  (insert " ") (setq modif nil) (backward-char 1))
693                           (?+ (delete-region (point) last-pt) (setq modif t))
694                           (?- (if (not modif)
695                                   (progn (forward-char 1)
696                                          (insert " "))
697                                 (delete-char 1)
698                                 (insert "! "))
699                               (backward-char 2))
700                           (?\\ (when (save-excursion (forward-line -1)
701                                                      (= (char-after) ?+))
702                                  (delete-region (point) last-pt) (setq modif t)))
703                           (t (setq modif nil))))))
704                   (goto-char (point-max))
705                   (save-excursion
706                     (insert "--- " line2 ","
707                             (number-to-string (+ (string-to-number line2)
708                                                  (string-to-number lines2)
709                                                  -1)) " ----\n" hunk))
710                   ;;(goto-char (point-min))
711                   (forward-line 1)
712                   (if (not (save-excursion (re-search-forward "^+" nil t)))
713                       (delete-region (point) (point-max))
714                     (let ((modif nil) (delete nil))
715                       (while (not (eobp))
716                         (case (char-after)
717                           (?  (insert " ") (setq modif nil) (backward-char 1))
718                           (?- (setq delete t) (setq modif t))
719                           (?+ (if (not modif)
720                                   (progn (forward-char 1)
721                                          (insert " "))
722                                 (delete-char 1)
723                                 (insert "! "))
724                               (backward-char 2))
725                           (?\\ (when (save-excursion (forward-line 1)
726                                                      (not (eobp)))
727                                  (setq delete t) (setq modif t)))
728                           (t (setq modif nil)))
729                         (let ((last-pt (point)))
730                           (forward-line 1)
731                           (when delete
732                             (delete-region last-pt (point))
733                             (setq delete nil)))))))))))))))
734
735 (defun diff-context->unified (start end)
736   "Convert context diffs to unified diffs.
737 START and END are either taken from the region (if a prefix arg is given) or
738 else cover the whole bufer."
739   (interactive (if current-prefix-arg
740                    (list (mark) (point))
741                  (list (point-min) (point-max))))
742   (unless (markerp end) (setq end (copy-marker end)))
743   (let (;;(diff-inhibit-after-change t)
744         (inhibit-read-only t))
745     (save-excursion
746       (goto-char start)
747       (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
748                   (< (point) end))
749         (combine-after-change-calls
750           (if (match-beginning 2)
751               ;; we matched a file header
752               ;; XEmacs change: don't use `replace-match'
753               ;; which has a different API there.
754               (save-excursion
755                ;; use reverse order to make sure the indices are kept valid
756                 (delete-region (match-beginning 3) (match-end 3))
757                 (goto-char (match-beginning 3))
758                 (insert-string "+++")
759                 (delete-region (match-beginning 2) (match-end 2))
760                 (goto-char (match-beginning 2))
761                 (insert-string "---"))
762             ;; we matched a hunk header
763             (let ((line1s (match-string 4))
764                   (line1e (match-string 5))
765                   (pt1 (match-beginning 0)))
766               (replace-match "")
767               (unless (re-search-forward
768                        "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
769                 (error "Can't find matching `--- n1,n2 ----' line"))
770               (let ((line2s (match-string 1))
771                     (line2e (match-string 2))
772                     (pt2 (progn
773                            (delete-region (progn (beginning-of-line) (point))
774                                           (progn (forward-line 1) (point)))
775                            (point-marker))))
776                 (goto-char pt1)
777                 (forward-line 1)
778                 (while (< (point) pt2)
779                   (case (char-after)
780                     ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
781                     (?\                 ;merge with the other half of the chunk
782                      (let* ((endline2
783                              (save-excursion
784                                (goto-char pt2) (forward-line 1) (point)))
785                             (c (char-after pt2)))
786                        (case c
787                          ((?! ?+)
788                           (insert "+"
789                                   (prog1 (buffer-substring (+ pt2 2) endline2)
790                                     (delete-region pt2 endline2))))
791                          (?\            ;FIXME: check consistency
792                           (delete-region pt2 endline2)
793                           (delete-char 1)
794                           (forward-line 1))
795                          (?\\ (forward-line 1))
796                          (t (delete-char 1) (forward-line 1)))))
797                     (t (forward-line 1))))
798                 (while (looking-at "[+! ] ")
799                   (if (/= (char-after) ?!) (forward-char 1)
800                     (delete-char 1) (insert "+"))
801                   (delete-char 1) (forward-line 1))
802                 (save-excursion
803                   (goto-char pt1)
804                   (insert "@@ -" line1s ","
805                           (number-to-string (- (string-to-number line1e)
806                                                (string-to-number line1s)
807                                                -1))
808                           " +" line2s ","
809                           (number-to-string (- (string-to-number line2e)
810                                                (string-to-number line2s)
811                                                -1)) " @@"))))))))))
812
813 ;; XEmacs change: extracted from `diff-reverse-direction'
814 (defvar diff-patch-start-regexp
815   (concat
816    ;; start
817    "^\\("
818    ;; Typical start of diff
819    ;; --- file
820    ;; +++ file
821    "\\([-*][-*][-*] \\)\\(.+\\)\n"
822    "\\([-+][-+][-+] \\)\\(.+\\)"
823    ;; or
824    "\\|"
825    ;; I'm not sure
826    "\\*\\{15\\}.*\n"
827    "\\*\\*\\* \\(.+\\) \\*\\*\\*\\*"
828    ;; or
829    "\\|"
830    ;; hunk
831    "@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*"
832    ;; end
833    "\\)$"))
834
835
836 ;; XEmacs change: use region (mark) if set, do whole buffer otherwise
837 (defun diff-reverse-direction (start end)
838   "Reverse the direction of the diffs.
839 START and END are either taken from the region (if it is set) or
840 else cover the whole buffer."
841   (interactive (if (mark)
842                    (list (mark) (point))
843                  (list (point-min) (point-max))))
844   (unless (markerp end) (setq end (copy-marker end)))
845   (let (;;(diff-inhibit-after-change t)
846         (inhibit-read-only t))
847     (save-excursion
848       (goto-char start)
849       ;; XEmacs change: use `diff-patch-start-regexp'
850       (while (and (re-search-forward diff-patch-start-regexp nil t)
851                   (< (point) end))
852         (combine-after-change-calls
853           (cond
854            ;; a file header
855            ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
856            ;; a context-diff hunk header
857            ((match-beginning 6)
858             (let ((pt-lines1 (match-beginning 6))
859                   (lines1 (match-string 6)))
860               (replace-match "" nil nil nil 6)
861               (forward-line 1)
862               (let ((half1s (point)))
863                 (while (looking-at "[-! \\][ \t]\\|#")
864                   (when (= (char-after) ?-) (delete-char 1) (insert "+"))
865                   (forward-line 1))
866                 (let ((half1 (delete-and-extract-region half1s (point))))
867                   (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
868                     (insert half1)
869                     (error "Can't find matching `--- n1,n2 ----' line"))
870                   (let ((str1 (match-string 1)))
871                     (replace-match lines1 nil nil nil 1)
872                     (forward-line 1)
873                     (let ((half2s (point)))
874                       (while (looking-at "[!+ \\][ \t]\\|#")
875                         (when (= (char-after) ?+) (delete-char 1) (insert "-"))
876                         (forward-line 1))
877                       (let ((half2 (delete-and-extract-region half2s (point))))
878                         (insert (or half1 ""))
879                         (goto-char half1s)
880                         (insert (or half2 ""))))
881                     (goto-char pt-lines1)
882                     (insert str1))))))
883            ;; a unified-diff hunk header
884            ((match-beginning 7)
885             (replace-match "@@ -\\8 +\\7 @@" nil)
886             (forward-line 1)
887             (let ((c (char-after)) first last)
888               (while (case (setq c (char-after))
889                        ;; XEmacs change: check for --- and +++ before reversing
890                        (?- (if (and (char= (char-after (+ 1 (point)))
891                                            ?-)
892                                     (char= (char-after (+ 2 (point)))
893                                            ?-))
894                                nil
895                                (progn
896                                  (setq first (or first (point)))
897                                  (delete-char 1)
898                                  (insert "+")
899                                  t)))
900                        (?+ (if (and (char= (char-after (+ 1 (point)))
901                                            ?+)
902                                     (char= (char-after (+ 2 (point)))
903                                            ?+))
904                                nil
905                                (progn
906                                  (setq last (or last (point)))
907                                  (delete-char 1)
908                                  (insert "-")
909                                  t)))
910                        ((?\\ ?#) t)
911                        (t (when (and first last (< first last))
912                             (insert (delete-and-extract-region first last)))
913                           (setq first nil last nil)
914                           (equal ?\  c)))
915                 (forward-line 1))))))))))
916
917 (defun diff-fixup-modifs (start end)
918   "Fixup the hunk headers (in case the buffer was modified).
919 START and END are either taken from the region (if a prefix arg is given) or
920 else cover the whole buffer."
921   (interactive (if current-prefix-arg
922                    (list (mark) (point))
923                  (list (point-min) (point-max))))
924   (let ((inhibit-read-only t))
925     (save-excursion
926       (goto-char end) (diff-end-of-hunk)
927       (let ((plus 0) (minus 0) (space 0) (bang 0))
928         (while (and (= (forward-line -1) 0) (<= start (point)))
929           (if (not (looking-at
930                     (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
931                             "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
932                             "\\|--- .+\n\\+\\+\\+ ")))
933               (case (char-after)
934                 (?\  (incf space))
935                 (?+ (incf plus))
936                 (?- (incf minus))
937                 (?! (incf bang))
938                 ((?\\ ?#) nil)
939                 (t  (setq space 0 plus 0 minus 0 bang 0)))
940             (cond
941              ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
942               (let* ((old1 (match-string 1))
943                      (old2 (match-string 2))
944                      (new1 (number-to-string (+ space minus)))
945                      (new2 (number-to-string (+ space plus))))
946                 (unless (string= new2 old2) (replace-match new2 t t nil 2))
947                 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
948              ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
949               (when (> (+ space bang plus) 0)
950                 (let* ((old1 (match-string 1))
951                        (old2 (match-string 2))
952                        (new (number-to-string
953                              (+ space bang plus -1 (string-to-number old1)))))
954                   (unless (string= new old2) (replace-match new t t nil 2)))))
955              ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
956               (when (> (+ space bang minus) 0)
957                 (let* ((old (match-string 1))
958                        (new (format
959                              (concat "%0" (number-to-string (length old)) "d")
960                              (+ space bang minus -1 (string-to-number old)))))
961                   (unless (string= new old) (replace-match new t t nil 2))))))
962             (setq space 0 plus 0 minus 0 bang 0)))))))
963
964 ;;;;
965 ;;;; Hooks
966 ;;;;
967
968 (defun diff-write-contents-hooks ()
969   "Fixup hunk headers if necessary."
970   (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
971   nil)
972
973 ;; XEmacs change: we don't seem to have this feature.
974 (defvar undo-in-progress nil)
975
976 ;; It turns out that making changes in the buffer from within an
977 ;; *-change-function is asking for trouble, whereas making them
978 ;; from a post-command-hook doesn't pose much problems
979 (defvar diff-unhandled-changes nil)
980 (defun diff-after-change-function (beg end len)
981   "Remember to fixup the hunk header.
982 See `after-change-functions' for the meaning of BEG, END and LEN."
983   ;; Ignoring changes when inhibit-read-only is set is strictly speaking
984   ;; incorrect, but it turns out that inhibit-read-only is normally not set
985   ;; inside editing commands, while it tends to be set when the buffer gets
986   ;; updated by an async process or by a conversion function, both of which
987   ;; would rather not be uselessly slowed down by this hook.
988   (when (and (not undo-in-progress) (not inhibit-read-only))
989     (if diff-unhandled-changes
990         (setq diff-unhandled-changes
991               (cons (min beg (car diff-unhandled-changes))
992                     (max end (cdr diff-unhandled-changes))))
993       (setq diff-unhandled-changes (cons beg end)))))
994
995 (defun diff-post-command-hook ()
996   "Fixup hunk headers if necessary."
997   (when (consp diff-unhandled-changes)
998     (ignore-errors
999       (save-excursion
1000         (goto-char (car diff-unhandled-changes))
1001         (unless (ignore-errors
1002                   (diff-beginning-of-hunk)
1003                   (save-excursion
1004                     (diff-end-of-hunk)
1005                     (> (point) (car diff-unhandled-changes))))
1006           (goto-char (car diff-unhandled-changes))
1007           (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
1008           (diff-beginning-of-hunk))
1009         (diff-fixup-modifs (point) (cdr diff-unhandled-changes))))
1010     (setq diff-unhandled-changes nil)))
1011
1012
1013 ;;;; 
1014 ;;;; The main function
1015 ;;;; 
1016
1017 ;; XEmacs hack: autoload a dummy autoload instead of a derived mode
1018 ;;;###autoload(autoload 'diff-mode "diff-mode" nil t)
1019 (define-derived-mode diff-mode fundamental-mode "Diff"
1020   "Major mode for viewing/editing context diffs.
1021 Supports unified and context diffs as well as (to a lesser extent)
1022 normal diffs.
1023 When the buffer is read-only, the ESC prefix is not necessary."
1024   (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1025   (set (make-local-variable 'outline-regexp) diff-outline-regexp)
1026   (set (make-local-variable 'imenu-generic-expression)
1027        diff-imenu-generic-expression)
1028   ;; These are not perfect.  They would be better done separately for
1029   ;; context diffs and unidiffs.
1030   ;; (set (make-local-variable 'paragraph-start)
1031   ;;        (concat "@@ "                       ; unidiff hunk
1032   ;;           "\\|\\*\\*\\* "          ; context diff hunk or file start
1033   ;;           "\\|--- [^\t]+\t"))      ; context or unidiff file
1034   ;;                                    ; start (first or second line)
1035   ;;   (set (make-local-variable 'paragraph-separate) paragraph-start)
1036   ;;   (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1037   ;; compile support
1038
1039   ;;;; compile support is not good enough yet.  Also it can be annoying
1040   ;; and should thus only be enabled conditionally.
1041   ;; (set (make-local-variable 'compilation-file-regexp-alist)
1042   ;;      diff-file-regexp-alist)
1043   ;; (set (make-local-variable 'compilation-error-regexp-alist)
1044   ;;      diff-error-regexp-alist)
1045   ;; (when (string-match "\\.rej\\'" (or buffer-file-name ""))
1046   ;;   (set (make-local-variable 'compilation-current-file)
1047   ;;     (substring buffer-file-name 0 (match-beginning 0))))
1048   ;; (compilation-shell-minor-mode 1)
1049
1050   (when (and (> (point-max) (point-min)) diff-default-read-only)
1051     (toggle-read-only t))
1052   ;; setup change hooks
1053   (if (not diff-update-on-the-fly)
1054       (add-hook 'write-contents-hooks 'diff-write-contents-hooks)
1055     (make-local-variable 'diff-unhandled-changes)
1056     ;; XEmacs change: make local
1057     (make-local-hook 'after-change-functions)
1058     (add-hook 'after-change-functions 'diff-after-change-function nil t)
1059     ;; XEmacs change: make local
1060     (make-local-hook 'post-command-hook)
1061     (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1062
1063   ;; Neat trick from Dave Love to add more bindings in read-only mode:
1064   ;; XEmacs change: we don't have minor-mode-overriding-map-alist
1065   (add-to-list (make-local-variable 'minor-mode-map-alist)
1066                (cons 'buffer-read-only diff-mode-shared-map))
1067   ;; add-log support
1068   (set (make-local-variable 'add-log-current-defun-function)
1069        'diff-current-defun)
1070   (set (make-local-variable 'add-log-buffer-file-name-function)
1071        'diff-find-file-name))
1072
1073 ;; XEmacs hack: autoload a dummy autoload instead of a minor mode
1074 ;;;###autoload(autoload 'diff-minor-mode "diff-mode" nil t)
1075 (define-minor-mode diff-minor-mode
1076   "Minor mode for viewing/editing context diffs.
1077 \\{diff-minor-mode-map}"
1078   nil " Diff" nil
1079   ;; FIXME: setup font-lock
1080   ;; setup change hooks
1081   (if (not diff-update-on-the-fly)
1082       (add-hook 'write-contents-hooks 'diff-write-contents-hooks)
1083     (make-local-variable 'diff-unhandled-changes)
1084     (add-hook 'after-change-functions 'diff-after-change-function nil t)
1085     (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1086
1087
1088 ;;;
1089 ;;; Misc operations that have proved useful at some point.
1090 ;;;
1091
1092 (defun diff-next-complex-hunk ()
1093   "Jump to the next \"complex\" hunk.
1094 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1095 Only works for unified diffs."
1096   (interactive)
1097   (while
1098       (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1099                               nil t)
1100            (equal (match-string 1) (match-string 2)))))
1101
1102 (defun diff-hunk-text (hunk destp &optional char-offset)
1103   "Return the literal source text from HUNK.
1104 if DESTP is nil return the source, otherwise the destination text.
1105 If CHAR-OFFSET is non-nil, it should be a char-offset in
1106 HUNK, and instead of a string, a cons cell is returned whose car is the
1107 appropriate text, and whose cdr is the corresponding char-offset in that text."
1108   (with-temp-buffer
1109     (insert hunk)
1110     (goto-char (point-min))
1111     (let ((src-pos nil)
1112           (dst-pos nil)
1113           (divider-pos nil)
1114           (num-pfx-chars 2))
1115       ;; Set the following variables:
1116       ;;  SRC-POS     buffer pos of the source part of the hunk or nil if none
1117       ;;  DST-POS     buffer pos of the destination part of the hunk or nil
1118       ;;  DIVIDER-POS buffer pos of any divider line separating the src & dst
1119       ;;  NUM-PFX-CHARS  number of line-prefix characters used by this format"
1120       (cond ((looking-at "^@@")
1121              ;; unified diff
1122              (setq num-pfx-chars 1)
1123              (forward-line 1)
1124              (setq src-pos (point) dst-pos (point)))
1125             ((looking-at "^\\*\\*")
1126              ;; context diff
1127              (forward-line 2)
1128              (setq src-pos (point))
1129              (re-search-forward "^--- " nil t)
1130              (forward-line 0)
1131              (setq divider-pos (point))
1132              (forward-line 1)
1133              (setq dst-pos (point)))
1134             ((looking-at "^[0-9]+a[0-9,]+$")
1135              ;; normal diff, insert
1136              (forward-line 1)
1137              (setq dst-pos (point)))
1138             ((looking-at "^[0-9,]+d[0-9]+$")
1139              ;; normal diff, delete
1140              (forward-line 1)
1141              (setq src-pos (point)))
1142             ((looking-at "^[0-9,]+c[0-9,]+$")
1143              ;; normal diff, change
1144              (forward-line 1)
1145              (setq src-pos (point))
1146              (re-search-forward "^---$" nil t)
1147              (forward-line 0)
1148              (setq divider-pos (point))
1149              (forward-line 1)
1150              (setq dst-pos (point)))
1151             (t
1152              (error "Unknown diff hunk type")))
1153
1154       (if (if destp (null dst-pos) (null src-pos))
1155           ;; Implied empty text
1156           (if char-offset '("" . 0) "")
1157
1158         ;; For context diffs, either side can be empty, (if there's only
1159         ;; added or only removed text).  We should then use the other side.
1160         (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1161               ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1162
1163         (when char-offset (goto-char (+ (point-min) char-offset)))
1164
1165         ;; Get rid of anything except the desired text.
1166         (save-excursion
1167           ;; Delete unused text region
1168           (let ((keep (if destp dst-pos src-pos)))
1169             (when (and divider-pos (> divider-pos keep))
1170               (delete-region divider-pos (point-max)))
1171             (delete-region (point-min) keep))
1172           ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1173           (let ((kill-char (if destp ?- ?+)))
1174             (goto-char (point-min))
1175             (while (not (eobp))
1176               (if (eq (char-after) kill-char)
1177                   (delete-region (point) (progn (forward-line 1) (point)))
1178                 (delete-char num-pfx-chars)
1179                 (forward-line 1)))))
1180
1181         (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1182           (if char-offset (cons text (- (point) (point-min))) text))))))
1183
1184
1185 (defun diff-find-text (text)
1186   "Return the buffer position of the nearest occurrence of TEXT.
1187 If TEXT isn't found, nil is returned."
1188   (let* ((orig (point))
1189          (forw (and (search-forward text nil t)
1190                           (match-beginning 0)))
1191          (back (and (goto-char (+ orig (length text)))
1192                     (search-backward text nil t)
1193                           (match-beginning 0))))
1194           ;; Choose the closest match.
1195     (if (and forw back)
1196         (if (> (- forw orig) (- orig back)) back forw)
1197       (or back forw))))
1198
1199 (defsubst diff-xor (a b) (if a (not b) b))
1200
1201 (defun diff-find-source-location (&optional other-file reverse)
1202   "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED)."
1203   (save-excursion
1204     (let* ((other (diff-xor other-file diff-jump-to-old-file))
1205            (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1206            (hunk (buffer-substring (point)
1207                                    (save-excursion (diff-end-of-hunk) (point))))
1208            (old (diff-hunk-text hunk reverse char-offset))
1209            (new (diff-hunk-text hunk (not reverse) char-offset))
1210            ;; Find the location specification.
1211            (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1212                      (error "Can't find the hunk header")
1213                    (if other (match-string 1)
1214                      (if (match-end 3) (match-string 3)
1215                        (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1216                          (error "Can't find the hunk separator"))
1217                        (match-string 1)))))
1218            (file (or (diff-find-file-name other) (error "Can't find the file")))
1219            (buf (find-file-noselect file)))
1220       ;; Update the user preference if he so wished.
1221       (when (> (prefix-numeric-value other-file) 8)
1222         (setq diff-jump-to-old-file other))
1223       (with-current-buffer buf
1224         (goto-line (string-to-number line))
1225         (let* ((orig-pos (point))
1226                (pos (diff-find-text (car old)))
1227                (switched nil))
1228           (when (null pos)
1229             (setq pos (diff-find-text (car new)) switched t))
1230           (nconc
1231            (list buf)
1232            (if pos (list (count-lines orig-pos pos) pos) (list nil orig-pos))
1233            (if switched (list new old t) (list old new))))))))
1234
1235
1236 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1237   (let ((msg (if dry-run
1238                  (if reversed "already applied" "not yet applied")
1239                (if reversed "undone" "applied"))))
1240     (message (cond ((null line-offset) "Hunk text not found")
1241                    ((= line-offset 0) "Hunk %s")
1242                    ((= line-offset 1) "Hunk %s at offset %d line")
1243                    (t "Hunk %s at offset %d lines"))
1244              msg line-offset)))
1245
1246
1247 (defun diff-apply-hunk (&optional reverse)
1248   "Apply the current hunk to the source file and go to the next.
1249 By default, the new source file is patched, but if the variable
1250 `diff-jump-to-old-file' is non-nil, then the old source file is
1251 patched instead (some commands, such as `diff-goto-source' can change
1252 the value of this variable when given an appropriate prefix argument).
1253
1254 With a prefix argument, REVERSE the hunk."
1255   (interactive "P")
1256   (destructuring-bind (buf line-offset pos old new &optional switched)
1257       ;; If REVERSE go to the new file, otherwise go to the old.
1258       (diff-find-source-location (not reverse) reverse)
1259     (cond
1260      ((null line-offset)
1261       (error "Can't find the text to patch"))
1262      ((and switched
1263            ;; A reversed patch was detected, perhaps apply it in reverse.
1264            (not (save-window-excursion
1265                   (pop-to-buffer buf)
1266                   (goto-char (+ pos (cdr old)))
1267                   (y-or-n-p
1268                    (if reverse
1269                        "Hunk hasn't been applied yet; apply it now? "
1270                      "Hunk has already been applied; undo it? ")))))
1271       (message "(Nothing done)"))
1272      (t
1273       ;; Apply the hunk
1274       (with-current-buffer buf
1275         (goto-char pos)
1276         (delete-char (length (car old)))
1277         (insert (car new)))
1278       ;; Display BUF in a window
1279       (set-window-point (display-buffer buf) (+ pos (cdr new)))
1280       (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1281       (when diff-advance-after-apply-hunk
1282         (diff-hunk-next))))))
1283
1284
1285 (defun diff-test-hunk (&optional reverse)
1286   "See whether it's possible to apply the current hunk.
1287 With a prefix argument, try to REVERSE the hunk."
1288   (interactive "P")
1289   (destructuring-bind (buf line-offset pos src dst &optional switched)
1290       ;; If REVERSE go to the new file, otherwise go to the old.
1291       (diff-find-source-location (not reverse) reverse)
1292     (set-window-point (display-buffer buf) (+ pos (cdr src)))
1293     (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1294
1295
1296 (defun diff-goto-source (&optional other-file)
1297   "Jump to the corresponding source line.
1298 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1299 is given) determines whether to jump to the old or the new file.
1300 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1301   then `diff-jump-to-old-file' is also set, for the next invocations."
1302   (interactive "P")
1303   ;; When pointing at a removal line, we probably want to jump to
1304   ;; the old location, and else to the new (i.e. as if reverting).
1305   ;; This is a convenient detail when using smerge-diff.
1306   (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1307     (destructuring-bind (buf line-offset pos src dst &optional switched)
1308         (diff-find-source-location other-file rev)
1309       (pop-to-buffer buf)
1310       (goto-char (+ pos (cdr src)))
1311       (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1312
1313
1314 (defun diff-current-defun ()
1315   "Find the name of function at point.
1316 For use in `add-log-current-defun-function'."
1317   (destructuring-bind (buf line-offset pos src dst &optional switched)
1318       (diff-find-source-location)
1319     (save-excursion
1320       (beginning-of-line)
1321       (or (when (memq (char-after) '(?< ?-))
1322             ;; Cursor is pointing at removed text.  This could be a removed
1323             ;; function, in which case, going to the source buffer will
1324             ;; not help since the function is now removed.  Instead,
1325             ;; try to figure out the function name just from the code-fragment.
1326             (let ((old (if switched dst src)))
1327               (with-temp-buffer
1328                 (insert (car old))
1329                 (goto-char (cdr old))
1330                 (funcall (with-current-buffer buf major-mode))
1331                 (add-log-current-defun))))
1332           (with-current-buffer buf
1333             (goto-char (+ pos (cdr src)))
1334             (add-log-current-defun))))))
1335
1336 ;; XEmacs change: added.
1337 ;;;###autoload(add-to-list 'auto-mode-alist '("\\.\\(diffs?\\|patch\\|rej\\)\\'" . diff-mode))
1338
1339 ;; provide the package
1340 (provide 'diff-mode)
1341
1342 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1343 ;; Revision 1.11  1999/10/09 23:38:29  monnier
1344 ;; (diff-mode-load-hook): dropped.
1345 ;; (auto-mode-alist): also catch *.diffs.
1346 ;; (diff-find-file-name, diff-mode):  add smarts to find the right file
1347 ;;     for *.rej files (that lack any file name indication).
1348 ;;
1349 ;; Revision 1.10  1999/09/30 15:32:11  monnier
1350 ;; added support for "\ No newline at end of file".
1351 ;;
1352 ;; Revision 1.9  1999/09/15 00:01:13  monnier
1353 ;; - added basic `compile' support.
1354 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1355 ;; - diff-kill-file now tries to kill the leading garbage as well.
1356 ;;
1357 ;; Revision 1.8  1999/09/13 21:10:09  monnier
1358 ;; - don't use CL in the autoloaded code
1359 ;; - accept diffs using -T
1360 ;;
1361 ;; Revision 1.7  1999/09/05 20:53:03  monnier
1362 ;; interface to ediff-patch
1363 ;;
1364 ;; Revision 1.6  1999/09/01 20:55:13  monnier
1365 ;; (ediff=patch-file):  add bindings to call ediff-patch.
1366 ;; (diff-find-file-name):  taken out of diff-goto-source.
1367 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1368 ;;  diff-fixup-modifs):  only use the region if a prefix arg is given.
1369 ;;
1370 ;; Revision 1.5  1999/08/31 19:18:52  monnier
1371 ;; (diff-beginning-of-file, diff-prev-file):  fixed wrong parenthesis.
1372 ;;
1373 ;; Revision 1.4  1999/08/31 13:01:44  monnier
1374 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1375 ;;
1376
1377 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1378 ;;; diff-mode.el ends here