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