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