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