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