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