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 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)
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.
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
38 ;; - Reverse doesn't work with normal diffs.
42 ;; - Add a `delete-after-apply' so C-c C-a automatically deletes hunks.
43 ;; Also allow C-c C-a to delete already-applied hunks.
45 ;; - Try `diff <file> <hunk>' to try and fuzzily discover the source location
46 ;; of a hunk. Show then the changes between <file> and <hunk> and make it
47 ;; possible to apply them to <file>, <hunk-src>, or <hunk-dst>.
48 ;; Or maybe just make it into a ".rej to diff3-markers converter".
49 ;; Maybe just use `wiggle' (by Neil Brown) to do it for us.
51 ;; - in diff-apply-hunk, strip context in replace-match to better
52 ;; preserve markers and spacing.
53 ;; - Handle `diff -b' output in context->unified.
56 (eval-when-compile (require 'cl
))
58 (defvar add-log-buffer-file-name-function
)
61 (defgroup diff-mode
()
62 "Major mode for viewing/editing diffs."
67 (defcustom diff-default-read-only nil
68 "If non-nil, `diff-mode' buffers default to being read-only."
72 (defcustom diff-jump-to-old-file nil
73 "Non-nil means `diff-goto-source' jumps to the old file.
74 Else, it jumps to the new file."
78 (defcustom diff-update-on-the-fly t
79 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
80 When editing a diff file, the line numbers in the hunk headers
81 need to be kept consistent with the actual diff. This can
82 either be done on the fly (but this sometimes interacts poorly with the
83 undo mechanism) or whenever the file is written (can be slow
84 when editing big diffs)."
88 (defcustom diff-advance-after-apply-hunk t
89 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
94 (defcustom diff-mode-hook nil
95 "Run after setting up the `diff-mode' major mode."
97 :options
'(diff-delete-empty-files diff-make-unified
)
100 (defvar diff-outline-regexp
101 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
104 ;;;; keymap, menu, ...
107 (easy-mmode-defmap diff-mode-shared-map
108 '(;; From Pavel Machek's patch-mode.
109 ("n" . diff-hunk-next
)
110 ("N" . diff-file-next
)
111 ("p" . diff-hunk-prev
)
112 ("P" . diff-file-prev
)
113 ("\t" . diff-hunk-next
)
114 ([backtab] . diff-hunk-prev)
115 ("k" . diff-hunk-kill)
116 ("K" . diff-file-kill)
117 ;; From compilation-minor-mode.
118 ("}" . diff-file-next)
119 ("{" . diff-file-prev)
120 ("\C-m" . diff-goto-source)
121 ([mouse-2] . diff-goto-source)
122 ;; From XEmacs' diff-mode.
123 ;; Standard M-w is useful, so don't change M-W.
125 ;;("." . diff-goto-source) ;display-buffer
126 ;;("f" . diff-goto-source) ;find-file
127 ("o" . diff-goto-source) ;other-window
128 ;;("w" . diff-goto-source) ;other-frame
129 ;;("N" . diff-narrow)
130 ;;("h" . diff-show-header)
131 ;;("j" . diff-show-difference) ;jump to Nth diff
133 ;; Not useful if you have to metafy them.
135 ;;("\177" . scroll-down)
136 ;; Standard M-a is useful, so don't change M-A.
137 ;;("A" . diff-ediff-patch)
138 ;; Standard M-r is useful, so don't change M-r or M-R.
139 ;;("r" . diff-restrict-view)
140 ;;("R" . diff-reverse-direction)
142 "Basic keymap for `diff-mode', bound to various prefix keys.")
144 (easy-mmode-defmap diff-mode-map
145 `(("\e" . ,diff-mode-shared-map)
146 ;; From compilation-minor-mode.
147 ("\C-c\C-c" . diff-goto-source)
149 ("\C-c\C-a" . diff-apply-hunk)
150 ("\C-c\C-e" . diff-ediff-patch)
151 ("\C-c\C-n" . diff-restrict-view)
152 ("\C-c\C-r" . diff-reverse-direction)
153 ("\C-c\C-s" . diff-split-hunk)
154 ("\C-c\C-t" . diff-test-hunk)
155 ("\C-c\C-u" . diff-context->unified)
156 ;; `d' because it duplicates the context :-( --Stef
157 ("\C-c\C-d" . diff-unified->context)
158 ("\C-c\C-w" . diff-refine-ignore-spaces-hunk)
159 ("\C-c\C-b" . diff-fine-highlight) ;No reason for `b' :-(
160 ("\C-c\C-f" . next-error-follow-minor-mode))
161 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
163 (easy-menu-define diff-mode-menu diff-mode-map
164 "Menu for `diff-mode'."
166 ["Jump to Source" diff-goto-source t]
167 ["Apply hunk" diff-apply-hunk t]
168 ["Test applying hunk" diff-test-hunk t]
169 ["Apply diff with Ediff" diff-ediff-patch t]
171 ["Reverse direction" diff-reverse-direction t]
172 ["Context -> Unified" diff-context->unified t]
173 ["Unified -> Context" diff-unified->context t]
174 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
176 ["Split hunk" diff-split-hunk (diff-splittable-p)]
177 ["Ignore whitespace changes" diff-refine-ignore-spaces-hunk t]
178 ["Highlight fine changes" diff-fine-highlight t]
179 ["Kill current hunk" diff-hunk-kill t]
180 ["Kill current file's hunks" diff-file-kill t]
182 ["Previous Hunk" diff-hunk-prev t]
183 ["Next Hunk" diff-hunk-next t]
184 ["Previous File" diff-file-prev t]
185 ["Next File" diff-file-next t]
188 (defcustom diff-minor-mode-prefix "\C-c="
189 "Prefix key for `diff-minor-mode' commands."
190 :type '(choice (string "\e") (string "C-c=") string)
193 (easy-mmode-defmap diff-minor-mode-map
194 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
195 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
199 ;;;; font-lock support
203 '((((class color) (min-colors 88) (background light))
204 :background "grey85")
205 (((class color) (min-colors 88) (background dark))
206 :background "grey45")
207 (((class color) (background light))
208 :foreground "blue1" :weight bold)
209 (((class color) (background dark))
210 :foreground "green" :weight bold)
212 "`diff-mode' face inherited by hunk and index header faces."
214 ;; backward-compatibility alias
215 (put 'diff-header-face 'face-alias 'diff-header)
216 (defvar diff-header-face 'diff-header)
218 (defface diff-file-header
219 '((((class color) (min-colors 88) (background light))
220 :background "grey70" :weight bold)
221 (((class color) (min-colors 88) (background dark))
222 :background "grey60" :weight bold)
223 (((class color) (background light))
224 :foreground "green" :weight bold)
225 (((class color) (background dark))
226 :foreground "cyan" :weight bold)
227 (t :weight bold)) ; :height 1.3
228 "`diff-mode' face used to highlight file header lines."
230 ;; backward-compatibility alias
231 (put 'diff-file-header-face 'face-alias 'diff-file-header)
232 (defvar diff-file-header-face 'diff-file-header)
235 '((t :inherit diff-file-header))
236 "`diff-mode' face used to highlight index header lines."
238 ;; backward-compatibility alias
239 (put 'diff-index-face 'face-alias 'diff-index)
240 (defvar diff-index-face 'diff-index)
242 (defface diff-hunk-header
243 '((t :inherit diff-header))
244 "`diff-mode' face used to highlight hunk header lines."
246 ;; backward-compatibility alias
247 (put 'diff-hunk-header-face 'face-alias 'diff-hunk-header)
248 (defvar diff-hunk-header-face 'diff-hunk-header)
250 (defface diff-removed
251 '((t :inherit diff-changed))
252 "`diff-mode' face used to highlight removed lines."
254 ;; backward-compatibility alias
255 (put 'diff-removed-face 'face-alias 'diff-removed)
256 (defvar diff-removed-face 'diff-removed)
259 '((t :inherit diff-changed))
260 "`diff-mode' face used to highlight added lines."
262 ;; backward-compatibility alias
263 (put 'diff-added-face 'face-alias 'diff-added)
264 (defvar diff-added-face 'diff-added)
266 (defface diff-changed
267 '((((type tty pc) (class color) (background light))
268 :foreground "magenta" :weight bold :slant italic)
269 (((type tty pc) (class color) (background dark))
270 :foreground "yellow" :weight bold :slant italic))
271 "`diff-mode' face used to highlight changed lines."
273 ;; backward-compatibility alias
274 (put 'diff-changed-face 'face-alias 'diff-changed)
275 (defvar diff-changed-face 'diff-changed)
277 (defface diff-indicator-removed
278 '((t :inherit diff-removed))
279 "`diff-mode' face used to highlight indicator of removed lines (-, <)."
282 (defvar diff-indicator-removed-face 'diff-indicator-removed)
284 (defface diff-indicator-added
285 '((t :inherit diff-added))
286 "`diff-mode' face used to highlight indicator of added lines (+, >)."
289 (defvar diff-indicator-added-face 'diff-indicator-added)
291 (defface diff-indicator-changed
292 '((t :inherit diff-changed))
293 "`diff-mode' face used to highlight indicator of changed lines."
296 (defvar diff-indicator-changed-face 'diff-indicator-changed)
298 (defface diff-function
299 '((t :inherit diff-header))
300 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
302 ;; backward-compatibility alias
303 (put 'diff-function-face 'face-alias 'diff-function)
304 (defvar diff-function-face 'diff-function)
306 (defface diff-context
307 '((((class color grayscale) (min-colors 88)) :inherit shadow))
308 "`diff-mode' face used to highlight context and other side-information."
310 ;; backward-compatibility alias
311 (put 'diff-context-face 'face-alias 'diff-context)
312 (defvar diff-context-face 'diff-context)
314 (defface diff-nonexistent
315 '((t :inherit diff-file-header))
316 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
318 ;; backward-compatibility alias
319 (put 'diff-nonexistent-face 'face-alias 'diff-nonexistent)
320 (defvar diff-nonexistent-face 'diff-nonexistent)
322 (defconst diff-yank-handler '(diff-yank-function))
323 (defun diff-yank-function (text)
324 ;; FIXME: the yank-handler is now called separately on each piece of text
325 ;; with a yank-handler property, so the next-single-property-change call
326 ;; below will always return nil :-( --stef
327 (let ((mixed (next-single-property-change 0 'yank-handler text))
329 ;; First insert the text.
331 ;; If the text does not include any diff markers and if we're not
332 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
333 (unless (or mixed (derived-mode-p 'diff-mode))
334 (undo-boundary) ; Just in case the user wanted the prefixes.
335 (let ((re (save-excursion
336 (if (re-search-backward "^[><!][ \t]" start t)
337 (if (eq (char-after) ?!)
338 "^[!+- ][ \t]" "^[<>][ \t]")
341 (while (re-search-backward re start t)
342 (replace-match "" t t)))))))
345 (defvar diff-font-lock-keywords
346 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
347 (1 diff-hunk-header-face) (2 diff-function-face))
348 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
349 (1 diff-hunk-header-face) (2 diff-function-face))
350 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
351 ("^--- .+ ----$" . diff-hunk-header-face) ;context
352 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face) ;normal
353 ("^---$" . diff-hunk-header-face) ;normal
354 ;; For file headers, accept files with spaces, but be careful to rule
355 ;; out false-positives when matching hunk headers.
356 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\([^\t\n]+?\\)\\(?:\t.*\\| \\(\\*\\*\\*\\*\\|----\\)\\)?\n"
358 (2 (if (not (match-end 3)) diff-file-header-face) prepend))
359 ("^\\([-<]\\)\\(.*\n\\)"
360 (1 diff-indicator-removed-face) (2 diff-removed-face))
361 ("^\\([+>]\\)\\(.*\n\\)"
362 (1 diff-indicator-added-face) (2 diff-added-face))
363 ("^\\(!\\)\\(.*\n\\)"
364 (1 diff-indicator-changed-face) (2 diff-changed-face))
365 ("^Index: \\(.+\\).*\n"
366 (0 diff-header-face) (1 diff-index-face prepend))
367 ("^Only in .*\n" . diff-nonexistent-face)
369 (1 font-lock-comment-delimiter-face)
370 (2 font-lock-comment-face))
371 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
373 (defconst diff-font-lock-defaults
374 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
376 (defvar diff-imenu-generic-expression
377 ;; Prefer second name as first is most likely to be a backup or
378 ;; version-control name. The [\t\n] at the end of the unidiff pattern
379 ;; catches Debian source diff files (which lack the trailing date).
380 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
381 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
387 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
388 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
389 (defvar diff-narrowed-to nil)
391 (defun diff-hunk-style (&optional style)
392 (when (looking-at diff-hunk-header-re)
393 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context)))))
394 (goto-char (match-end 0)))
397 (defun diff-end-of-hunk (&optional style)
398 ;; Especially important for unified (because headers are ambiguous).
399 (setq style (diff-hunk-style style))
400 (let ((end (and (re-search-forward (case style
401 ;; A `unified' header is ambiguous.
402 (unified (concat "^[^-+# \\]\\|"
403 diff-file-header-re))
404 (context "^[^-+#! \\]")
408 (match-beginning 0))))
409 ;; The return value is used by easy-mmode-define-navigation.
410 (goto-char (or end (point-max)))))
412 (defun diff-beginning-of-hunk (&optional try-harder)
413 "Move back to beginning of hunk.
414 If TRY-HARDER is non-nil, try to cater to the case where we're not in a hunk
415 but in the file header instead, in which case move forward to the first hunk."
417 (unless (looking-at diff-hunk-header-re)
420 (re-search-backward diff-hunk-header-re)
423 (error "Can't find the beginning of the hunk")
424 (diff-beginning-of-file-and-junk)
425 (diff-hunk-next))))))
427 (defun diff-unified-hunk-p ()
430 (diff-beginning-of-hunk)
431 (looking-at "^@@"))))
433 (defun diff-beginning-of-file ()
435 (unless (looking-at diff-file-header-re)
436 (let ((start (point))
438 ;; diff-file-header-re may need to match up to 4 lines, so in case
439 ;; we're inside the header, we need to move up to 3 lines forward.
441 (if (and (setq res (re-search-backward diff-file-header-re nil t))
442 ;; Maybe the 3 lines forward were too much and we matched
443 ;; a file header after our starting point :-(
444 (or (<= (point) start)
445 (setq res (re-search-backward diff-file-header-re nil t))))
448 (error "Can't find the beginning of the file")))))
451 (defun diff-end-of-file ()
452 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
453 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
455 (if (match-beginning 1)
456 (goto-char (match-beginning 1))
457 (beginning-of-line)))
459 ;; Define diff-{hunk,file}-{prev,next}
460 (easy-mmode-define-navigation
461 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
462 (easy-mmode-define-navigation
463 diff-file diff-file-header-re "file" diff-end-of-hunk)
465 (defun diff-restrict-view (&optional arg)
466 "Restrict the view to the current hunk.
467 If the prefix ARG is given, restrict the view to the current file instead."
470 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk 'try-harder))
471 (narrow-to-region (point)
472 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
474 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
477 (defun diff-hunk-kill ()
480 (diff-beginning-of-hunk)
481 (let* ((start (point))
482 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
483 (match-beginning 0)))
484 (firsthunk (ignore-errors
486 (diff-beginning-of-file) (diff-hunk-next) (point)))
487 (nextfile (ignore-errors (diff-file-next) (point)))
488 (inhibit-read-only t))
490 (if (and firsthunk (= firsthunk start)
492 (and nextfile (> nexthunk nextfile))))
493 ;; It's the only hunk for this file, so kill the file.
496 (kill-region start (point)))))
498 (defun diff-beginning-of-file-and-junk ()
499 "Go to the beginning of file-related diff-info.
500 This is like `diff-beginning-of-file' except it tries to skip back over leading
501 data such as \"Index: ...\" and such."
502 (let* ((start (point))
503 (prevfile (condition-case err
504 (save-excursion (diff-beginning-of-file) (point))
506 (err (if (consp prevfile) prevfile))
507 (nextfile (ignore-errors
509 (goto-char start) (diff-file-next) (point))))
510 ;; prevhunk is one of the limits.
511 (prevhunk (save-excursion
513 (if (numberp prevfile) (goto-char prevfile))
514 (diff-hunk-prev) (point))))
515 (previndex (save-excursion
516 (re-search-backward "^Index: " prevhunk t))))
517 ;; If we're in the junk, we should use nextfile instead of prevfile.
518 (if (and (numberp nextfile)
519 (or (not (numberp prevfile))
520 (and previndex (> previndex prevfile))))
521 (setq prevfile nextfile))
522 (if (and previndex (numberp prevfile) (< previndex prevfile))
523 (setq prevfile previndex))
524 (if (and (numberp prevfile) (<= prevfile start))
526 ;; File starts *after* the starting point: we really weren't in
527 ;; a file diff but elsewhere.
529 (signal (car err) (cdr err)))))
531 (defun diff-file-kill ()
532 "Kill current file's hunks."
534 (diff-beginning-of-file-and-junk)
535 (let* ((start (point))
536 (inhibit-read-only t))
538 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
539 (kill-region start (point))))
541 (defun diff-kill-junk ()
542 "Kill spurious empty diffs."
545 (let ((inhibit-read-only t))
546 (goto-char (point-min))
547 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
548 "\\([^-+!* <>].*\n\\)*?"
549 "\\(\\(Index:\\) \\|"
550 diff-file-header-re "\\)")
552 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
554 (beginning-of-line)))))
556 (defun diff-count-matches (re start end)
560 (while (re-search-forward re end t) (incf n))
563 (defun diff-splittable-p ()
566 (and (looking-at "^[-+ ]")
567 (progn (forward-line -1) (looking-at "^[-+ ]"))
568 (diff-unified-hunk-p))))
570 (defun diff-split-hunk ()
571 "Split the current (unified diff) hunk at point into two hunks."
575 (start (progn (diff-beginning-of-hunk) (point))))
576 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
577 (error "diff-split-hunk only works on unified context diffs"))
579 (let* ((start1 (string-to-number (match-string 1)))
580 (start2 (string-to-number (match-string 2)))
581 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
582 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
583 (inhibit-read-only t))
585 ;; Hopefully the after-change-function will not screw us over.
586 (insert "@@ -" (number-to-string newstart1) ",1 +"
587 (number-to-string newstart2) ",1 @@\n")
588 ;; Fix the original hunk-header.
589 (diff-fixup-modifs start pos))))
593 ;;;; jump to other buffers
596 (defvar diff-remembered-files-alist nil)
598 (defun diff-filename-drop-dir (file)
599 (when (string-match "/" file) (substring file (match-end 0))))
601 (defun diff-merge-strings (ancestor from to)
602 "Merge the diff between ANCESTOR and FROM into TO.
603 Returns the merged string if successful or nil otherwise.
604 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
605 If ANCESTOR = FROM, returns TO.
606 If ANCESTOR = TO, returns FROM.
607 The heuristic is simplistic and only really works for cases
608 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
610 ;; AMB ANB CMD -> CND
611 ;; but that's ambiguous if `foo' or `bar' is empty:
612 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
613 (let ((str (concat ancestor "\n" from "\n" to)))
614 (when (and (string-match (concat
615 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
617 "\\(.*\\(\\2\\).*\\)\\'") str)
618 (equal to (match-string 5 str)))
619 (concat (substring str (match-beginning 5) (match-beginning 6))
621 (substring str (match-end 6) (match-end 5))))))
623 (defun diff-tell-file-name (old name)
624 "Tell Emacs where the find the source file of the current hunk.
625 If the OLD prefix arg is passed, tell the file NAME of the old file."
627 (let* ((old current-prefix-arg)
628 (fs (diff-hunk-file-names current-prefix-arg)))
629 (unless fs (error "No file name to look for"))
630 (list old (read-file-name (format "File for %s: " (car fs))
631 nil (diff-find-file-name old) t))))
632 (let ((fs (diff-hunk-file-names old)))
633 (unless fs (error "No file name to look for"))
634 (push (cons fs name) diff-remembered-files-alist)))
636 (defun diff-hunk-file-names (&optional old)
637 "Give the list of file names textually mentioned for the current hunk."
639 (unless (looking-at diff-file-header-re)
640 (or (ignore-errors (diff-beginning-of-file))
641 (re-search-forward diff-file-header-re nil t)))
642 (let ((limit (save-excursion
644 (progn (diff-hunk-prev) (point))
645 (error (point-min)))))
647 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
648 (list (if old (match-string 1) (match-string 3))
649 (if old (match-string 3) (match-string 1)))
650 (forward-line 1) nil)))
655 (re-search-backward "^Index: \\(.+\\)" limit t)))
656 (list (match-string 1)))
658 (when (re-search-backward
659 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
661 (list (if old (match-string 2) (match-string 4))
662 (if old (match-string 4) (match-string 2)))))))))
664 (defun diff-find-file-name (&optional old batch prefix)
665 "Return the file corresponding to the current patch.
666 Non-nil OLD means that we want the old file.
667 Non-nil BATCH means to prefer returning an incorrect answer than to prompt
669 PREFIX is only used internally: don't use it."
671 (unless (looking-at diff-file-header-re)
672 (or (ignore-errors (diff-beginning-of-file))
673 (re-search-forward diff-file-header-re nil t)))
674 (let ((fs (diff-hunk-file-names old)))
675 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
677 ;; use any previously used preference
678 (cdr (assoc fs diff-remembered-files-alist))
679 ;; try to be clever and use previous choices as an inspiration
680 (dolist (rf diff-remembered-files-alist)
681 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
682 (if (and newfile (file-exists-p newfile)) (return newfile))))
683 ;; look for each file in turn. If none found, try again but
684 ;; ignoring the first level of directory, ...
685 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
688 (setq file (do* ((files files (cdr files))
689 (file (car files) (car files)))
690 ;; Use file-regular-p to avoid
691 ;; /dev/null, directories, etc.
692 ((or (null file) (file-regular-p file))
695 ;; <foo>.rej patches implicitly apply to <foo>
696 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
697 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
698 (when (file-exists-p file) file)))
699 ;; If we haven't found the file, maybe it's because we haven't paid
700 ;; attention to the PCL-CVS hint.
702 (boundp 'cvs-pcl-cvs-dirchange-re)
704 (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
705 (diff-find-file-name old batch (match-string 1)))
706 ;; Invent something, if necessary.
708 (or (car fs) default-directory))
709 ;; if all else fails, ask the user
710 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
711 nil (first fs) t (first fs))))
712 (set (make-local-variable 'diff-remembered-files-alist)
713 (cons (cons fs file) diff-remembered-files-alist))
717 (defun diff-ediff-patch ()
718 "Call `ediff-patch-file' on the current buffer."
721 (ediff-patch-file nil (current-buffer))
722 (wrong-number-of-arguments (ediff-patch-file))))
725 ;;;; Conversion functions
728 ;;(defvar diff-inhibit-after-change nil
729 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
731 (defun diff-unified->context (start end)
732 "Convert unified diffs to context diffs.
733 START and END are either taken from the region (if a prefix arg is given) or
734 else cover the whole buffer."
735 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
736 (list (region-beginning) (region-end))
737 (list (point-min) (point-max))))
738 (unless (markerp end) (setq end (copy-marker end t)))
739 (let (;;(diff-inhibit-after-change t)
740 (inhibit-read-only t))
743 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
745 (combine-after-change-calls
746 (if (match-beginning 2)
747 ;; we matched a file header
749 ;; use reverse order to make sure the indices are kept valid
750 (replace-match "---" t t nil 3)
751 (replace-match "***" t t nil 2))
752 ;; we matched a hunk header
753 (let ((line1 (match-string 4))
754 (lines1 (match-string 5))
755 (line2 (match-string 6))
756 (lines2 (match-string 7))
757 ;; Variables to use the special undo function.
758 (old-undo buffer-undo-list)
759 (old-end (marker-position end))
760 (start (match-beginning 0))
763 (concat "***************\n*** " line1 ","
764 (number-to-string (+ (string-to-number line1)
765 (string-to-number lines1)
769 (narrow-to-region (point)
770 (progn (diff-end-of-hunk 'unified) (point)))
771 (let ((hunk (buffer-string)))
772 (goto-char (point-min))
773 (if (not (save-excursion (re-search-forward "^-" nil t)))
774 (delete-region (point) (point-max))
775 (goto-char (point-max))
776 (let ((modif nil) last-pt)
777 (while (progn (setq last-pt (point))
778 (= (forward-line -1) 0))
780 (?\s (insert " ") (setq modif nil) (backward-char 1))
781 (?+ (delete-region (point) last-pt) (setq modif t))
783 (progn (forward-char 1)
788 (?\\ (when (save-excursion (forward-line -1)
790 (delete-region (point) last-pt) (setq modif t)))
791 (t (setq modif nil))))))
792 (goto-char (point-max))
794 (insert "--- " line2 ","
795 (number-to-string (+ (string-to-number line2)
796 (string-to-number lines2)
797 -1)) " ----\n" hunk))
798 ;;(goto-char (point-min))
800 (if (not (save-excursion (re-search-forward "^+" nil t)))
801 (delete-region (point) (point-max))
802 (let ((modif nil) (delete nil))
803 (if (save-excursion (re-search-forward "^\\+.*\n-" nil t))
804 ;; Normally, lines in a substitution come with
805 ;; first the removals and then the additions, and
806 ;; the context->unified function follows this
807 ;; convention, of course. Yet, other alternatives
808 ;; are valid as well, but they preclude the use of
809 ;; context->unified as an undo command.
810 (setq reversible nil))
813 (?\s (insert " ") (setq modif nil) (backward-char 1))
814 (?- (setq delete t) (setq modif t))
816 (progn (forward-char 1)
821 (?\\ (when (save-excursion (forward-line 1)
823 (setq delete t) (setq modif t)))
824 (t (setq modif nil)))
825 (let ((last-pt (point)))
828 (delete-region last-pt (point))
829 (setq delete nil)))))))
830 (unless (or (not reversible) (eq buffer-undo-list t))
831 ;; Drop the many undo entries and replace them with
832 ;; a single entry that uses diff-context->unified to do
834 (setq buffer-undo-list
835 (cons (list 'apply (- old-end end) start (point-max)
836 'diff-context->unified start (point-max))
839 (defun diff-context->unified (start end &optional to-context)
840 "Convert context diffs to unified diffs.
841 START and END are either taken from the region
842 \(when it is highlighted) or else cover the whole buffer.
843 With a prefix argument, convert unified format to context format."
844 (interactive (if (and transient-mark-mode mark-active)
845 (list (region-beginning) (region-end) current-prefix-arg)
846 (list (point-min) (point-max) current-prefix-arg)))
848 (diff-unified->context start end)
849 (unless (markerp end) (setq end (copy-marker end t)))
850 (let ( ;;(diff-inhibit-after-change t)
851 (inhibit-read-only t))
854 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
856 (combine-after-change-calls
857 (if (match-beginning 2)
858 ;; we matched a file header
860 ;; use reverse order to make sure the indices are kept valid
861 (replace-match "+++" t t nil 3)
862 (replace-match "---" t t nil 2))
863 ;; we matched a hunk header
864 (let ((line1s (match-string 4))
865 (line1e (match-string 5))
866 (pt1 (match-beginning 0))
867 ;; Variables to use the special undo function.
868 (old-undo buffer-undo-list)
869 (old-end (marker-position end))
872 (unless (re-search-forward
873 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
874 (error "Can't find matching `--- n1,n2 ----' line"))
875 (let ((line2s (match-string 1))
876 (line2e (match-string 2))
878 (delete-region (progn (beginning-of-line) (point))
879 (progn (forward-line 1) (point)))
883 (while (< (point) pt2)
885 (?! (delete-char 2) (insert "-") (forward-line 1))
886 (?- (forward-char 1) (delete-char 1) (forward-line 1))
887 (?\s ;merge with the other half of the chunk
890 (goto-char pt2) (forward-line 1) (point))))
891 (case (char-after pt2)
894 (prog1 (buffer-substring (+ pt2 2) endline2)
895 (delete-region pt2 endline2))))
897 (unless (= (- endline2 pt2)
898 (- (line-beginning-position 2) (point)))
899 ;; If the two lines we're merging don't have the
900 ;; same length (can happen with "diff -b"), then
901 ;; diff-unified->context will not properly undo
903 (setq reversible nil))
904 (delete-region pt2 endline2)
907 (?\\ (forward-line 1))
908 (t (setq reversible nil)
909 (delete-char 1) (forward-line 1)))))
910 (t (setq reversible nil) (forward-line 1))))
911 (while (looking-at "[+! ] ")
912 (if (/= (char-after) ?!) (forward-char 1)
913 (delete-char 1) (insert "+"))
914 (delete-char 1) (forward-line 1))
917 (insert "@@ -" line1s ","
918 (number-to-string (- (string-to-number line1e)
919 (string-to-number line1s)
922 (number-to-string (- (string-to-number line2e)
923 (string-to-number line2s)
926 ;; The whole procedure succeeded, let's replace the myriad
927 ;; of undo elements with just a single special one.
928 (unless (or (not reversible) (eq buffer-undo-list t))
929 (setq buffer-undo-list
930 (cons (list 'apply (- old-end end) pt1 (point)
931 'diff-unified->context pt1 (point))
935 (defun diff-reverse-direction (start end)
936 "Reverse the direction of the diffs.
937 START and END are either taken from the region (if a prefix arg is given) or
938 else cover the whole buffer."
939 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
940 (list (region-beginning) (region-end))
941 (list (point-min) (point-max))))
942 (unless (markerp end) (setq end (copy-marker end t)))
943 (let (;;(diff-inhibit-after-change t)
944 (inhibit-read-only t))
947 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
949 (combine-after-change-calls
952 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
953 ;; a context-diff hunk header
955 (let ((pt-lines1 (match-beginning 6))
956 (lines1 (match-string 6)))
957 (replace-match "" nil nil nil 6)
959 (let ((half1s (point)))
960 (while (looking-at "[-! \\][ \t]\\|#")
961 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
963 (let ((half1 (delete-and-extract-region half1s (point))))
964 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
966 (error "Can't find matching `--- n1,n2 ----' line"))
967 (let ((str1 (match-string 1)))
968 (replace-match lines1 nil nil nil 1)
970 (let ((half2s (point)))
971 (while (looking-at "[!+ \\][ \t]\\|#")
972 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
974 (let ((half2 (delete-and-extract-region half2s (point))))
975 (insert (or half1 ""))
977 (insert (or half2 ""))))
978 (goto-char pt-lines1)
980 ;; a unified-diff hunk header
982 (replace-match "@@ -\\8 +\\7 @@" nil)
984 (let ((c (char-after)) first last)
985 (while (case (setq c (char-after))
986 (?- (setq first (or first (point)))
987 (delete-char 1) (insert "+") t)
988 (?+ (setq last (or last (point)))
989 (delete-char 1) (insert "-") t)
991 (t (when (and first last (< first last))
992 (insert (delete-and-extract-region first last)))
993 (setq first nil last nil)
995 (forward-line 1))))))))))
997 (defun diff-fixup-modifs (start end)
998 "Fixup the hunk headers (in case the buffer was modified).
999 START and END are either taken from the region (if a prefix arg is given) or
1000 else cover the whole buffer."
1001 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
1002 (list (region-beginning) (region-end))
1003 (list (point-min) (point-max))))
1004 (let ((inhibit-read-only t))
1006 (goto-char end) (diff-end-of-hunk)
1007 (let ((plus 0) (minus 0) (space 0) (bang 0))
1008 (while (and (= (forward-line -1) 0) (<= start (point)))
1009 (if (not (looking-at
1010 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
1011 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
1012 "\\|--- .+\n\\+\\+\\+ ")))
1019 (t (setq space 0 plus 0 minus 0 bang 0)))
1021 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
1022 (let* ((old1 (match-string 1))
1023 (old2 (match-string 2))
1024 (new1 (number-to-string (+ space minus)))
1025 (new2 (number-to-string (+ space plus))))
1026 (unless (string= new2 old2) (replace-match new2 t t nil 2))
1027 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
1028 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
1029 (when (> (+ space bang plus) 0)
1030 (let* ((old1 (match-string 1))
1031 (old2 (match-string 2))
1032 (new (number-to-string
1033 (+ space bang plus -1 (string-to-number old1)))))
1034 (unless (string= new old2) (replace-match new t t nil 2)))))
1035 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
1036 (when (> (+ space bang minus) 0)
1037 (let* ((old (match-string 1))
1039 (concat "%0" (number-to-string (length old)) "d")
1040 (+ space bang minus -1 (string-to-number old)))))
1041 (unless (string= new old) (replace-match new t t nil 2))))))
1042 (setq space 0 plus 0 minus 0 bang 0)))))))
1048 (defun diff-write-contents-hooks ()
1049 "Fixup hunk headers if necessary."
1050 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
1053 ;; It turns out that making changes in the buffer from within an
1054 ;; *-change-function is asking for trouble, whereas making them
1055 ;; from a post-command-hook doesn't pose much problems
1056 (defvar diff-unhandled-changes nil)
1057 (defun diff-after-change-function (beg end len)
1058 "Remember to fixup the hunk header.
1059 See `after-change-functions' for the meaning of BEG, END and LEN."
1060 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
1061 ;; incorrect, but it turns out that inhibit-read-only is normally not set
1062 ;; inside editing commands, while it tends to be set when the buffer gets
1063 ;; updated by an async process or by a conversion function, both of which
1064 ;; would rather not be uselessly slowed down by this hook.
1065 (when (and (not undo-in-progress) (not inhibit-read-only))
1066 (if diff-unhandled-changes
1067 (setq diff-unhandled-changes
1068 (cons (min beg (car diff-unhandled-changes))
1069 (max end (cdr diff-unhandled-changes))))
1070 (setq diff-unhandled-changes (cons beg end)))))
1072 (defun diff-post-command-hook ()
1073 "Fixup hunk headers if necessary."
1074 (when (consp diff-unhandled-changes)
1077 (goto-char (car diff-unhandled-changes))
1078 ;; Maybe we've cut the end of the hunk before point.
1079 (if (and (bolp) (not (bobp))) (backward-char 1))
1080 ;; We used to fixup modifs on all the changes, but it turns out
1081 ;; that it's safer not to do it on big changes, for example
1082 ;; when yanking a big diff, since we might then screw up perfectly
1083 ;; correct values. -stef
1084 ;; (unless (ignore-errors
1085 ;; (diff-beginning-of-hunk)
1087 ;; (diff-end-of-hunk)
1088 ;; (> (point) (car diff-unhandled-changes))))
1089 ;; (goto-char (car diff-unhandled-changes))
1090 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
1091 ;; (diff-beginning-of-hunk))
1092 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
1093 (diff-beginning-of-hunk)
1094 (when (save-excursion
1096 (>= (point) (cdr diff-unhandled-changes)))
1097 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
1098 (setq diff-unhandled-changes nil)))
1100 (defun diff-next-error (arg reset)
1101 ;; Select a window that displays the current buffer so that point
1102 ;; movements are reflected in that window. Otherwise, the user might
1103 ;; never see the hunk corresponding to the source she's jumping to.
1104 (pop-to-buffer (current-buffer))
1105 (if reset (goto-char (point-min)))
1106 (diff-hunk-next arg)
1110 (define-derived-mode diff-mode fundamental-mode "Diff"
1111 "Major mode for viewing/editing context diffs.
1112 Supports unified and context diffs as well as (to a lesser extent)
1115 When the buffer is read-only, the ESC prefix is not necessary.
1116 If you edit the buffer manually, diff-mode will try to update the hunk
1117 headers for you on-the-fly.
1119 You can also switch between context diff and unified diff with \\[diff-context->unified],
1120 or vice versa with \\[diff-unified->context] and you can also reverse the direction of
1121 a diff with \\[diff-reverse-direction].
1125 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1126 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
1127 (set (make-local-variable 'imenu-generic-expression)
1128 diff-imenu-generic-expression)
1129 ;; These are not perfect. They would be better done separately for
1130 ;; context diffs and unidiffs.
1131 ;; (set (make-local-variable 'paragraph-start)
1132 ;; (concat "@@ " ; unidiff hunk
1133 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1134 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1135 ;; ; start (first or second line)
1136 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1137 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1139 (set (make-local-variable 'next-error-function) 'diff-next-error)
1141 (setq buffer-read-only diff-default-read-only)
1142 ;; setup change hooks
1143 (if (not diff-update-on-the-fly)
1144 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1145 (make-local-variable 'diff-unhandled-changes)
1146 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1147 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1148 ;; Neat trick from Dave Love to add more bindings in read-only mode:
1149 (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
1150 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1151 ;; Turn off this little trick in case the buffer is put in view-mode.
1152 (add-hook 'view-mode-hook
1154 (setq minor-mode-overriding-map-alist
1155 (delq ro-bind minor-mode-overriding-map-alist)))
1158 (set (make-local-variable 'add-log-current-defun-function)
1159 'diff-current-defun)
1160 (set (make-local-variable 'add-log-buffer-file-name-function)
1161 'diff-find-file-name))
1164 (define-minor-mode diff-minor-mode
1165 "Minor mode for viewing/editing context diffs.
1166 \\{diff-minor-mode-map}"
1167 :group 'diff-mode :lighter " Diff"
1168 ;; FIXME: setup font-lock
1169 ;; setup change hooks
1170 (if (not diff-update-on-the-fly)
1171 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1172 (make-local-variable 'diff-unhandled-changes)
1173 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1174 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1176 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1178 (defun diff-delete-if-empty ()
1179 ;; An empty diff file means there's no more diffs to integrate, so we
1180 ;; can just remove the file altogether. Very handy for .rej files if we
1181 ;; remove hunks as we apply them.
1182 (when (and buffer-file-name
1183 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1184 (delete-file buffer-file-name)))
1186 (defun diff-delete-empty-files ()
1187 "Arrange for empty diff files to be removed."
1188 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1190 (defun diff-make-unified ()
1191 "Turn context diffs into unified diffs if applicable."
1193 (goto-char (point-min))
1194 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
1195 (let ((mod (buffer-modified-p)))
1197 (diff-context->unified (point-min) (point-max))
1198 (restore-buffer-modified-p mod)))))
1201 ;;; Misc operations that have proved useful at some point.
1204 (defun diff-next-complex-hunk ()
1205 "Jump to the next \"complex\" hunk.
1206 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1207 Only works for unified diffs."
1210 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1212 (equal (match-string 1) (match-string 2)))))
1214 (defun diff-sanity-check-context-hunk-half (lines)
1215 (let ((count lines))
1218 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1219 (memq (char-after (1+ (point))) '(?\s ?\t)))
1221 ((or (zerop count) (= count lines)) nil)
1222 ((memq (char-after) '(?! ?+ ?-))
1223 (if (not (and (eq (char-after (1+ (point))) ?\n)
1224 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1225 (error "End of hunk ambiguously marked")
1226 (forward-char 1) (insert " ") (forward-line -1) t))
1228 (error "End of hunk ambiguously marked"))
1229 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1231 ((eolp) (insert " ") (forward-line -1) t)
1232 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1235 (defun diff-sanity-check-hunk ()
1236 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1237 ;; OK to override a read-only setting.
1238 (inhibit-read-only t))
1241 ((not (looking-at diff-hunk-header-re))
1242 (error "Not recognizable hunk header"))
1245 ((eq (char-after) ?*)
1246 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\*\\*\\*\\*"))
1247 (error "Unrecognized context diff first hunk header format")
1249 (diff-sanity-check-context-hunk-half
1250 (if (match-string 2)
1251 (1+ (- (string-to-number (match-string 2))
1252 (string-to-number (match-string 1))))
1254 (if (not (looking-at "--- \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? ----$"))
1255 (error "Unrecognized context diff second hunk header format")
1257 (diff-sanity-check-context-hunk-half
1258 (if (match-string 2)
1259 (1+ (- (string-to-number (match-string 2))
1260 (string-to-number (match-string 1))))
1264 ((eq (char-after) ?@)
1265 (if (not (looking-at
1266 "@@ -[0-9]+\\(?:,\\([0-9]+\\)\\)? \\+[0-9]+\\(?:,\\([0-9]+\\)\\)? @@"))
1267 (error "Unrecognized unified diff hunk header format")
1268 (let ((before (if (match-string 1) (string-to-number (match-string 1)) 1))
1269 (after (if (match-string 2) (string-to-number (match-string 2)) 1)))
1273 (?\s (decf before) (decf after) t)
1275 (if (and (looking-at diff-file-header-re)
1276 (zerop before) (zerop after))
1277 ;; No need to query: this is a case where two patches
1278 ;; are concatenated and only counting the lines will
1279 ;; give the right result. Let's just add an empty
1280 ;; line so that our code which doesn't count lines
1281 ;; will not get confused.
1282 (progn (save-excursion (insert "\n")) nil)
1287 ((and (zerop before) (zerop after)) nil)
1288 ((or (< before 0) (< after 0))
1289 (error (if (or (zerop before) (zerop after))
1290 "End of hunk ambiguously marked"
1291 "Hunk seriously messed up")))
1292 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1294 ((eolp) (insert " ") (forward-line -1) t)
1296 (delete-region (- (point) 2) (- (point) 1)) t))))
1304 (defun diff-hunk-text (hunk destp char-offset)
1305 "Return the literal source text from HUNK as (TEXT . OFFSET).
1306 If DESTP is nil, TEXT is the source, otherwise the destination text.
1307 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1308 char-offset in TEXT."
1311 (goto-char (point-min))
1316 ;; Set the following variables:
1317 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1318 ;; DST-POS buffer pos of the destination part of the hunk or nil
1319 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1320 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1321 (cond ((looking-at "^@@")
1323 (setq num-pfx-chars 1)
1325 (setq src-pos (point) dst-pos (point)))
1326 ((looking-at "^\\*\\*")
1329 (setq src-pos (point))
1330 (re-search-forward "^--- " nil t)
1332 (setq divider-pos (point))
1334 (setq dst-pos (point)))
1335 ((looking-at "^[0-9]+a[0-9,]+$")
1336 ;; normal diff, insert
1338 (setq dst-pos (point)))
1339 ((looking-at "^[0-9,]+d[0-9]+$")
1340 ;; normal diff, delete
1342 (setq src-pos (point)))
1343 ((looking-at "^[0-9,]+c[0-9,]+$")
1344 ;; normal diff, change
1346 (setq src-pos (point))
1347 (re-search-forward "^---$" nil t)
1349 (setq divider-pos (point))
1351 (setq dst-pos (point)))
1353 (error "Unknown diff hunk type")))
1355 (if (if destp (null dst-pos) (null src-pos))
1356 ;; Implied empty text
1357 (if char-offset '("" . 0) "")
1359 ;; For context diffs, either side can be empty, (if there's only
1360 ;; added or only removed text). We should then use the other side.
1361 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1362 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1364 (when char-offset (goto-char (+ (point-min) char-offset)))
1366 ;; Get rid of anything except the desired text.
1368 ;; Delete unused text region
1369 (let ((keep (if destp dst-pos src-pos)))
1370 (when (and divider-pos (> divider-pos keep))
1371 (delete-region divider-pos (point-max)))
1372 (delete-region (point-min) keep))
1373 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1374 (let ((kill-char (if destp ?- ?+)))
1375 (goto-char (point-min))
1377 (if (eq (char-after) kill-char)
1378 (delete-region (point) (progn (forward-line 1) (point)))
1379 (delete-char num-pfx-chars)
1380 (forward-line 1)))))
1382 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1383 (if char-offset (cons text (- (point) (point-min))) text))))))
1386 (defun diff-find-text (text)
1387 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1388 If TEXT isn't found, nil is returned."
1389 (let* ((orig (point))
1390 (forw (and (search-forward text nil t)
1391 (cons (match-beginning 0) (match-end 0))))
1392 (back (and (goto-char (+ orig (length text)))
1393 (search-backward text nil t)
1394 (cons (match-beginning 0) (match-end 0)))))
1395 ;; Choose the closest match.
1397 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1400 (defun diff-find-approx-text (text)
1401 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1402 Whitespace differences are ignored."
1403 (let* ((orig (point))
1404 (re (concat "^[ \t\n\f]*"
1405 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1407 (forw (and (re-search-forward re nil t)
1408 (cons (match-beginning 0) (match-end 0))))
1409 (back (and (goto-char (+ orig (length text)))
1410 (re-search-backward re nil t)
1411 (cons (match-beginning 0) (match-end 0)))))
1412 ;; Choose the closest match.
1414 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1417 (defsubst diff-xor (a b) (if a (if (not b) a) b))
1419 (defun diff-find-source-location (&optional other-file reverse)
1420 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1421 BUF is the buffer corresponding to the source file.
1422 LINE-OFFSET is the offset between the expected and actual positions
1423 of the text of the hunk or nil if the text was not found.
1424 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1425 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1426 SRC is the variant that was found in the buffer.
1427 SWITCHED is non-nil if the patch is already applied."
1429 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1430 (char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1432 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1433 ;; the user may disagree on what constitutes the hunk
1434 ;; (e.g. because an empty line truncates the hunk mid-course),
1435 ;; leading to potentially nasty surprises for the user.
1436 (_ (diff-sanity-check-hunk))
1437 (hunk (buffer-substring (point)
1438 (save-excursion (diff-end-of-hunk) (point))))
1439 (old (diff-hunk-text hunk reverse char-offset))
1440 (new (diff-hunk-text hunk (not reverse) char-offset))
1441 ;; Find the location specification.
1442 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1443 (error "Can't find the hunk header")
1444 (if other (match-string 1)
1445 (if (match-end 3) (match-string 3)
1446 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1447 (error "Can't find the hunk separator"))
1448 (match-string 1)))))
1449 (file (or (diff-find-file-name other) (error "Can't find the file")))
1450 (buf (find-file-noselect file)))
1451 ;; Update the user preference if he so wished.
1452 (when (> (prefix-numeric-value other-file) 8)
1453 (setq diff-jump-to-old-file other))
1454 (with-current-buffer buf
1455 (goto-line (string-to-number line))
1456 (let* ((orig-pos (point))
1458 ;; FIXME: Check for case where both OLD and NEW are found.
1459 (pos (or (diff-find-text (car old))
1460 (progn (setq switched t) (diff-find-text (car new)))
1461 (progn (setq switched nil)
1463 (diff-find-approx-text (car old))
1464 (invalid-regexp nil))) ;Regex too big.
1465 (progn (setq switched t)
1467 (diff-find-approx-text (car new))
1468 (invalid-regexp nil))) ;Regex too big.
1469 (progn (setq switched nil) nil))))
1473 (list (count-lines orig-pos (car pos)) pos)
1474 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1475 (if switched (list new old t) (list old new))))))))
1478 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1479 (let ((msg (if dry-run
1480 (if reversed "already applied" "not yet applied")
1481 (if reversed "undone" "applied"))))
1482 (message (cond ((null line-offset) "Hunk text not found")
1483 ((= line-offset 0) "Hunk %s")
1484 ((= line-offset 1) "Hunk %s at offset %d line")
1485 (t "Hunk %s at offset %d lines"))
1488 (defvar diff-apply-hunk-to-backup-file nil)
1490 (defun diff-apply-hunk (&optional reverse)
1491 "Apply the current hunk to the source file and go to the next.
1492 By default, the new source file is patched, but if the variable
1493 `diff-jump-to-old-file' is non-nil, then the old source file is
1494 patched instead (some commands, such as `diff-goto-source' can change
1495 the value of this variable when given an appropriate prefix argument).
1497 With a prefix argument, REVERSE the hunk."
1499 (destructuring-bind (buf line-offset pos old new &optional switched)
1500 ;; Sometimes we'd like to have the following behavior: if REVERSE go
1501 ;; to the new file, otherwise go to the old. But that means that by
1502 ;; default we use the old file, which is the opposite of the default
1503 ;; for diff-goto-source, and is thus confusing. Also when you don't
1504 ;; know about it it's pretty surprising.
1505 ;; TODO: make it possible to ask explicitly for this behavior.
1507 ;; This is duplicated in diff-test-hunk.
1508 (diff-find-source-location nil reverse)
1511 (error "Can't find the text to patch"))
1512 ((with-current-buffer buf
1513 (and buffer-file-name
1514 (backup-file-name-p buffer-file-name)
1515 (not diff-apply-hunk-to-backup-file)
1516 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1517 (yes-or-no-p (format "Really apply this hunk to %s? "
1518 (file-name-nondirectory
1519 buffer-file-name)))))))
1521 (substitute-command-keys
1522 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1523 (if (not reverse) "\\[universal-argument] ")))))
1525 ;; A reversed patch was detected, perhaps apply it in reverse.
1526 (not (save-window-excursion
1528 (goto-char (+ (car pos) (cdr old)))
1531 "Hunk hasn't been applied yet; apply it now? "
1532 "Hunk has already been applied; undo it? ")))))
1533 (message "(Nothing done)"))
1536 (with-current-buffer buf
1537 (goto-char (car pos))
1538 (delete-region (car pos) (cdr pos))
1540 ;; Display BUF in a window
1541 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1542 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1543 (when diff-advance-after-apply-hunk
1544 (diff-hunk-next))))))
1547 (defun diff-test-hunk (&optional reverse)
1548 "See whether it's possible to apply the current hunk.
1549 With a prefix argument, try to REVERSE the hunk."
1551 (destructuring-bind (buf line-offset pos src dst &optional switched)
1552 (diff-find-source-location nil reverse)
1553 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1554 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1557 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1559 (defun diff-goto-source (&optional other-file event)
1560 "Jump to the corresponding source line.
1561 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1562 is given) determines whether to jump to the old or the new file.
1563 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1564 then `diff-jump-to-old-file' is also set, for the next invocations."
1565 (interactive (list current-prefix-arg last-input-event))
1566 ;; When pointing at a removal line, we probably want to jump to
1567 ;; the old location, and else to the new (i.e. as if reverting).
1568 ;; This is a convenient detail when using smerge-diff.
1569 (if event (posn-set-point (event-end event)))
1570 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1571 (destructuring-bind (buf line-offset pos src dst &optional switched)
1572 (diff-find-source-location other-file rev)
1574 (goto-char (+ (car pos) (cdr src)))
1575 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1578 (defun diff-current-defun ()
1579 "Find the name of function at point.
1580 For use in `add-log-current-defun-function'."
1582 (when (looking-at diff-hunk-header-re)
1584 (re-search-forward "^[^ ]" nil t))
1585 (destructuring-bind (buf line-offset pos src dst &optional switched)
1586 (diff-find-source-location)
1588 (or (when (memq (char-after) '(?< ?-))
1589 ;; Cursor is pointing at removed text. This could be a removed
1590 ;; function, in which case, going to the source buffer will
1591 ;; not help since the function is now removed. Instead,
1592 ;; try to figure out the function name just from the code-fragment.
1593 (let ((old (if switched dst src)))
1596 (funcall (with-current-buffer buf major-mode))
1597 (goto-char (+ (point-min) (cdr old)))
1598 (add-log-current-defun))))
1599 (with-current-buffer buf
1600 (goto-char (+ (car pos) (cdr src)))
1601 (add-log-current-defun))))))
1603 (defun diff-refine-ignore-spaces-hunk ()
1604 "Refine the current hunk by ignoring space differences."
1606 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1608 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1609 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1610 (error "Can't find line number"))
1611 (string-to-number (match-string 1))))
1612 (hunk (delete-and-extract-region
1613 (point) (save-excursion (diff-end-of-hunk) (point))))
1614 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1615 (file1 (make-temp-file "diff1"))
1616 (file2 (make-temp-file "diff2"))
1617 (coding-system-for-read buffer-file-coding-system)
1618 (inhibit-read-only t)
1622 (setq old (diff-hunk-text hunk nil char-offset))
1623 (setq new (diff-hunk-text hunk t char-offset))
1624 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1625 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1628 (call-process diff-command nil t nil
1631 (0 nil) ;Nothing to reformat.
1632 (1 (goto-char (point-min))
1633 ;; Remove the file-header.
1634 (when (re-search-forward diff-hunk-header-re nil t)
1635 (delete-region (point-min) (match-beginning 0))))
1636 (t (goto-char (point-max))
1637 (unless (bolp) (insert "\n"))
1639 (setq hunk (buffer-string))
1640 (unless (memq status '(0 1))
1641 (error "Diff returned: %s" status)))))
1642 ;; Whatever happens, put back some equivalent text: either the new
1643 ;; one or the original one in case some error happened.
1646 (delete-file file2))))
1648 ;;; Fine change highlighting.
1650 (defface diff-fine-change
1651 '((t :background "yellow"))
1652 "Face used for char-based changes shown by `diff-fine-highlight'.")
1654 (defun diff-fine-highlight-preproc ()
1655 (while (re-search-forward "^." nil t)
1656 ;; Replace the hunk's leading prefix (+, -, !, <, or >) on each line
1657 ;; with something constant, otherwise it'll be flagged as changes
1658 ;; (since it's typically "-" on one side and "+" on the other).
1659 ;; Note that we keep the same number of chars: we treat the prefix
1660 ;; as part of the texts-to-diff, so that finding the right char
1661 ;; afterwards will be easier. This only makes sense because we make
1662 ;; diffs at char-granularity.
1663 (replace-match " ")))
1665 (defun diff-fine-highlight ()
1666 "Highlight changes of hunk at point at a finer granularity."
1668 (require 'smerge-mode)
1669 (diff-beginning-of-hunk 'try-harder)
1670 (let* ((style (diff-hunk-style)) ;Skips the hunk header as well.
1672 (props '((diff-mode . fine) (face diff-fine-change)))
1673 (end (progn (diff-end-of-hunk) (point))))
1675 (remove-overlays beg end 'diff-mode 'fine)
1680 (while (re-search-forward "^\\(?:-.*\n\\)+\\(\\)\\(?:\\+.*\n\\)+" end t)
1681 (smerge-refine-subst (match-beginning 0) (match-end 1)
1682 (match-end 1) (match-end 0)
1683 props 'diff-fine-highlight-preproc)))
1685 (let* ((middle (save-excursion (re-search-forward "^---")))
1687 (while (re-search-forward "^\\(?:!.*\n\\)+" middle t)
1688 (smerge-refine-subst (match-beginning 0) (match-end 0)
1691 (re-search-forward "^\\(?:!.*\n\\)+" end)
1692 (setq other (match-end 0))
1693 (match-beginning 0))
1695 props 'diff-fine-highlight-preproc))))
1697 (let ((beg1 (1+ (point))))
1698 (when (re-search-forward "^---.*\n" end t)
1699 ;; It's a combined add&remove, so there's something to do.
1700 (smerge-refine-subst beg1 (match-beginning 0)
1702 props 'diff-fine-highlight-preproc)))))))
1705 ;; provide the package
1706 (provide 'diff-mode)
1708 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1709 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1710 ;; (diff-mode-load-hook): dropped.
1711 ;; (auto-mode-alist): also catch *.diffs.
1712 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1713 ;; for *.rej files (that lack any file name indication).
1715 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1716 ;; added support for "\ No newline at end of file".
1718 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1719 ;; - added basic `compile' support.
1720 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1721 ;; - diff-kill-file now tries to kill the leading garbage as well.
1723 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1724 ;; - don't use CL in the autoloaded code
1725 ;; - accept diffs using -T
1727 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1728 ;; interface to ediff-patch
1730 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1731 ;; (ediff=patch-file): add bindings to call ediff-patch.
1732 ;; (diff-find-file-name): taken out of diff-goto-source.
1733 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1734 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1736 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1737 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1739 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1740 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1743 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1744 ;;; diff-mode.el ends here