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