Must define LIB_X!!_LIBS to empty
[bpt/emacs.git] / lisp / diff-mode.el
CommitLineData
b532d575 1;;; diff-mode.el --- a mode for viewing/editing context diffs
610a6418 2
0d30b337 3;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3a349573 4;; 2005, 2006, 2007 Free Software Foundation, Inc.
610a6418 5
cc1eecfd 6;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
b532d575 7;; Keywords: convenience patch diff
610a6418
SM
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
086add15
LK
23;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24;; Boston, MA 02110-1301, USA.
610a6418
SM
25
26;;; Commentary:
27
cdbb79c1 28;; Provides support for font-lock, outline, navigation
610a6418
SM
29;; commands, editing and various conversions as well as jumping
30;; to the corresponding source file.
31
3ccdb14e 32;; Inspired by Pavel Machek's patch-mode.el (<pavel@@atrey.karlin.mff.cuni.cz>)
b532d575 33;; Some efforts were spent to have it somewhat compatible with XEmacs'
610a6418
SM
34;; diff-mode as well as with compilation-minor-mode
35
610a6418
SM
36;; Bugs:
37
027ac3f8 38;; - Reverse doesn't work with normal diffs.
610a6418
SM
39
40;; Todo:
41
22cd1973
SM
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".
e78cf8e5 49;; Maybe just use `wiggle' (by Neil Brown) to do it for us.
22cd1973
SM
50;;
51;; - Refine hunk on a word-by-word basis.
e78cf8e5
SM
52;;
53;; - in diff-apply-hunk, strip context in replace-match to better
54;; preserve markers and spacing.
027ac3f8 55;; - Handle `diff -b' output in context->unified.
610a6418
SM
56
57;;; Code:
610a6418
SM
58(eval-when-compile (require 'cl))
59
6e0f362c
JB
60(defvar add-log-buffer-file-name-function)
61
610a6418
SM
62
63(defgroup diff-mode ()
aa753196 64 "Major mode for viewing/editing diffs."
ccce6558 65 :version "21.1"
610a6418
SM
66 :group 'tools
67 :group 'diff)
68
22cd1973 69(defcustom diff-default-read-only nil
769dd0f1
SM
70 "If non-nil, `diff-mode' buffers default to being read-only."
71 :type 'boolean
72 :group 'diff-mode)
73
e8a1ed31 74(defcustom diff-jump-to-old-file nil
610a6418
SM
75 "*Non-nil means `diff-goto-source' jumps to the old file.
76Else, it jumps to the new file."
f5307782
JB
77 :type 'boolean
78 :group 'diff-mode)
610a6418 79
e8a1ed31 80(defcustom diff-update-on-the-fly t
610a6418
SM
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)."
f5307782
JB
87 :type 'boolean
88 :group 'diff-mode)
610a6418 89
00df919e
MB
90(defcustom diff-advance-after-apply-hunk t
91 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
f5307782
JB
92 :type 'boolean
93 :group 'diff-mode)
00df919e
MB
94
95
22cd1973
SM
96(defcustom diff-mode-hook nil
97 "Run after setting up the `diff-mode' major mode."
98 :type 'hook
f5307782
JB
99 :options '(diff-delete-empty-files diff-make-unified)
100 :group 'diff-mode)
610a6418
SM
101
102(defvar diff-outline-regexp
103 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
104
cd632e57 105;;;;
610a6418 106;;;; keymap, menu, ...
cd632e57 107;;;;
610a6418 108
d87e5627 109(easy-mmode-defmap diff-mode-shared-map
027ac3f8 110 '(;; From Pavel Machek's patch-mode.
d87e5627
SM
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)
027ac3f8 117 ;; From compilation-minor-mode.
d87e5627
SM
118 ("}" . diff-file-next)
119 ("{" . diff-file-prev)
610a6418 120 ("\C-m" . diff-goto-source)
a1e2d7f7 121 ([mouse-2] . diff-goto-source)
027ac3f8 122 ;; From XEmacs' diff-mode.
fe39af99
SM
123 ;; Standard M-w is useful, so don't change M-W.
124 ;;("W" . widen)
610a6418
SM
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)
e78cf8e5
SM
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)
c010ecfa 141 ("q" . quit-window))
0b82e382 142 "Basic keymap for `diff-mode', bound to various prefix keys.")
610a6418 143
d87e5627 144(easy-mmode-defmap diff-mode-map
610a6418 145 `(("\e" . ,diff-mode-shared-map)
027ac3f8
SM
146 ;; From compilation-minor-mode.
147 ("\C-c\C-c" . diff-goto-source)
148 ;; Misc operations.
3cec9c57 149 ("\C-c\C-a" . diff-apply-hunk)
28408bfd
RS
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)
b711788a 154 ("\C-c\C-t" . diff-test-hunk)
28408bfd 155 ("\C-c\C-u" . diff-context->unified)
fe39af99
SM
156 ;; `d' because it duplicates the context :-( --Stef
157 ("\C-c\C-d" . diff-unified->context)
28408bfd 158 ("\C-c\C-w" . diff-refine-hunk)
677c0382 159 ("\C-c\C-f" . next-error-follow-minor-mode))
610a6418
SM
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]
cd632e57
SM
166 ["Apply hunk" diff-apply-hunk t]
167 ["Apply diff with Ediff" diff-ediff-patch t]
610a6418
SM
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
3cec9c57 175(defcustom diff-minor-mode-prefix "\C-c="
0b82e382 176 "Prefix key for `diff-minor-mode' commands."
f5307782
JB
177 :type '(choice (string "\e") (string "C-c=") string)
178 :group 'diff-mode)
0b82e382 179
d87e5627
SM
180(easy-mmode-defmap diff-minor-mode-map
181 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
0b82e382
SM
182 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
183
610a6418 184
cd632e57 185;;;;
610a6418 186;;;; font-lock support
cd632e57 187;;;;
610a6418 188
221711eb 189(defface diff-header
55f2eb7e 190 '((((class color) (min-colors 88) (background light))
4f815065 191 :background "grey85")
55f2eb7e 192 (((class color) (min-colors 88) (background dark))
4f815065 193 :background "grey45")
55f2eb7e 194 (((class color) (background light))
4f815065 195 :foreground "blue1" :weight bold)
55f2eb7e 196 (((class color) (background dark))
4f815065
SM
197 :foreground "green" :weight bold)
198 (t :weight bold))
d676819e
LK
199 "`diff-mode' face inherited by hunk and index header faces."
200 :group 'diff-mode)
221711eb
MB
201;; backward-compatibility alias
202(put 'diff-header-face 'face-alias 'diff-header)
203(defvar diff-header-face 'diff-header)
c0aa75f7 204
221711eb 205(defface diff-file-header
55f2eb7e 206 '((((class color) (min-colors 88) (background light))
4f815065 207 :background "grey70" :weight bold)
55f2eb7e 208 (((class color) (min-colors 88) (background dark))
4f815065 209 :background "grey60" :weight bold)
55f2eb7e 210 (((class color) (background light))
f3abba99 211 :foreground "green" :weight bold)
55f2eb7e 212 (((class color) (background dark))
4f815065
SM
213 :foreground "cyan" :weight bold)
214 (t :weight bold)) ; :height 1.3
d676819e
LK
215 "`diff-mode' face used to highlight file header lines."
216 :group 'diff-mode)
221711eb
MB
217;; backward-compatibility alias
218(put 'diff-file-header-face 'face-alias 'diff-file-header)
219(defvar diff-file-header-face 'diff-file-header)
610a6418 220
221711eb
MB
221(defface diff-index
222 '((t :inherit diff-file-header))
d676819e
LK
223 "`diff-mode' face used to highlight index header lines."
224 :group 'diff-mode)
221711eb
MB
225;; backward-compatibility alias
226(put 'diff-index-face 'face-alias 'diff-index)
227(defvar diff-index-face 'diff-index)
610a6418 228
221711eb
MB
229(defface diff-hunk-header
230 '((t :inherit diff-header))
d676819e
LK
231 "`diff-mode' face used to highlight hunk header lines."
232 :group 'diff-mode)
221711eb
MB
233;; backward-compatibility alias
234(put 'diff-hunk-header-face 'face-alias 'diff-hunk-header)
235(defvar diff-hunk-header-face 'diff-hunk-header)
610a6418 236
221711eb
MB
237(defface diff-removed
238 '((t :inherit diff-changed))
d676819e
LK
239 "`diff-mode' face used to highlight removed lines."
240 :group 'diff-mode)
221711eb
MB
241;; backward-compatibility alias
242(put 'diff-removed-face 'face-alias 'diff-removed)
243(defvar diff-removed-face 'diff-removed)
610a6418 244
221711eb
MB
245(defface diff-added
246 '((t :inherit diff-changed))
d676819e
LK
247 "`diff-mode' face used to highlight added lines."
248 :group 'diff-mode)
221711eb
MB
249;; backward-compatibility alias
250(put 'diff-added-face 'face-alias 'diff-added)
251(defvar diff-added-face 'diff-added)
610a6418 252
221711eb 253(defface diff-changed
86a27a3a 254 '((((type tty pc) (class color) (background light))
4f815065 255 :foreground "magenta" :weight bold :slant italic)
86a27a3a 256 (((type tty pc) (class color) (background dark))
4f815065 257 :foreground "yellow" :weight bold :slant italic))
d676819e
LK
258 "`diff-mode' face used to highlight changed lines."
259 :group 'diff-mode)
221711eb
MB
260;; backward-compatibility alias
261(put 'diff-changed-face 'face-alias 'diff-changed)
262(defvar diff-changed-face 'diff-changed)
610a6418 263
f3abba99
JL
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
221711eb 285(defface diff-function
ea5d66db 286 '((t :inherit diff-header))
d676819e
LK
287 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
288 :group 'diff-mode)
221711eb
MB
289;; backward-compatibility alias
290(put 'diff-function-face 'face-alias 'diff-function)
291(defvar diff-function-face 'diff-function)
34460354 292
221711eb 293(defface diff-context
f3abba99 294 '((((class color grayscale) (min-colors 88)) :inherit shadow))
d676819e
LK
295 "`diff-mode' face used to highlight context and other side-information."
296 :group 'diff-mode)
221711eb
MB
297;; backward-compatibility alias
298(put 'diff-context-face 'face-alias 'diff-context)
299(defvar diff-context-face 'diff-context)
c0aa75f7 300
221711eb
MB
301(defface diff-nonexistent
302 '((t :inherit diff-file-header))
d676819e
LK
303 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
304 :group 'diff-mode)
221711eb
MB
305;; backward-compatibility alias
306(put 'diff-nonexistent-face 'face-alias 'diff-nonexistent)
307(defvar diff-nonexistent-face 'diff-nonexistent)
469fc0a2 308
22cd1973
SM
309(defconst diff-yank-handler '(diff-yank-function))
310(defun diff-yank-function (text)
1ec7bd14
SM
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
22cd1973
SM
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)))))))
cfc80227 330
22cd1973 331
610a6418 332(defvar diff-font-lock-keywords
f3abba99
JL
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))
370d860c 337 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
f3abba99
JL
338 ("^--- .+ ----$" . diff-hunk-header-face) ;context
339 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face) ;normal
340 ("^---$" . diff-hunk-header-face) ;normal
a6373340 341 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
c0aa75f7 342 (0 diff-header-face) (2 diff-file-header-face prepend))
f3abba99
JL
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))
7dfb000f 351 ("^Only in .*\n" . diff-nonexistent-face)
f3abba99 352 ("^\\(#\\)\\(.*\\)"
050dcc13
JL
353 (1 font-lock-comment-delimiter-face)
354 (2 font-lock-comment-face))
f3abba99 355 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
610a6418
SM
356
357(defconst diff-font-lock-defaults
0e104800 358 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
610a6418 359
ccce6558
DL
360(defvar diff-imenu-generic-expression
361 ;; Prefer second name as first is most likely to be a backup or
824693e7
DL
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
ccce6558
DL
365 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
366
cd632e57 367;;;;
610a6418 368;;;; Movement
cd632e57 369;;;;
610a6418 370
c0078a04 371(defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
bd9d7d76 372(defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
610a6418
SM
373(defvar diff-narrowed-to nil)
374
375(defun diff-end-of-hunk (&optional style)
996884b2
SM
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)))
0e104800 381 (let ((end (and (re-search-forward (case style
1eabc5e6
SM
382 ;; A `unified' header is ambiguous.
383 (unified (concat "^[^-+# \\]\\|"
384 diff-file-header-re))
0e104800
SM
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)))))
610a6418
SM
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 ()
0e104800 410 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
22cd1973
SM
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)))
610a6418 416
d87e5627
SM
417;; Define diff-{hunk,file}-{prev,next}
418(easy-mmode-define-navigation
067b4094 419 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
d87e5627
SM
420(easy-mmode-define-navigation
421 diff-file diff-file-header-re "file" diff-end-of-hunk)
610a6418
SM
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
d87e5627 435(defun diff-hunk-kill ()
610a6418
SM
436 "Kill current hunk."
437 (interactive)
438 (diff-beginning-of-hunk)
1eabc5e6 439 (let* ((start (point))
22cd1973
SM
440 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
441 (match-beginning 0)))
1eabc5e6
SM
442 (firsthunk (ignore-errors
443 (goto-char start)
444 (diff-beginning-of-file) (diff-hunk-next) (point)))
dd24cb37
CY
445 (nextfile (ignore-errors (diff-file-next) (point)))
446 (inhibit-read-only t))
1eabc5e6 447 (goto-char start)
610a6418
SM
448 (if (and firsthunk (= firsthunk start)
449 (or (null nexthunk)
450 (and nextfile (> nexthunk nextfile))))
1eabc5e6 451 ;; It's the only hunk for this file, so kill the file.
d87e5627 452 (diff-file-kill)
610a6418
SM
453 (diff-end-of-hunk)
454 (kill-region start (point)))))
455
d87e5627 456(defun diff-file-kill ()
610a6418
SM
457 "Kill current file's hunks."
458 (interactive)
459 (diff-beginning-of-file)
460 (let* ((start (point))
461 (prevhunk (save-excursion
462 (ignore-errors
d87e5627 463 (diff-hunk-prev) (point))))
610a6418 464 (index (save-excursion
dd24cb37
CY
465 (re-search-backward "^Index: " prevhunk t)))
466 (inhibit-read-only t))
610a6418
SM
467 (when index (setq start index))
468 (diff-end-of-file)
22cd1973 469 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
610a6418
SM
470 (kill-region start (point))))
471
fef8c55b
SM
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
cd632e57
SM
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)))
dd24cb37
CY
506 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
507 (inhibit-read-only t))
cd632e57
SM
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))))
71296446 514
cd632e57 515
610a6418
SM
516;;;;
517;;;; jump to other buffers
518;;;;
519
0b82e382
SM
520(defvar diff-remembered-files-alist nil)
521
610a6418
SM
522(defun diff-filename-drop-dir (file)
523 (when (string-match "/" file) (substring file (match-end 0))))
524
0b82e382
SM
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.
d87e5627 528The strings are assumed not to contain any \"\\n\" (i.e. end of line).
0b82e382
SM
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
d87e5627 537 (let ((str (concat ancestor "\n" from "\n" to)))
0b82e382 538 (when (and (string-match (concat
d87e5627
SM
539 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
540 "\\1\\(.*\\)\\3\n"
0b82e382
SM
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
22cd1973
SM
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)))
cfc80227 559
22cd1973
SM
560(defun diff-hunk-file-names (&optional old)
561 "Give the list of file names textually mentioned for the current hunk."
610a6418
SM
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)))
22cd1973 566 (let ((limit (save-excursion
610a6418 567 (condition-case ()
d87e5627 568 (progn (diff-hunk-prev) (point))
610a6418 569 (error (point-min)))))
22cd1973
SM
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
e78cf8e5 588(defun diff-find-file-name (&optional old prefix)
22cd1973 589 "Return the file corresponding to the current patch.
e78cf8e5
SM
590Non-nil OLD means that we want the old file.
591PREFIX is only used internally: don't use it."
22cd1973
SM
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)))
e78cf8e5 597 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
610a6418 598 (or
0b82e382
SM
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>
610a6418
SM
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)))
e78cf8e5
SM
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)))
0b82e382
SM
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))
610a6418
SM
631 file)))))
632
1b1b5dae 633
610a6418
SM
634(defun diff-ediff-patch ()
635 "Call `ediff-patch-file' on the current buffer."
636 (interactive)
637 (condition-case err
0e104800 638 (ediff-patch-file nil (current-buffer))
610a6418
SM
639 (wrong-number-of-arguments (ediff-patch-file))))
640
71296446 641;;;;
610a6418 642;;;; Conversion functions
71296446 643;;;;
610a6418
SM
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."
a70b0ff8
JL
652 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
653 (list (region-beginning) (region-end))
610a6418 654 (list (point-min) (point-max))))
e78cf8e5 655 (unless (markerp end) (setq end (copy-marker end t)))
610a6418
SM
656 (let (;;(diff-inhibit-after-change t)
657 (inhibit-read-only t))
658 (save-excursion
659 (goto-char start)
c0078a04 660 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
610a6418
SM
661 (< (point) end))
662 (combine-after-change-calls
663 (if (match-beginning 2)
0e104800 664 ;; we matched a file header
610a6418
SM
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)
bdad2e31 692 (?\s (insert " ") (setq modif nil) (backward-char 1))
610a6418
SM
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)
bdad2e31 717 (?\s (insert " ") (setq modif nil) (backward-char 1))
610a6418
SM
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
28408bfd 735(defun diff-context->unified (start end &optional to-context)
610a6418 736 "Convert context diffs to unified diffs.
28408bfd
RS
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)
a70b0ff8 741 (list (region-beginning) (region-end) current-prefix-arg)
28408bfd
RS
742 (list (point-min) (point-max) current-prefix-arg)))
743 (if to-context
744 (diff-unified->context start end)
e78cf8e5 745 (unless (markerp end) (setq end (copy-marker end t)))
28408bfd
RS
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))))
610a6418 773 (goto-char pt1)
28408bfd
RS
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)) " @@")))))))))))
610a6418
SM
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."
a70b0ff8
JL
814 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
815 (list (region-beginning) (region-end))
610a6418 816 (list (point-min) (point-max))))
e78cf8e5 817 (unless (markerp end) (setq end (copy-marker end t)))
610a6418
SM
818 (let (;;(diff-inhibit-after-change t)
819 (inhibit-read-only t))
820 (save-excursion
821 (goto-char start)
c0078a04 822 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
610a6418
SM
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)))
0e104800 835 (while (looking-at "[-! \\][ \t]\\|#")
610a6418
SM
836 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
837 (forward-line 1))
fef8c55b 838 (let ((half1 (delete-and-extract-region half1s (point))))
610a6418
SM
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)))
0e104800 846 (while (looking-at "[!+ \\][ \t]\\|#")
610a6418
SM
847 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
848 (forward-line 1))
fef8c55b 849 (let ((half2 (delete-and-extract-region half2s (point))))
0e104800 850 (insert (or half1 ""))
610a6418 851 (goto-char half1s)
0e104800 852 (insert (or half2 ""))))
610a6418
SM
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)
0e104800 865 ((?\\ ?#) t)
610a6418 866 (t (when (and first last (< first last))
cb4e8176 867 (insert (delete-and-extract-region first last)))
610a6418 868 (setq first nil last nil)
aa753196 869 (equal ?\s c)))
610a6418
SM
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."
a70b0ff8
JL
876 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
877 (list (region-beginning) (region-end))
610a6418
SM
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)))
bd9d7d76
SM
884 (if (not (looking-at
885 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
886 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
887 "\\|--- .+\n\\+\\+\\+ ")))
610a6418 888 (case (char-after)
bd9d7d76 889 (?\s (incf space))
610a6418
SM
890 (?+ (incf plus))
891 (?- (incf minus))
892 (?! (incf bang))
0e104800 893 ((?\\ ?#) nil)
610a6418
SM
894 (t (setq space 0 plus 0 minus 0 bang 0)))
895 (cond
c0078a04 896 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
610a6418
SM
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
71296446 919;;;;
610a6418 920;;;; Hooks
71296446 921;;;;
610a6418
SM
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
610a6418
SM
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."
c0078a04
SM
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.
610a6418
SM
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))
cb4e8176 944 (max end (cdr diff-unhandled-changes))))
610a6418
SM
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
fef8c55b 952 (goto-char (car diff-unhandled-changes))
cb4e8176
SM
953 ;; Maybe we've cut the end of the hunk before point.
954 (if (and (bolp) (not (bobp))) (backward-char 1))
1eabc5e6
SM
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)
cb4e8176 971 (>= (point) (cdr diff-unhandled-changes)))
1eabc5e6 972 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
610a6418
SM
973 (setq diff-unhandled-changes nil)))
974
6fc049f6
SM
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))
610a6418 983
610a6418 984;;;###autoload
d87e5627 985(define-derived-mode diff-mode fundamental-mode "Diff"
0b82e382 986 "Major mode for viewing/editing context diffs.
769dd0f1
SM
987Supports unified and context diffs as well as (to a lesser extent)
988normal diffs.
df52e0e7 989When the buffer is read-only, the ESC prefix is not necessary.
3b696504 990If you edit the buffer manually, diff-mode will try to update the hunk
df52e0e7
SM
991headers for you on-the-fly.
992
993You can also switch between context diff and unified diff with \\[diff-context->unified],
72147c53 994or vice versa with \\[diff-unified->context] and you can also reverse the direction of
e78cf8e5
SM
995a diff with \\[diff-reverse-direction].
996\\{diff-mode-map}"
610a6418
SM
997 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
998 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
ccce6558
DL
999 (set (make-local-variable 'imenu-generic-expression)
1000 diff-imenu-generic-expression)
19e713d8
DL
1001 ;; These are not perfect. They would be better done separately for
1002 ;; context diffs and unidiffs.
1003 ;; (set (make-local-variable 'paragraph-start)
1004 ;; (concat "@@ " ; unidiff hunk
1005 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1006 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1007 ;; ; start (first or second line)
1008 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1009 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1010 ;; compile support
6fc049f6 1011 (set (make-local-variable 'next-error-function) 'diff-next-error)
cdbb79c1 1012
53dd481c 1013 (setq buffer-read-only diff-default-read-only)
769dd0f1 1014 ;; setup change hooks
e8a1ed31 1015 (if (not diff-update-on-the-fly)
3ccdb14e 1016 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
610a6418 1017 (make-local-variable 'diff-unhandled-changes)
3cec9c57
SM
1018 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1019 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
610a6418 1020 ;; Neat trick from Dave Love to add more bindings in read-only mode:
e78cf8e5 1021 (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
22cd1973
SM
1022 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1023 ;; Turn off this little trick in case the buffer is put in view-mode.
1024 (add-hook 'view-mode-hook
e78cf8e5
SM
1025 (lambda ()
1026 (setq minor-mode-overriding-map-alist
1027 (delq ro-bind minor-mode-overriding-map-alist)))
22cd1973 1028 nil t))
281096ed
SM
1029 ;; add-log support
1030 (set (make-local-variable 'add-log-current-defun-function)
1031 'diff-current-defun)
1b1b5dae
SM
1032 (set (make-local-variable 'add-log-buffer-file-name-function)
1033 'diff-find-file-name))
610a6418
SM
1034
1035;;;###autoload
0b82e382
SM
1036(define-minor-mode diff-minor-mode
1037 "Minor mode for viewing/editing context diffs.
1038\\{diff-minor-mode-map}"
cfc80227 1039 :group 'diff-mode :lighter " Diff"
0b82e382 1040 ;; FIXME: setup font-lock
fef8c55b 1041 ;; setup change hooks
e8a1ed31 1042 (if (not diff-update-on-the-fly)
3ccdb14e 1043 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
fef8c55b 1044 (make-local-variable 'diff-unhandled-changes)
3cec9c57
SM
1045 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1046 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
0b82e382 1047
e78cf8e5 1048;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22cd1973
SM
1049
1050(defun diff-delete-if-empty ()
1051 ;; An empty diff file means there's no more diffs to integrate, so we
1052 ;; can just remove the file altogether. Very handy for .rej files if we
1053 ;; remove hunks as we apply them.
1054 (when (and buffer-file-name
1055 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1056 (delete-file buffer-file-name)))
1057
1058(defun diff-delete-empty-files ()
1059 "Arrange for empty diff files to be removed."
1060 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1061
1062(defun diff-make-unified ()
1063 "Turn context diffs into unified diffs if applicable."
1064 (if (save-excursion
1065 (goto-char (point-min))
4c174fb4 1066 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
22cd1973
SM
1067 (let ((mod (buffer-modified-p)))
1068 (unwind-protect
1069 (diff-context->unified (point-min) (point-max))
1070 (restore-buffer-modified-p mod)))))
610a6418 1071
027ac3f8
SM
1072;;;
1073;;; Misc operations that have proved useful at some point.
1074;;;
1075
1076(defun diff-next-complex-hunk ()
1077 "Jump to the next \"complex\" hunk.
1078\"Complex\" is approximated by \"the hunk changes the number of lines\".
1079Only works for unified diffs."
1080 (interactive)
1081 (while
1082 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1083 nil t)
1084 (equal (match-string 1) (match-string 2)))))
1085
3a349573
SM
1086(defun diff-sanity-check-context-hunk-half (lines)
1087 (let ((count lines))
1088 (while
1089 (cond
1090 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1091 (memq (char-after (1+ (point))) '(?\s ?\t)))
1092 (decf count) t)
1093 ((or (zerop count) (= count lines)) nil)
1094 ((memq (char-after) '(?! ?+ ?-))
1095 (if (not (and (eq (char-after (1+ (point))) ?\n)
1096 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1097 (error "End of hunk ambiguously marked")
1098 (forward-char 1) (insert " ") (forward-line -1) t))
1099 ((< lines 0)
1100 (error "End of hunk ambiguously marked"))
1101 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1102 (error "Abort!"))
1103 ((eolp) (insert " ") (forward-line -1) t)
1104 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1105 (forward-line))))
1106
1107(defun diff-sanity-check-hunk ()
1108 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1109 ;; OK to override a read-only setting.
1110 (inhibit-read-only t))
1111 (save-excursion
1112 (cond
1113 ((not (looking-at diff-hunk-header-re))
1114 (error "Not recognizable hunk header"))
1115
1116 ;; A context diff.
1117 ((eq (char-after) ?*)
1118 (if (not (looking-at "\\*\\{15\\}\n\\*\\*\\* \\([0-9]+\\),\\([0-9]+\\) \\*\\*\\*\\*$"))
1119 (error "Unrecognized context diff first hunk header format")
1120 (forward-line 2)
1121 (diff-sanity-check-context-hunk-half
1122 (1+ (- (string-to-number (match-string 2))
1123 (string-to-number (match-string 1)))))
1124 (if (not (looking-at "--- \\([0-9]+\\),\\([0-9]+\\) ----$"))
1125 (error "Unrecognized context diff second hunk header format")
1126 (forward-line)
1127 (diff-sanity-check-context-hunk-half
1128 (1+ (- (string-to-number (match-string 2))
1129 (string-to-number (match-string 1))))))))
1130
1131 ;; A unified diff.
1132 ((eq (char-after) ?@)
1133 (if (not (looking-at
1134 "@@ -[0-9]+,\\([0-9]+\\) \\+[0-9]+,\\([0-9]+\\) @@$"))
1135 (error "Unrecognized unified diff hunk header format")
1136 (let ((before (string-to-number (match-string 1)))
1137 (after (string-to-number (match-string 2))))
1138 (forward-line)
1139 (while
1140 (case (char-after)
1141 (?\s (decf before) (decf after) t)
1142 (?- (decf before) t)
1143 (?+ (decf after) t)
1144 (t
1145 (cond
1146 ((and (zerop before) (zerop after)) nil)
1147 ((or (< before 0) (< after 0))
1148 (error (if (or (zerop before) (zerop after))
1149 "End of hunk ambiguously marked"
1150 "Hunk seriously messed up")))
1151 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1152 (error "Abort!"))
1153 ((eolp) (insert " ") (forward-line -1) t)
1154 (t (insert " ")
1155 (delete-region (- (point) 2) (- (point) 1)) t))))
1156 (forward-line)))))
1157
1158 ;; A plain diff.
1159 (t
1160 ;; TODO.
1161 )))))
1162
1eabc5e6
SM
1163(defun diff-hunk-text (hunk destp char-offset)
1164 "Return the literal source text from HUNK as (TEXT . OFFSET).
a70b0ff8 1165If DESTP is nil, TEXT is the source, otherwise the destination text.
1eabc5e6
SM
1166CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1167char-offset in TEXT."
3017133f 1168 (with-temp-buffer
6e4e8a3b
SM
1169 (insert hunk)
1170 (goto-char (point-min))
1171 (let ((src-pos nil)
1172 (dst-pos nil)
1173 (divider-pos nil)
1174 (num-pfx-chars 2))
1175 ;; Set the following variables:
1176 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1177 ;; DST-POS buffer pos of the destination part of the hunk or nil
1178 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1179 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1180 (cond ((looking-at "^@@")
1181 ;; unified diff
1182 (setq num-pfx-chars 1)
1183 (forward-line 1)
1184 (setq src-pos (point) dst-pos (point)))
1185 ((looking-at "^\\*\\*")
1186 ;; context diff
1187 (forward-line 2)
1188 (setq src-pos (point))
1189 (re-search-forward "^--- " nil t)
1190 (forward-line 0)
1191 (setq divider-pos (point))
1192 (forward-line 1)
1193 (setq dst-pos (point)))
1194 ((looking-at "^[0-9]+a[0-9,]+$")
1195 ;; normal diff, insert
1196 (forward-line 1)
1197 (setq dst-pos (point)))
1198 ((looking-at "^[0-9,]+d[0-9]+$")
1199 ;; normal diff, delete
1200 (forward-line 1)
1201 (setq src-pos (point)))
1202 ((looking-at "^[0-9,]+c[0-9,]+$")
1203 ;; normal diff, change
1204 (forward-line 1)
1205 (setq src-pos (point))
1206 (re-search-forward "^---$" nil t)
1207 (forward-line 0)
1208 (setq divider-pos (point))
1209 (forward-line 1)
1210 (setq dst-pos (point)))
1211 (t
1212 (error "Unknown diff hunk type")))
1213
1214 (if (if destp (null dst-pos) (null src-pos))
1215 ;; Implied empty text
1216 (if char-offset '("" . 0) "")
1217
1218 ;; For context diffs, either side can be empty, (if there's only
1219 ;; added or only removed text). We should then use the other side.
1220 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1221 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1222
1223 (when char-offset (goto-char (+ (point-min) char-offset)))
1224
1225 ;; Get rid of anything except the desired text.
1226 (save-excursion
1227 ;; Delete unused text region
1228 (let ((keep (if destp dst-pos src-pos)))
1229 (when (and divider-pos (> divider-pos keep))
1230 (delete-region divider-pos (point-max)))
1231 (delete-region (point-min) keep))
1232 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1233 (let ((kill-char (if destp ?- ?+)))
1234 (goto-char (point-min))
1235 (while (not (eobp))
1236 (if (eq (char-after) kill-char)
1237 (delete-region (point) (progn (forward-line 1) (point)))
1238 (delete-char num-pfx-chars)
1239 (forward-line 1)))))
1240
1241 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1242 (if char-offset (cons text (- (point) (point-min))) text))))))
370d860c 1243
7530b6da 1244
c0aa75f7 1245(defun diff-find-text (text)
1eabc5e6 1246 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
7530b6da 1247If TEXT isn't found, nil is returned."
7530b6da
MB
1248 (let* ((orig (point))
1249 (forw (and (search-forward text nil t)
1eabc5e6 1250 (cons (match-beginning 0) (match-end 0))))
7530b6da
MB
1251 (back (and (goto-char (+ orig (length text)))
1252 (search-backward text nil t)
1eabc5e6
SM
1253 (cons (match-beginning 0) (match-end 0)))))
1254 ;; Choose the closest match.
1255 (if (and forw back)
1256 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1257 (or back forw))))
1258
1259(defun diff-find-approx-text (text)
1260 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1261Whitespace differences are ignored."
1262 (let* ((orig (point))
1263 (re (concat "^[ \t\n\f]*"
1264 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1265 "[ \t\n\f]*\n"))
1266 (forw (and (re-search-forward re nil t)
1267 (cons (match-beginning 0) (match-end 0))))
1268 (back (and (goto-char (+ orig (length text)))
1269 (re-search-backward re nil t)
1270 (cons (match-beginning 0) (match-end 0)))))
1271 ;; Choose the closest match.
7530b6da 1272 (if (and forw back)
1eabc5e6 1273 (if (> (- (car forw) orig) (- orig (car back))) back forw)
7530b6da
MB
1274 (or back forw))))
1275
370d860c
SM
1276(defsubst diff-xor (a b) (if a (not b) b))
1277
d868b3bd 1278(defun diff-find-source-location (&optional other-file reverse)
1eabc5e6
SM
1279 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1280BUF is the buffer corresponding to the source file.
1281LINE-OFFSET is the offset between the expected and actual positions
1282 of the text of the hunk or nil if the text was not found.
1283POS is a pair (BEG . END) indicating the position of the text in the buffer.
1284SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1285 SRC is the variant that was found in the buffer.
1286SWITCHED is non-nil if the patch is already applied."
7b91e0f2 1287 (save-excursion
e8a1ed31 1288 (let* ((other (diff-xor other-file diff-jump-to-old-file))
370d860c 1289 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
3a349573
SM
1290 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1291 ;; the user may disagree on what constitutes the hunk
1292 ;; (e.g. because an empty line truncates the hunk mid-course),
1293 ;; leading to potentially nasty surprises for the user.
1294 (_ (diff-sanity-check-hunk))
370d860c
SM
1295 (hunk (buffer-substring (point)
1296 (save-excursion (diff-end-of-hunk) (point))))
1297 (old (diff-hunk-text hunk reverse char-offset))
1298 (new (diff-hunk-text hunk (not reverse) char-offset))
7b91e0f2 1299 ;; Find the location specification.
d868b3bd 1300 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
370d860c
SM
1301 (error "Can't find the hunk header")
1302 (if other (match-string 1)
1303 (if (match-end 3) (match-string 3)
1304 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1305 (error "Can't find the hunk separator"))
1306 (match-string 1)))))
1307 (file (or (diff-find-file-name other) (error "Can't find the file")))
1308 (buf (find-file-noselect file)))
7b91e0f2
SM
1309 ;; Update the user preference if he so wished.
1310 (when (> (prefix-numeric-value other-file) 8)
e8a1ed31 1311 (setq diff-jump-to-old-file other))
d868b3bd
SM
1312 (with-current-buffer buf
1313 (goto-line (string-to-number line))
1314 (let* ((orig-pos (point))
1eabc5e6 1315 (switched nil)
22cd1973 1316 ;; FIXME: Check for case where both OLD and NEW are found.
1eabc5e6
SM
1317 (pos (or (diff-find-text (car old))
1318 (progn (setq switched t) (diff-find-text (car new)))
1319 (progn (setq switched nil)
22cd1973
SM
1320 (condition-case nil
1321 (diff-find-approx-text (car old))
1322 (invalid-regexp nil))) ;Regex too big.
1eabc5e6 1323 (progn (setq switched t)
22cd1973
SM
1324 (condition-case nil
1325 (diff-find-approx-text (car new))
1326 (invalid-regexp nil))) ;Regex too big.
1eabc5e6 1327 (progn (setq switched nil) nil))))
370d860c
SM
1328 (nconc
1329 (list buf)
1eabc5e6
SM
1330 (if pos
1331 (list (count-lines orig-pos (car pos)) pos)
1332 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
370d860c
SM
1333 (if switched (list new old t) (list old new))))))))
1334
7b91e0f2 1335
370d860c
SM
1336(defun diff-hunk-status-msg (line-offset reversed dry-run)
1337 (let ((msg (if dry-run
1338 (if reversed "already applied" "not yet applied")
1339 (if reversed "undone" "applied"))))
1340 (message (cond ((null line-offset) "Hunk text not found")
1341 ((= line-offset 0) "Hunk %s")
1342 ((= line-offset 1) "Hunk %s at offset %d line")
1343 (t "Hunk %s at offset %d lines"))
1344 msg line-offset)))
1345
cb9a30c8 1346(defvar diff-apply-hunk-to-backup-file nil)
370d860c
SM
1347
1348(defun diff-apply-hunk (&optional reverse)
6e4e8a3b 1349 "Apply the current hunk to the source file and go to the next.
7530b6da 1350By default, the new source file is patched, but if the variable
e8a1ed31 1351`diff-jump-to-old-file' is non-nil, then the old source file is
7530b6da
MB
1352patched instead (some commands, such as `diff-goto-source' can change
1353the value of this variable when given an appropriate prefix argument).
1354
4eaa6852 1355With a prefix argument, REVERSE the hunk."
370d860c 1356 (interactive "P")
281096ed 1357 (destructuring-bind (buf line-offset pos old new &optional switched)
22cd1973
SM
1358 ;; If REVERSE go to the new file, otherwise go to the old.
1359 (diff-find-source-location (not reverse) reverse)
370d860c 1360 (cond
4eaa6852
MB
1361 ((null line-offset)
1362 (error "Can't find the text to patch"))
cb9a30c8
SM
1363 ((with-current-buffer buf
1364 (and buffer-file-name
1365 (backup-file-name-p buffer-file-name)
1366 (not diff-apply-hunk-to-backup-file)
1367 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1368 (yes-or-no-p (format "Really apply this hunk to %s? "
1369 (file-name-nondirectory
1370 buffer-file-name)))))))
1371 (error (substitute-command-keys
1372 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1373 (if (not reverse) "\\[universal-argument] ")))))
370d860c 1374 ((and switched
cdbb79c1 1375 ;; A reversed patch was detected, perhaps apply it in reverse.
370d860c
SM
1376 (not (save-window-excursion
1377 (pop-to-buffer buf)
1eabc5e6 1378 (goto-char (+ (car pos) (cdr old)))
370d860c
SM
1379 (y-or-n-p
1380 (if reverse
1381 "Hunk hasn't been applied yet; apply it now? "
1382 "Hunk has already been applied; undo it? ")))))
4eaa6852 1383 (message "(Nothing done)"))
370d860c 1384 (t
4eaa6852
MB
1385 ;; Apply the hunk
1386 (with-current-buffer buf
1eabc5e6
SM
1387 (goto-char (car pos))
1388 (delete-region (car pos) (cdr pos))
4eaa6852
MB
1389 (insert (car new)))
1390 ;; Display BUF in a window
1eabc5e6 1391 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
4eaa6852
MB
1392 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1393 (when diff-advance-after-apply-hunk
1394 (diff-hunk-next))))))
370d860c 1395
7530b6da 1396
7530b6da
MB
1397(defun diff-test-hunk (&optional reverse)
1398 "See whether it's possible to apply the current hunk.
4eaa6852 1399With a prefix argument, try to REVERSE the hunk."
7530b6da 1400 (interactive "P")
370d860c 1401 (destructuring-bind (buf line-offset pos src dst &optional switched)
22cd1973
SM
1402 ;; If REVERSE go to the new file, otherwise go to the old.
1403 (diff-find-source-location (not reverse) reverse)
1eabc5e6 1404 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
4eaa6852 1405 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
370d860c 1406
7530b6da 1407
a1e2d7f7
SM
1408(defalias 'diff-mouse-goto-source 'diff-goto-source)
1409
1410(defun diff-goto-source (&optional other-file event)
7530b6da 1411 "Jump to the corresponding source line.
e8a1ed31 1412`diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
281096ed 1413is given) determines whether to jump to the old or the new file.
7530b6da 1414If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
a70b0ff8 1415then `diff-jump-to-old-file' is also set, for the next invocations."
a1e2d7f7 1416 (interactive (list current-prefix-arg last-input-event))
a6373340
SM
1417 ;; When pointing at a removal line, we probably want to jump to
1418 ;; the old location, and else to the new (i.e. as if reverting).
1419 ;; This is a convenient detail when using smerge-diff.
a1e2d7f7 1420 (if event (posn-set-point (event-end event)))
a6373340
SM
1421 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1422 (destructuring-bind (buf line-offset pos src dst &optional switched)
1423 (diff-find-source-location other-file rev)
1424 (pop-to-buffer buf)
1eabc5e6 1425 (goto-char (+ (car pos) (cdr src)))
55d5d717 1426 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
370d860c 1427
7530b6da 1428
281096ed 1429(defun diff-current-defun ()
370d860c
SM
1430 "Find the name of function at point.
1431For use in `add-log-current-defun-function'."
2f9edc8b
KG
1432 (save-excursion
1433 (when (looking-at diff-hunk-header-re)
1434 (forward-line 1)
4f815065 1435 (re-search-forward "^[^ ]" nil t))
2f9edc8b
KG
1436 (destructuring-bind (buf line-offset pos src dst &optional switched)
1437 (diff-find-source-location)
281096ed
SM
1438 (beginning-of-line)
1439 (or (when (memq (char-after) '(?< ?-))
370d860c
SM
1440 ;; Cursor is pointing at removed text. This could be a removed
1441 ;; function, in which case, going to the source buffer will
1442 ;; not help since the function is now removed. Instead,
1443 ;; try to figure out the function name just from the code-fragment.
281096ed
SM
1444 (let ((old (if switched dst src)))
1445 (with-temp-buffer
1446 (insert (car old))
281096ed 1447 (funcall (with-current-buffer buf major-mode))
cb4e8176 1448 (goto-char (+ (point-min) (cdr old)))
281096ed
SM
1449 (add-log-current-defun))))
1450 (with-current-buffer buf
1eabc5e6 1451 (goto-char (+ (car pos) (cdr src)))
281096ed 1452 (add-log-current-defun))))))
027ac3f8 1453
22cd1973
SM
1454(defun diff-refine-hunk ()
1455 "Refine the current hunk by ignoring space differences."
1456 (interactive)
1457 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1458 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1459 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1460 (error "Can't find line number"))
1461 (string-to-number (match-string 1))))
1462 (hunk (delete-and-extract-region
1463 (point) (save-excursion (diff-end-of-hunk) (point))))
1464 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1465 (file1 (make-temp-file "diff1"))
1466 (file2 (make-temp-file "diff2"))
1467 (coding-system-for-read buffer-file-coding-system)
dd24cb37 1468 (inhibit-read-only t)
22cd1973
SM
1469 old new)
1470 (unwind-protect
1471 (save-excursion
1472 (setq old (diff-hunk-text hunk nil char-offset))
1473 (setq new (diff-hunk-text hunk t char-offset))
1474 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1475 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1476 (with-temp-buffer
1477 (let ((status
1478 (call-process diff-command nil t nil
1479 opts file1 file2)))
1480 (case status
1481 (0 nil) ;Nothing to reformat.
1482 (1 (goto-char (point-min))
1483 ;; Remove the file-header.
1484 (when (re-search-forward diff-hunk-header-re nil t)
1485 (delete-region (point-min) (match-beginning 0))))
1486 (t (goto-char (point-max))
1487 (unless (bolp) (insert "\n"))
1488 (insert hunk)))
1489 (setq hunk (buffer-string))
1490 (unless (memq status '(0 1))
1491 (error "Diff returned: %s" status)))))
1492 ;; Whatever happens, put back some equivalent text: either the new
1493 ;; one or the original one in case some error happened.
1494 (insert hunk)
1495 (delete-file file1)
1496 (delete-file file2))))
1497
610a6418
SM
1498;; provide the package
1499(provide 'diff-mode)
1500
027ac3f8 1501;;; Old Change Log from when diff-mode wasn't part of Emacs:
610a6418
SM
1502;; Revision 1.11 1999/10/09 23:38:29 monnier
1503;; (diff-mode-load-hook): dropped.
1504;; (auto-mode-alist): also catch *.diffs.
1505;; (diff-find-file-name, diff-mode): add smarts to find the right file
1506;; for *.rej files (that lack any file name indication).
1507;;
1508;; Revision 1.10 1999/09/30 15:32:11 monnier
1509;; added support for "\ No newline at end of file".
1510;;
1511;; Revision 1.9 1999/09/15 00:01:13 monnier
1512;; - added basic `compile' support.
1513;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1514;; - diff-kill-file now tries to kill the leading garbage as well.
1515;;
1516;; Revision 1.8 1999/09/13 21:10:09 monnier
1517;; - don't use CL in the autoloaded code
1518;; - accept diffs using -T
1519;;
1520;; Revision 1.7 1999/09/05 20:53:03 monnier
1521;; interface to ediff-patch
1522;;
1523;; Revision 1.6 1999/09/01 20:55:13 monnier
1524;; (ediff=patch-file): add bindings to call ediff-patch.
1525;; (diff-find-file-name): taken out of diff-goto-source.
1526;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1527;; diff-fixup-modifs): only use the region if a prefix arg is given.
1528;;
1529;; Revision 1.5 1999/08/31 19:18:52 monnier
1530;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1531;;
1532;; Revision 1.4 1999/08/31 13:01:44 monnier
1533;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1534;;
1535
4f815065 1536;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
610a6418 1537;;; diff-mode.el ends here