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