1;;; diff-mode.el --- a mode for viewing/editing context diffs
2
3;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4;;   2005, 2006, 2007 Free Software Foundation, Inc.
5
6;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7;; Keywords: convenience patch diff
8
9;; This file is part of GNU Emacs.
10
11;; GNU Emacs 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;; GNU Emacs 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 GNU Emacs; 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;;; Commentary:
27
28;; Provides support for font-lock, outline, navigation
29;; commands, editing and various conversions as well as jumping
30;; to the corresponding source file.
31
32;; Inspired by Pavel Machek's patch-mode.el (<pavel@@atrey.karlin.mff.cuni.cz>)
33;; Some efforts were spent to have it somewhat compatible with XEmacs'
34;; diff-mode as well as with compilation-minor-mode
35
36;; Bugs:
37
38;; - Reverse doesn't work with normal diffs.
39
40;; Todo:
41
42;; - Add a `delete-after-apply' so C-c C-a automatically deletes hunks.
43;;   Also allow C-c C-a to delete already-applied hunks.
44;;
45;; - Try `diff <file> <hunk>' to try and fuzzily discover the source location
46;;   of a hunk.  Show then the changes between <file> and <hunk> and make it
47;;   possible to apply them to <file>, <hunk-src>, or <hunk-dst>.
48;;   Or maybe just make it into a ".rej to diff3-markers converter".
49;;   Maybe just use `wiggle' (by Neil Brown) to do it for us.
50;;
51;; - Refine hunk on a word-by-word basis.
52;;
53;; - in diff-apply-hunk, strip context in replace-match to better
54;;   preserve markers and spacing.
55;; - Handle `diff -b' output in context->unified.
56
57;;; Code:
58(eval-when-compile (require 'cl))
59
60(defvar add-log-buffer-file-name-function)
61
62
63(defgroup diff-mode ()
64  "Major mode for viewing/editing diffs."
65  :version "21.1"
66  :group 'tools
67  :group 'diff)
68
69(defcustom diff-default-read-only nil
70  "If non-nil, `diff-mode' buffers default to being read-only."
71  :type 'boolean
72  :group 'diff-mode)
73
74(defcustom diff-jump-to-old-file nil
75  "*Non-nil means `diff-goto-source' jumps to the old file.
76Else, it jumps to the new file."
77  :type 'boolean
78  :group 'diff-mode)
79
80(defcustom diff-update-on-the-fly t
81  "*Non-nil means hunk headers are kept up-to-date on-the-fly.
82When editing a diff file, the line numbers in the hunk headers
83need to be kept consistent with the actual diff.  This can
84either be done on the fly (but this sometimes interacts poorly with the
85undo mechanism) or whenever the file is written (can be slow
86when editing big diffs)."
87  :type 'boolean
88  :group 'diff-mode)
89
90(defcustom diff-advance-after-apply-hunk t
91  "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
92  :type 'boolean
93  :group 'diff-mode)
94
95
96(defcustom diff-mode-hook nil
97  "Run after setting up the `diff-mode' major mode."
98  :type 'hook
99  :options '(diff-delete-empty-files diff-make-unified)
100  :group 'diff-mode)
101
102(defvar diff-outline-regexp
103  "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
104
105;;;;
106;;;; keymap, menu, ...
107;;;;
108
109(easy-mmode-defmap diff-mode-shared-map
110  '(;; From Pavel Machek's patch-mode.
111    ("n" . diff-hunk-next)
112    ("N" . diff-file-next)
113    ("p" . diff-hunk-prev)
114    ("P" . diff-file-prev)
115    ("k" . diff-hunk-kill)
116    ("K" . diff-file-kill)
117    ;; From compilation-minor-mode.
118    ("}" . diff-file-next)
119    ("{" . diff-file-prev)
120    ("\C-m" . diff-goto-source)
121    ([mouse-2] . diff-goto-source)
122    ;; From XEmacs' diff-mode.
123    ;; Standard M-w is useful, so don't change M-W.
124    ;;("W" . widen)
125    ;;("." . diff-goto-source)		;display-buffer
126    ;;("f" . diff-goto-source)		;find-file
127    ("o" . diff-goto-source)		;other-window
128    ;;("w" . diff-goto-source)		;other-frame
129    ;;("N" . diff-narrow)
130    ;;("h" . diff-show-header)
131    ;;("j" . diff-show-difference)	;jump to Nth diff
132    ;;("q" . diff-quit)
133    ;; Not useful if you have to metafy them.
134    ;;(" " . scroll-up)
135    ;;("\177" . scroll-down)
136    ;; Standard M-a is useful, so don't change M-A.
137    ;;("A" . diff-ediff-patch)
138    ;; Standard M-r is useful, so don't change M-r or M-R.
139    ;;("r" . diff-restrict-view)
140    ;;("R" . diff-reverse-direction)
141    ("q" . quit-window))
142  "Basic keymap for `diff-mode', bound to various prefix keys.")
143
144(easy-mmode-defmap diff-mode-map
145  `(("\e" . ,diff-mode-shared-map)
146    ;; From compilation-minor-mode.
147    ("\C-c\C-c" . diff-goto-source)
148    ;; Misc operations.
149    ("\C-c\C-a" . diff-apply-hunk)
150    ("\C-c\C-e" . diff-ediff-patch)
151    ("\C-c\C-n" . diff-restrict-view)
152    ("\C-c\C-r" . diff-reverse-direction)
153    ("\C-c\C-s" . diff-split-hunk)
154    ("\C-c\C-t" . diff-test-hunk)
155    ("\C-c\C-u" . diff-context->unified)
156    ;; `d' because it duplicates the context :-(  --Stef
157    ("\C-c\C-d" . diff-unified->context)
158    ("\C-c\C-w" . diff-refine-hunk)
159    ("\C-c\C-f" . next-error-follow-minor-mode))
160  "Keymap for `diff-mode'.  See also `diff-mode-shared-map'.")
161
162(easy-menu-define diff-mode-menu diff-mode-map
163  "Menu for `diff-mode'."
164  '("Diff"
165    ["Jump to Source"		diff-goto-source	t]
166    ["Apply hunk"		diff-apply-hunk		t]
167    ["Apply diff with Ediff"	diff-ediff-patch	t]
168    ["-----" nil nil]
169    ["Reverse direction"	diff-reverse-direction	t]
170    ["Context -> Unified"	diff-context->unified	t]
171    ["Unified -> Context"	diff-unified->context	t]
172    ;;["Fixup Headers"		diff-fixup-modifs	(not buffer-read-only)]
173    ))
174
175(defcustom diff-minor-mode-prefix "\C-c="
176  "Prefix key for `diff-minor-mode' commands."
177  :type '(choice (string "\e") (string "C-c=") string)
178  :group 'diff-mode)
179
180(easy-mmode-defmap diff-minor-mode-map
181  `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
182  "Keymap for `diff-minor-mode'.  See also `diff-mode-shared-map'.")
183
184
185;;;;
186;;;; font-lock support
187;;;;
188
189(defface diff-header
190  '((((class color) (min-colors 88) (background light))
191     :background "grey85")
192    (((class color) (min-colors 88) (background dark))
193     :background "grey45")
194    (((class color) (background light))
195     :foreground "blue1" :weight bold)
196    (((class color) (background dark))
197     :foreground "green" :weight bold)
198    (t :weight bold))
199  "`diff-mode' face inherited by hunk and index header faces."
200  :group 'diff-mode)
201;; backward-compatibility alias
202(put 'diff-header-face 'face-alias 'diff-header)
203(defvar diff-header-face 'diff-header)
204
205(defface diff-file-header
206  '((((class color) (min-colors 88) (background light))
207     :background "grey70" :weight bold)
208    (((class color) (min-colors 88) (background dark))
209     :background "grey60" :weight bold)
210    (((class color) (background light))
211     :foreground "green" :weight bold)
212    (((class color) (background dark))
213     :foreground "cyan" :weight bold)
214    (t :weight bold))			; :height 1.3
215  "`diff-mode' face used to highlight file header lines."
216  :group 'diff-mode)
217;; backward-compatibility alias
218(put 'diff-file-header-face 'face-alias 'diff-file-header)
219(defvar diff-file-header-face 'diff-file-header)
220
221(defface diff-index
222  '((t :inherit diff-file-header))
223  "`diff-mode' face used to highlight index header lines."
224  :group 'diff-mode)
225;; backward-compatibility alias
226(put 'diff-index-face 'face-alias 'diff-index)
227(defvar diff-index-face 'diff-index)
228
229(defface diff-hunk-header
230  '((t :inherit diff-header))
231  "`diff-mode' face used to highlight hunk header lines."
232  :group 'diff-mode)
233;; backward-compatibility alias
234(put 'diff-hunk-header-face 'face-alias 'diff-hunk-header)
235(defvar diff-hunk-header-face 'diff-hunk-header)
236
237(defface diff-removed
238  '((t :inherit diff-changed))
239  "`diff-mode' face used to highlight removed lines."
240  :group 'diff-mode)
241;; backward-compatibility alias
242(put 'diff-removed-face 'face-alias 'diff-removed)
243(defvar diff-removed-face 'diff-removed)
244
245(defface diff-added
246  '((t :inherit diff-changed))
247  "`diff-mode' face used to highlight added lines."
248  :group 'diff-mode)
249;; backward-compatibility alias
250(put 'diff-added-face 'face-alias 'diff-added)
251(defvar diff-added-face 'diff-added)
252
253(defface diff-changed
254  '((((type tty pc) (class color) (background light))
255     :foreground "magenta" :weight bold :slant italic)
256    (((type tty pc) (class color) (background dark))
257     :foreground "yellow" :weight bold :slant italic))
258  "`diff-mode' face used to highlight changed lines."
259  :group 'diff-mode)
260;; backward-compatibility alias
261(put 'diff-changed-face 'face-alias 'diff-changed)
262(defvar diff-changed-face 'diff-changed)
263
264(defface diff-indicator-removed
265  '((t :inherit diff-removed))
266  "`diff-mode' face used to highlight indicator of removed lines (-, <)."
267  :group 'diff-mode
268  :version "22.1")
269(defvar diff-indicator-removed-face 'diff-indicator-removed)
270
271(defface diff-indicator-added
272  '((t :inherit diff-added))
273  "`diff-mode' face used to highlight indicator of added lines (+, >)."
274  :group 'diff-mode
275  :version "22.1")
276(defvar diff-indicator-added-face 'diff-indicator-added)
277
278(defface diff-indicator-changed
279  '((t :inherit diff-changed))
280  "`diff-mode' face used to highlight indicator of changed lines."
281  :group 'diff-mode
282  :version "22.1")
283(defvar diff-indicator-changed-face 'diff-indicator-changed)
284
285(defface diff-function
286  '((t :inherit diff-header))
287  "`diff-mode' face used to highlight function names produced by \"diff -p\"."
288  :group 'diff-mode)
289;; backward-compatibility alias
290(put 'diff-function-face 'face-alias 'diff-function)
291(defvar diff-function-face 'diff-function)
292
293(defface diff-context
294  '((((class color grayscale) (min-colors 88)) :inherit shadow))
295  "`diff-mode' face used to highlight context and other side-information."
296  :group 'diff-mode)
297;; backward-compatibility alias
298(put 'diff-context-face 'face-alias 'diff-context)
299(defvar diff-context-face 'diff-context)
300
301(defface diff-nonexistent
302  '((t :inherit diff-file-header))
303  "`diff-mode' face used to highlight nonexistent files in recursive diffs."
304  :group 'diff-mode)
305;; backward-compatibility alias
306(put 'diff-nonexistent-face 'face-alias 'diff-nonexistent)
307(defvar diff-nonexistent-face 'diff-nonexistent)
308
309(defconst diff-yank-handler '(diff-yank-function))
310(defun diff-yank-function (text)
311  ;; FIXME: the yank-handler is now called separately on each piece of text
312  ;; with a yank-handler property, so the next-single-property-change call
313  ;; below will always return nil :-(   --stef
314  (let ((mixed (next-single-property-change 0 'yank-handler text))
315	(start (point)))
316    ;; First insert the text.
317    (insert text)
318    ;; If the text does not include any diff markers and if we're not
319    ;; yanking back into a diff-mode buffer, get rid of the prefixes.
320    (unless (or mixed (derived-mode-p 'diff-mode))
321      (undo-boundary)		; Just in case the user wanted the prefixes.
322      (let ((re (save-excursion
323		  (if (re-search-backward "^[><!][ \t]" start t)
324		      (if (eq (char-after) ?!)
325			  "^[!+- ][ \t]" "^[<>][ \t]")
326		    "^[ <>!+-]"))))
327	(save-excursion
328	  (while (re-search-backward re start t)
329	    (replace-match "" t t)))))))
330
331
332(defvar diff-font-lock-keywords
333  `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$"          ;unified
334     (1 diff-hunk-header-face) (2 diff-function-face))
335    ("^\\(\\*\\{15\\}\\)\\(.*\\)$"                        ;context
336     (1 diff-hunk-header-face) (2 diff-function-face))
337    ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
338    ("^--- .+ ----$"             . diff-hunk-header-face) ;context
339    ("^[0-9,]+[acd][0-9,]+$"     . diff-hunk-header-face) ;normal
340    ("^---$"                     . diff-hunk-header-face) ;normal
341    ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
342     (0 diff-header-face) (2 diff-file-header-face prepend))
343    ("^\\([-<]\\)\\(.*\n\\)"
344     (1 diff-indicator-removed-face) (2 diff-removed-face))
345    ("^\\([+>]\\)\\(.*\n\\)"
346     (1 diff-indicator-added-face) (2 diff-added-face))
347    ("^\\(!\\)\\(.*\n\\)"
348     (1 diff-indicator-changed-face) (2 diff-changed-face))
349    ("^Index: \\(.+\\).*\n"
350     (0 diff-header-face) (1 diff-index-face prepend))
351    ("^Only in .*\n" . diff-nonexistent-face)
352    ("^\\(#\\)\\(.*\\)"
353     (1 font-lock-comment-delimiter-face)
354     (2 font-lock-comment-face))
355    ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
356
357(defconst diff-font-lock-defaults
358  '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
359
360(defvar diff-imenu-generic-expression
361  ;; Prefer second name as first is most likely to be a backup or
362  ;; version-control name.  The [\t\n] at the end of the unidiff pattern
363  ;; catches Debian source diff files (which lack the trailing date).
364  '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
365    (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
366
367;;;;
368;;;; Movement
369;;;;
370
371(defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
372(defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
373(defvar diff-narrowed-to nil)
374
375(defun diff-end-of-hunk (&optional style)
376  (when (looking-at diff-hunk-header-re)
377    (unless style
378      ;; Especially important for unified (because headers are ambiguous).
379      (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
380    (goto-char (match-end 0)))
381  (let ((end (and (re-search-forward (case style
382				       ;; A `unified' header is ambiguous.
383				       (unified (concat "^[^-+# \\]\\|"
384							diff-file-header-re))
385				       (context "^[^-+#! \\]")
386				       (normal "^[^<>#\\]")
387				       (t "^[^-+#!<> \\]"))
388				     nil t)
389		  (match-beginning 0))))
390    ;; The return value is used by easy-mmode-define-navigation.
391    (goto-char (or end (point-max)))))
392
393(defun diff-beginning-of-hunk ()
394  (beginning-of-line)
395  (unless (looking-at diff-hunk-header-re)
396    (forward-line 1)
397    (condition-case ()
398	(re-search-backward diff-hunk-header-re)
399      (error (error "Can't find the beginning of the hunk")))))
400
401(defun diff-beginning-of-file ()
402  (beginning-of-line)
403  (unless (looking-at diff-file-header-re)
404    (forward-line 2)
405    (condition-case ()
406	(re-search-backward diff-file-header-re)
407      (error (error "Can't find the beginning of the file")))))
408
409(defun diff-end-of-file ()
410  (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
411  (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
412		     nil 'move)
413  (if (match-beginning 1)
414      (goto-char (match-beginning 1))
415    (beginning-of-line)))
416
417;; Define diff-{hunk,file}-{prev,next}
418(easy-mmode-define-navigation
419 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
420(easy-mmode-define-navigation
421 diff-file diff-file-header-re "file" diff-end-of-hunk)
422
423(defun diff-restrict-view (&optional arg)
424  "Restrict the view to the current hunk.
425If the prefix ARG is given, restrict the view to the current file instead."
426  (interactive "P")
427  (save-excursion
428    (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
429    (narrow-to-region (point)
430		      (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
431			     (point)))
432    (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
433
434
435(defun diff-hunk-kill ()
436  "Kill current hunk."
437  (interactive)
438  (diff-beginning-of-hunk)
439  (let* ((start (point))
440	 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
441		     (match-beginning 0)))
442	 (firsthunk (ignore-errors
443		      (goto-char start)
444		      (diff-beginning-of-file) (diff-hunk-next) (point)))
445	 (nextfile (ignore-errors (diff-file-next) (point)))
446	 (inhibit-read-only t))
447    (goto-char start)
448    (if (and firsthunk (= firsthunk start)
449	     (or (null nexthunk)
450		 (and nextfile (> nexthunk nextfile))))
451	;; It's the only hunk for this file, so kill the file.
452	(diff-file-kill)
453      (diff-end-of-hunk)
454      (kill-region start (point)))))
455
456(defun diff-file-kill ()
457  "Kill current file's hunks."
458  (interactive)
459  (diff-beginning-of-file)
460  (let* ((start (point))
461	 (prevhunk (save-excursion
462		     (ignore-errors
463		       (diff-hunk-prev) (point))))
464	 (index (save-excursion
465		  (re-search-backward "^Index: " prevhunk t)))
466	 (inhibit-read-only t))
467    (when index (setq start index))
468    (diff-end-of-file)
469    (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
470    (kill-region start (point))))
471
472(defun diff-kill-junk ()
473  "Kill spurious empty diffs."
474  (interactive)
475  (save-excursion
476    (let ((inhibit-read-only t))
477      (goto-char (point-min))
478      (while (re-search-forward (concat "^\\(Index: .*\n\\)"
479					"\\([^-+!* <>].*\n\\)*?"
480					"\\(\\(Index:\\) \\|"
481					diff-file-header-re "\\)")
482				nil t)
483	(delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
484		       (match-beginning 3))
485	(beginning-of-line)))))
486
487(defun diff-count-matches (re start end)
488  (save-excursion
489    (let ((n 0))
490      (goto-char start)
491      (while (re-search-forward re end t) (incf n))
492      n)))
493
494(defun diff-split-hunk ()
495  "Split the current (unified diff) hunk at point into two hunks."
496  (interactive)
497  (beginning-of-line)
498  (let ((pos (point))
499	(start (progn (diff-beginning-of-hunk) (point))))
500    (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
501      (error "diff-split-hunk only works on unified context diffs"))
502    (forward-line 1)
503    (let* ((start1 (string-to-number (match-string 1)))
504	   (start2 (string-to-number (match-string 2)))
505	   (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
506	   (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
507	   (inhibit-read-only t))
508      (goto-char pos)
509      ;; Hopefully the after-change-function will not screw us over.
510      (insert "@@ -" (number-to-string newstart1) ",1 +"
511	      (number-to-string newstart2) ",1 @@\n")
512      ;; Fix the original hunk-header.
513      (diff-fixup-modifs start pos))))
514
515
516;;;;
517;;;; jump to other buffers
518;;;;
519
520(defvar diff-remembered-files-alist nil)
521
522(defun diff-filename-drop-dir (file)
523  (when (string-match "/" file) (substring file (match-end 0))))
524
525(defun diff-merge-strings (ancestor from to)
526  "Merge the diff between ANCESTOR and FROM into TO.
527Returns the merged string if successful or nil otherwise.
528The strings are assumed not to contain any \"\\n\" (i.e. end of line).
529If ANCESTOR = FROM, returns TO.
530If ANCESTOR = TO, returns FROM.
531The heuristic is simplistic and only really works for cases
532like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
533  ;; Ideally, we want:
534  ;;   AMB ANB CMD -> CND
535  ;; but that's ambiguous if `foo' or `bar' is empty:
536  ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
537  (let ((str (concat ancestor "\n" from "\n" to)))
538    (when (and (string-match (concat
539			      "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
540			      "\\1\\(.*\\)\\3\n"
541			      "\\(.*\\(\\2\\).*\\)\\'") str)
542	       (equal to (match-string 5 str)))
543      (concat (substring str (match-beginning 5) (match-beginning 6))
544	      (match-string 4 str)
545	      (substring str (match-end 6) (match-end 5))))))
546
547(defun diff-tell-file-name (old name)
548  "Tell Emacs where the find the source file of the current hunk.
549If the OLD prefix arg is passed, tell the file NAME of the old file."
550  (interactive
551   (let* ((old current-prefix-arg)
552	  (fs (diff-hunk-file-names current-prefix-arg)))
553     (unless fs (error "No file name to look for"))
554     (list old (read-file-name (format "File for %s: " (car fs))
555			       nil (diff-find-file-name old) t))))
556  (let ((fs (diff-hunk-file-names old)))
557    (unless fs (error "No file name to look for"))
558    (push (cons fs name) diff-remembered-files-alist)))
559
560(defun diff-hunk-file-names (&optional old)
561  "Give the list of file names textually mentioned for the current hunk."
562  (save-excursion
563    (unless (looking-at diff-file-header-re)
564      (or (ignore-errors (diff-beginning-of-file))
565	  (re-search-forward diff-file-header-re nil t)))
566    (let ((limit (save-excursion
567		   (condition-case ()
568		       (progn (diff-hunk-prev) (point))
569		     (error (point-min)))))
570	  (header-files
571	   (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
572	       (list (if old (match-string 1) (match-string 3))
573		     (if old (match-string 3) (match-string 1)))
574	     (forward-line 1) nil)))
575      (delq nil
576	    (append
577	     (when (and (not old)
578			(save-excursion
579			  (re-search-backward "^Index: \\(.+\\)" limit t)))
580	       (list (match-string 1)))
581	     header-files
582	     (when (re-search-backward
583		    "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
584		    nil t)
585	       (list (if old (match-string 2) (match-string 4))
586		     (if old (match-string 4) (match-string 2)))))))))
587
588(defun diff-find-file-name (&optional old prefix)
589  "Return the file corresponding to the current patch.
590Non-nil OLD means that we want the old file.
591PREFIX is only used internally: don't use it."
592  (save-excursion
593    (unless (looking-at diff-file-header-re)
594      (or (ignore-errors (diff-beginning-of-file))
595	  (re-search-forward diff-file-header-re nil t)))
596    (let ((fs (diff-hunk-file-names old)))
597      (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
598      (or
599       ;; use any previously used preference
600       (cdr (assoc fs diff-remembered-files-alist))
601       ;; try to be clever and use previous choices as an inspiration
602       (dolist (rf diff-remembered-files-alist)
603	 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
604	   (if (and newfile (file-exists-p newfile)) (return newfile))))
605       ;; look for each file in turn.  If none found, try again but
606       ;; ignoring the first level of directory, ...
607       (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
608	     (file nil nil))
609	   ((or (null files)
610		(setq file (do* ((files files (cdr files))
611				 (file (car files) (car files)))
612			       ((or (null file) (file-exists-p file))
613				file))))
614	    file))
615       ;; <foo>.rej patches implicitly apply to <foo>
616       (and (string-match "\\.rej\\'" (or buffer-file-name ""))
617	    (let ((file (substring buffer-file-name 0 (match-beginning 0))))
618	      (when (file-exists-p file) file)))
619       ;; If we haven't found the file, maybe it's because we haven't paid
620       ;; attention to the PCL-CVS hint.
621       (and (not prefix)
622	    (boundp 'cvs-pcl-cvs-dirchange-re)
623	    (save-excursion
624	      (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
625	    (diff-find-file-name old (match-string 1)))
626       ;; if all else fails, ask the user
627       (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
628				   nil (first fs) t (first fs))))
629	 (set (make-local-variable 'diff-remembered-files-alist)
630	      (cons (cons fs file) diff-remembered-files-alist))
631	 file)))))
632
633
634(defun diff-ediff-patch ()
635  "Call `ediff-patch-file' on the current buffer."
636  (interactive)
637  (condition-case err
638      (ediff-patch-file nil (current-buffer))
639    (wrong-number-of-arguments (ediff-patch-file))))
640
641;;;;
642;;;; Conversion functions
643;;;;
644
645;;(defvar diff-inhibit-after-change nil
646;;  "Non-nil means inhibit `diff-mode's after-change functions.")
647
648(defun diff-unified->context (start end)
649  "Convert unified diffs to context diffs.
650START and END are either taken from the region (if a prefix arg is given) or
651else cover the whole bufer."
652  (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
653		   (list (region-beginning) (region-end))
654		 (list (point-min) (point-max))))
655  (unless (markerp end) (setq end (copy-marker end t)))
656  (let (;;(diff-inhibit-after-change t)
657	(inhibit-read-only t))
658    (save-excursion
659      (goto-char start)
660      (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
661		  (< (point) end))
662	(combine-after-change-calls
663	  (if (match-beginning 2)
664	      ;; we matched a file header
665	      (progn
666		;; use reverse order to make sure the indices are kept valid
667		(replace-match "---" t t nil 3)
668		(replace-match "***" t t nil 2))
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			  (?\s (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			  (?\s (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 &optional to-context)
736  "Convert context diffs to unified diffs.
737START and END are either taken from the region
738\(when it is highlighted) or else cover the whole buffer.
739With a prefix argument, convert unified format to context format."
740  (interactive (if (and transient-mark-mode mark-active)
741		   (list (region-beginning) (region-end) current-prefix-arg)
742		 (list (point-min) (point-max) current-prefix-arg)))
743  (if to-context
744      (diff-unified->context start end)
745    (unless (markerp end) (setq end (copy-marker end t)))
746    (let ( ;;(diff-inhibit-after-change t)
747	  (inhibit-read-only t))
748      (save-excursion
749	(goto-char start)
750	(while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
751		    (< (point) end))
752	  (combine-after-change-calls
753	    (if (match-beginning 2)
754		;; we matched a file header
755		(progn
756		  ;; use reverse order to make sure the indices are kept valid
757		  (replace-match "+++" t t nil 3)
758		  (replace-match "---" t t nil 2))
759	      ;; we matched a hunk header
760	      (let ((line1s (match-string 4))
761		    (line1e (match-string 5))
762		    (pt1 (match-beginning 0)))
763		(replace-match "")
764		(unless (re-search-forward
765			 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
766		  (error "Can't find matching `--- n1,n2 ----' line"))
767		(let ((line2s (match-string 1))
768		      (line2e (match-string 2))
769		      (pt2 (progn
770			     (delete-region (progn (beginning-of-line) (point))
771					    (progn (forward-line 1) (point)))
772			     (point-marker))))
773		  (goto-char pt1)
774		  (forward-line 1)
775		  (while (< (point) pt2)
776		    (case (char-after)
777		      ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
778		      (?\s     ;merge with the other half of the chunk
779		       (let* ((endline2
780			       (save-excursion
781				 (goto-char pt2) (forward-line 1) (point)))
782			      (c (char-after pt2)))
783			 (case c
784			   ((?! ?+)
785			    (insert "+"
786				    (prog1 (buffer-substring (+ pt2 2) endline2)
787				      (delete-region pt2 endline2))))
788			   (?\s		;FIXME: check consistency
789			    (delete-region pt2 endline2)
790			    (delete-char 1)
791			    (forward-line 1))
792			   (?\\ (forward-line 1))
793			   (t (delete-char 1) (forward-line 1)))))
794		      (t (forward-line 1))))
795		  (while (looking-at "[+! ] ")
796		    (if (/= (char-after) ?!) (forward-char 1)
797		      (delete-char 1) (insert "+"))
798		    (delete-char 1) (forward-line 1))
799		  (save-excursion
800		    (goto-char pt1)
801		    (insert "@@ -" line1s ","
802			    (number-to-string (- (string-to-number line1e)
803						 (string-to-number line1s)
804						 -1))
805			    " +" line2s ","
806			    (number-to-string (- (string-to-number line2e)
807						 (string-to-number line2s)
808						 -1)) " @@")))))))))))
809
810(defun diff-reverse-direction (start end)
811  "Reverse the direction of the diffs.
812START and END are either taken from the region (if a prefix arg is given) or
813else cover the whole bufer."
814  (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
815		   (list (region-beginning) (region-end))
816		 (list (point-min) (point-max))))
817  (unless (markerp end) (setq end (copy-marker end t)))
818  (let (;;(diff-inhibit-after-change t)
819	(inhibit-read-only t))
820    (save-excursion
821      (goto-char start)
822      (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
823		  (< (point) end))
824	(combine-after-change-calls
825	  (cond
826	   ;; a file header
827	   ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
828	   ;; a context-diff hunk header
829	   ((match-beginning 6)
830	    (let ((pt-lines1 (match-beginning 6))
831		  (lines1 (match-string 6)))
832	      (replace-match "" nil nil nil 6)
833	      (forward-line 1)
834	      (let ((half1s (point)))
835		(while (looking-at "[-! \\][ \t]\\|#")
836		  (when (= (char-after) ?-) (delete-char 1) (insert "+"))
837		  (forward-line 1))
838		(let ((half1 (delete-and-extract-region half1s (point))))
839		  (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
840		    (insert half1)
841		    (error "Can't find matching `--- n1,n2 ----' line"))
842		  (let ((str1 (match-string 1)))
843		    (replace-match lines1 nil nil nil 1)
844		    (forward-line 1)
845		    (let ((half2s (point)))
846		      (while (looking-at "[!+ \\][ \t]\\|#")
847			(when (= (char-after) ?+) (delete-char 1) (insert "-"))
848			(forward-line 1))
849		      (let ((half2 (delete-and-extract-region half2s (point))))
850			(insert (or half1 ""))
851			(goto-char half1s)
852			(insert (or half2 ""))))
853		    (goto-char pt-lines1)
854		    (insert str1))))))
855	   ;; a unified-diff hunk header
856	   ((match-beginning 7)
857	    (replace-match "@@ -\\8 +\\7 @@" nil)
858	    (forward-line 1)
859	    (let ((c (char-after)) first last)
860	      (while (case (setq c (char-after))
861		       (?- (setq first (or first (point)))
862			   (delete-char 1) (insert "+") t)
863		       (?+ (setq last (or last (point)))
864			   (delete-char 1) (insert "-") t)
865		       ((?\\ ?#) t)
866		       (t (when (and first last (< first last))
867			    (insert (delete-and-extract-region first last)))
868			  (setq first nil last nil)
869			  (equal ?\s c)))
870		(forward-line 1))))))))))
871
872(defun diff-fixup-modifs (start end)
873  "Fixup the hunk headers (in case the buffer was modified).
874START and END are either taken from the region (if a prefix arg is given) or
875else cover the whole bufer."
876  (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
877		   (list (region-beginning) (region-end))
878		 (list (point-min) (point-max))))
879  (let ((inhibit-read-only t))
880    (save-excursion
881      (goto-char end) (diff-end-of-hunk)
882      (let ((plus 0) (minus 0) (space 0) (bang 0))
883	(while (and (= (forward-line -1) 0) (<= start (point)))
884	  (if (not (looking-at
885		    (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
886			    "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
887			    "\\|--- .+\n\\+\\+\\+ ")))
888	      (case (char-after)
889		(?\s (incf space))
890		(?+ (incf plus))
891		(?- (incf minus))
892		(?! (incf bang))
893		((?\\ ?#) nil)
894		(t  (setq space 0 plus 0 minus 0 bang 0)))
895	    (cond
896	     ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
897	      (let* ((old1 (match-string 1))
898		     (old2 (match-string 2))
899		     (new1 (number-to-string (+ space minus)))
900		     (new2 (number-to-string (+ space plus))))
901		(unless (string= new2 old2) (replace-match new2 t t nil 2))
902		(unless (string= new1 old1) (replace-match new1 t t nil 1))))
903	     ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
904	      (when (> (+ space bang plus) 0)
905		(let* ((old1 (match-string 1))
906		       (old2 (match-string 2))
907		       (new (number-to-string
908			     (+ space bang plus -1 (string-to-number old1)))))
909		  (unless (string= new old2) (replace-match new t t nil 2)))))
910	     ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
911	      (when (> (+ space bang minus) 0)
912		(let* ((old (match-string 1))
913		       (new (format
914			     (concat "%0" (number-to-string (length old)) "d")
915			     (+ space bang minus -1 (string-to-number old)))))
916		  (unless (string= new old) (replace-match new t t nil 2))))))
917	    (setq space 0 plus 0 minus 0 bang 0)))))))
918
919;;;;
920;;;; Hooks
921;;;;
922
923(defun diff-write-contents-hooks ()
924  "Fixup hunk headers if necessary."
925  (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
926  nil)
927
928;; It turns out that making changes in the buffer from within an
929;; *-change-function is asking for trouble, whereas making them
930;; from a post-command-hook doesn't pose much problems
931(defvar diff-unhandled-changes nil)
932(defun diff-after-change-function (beg end len)
933  "Remember to fixup the hunk header.
934See `after-change-functions' for the meaning of BEG, END and LEN."
935  ;; Ignoring changes when inhibit-read-only is set is strictly speaking
936  ;; incorrect, but it turns out that inhibit-read-only is normally not set
937  ;; inside editing commands, while it tends to be set when the buffer gets
938  ;; updated by an async process or by a conversion function, both of which
939  ;; would rather not be uselessly slowed down by this hook.
940  (when (and (not undo-in-progress) (not inhibit-read-only))
941    (if diff-unhandled-changes
942	(setq diff-unhandled-changes
943	      (cons (min beg (car diff-unhandled-changes))
944		    (max end (cdr diff-unhandled-changes))))
945      (setq diff-unhandled-changes (cons beg end)))))
946
947(defun diff-post-command-hook ()
948  "Fixup hunk headers if necessary."
949  (when (consp diff-unhandled-changes)
950    (ignore-errors
951      (save-excursion
952	(goto-char (car diff-unhandled-changes))
953	;; Maybe we've cut the end of the hunk before point.
954	(if (and (bolp) (not (bobp))) (backward-char 1))
955	;; We used to fixup modifs on all the changes, but it turns out
956	;; that it's safer not to do it on big changes, for example
957	;; when yanking a big diff, since we might then screw up perfectly
958	;; correct values.  -stef
959	;; (unless (ignore-errors
960	;; 	  (diff-beginning-of-hunk)
961	;; 	  (save-excursion
962	;; 	    (diff-end-of-hunk)
963	;; 	    (> (point) (car diff-unhandled-changes))))
964	;;   (goto-char (car diff-unhandled-changes))
965	;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
966	;;   (diff-beginning-of-hunk))
967	;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
968	(diff-beginning-of-hunk)
969	(when (save-excursion
970		(diff-end-of-hunk)
971		(>= (point) (cdr diff-unhandled-changes)))
972	  (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
973    (setq diff-unhandled-changes nil)))
974
975(defun diff-next-error (arg reset)
976  ;; Select a window that displays the current buffer so that point
977  ;; movements are reflected in that window.  Otherwise, the user might
978  ;; never see the hunk corresponding to the source she's jumping to.
979  (pop-to-buffer (current-buffer))
980  (if reset (goto-char (point-min)))
981  (diff-hunk-next arg)
982  (diff-goto-source))
983
984;;;###autoload
985(define-derived-mode diff-mode fundamental-mode "Diff"
986  "Major mode for viewing/editing context diffs.
987Supports unified and context diffs as well as (to a lesser extent)
988normal diffs.
989
990When the buffer is read-only, the ESC prefix is not necessary.
991If you edit the buffer manually, diff-mode will try to update the hunk
992headers for you on-the-fly.
993
994You can also switch between context diff and unified diff with \\[diff-context->unified],
995or vice versa with \\[diff-unified->context] and you can also reverse the direction of
996a diff with \\[diff-reverse-direction].
997
998   \\{diff-mode-map}"
999
1000  (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1001  (set (make-local-variable 'outline-regexp) diff-outline-regexp)
1002  (set (make-local-variable 'imenu-generic-expression)
1003       diff-imenu-generic-expression)
1004  ;; These are not perfect.  They would be better done separately for
1005  ;; context diffs and unidiffs.
1006  ;; (set (make-local-variable 'paragraph-start)
1007  ;;        (concat "@@ "			; unidiff hunk
1008  ;; 	       "\\|\\*\\*\\* "		; context diff hunk or file start
1009  ;; 	       "\\|--- [^\t]+\t"))	; context or unidiff file
1010  ;; 					; start (first or second line)
1011  ;;   (set (make-local-variable 'paragraph-separate) paragraph-start)
1012  ;;   (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1013  ;; compile support
1014  (set (make-local-variable 'next-error-function) 'diff-next-error)
1015
1016  (setq buffer-read-only diff-default-read-only)
1017  ;; setup change hooks
1018  (if (not diff-update-on-the-fly)
1019      (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1020    (make-local-variable 'diff-unhandled-changes)
1021    (add-hook 'after-change-functions 'diff-after-change-function nil t)
1022    (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1023  ;; Neat trick from Dave Love to add more bindings in read-only mode:
1024  (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
1025    (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1026    ;; Turn off this little trick in case the buffer is put in view-mode.
1027    (add-hook 'view-mode-hook
1028	      (lambda ()
1029		(setq minor-mode-overriding-map-alist
1030		      (delq ro-bind minor-mode-overriding-map-alist)))
1031	      nil t))
1032  ;; add-log support
1033  (set (make-local-variable 'add-log-current-defun-function)
1034       'diff-current-defun)
1035  (set (make-local-variable 'add-log-buffer-file-name-function)
1036       'diff-find-file-name))
1037
1038;;;###autoload
1039(define-minor-mode diff-minor-mode
1040  "Minor mode for viewing/editing context diffs.
1041\\{diff-minor-mode-map}"
1042  :group 'diff-mode :lighter " Diff"
1043  ;; FIXME: setup font-lock
1044  ;; setup change hooks
1045  (if (not diff-update-on-the-fly)
1046      (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1047    (make-local-variable 'diff-unhandled-changes)
1048    (add-hook 'after-change-functions 'diff-after-change-function nil t)
1049    (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1050
1051;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1052
1053(defun diff-delete-if-empty ()
1054  ;; An empty diff file means there's no more diffs to integrate, so we
1055  ;; can just remove the file altogether.  Very handy for .rej files if we
1056  ;; remove hunks as we apply them.
1057  (when (and buffer-file-name
1058	     (eq 0 (nth 7 (file-attributes buffer-file-name))))
1059    (delete-file buffer-file-name)))
1060
1061(defun diff-delete-empty-files ()
1062  "Arrange for empty diff files to be removed."
1063  (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1064
1065(defun diff-make-unified ()
1066  "Turn context diffs into unified diffs if applicable."
1067  (if (save-excursion
1068	(goto-char (point-min))
1069	(and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
1070      (let ((mod (buffer-modified-p)))
1071	(unwind-protect
1072	    (diff-context->unified (point-min) (point-max))
1073	  (restore-buffer-modified-p mod)))))
1074
1075;;;
1076;;; Misc operations that have proved useful at some point.
1077;;;
1078
1079(defun diff-next-complex-hunk ()
1080  "Jump to the next \"complex\" hunk.
1081\"Complex\" is approximated by \"the hunk changes the number of lines\".
1082Only works for unified diffs."
1083  (interactive)
1084  (while
1085      (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1086			      nil t)
1087	   (equal (match-string 1) (match-string 2)))))
1088
1089(defun diff-sanity-check-context-hunk-half (lines)
1090  (let ((count lines))
1091    (while
1092        (cond
1093         ((and (memq (char-after) '(?\s ?! ?+ ?-))
1094               (memq (char-after (1+ (point))) '(?\s ?\t)))
1095          (decf count) t)
1096         ((or (zerop count) (= count lines)) nil)
1097         ((memq (char-after) '(?! ?+ ?-))
1098          (if (not (and (eq (char-after (1+ (point))) ?\n)
1099                        (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1100              (error "End of hunk ambiguously marked")
1101            (forward-char 1) (insert " ") (forward-line -1) t))
1102         ((< lines 0)
1103          (error "End of hunk ambiguously marked"))
1104         ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1105          (error "Abort!"))
1106         ((eolp) (insert "  ") (forward-line -1) t)
1107         (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1108      (forward-line))))
1109
1110(defun diff-sanity-check-hunk ()
1111  (let (;; Every modification is protected by a y-or-n-p, so it's probably
1112        ;; OK to override a read-only setting.
1113        (inhibit-read-only t))
1114    (save-excursion
1115      (cond
1116       ((not (looking-at diff-hunk-header-re))
1117        (error "Not recognizable hunk header"))
1118
1119       ;; A context diff.
1120       ((eq (char-after) ?*)
1121        (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\),\\([0-9]+\\) \\*\\*\\*\\*"))
1122            (error "Unrecognized context diff first hunk header format")
1123          (forward-line 2)
1124          (diff-sanity-check-context-hunk-half
1125           (1+ (- (string-to-number (match-string 2))
1126                  (string-to-number (match-string 1)))))
1127          (if (not (looking-at "--- \\([0-9]+\\),\\([0-9]+\\) ----$"))
1128              (error "Unrecognized context diff second hunk header format")
1129            (forward-line)
1130            (diff-sanity-check-context-hunk-half
1131             (1+ (- (string-to-number (match-string 2))
1132                    (string-to-number (match-string 1))))))))
1133
1134       ;; A unified diff.
1135       ((eq (char-after) ?@)
1136        (if (not (looking-at
1137                  "@@ -[0-9]+,\\([0-9]+\\) \\+[0-9]+,\\([0-9]+\\) @@"))
1138            (error "Unrecognized unified diff hunk header format")
1139          (let ((before (string-to-number (match-string 1)))
1140                (after (string-to-number (match-string 2))))
1141            (forward-line)
1142            (while
1143                (case (char-after)
1144                  (?\s (decf before) (decf after) t)
1145                  (?- (decf before) t)
1146                  (?+ (decf after) t)
1147                  (t
1148                   (cond
1149                    ((and (zerop before) (zerop after)) nil)
1150                    ((or (< before 0) (< after 0))
1151                     (error (if (or (zerop before) (zerop after))
1152                                "End of hunk ambiguously marked"
1153                              "Hunk seriously messed up")))
1154                    ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1155                     (error "Abort!"))
1156                    ((eolp) (insert " ") (forward-line -1) t)
1157                    (t (insert " ")
1158                       (delete-region (- (point) 2) (- (point) 1)) t))))
1159              (forward-line)))))
1160
1161       ;; A plain diff.
1162       (t
1163        ;; TODO.
1164        )))))
1165
1166(defun diff-hunk-text (hunk destp char-offset)
1167  "Return the literal source text from HUNK as (TEXT . OFFSET).
1168If DESTP is nil, TEXT is the source, otherwise the destination text.
1169CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1170char-offset in TEXT."
1171  (with-temp-buffer
1172    (insert hunk)
1173    (goto-char (point-min))
1174    (let ((src-pos nil)
1175	  (dst-pos nil)
1176	  (divider-pos nil)
1177	  (num-pfx-chars 2))
1178      ;; Set the following variables:
1179      ;;  SRC-POS     buffer pos of the source part of the hunk or nil if none
1180      ;;  DST-POS     buffer pos of the destination part of the hunk or nil
1181      ;;  DIVIDER-POS buffer pos of any divider line separating the src & dst
1182      ;;  NUM-PFX-CHARS  number of line-prefix characters used by this format"
1183      (cond ((looking-at "^@@")
1184	     ;; unified diff
1185	     (setq num-pfx-chars 1)
1186	     (forward-line 1)
1187	     (setq src-pos (point) dst-pos (point)))
1188	    ((looking-at "^\\*\\*")
1189	     ;; context diff
1190	     (forward-line 2)
1191	     (setq src-pos (point))
1192	     (re-search-forward "^--- " nil t)
1193	     (forward-line 0)
1194	     (setq divider-pos (point))
1195	     (forward-line 1)
1196	     (setq dst-pos (point)))
1197	    ((looking-at "^[0-9]+a[0-9,]+$")
1198	     ;; normal diff, insert
1199	     (forward-line 1)
1200	     (setq dst-pos (point)))
1201	    ((looking-at "^[0-9,]+d[0-9]+$")
1202	     ;; normal diff, delete
1203	     (forward-line 1)
1204	     (setq src-pos (point)))
1205	    ((looking-at "^[0-9,]+c[0-9,]+$")
1206	     ;; normal diff, change
1207	     (forward-line 1)
1208	     (setq src-pos (point))
1209	     (re-search-forward "^---$" nil t)
1210	     (forward-line 0)
1211	     (setq divider-pos (point))
1212	     (forward-line 1)
1213	     (setq dst-pos (point)))
1214	    (t
1215	     (error "Unknown diff hunk type")))
1216
1217      (if (if destp (null dst-pos) (null src-pos))
1218	  ;; Implied empty text
1219	  (if char-offset '("" . 0) "")
1220
1221	;; For context diffs, either side can be empty, (if there's only
1222	;; added or only removed text).  We should then use the other side.
1223	(cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1224	      ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1225
1226	(when char-offset (goto-char (+ (point-min) char-offset)))
1227
1228	;; Get rid of anything except the desired text.
1229	(save-excursion
1230	  ;; Delete unused text region
1231	  (let ((keep (if destp dst-pos src-pos)))
1232	    (when (and divider-pos (> divider-pos keep))
1233	      (delete-region divider-pos (point-max)))
1234	    (delete-region (point-min) keep))
1235	  ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1236	  (let ((kill-char (if destp ?- ?+)))
1237	    (goto-char (point-min))
1238	    (while (not (eobp))
1239	      (if (eq (char-after) kill-char)
1240		  (delete-region (point) (progn (forward-line 1) (point)))
1241		(delete-char num-pfx-chars)
1242		(forward-line 1)))))
1243
1244	(let ((text (buffer-substring-no-properties (point-min) (point-max))))
1245	  (if char-offset (cons text (- (point) (point-min))) text))))))
1246
1247
1248(defun diff-find-text (text)
1249  "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1250If TEXT isn't found, nil is returned."
1251  (let* ((orig (point))
1252	 (forw (and (search-forward text nil t)
1253		    (cons (match-beginning 0) (match-end 0))))
1254	 (back (and (goto-char (+ orig (length text)))
1255		    (search-backward text nil t)
1256		    (cons (match-beginning 0) (match-end 0)))))
1257    ;; Choose the closest match.
1258    (if (and forw back)
1259	(if (> (- (car forw) orig) (- orig (car back))) back forw)
1260      (or back forw))))
1261
1262(defun diff-find-approx-text (text)
1263  "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1264Whitespace differences are ignored."
1265  (let* ((orig (point))
1266	 (re (concat "^[ \t\n]*"
1267		     (mapconcat 'regexp-quote (split-string text) "[ \t\n]+")
1268		     "[ \t\n]*\n"))
1269	 (forw (and (re-search-forward re nil t)
1270		    (cons (match-beginning 0) (match-end 0))))
1271	 (back (and (goto-char (+ orig (length text)))
1272		    (re-search-backward re nil t)
1273		    (cons (match-beginning 0) (match-end 0)))))
1274    ;; Choose the closest match.
1275    (if (and forw back)
1276	(if (> (- (car forw) orig) (- orig (car back))) back forw)
1277      (or back forw))))
1278
1279(defsubst diff-xor (a b) (if a (not b) b))
1280
1281(defun diff-find-source-location (&optional other-file reverse)
1282  "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1283BUF is the buffer corresponding to the source file.
1284LINE-OFFSET is the offset between the expected and actual positions
1285  of the text of the hunk or nil if the text was not found.
1286POS is a pair (BEG . END) indicating the position of the text in the buffer.
1287SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1288  SRC is the variant that was found in the buffer.
1289SWITCHED is non-nil if the patch is already applied."
1290  (save-excursion
1291    (let* ((other (diff-xor other-file diff-jump-to-old-file))
1292	   (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1293           ;; Check that the hunk is well-formed.  Otherwise diff-mode and
1294           ;; the user may disagree on what constitutes the hunk
1295           ;; (e.g. because an empty line truncates the hunk mid-course),
1296           ;; leading to potentially nasty surprises for the user.
1297           (_ (diff-sanity-check-hunk))
1298	   (hunk (buffer-substring (point)
1299				   (save-excursion (diff-end-of-hunk) (point))))
1300	   (old (diff-hunk-text hunk reverse char-offset))
1301	   (new (diff-hunk-text hunk (not reverse) char-offset))
1302	   ;; Find the location specification.
1303	   (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1304		     (error "Can't find the hunk header")
1305		   (if other (match-string 1)
1306		     (if (match-end 3) (match-string 3)
1307		       (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1308			 (error "Can't find the hunk separator"))
1309		       (match-string 1)))))
1310	   (file (or (diff-find-file-name other) (error "Can't find the file")))
1311	   (buf (find-file-noselect file)))
1312      ;; Update the user preference if he so wished.
1313      (when (> (prefix-numeric-value other-file) 8)
1314	(setq diff-jump-to-old-file other))
1315      (with-current-buffer buf
1316	(goto-line (string-to-number line))
1317	(let* ((orig-pos (point))
1318	       (switched nil)
1319	       ;; FIXME: Check for case where both OLD and NEW are found.
1320	       (pos (or (diff-find-text (car old))
1321			(progn (setq switched t) (diff-find-text (car new)))
1322			(progn (setq switched nil)
1323			       (condition-case nil
1324				   (diff-find-approx-text (car old))
1325				 (invalid-regexp nil)))	;Regex too big.
1326			(progn (setq switched t)
1327			       (condition-case nil
1328				   (diff-find-approx-text (car new))
1329				 (invalid-regexp nil)))	;Regex too big.
1330			(progn (setq switched nil) nil))))
1331	  (nconc
1332	   (list buf)
1333	   (if pos
1334	       (list (count-lines orig-pos (car pos)) pos)
1335	     (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1336	   (if switched (list new old t) (list old new))))))))
1337
1338
1339(defun diff-hunk-status-msg (line-offset reversed dry-run)
1340  (let ((msg (if dry-run
1341		 (if reversed "already applied" "not yet applied")
1342	       (if reversed "undone" "applied"))))
1343    (message (cond ((null line-offset) "Hunk text not found")
1344		   ((= line-offset 0) "Hunk %s")
1345		   ((= line-offset 1) "Hunk %s at offset %d line")
1346		   (t "Hunk %s at offset %d lines"))
1347	     msg line-offset)))
1348
1349(defvar diff-apply-hunk-to-backup-file nil)
1350
1351(defun diff-apply-hunk (&optional reverse)
1352  "Apply the current hunk to the source file and go to the next.
1353By default, the new source file is patched, but if the variable
1354`diff-jump-to-old-file' is non-nil, then the old source file is
1355patched instead (some commands, such as `diff-goto-source' can change
1356the value of this variable when given an appropriate prefix argument).
1357
1358With a prefix argument, REVERSE the hunk."
1359  (interactive "P")
1360  (destructuring-bind (buf line-offset pos old new &optional switched)
1361      ;; If REVERSE go to the new file, otherwise go to the old.
1362      (diff-find-source-location (not reverse) reverse)
1363    (cond
1364     ((null line-offset)
1365      (error "Can't find the text to patch"))
1366     ((with-current-buffer buf
1367        (and buffer-file-name
1368             (backup-file-name-p buffer-file-name)
1369             (not diff-apply-hunk-to-backup-file)
1370             (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1371                       (yes-or-no-p (format "Really apply this hunk to %s? "
1372                                            (file-name-nondirectory
1373                                             buffer-file-name)))))))
1374      (error "%s"
1375	     (substitute-command-keys
1376              (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1377                      (if (not reverse) "\\[universal-argument] ")))))
1378     ((and switched
1379	   ;; A reversed patch was detected, perhaps apply it in reverse.
1380	   (not (save-window-excursion
1381		  (pop-to-buffer buf)
1382		  (goto-char (+ (car pos) (cdr old)))
1383		  (y-or-n-p
1384		   (if reverse
1385		       "Hunk hasn't been applied yet; apply it now? "
1386		     "Hunk has already been applied; undo it? ")))))
1387      (message "(Nothing done)"))
1388     (t
1389      ;; Apply the hunk
1390      (with-current-buffer buf
1391	(goto-char (car pos))
1392	(delete-region (car pos) (cdr pos))
1393	(insert (car new)))
1394      ;; Display BUF in a window
1395      (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1396      (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1397      (when diff-advance-after-apply-hunk
1398	(diff-hunk-next))))))
1399
1400
1401(defun diff-test-hunk (&optional reverse)
1402  "See whether it's possible to apply the current hunk.
1403With a prefix argument, try to REVERSE the hunk."
1404  (interactive "P")
1405  (destructuring-bind (buf line-offset pos src dst &optional switched)
1406      ;; If REVERSE go to the new file, otherwise go to the old.
1407      (diff-find-source-location (not reverse) reverse)
1408    (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1409    (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1410
1411
1412(defalias 'diff-mouse-goto-source 'diff-goto-source)
1413
1414(defun diff-goto-source (&optional other-file event)
1415  "Jump to the corresponding source line.
1416`diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1417is given) determines whether to jump to the old or the new file.
1418If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1419then `diff-jump-to-old-file' is also set, for the next invocations."
1420  (interactive (list current-prefix-arg last-input-event))
1421  ;; When pointing at a removal line, we probably want to jump to
1422  ;; the old location, and else to the new (i.e. as if reverting).
1423  ;; This is a convenient detail when using smerge-diff.
1424  (if event (posn-set-point (event-end event)))
1425  (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1426    (destructuring-bind (buf line-offset pos src dst &optional switched)
1427	(diff-find-source-location other-file rev)
1428      (pop-to-buffer buf)
1429      (goto-char (+ (car pos) (cdr src)))
1430      (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1431
1432
1433(defun diff-current-defun ()
1434  "Find the name of function at point.
1435For use in `add-log-current-defun-function'."
1436  (save-excursion
1437    (when (looking-at diff-hunk-header-re)
1438      (forward-line 1)
1439      (re-search-forward "^[^ ]" nil t))
1440    (destructuring-bind (buf line-offset pos src dst &optional switched)
1441	(diff-find-source-location)
1442      (beginning-of-line)
1443      (or (when (memq (char-after) '(?< ?-))
1444	    ;; Cursor is pointing at removed text.  This could be a removed
1445	    ;; function, in which case, going to the source buffer will
1446	    ;; not help since the function is now removed.  Instead,
1447	    ;; try to figure out the function name just from the code-fragment.
1448	    (let ((old (if switched dst src)))
1449	      (with-temp-buffer
1450		(insert (car old))
1451		(funcall (with-current-buffer buf major-mode))
1452		(goto-char (+ (point-min) (cdr old)))
1453		(add-log-current-defun))))
1454	  (with-current-buffer buf
1455	    (goto-char (+ (car pos) (cdr src)))
1456	    (add-log-current-defun))))))
1457
1458(defun diff-refine-hunk ()
1459  "Refine the current hunk by ignoring space differences."
1460  (interactive)
1461  (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1462	 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1463	 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1464			   (error "Can't find line number"))
1465		       (string-to-number (match-string 1))))
1466	 (hunk (delete-and-extract-region
1467		(point) (save-excursion (diff-end-of-hunk) (point))))
1468	 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1469	 (file1 (make-temp-file "diff1"))
1470	 (file2 (make-temp-file "diff2"))
1471	 (coding-system-for-read buffer-file-coding-system)
1472	 (inhibit-read-only t)
1473	 old new)
1474    (unwind-protect
1475	(save-excursion
1476	  (setq old (diff-hunk-text hunk nil char-offset))
1477	  (setq new (diff-hunk-text hunk t char-offset))
1478	  (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1479	  (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1480	  (with-temp-buffer
1481	    (let ((status
1482		   (call-process diff-command nil t nil
1483				 opts file1 file2)))
1484	      (case status
1485		(0 nil)			;Nothing to reformat.
1486		(1 (goto-char (point-min))
1487		   ;; Remove the file-header.
1488		   (when (re-search-forward diff-hunk-header-re nil t)
1489		     (delete-region (point-min) (match-beginning 0))))
1490		(t (goto-char (point-max))
1491		   (unless (bolp) (insert "\n"))
1492		   (insert hunk)))
1493	      (setq hunk (buffer-string))
1494	      (unless (memq status '(0 1))
1495		(error "Diff returned: %s" status)))))
1496      ;; Whatever happens, put back some equivalent text: either the new
1497      ;; one or the original one in case some error happened.
1498      (insert hunk)
1499      (delete-file file1)
1500      (delete-file file2))))
1501
1502;; provide the package
1503(provide 'diff-mode)
1504
1505;;; Old Change Log from when diff-mode wasn't part of Emacs:
1506;; Revision 1.11  1999/10/09 23:38:29  monnier
1507;; (diff-mode-load-hook): dropped.
1508;; (auto-mode-alist): also catch *.diffs.
1509;; (diff-find-file-name, diff-mode):  add smarts to find the right file
1510;;     for *.rej files (that lack any file name indication).
1511;;
1512;; Revision 1.10  1999/09/30 15:32:11  monnier
1513;; added support for "\ No newline at end of file".
1514;;
1515;; Revision 1.9  1999/09/15 00:01:13  monnier
1516;; - added basic `compile' support.
1517;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1518;; - diff-kill-file now tries to kill the leading garbage as well.
1519;;
1520;; Revision 1.8  1999/09/13 21:10:09  monnier
1521;; - don't use CL in the autoloaded code
1522;; - accept diffs using -T
1523;;
1524;; Revision 1.7  1999/09/05 20:53:03  monnier
1525;; interface to ediff-patch
1526;;
1527;; Revision 1.6  1999/09/01 20:55:13  monnier
1528;; (ediff=patch-file):  add bindings to call ediff-patch.
1529;; (diff-find-file-name):  taken out of diff-goto-source.
1530;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1531;;  diff-fixup-modifs):  only use the region if a prefix arg is given.
1532;;
1533;; Revision 1.5  1999/08/31 19:18:52  monnier
1534;; (diff-beginning-of-file, diff-prev-file):  fixed wrong parenthesis.
1535;;
1536;; Revision 1.4  1999/08/31 13:01:44  monnier
1537;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1538;;
1539
1540;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1541;;; diff-mode.el ends here
1542