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)
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 ;; - Refine hunk on a word-by-word basis.
53 ;; - in diff-apply-hunk, strip context in replace-match to better
54 ;; preserve markers and spacing.
55 ;; - Handle `diff -b' output in context->unified.
58 (eval-when-compile (require 'cl
))
60 (defvar add-log-buffer-file-name-function
)
63 (defgroup diff-mode
()
64 "Major mode for viewing/editing diffs."
69 (defcustom diff-default-read-only nil
70 "If non-nil, `diff-mode' buffers default to being read-only."
74 (defcustom diff-jump-to-old-file nil
75 "*Non-nil means `diff-goto-source' jumps to the old file.
76 Else, it jumps to the new file."
80 (defcustom diff-update-on-the-fly t
81 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
82 When editing a diff file, the line numbers in the hunk headers
83 need to be kept consistent with the actual diff. This can
84 either be done on the fly (but this sometimes interacts poorly with the
85 undo mechanism) or whenever the file is written (can be slow
86 when editing big diffs)."
90 (defcustom diff-advance-after-apply-hunk t
91 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
96 (defcustom diff-mode-hook nil
97 "Run after setting up the `diff-mode' major mode."
99 :options
'(diff-delete-empty-files diff-make-unified
)
102 (defvar diff-outline-regexp
103 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
106 ;;;; keymap, menu, ...
109 (easy-mmode-defmap diff-mode-shared-map
110 '(;; From Pavel Machek's patch-mode.
111 ("n" . diff-hunk-next
)
112 ("N" . diff-file-next
)
113 ("p" . diff-hunk-prev
)
114 ("P" . diff-file-prev
)
115 ("\t" . diff-hunk-next
)
116 ([backtab] . diff-hunk-prev)
117 ("k" . diff-hunk-kill)
118 ("K" . diff-file-kill)
119 ;; From compilation-minor-mode.
120 ("}" . diff-file-next)
121 ("{" . diff-file-prev)
122 ("\C-m" . diff-goto-source)
123 ([mouse-2] . diff-goto-source)
124 ;; From XEmacs' diff-mode.
125 ;; Standard M-w is useful, so don't change M-W.
127 ;;("." . diff-goto-source) ;display-buffer
128 ;;("f" . diff-goto-source) ;find-file
129 ("o" . diff-goto-source) ;other-window
130 ;;("w" . diff-goto-source) ;other-frame
131 ;;("N" . diff-narrow)
132 ;;("h" . diff-show-header)
133 ;;("j" . diff-show-difference) ;jump to Nth diff
135 ;; Not useful if you have to metafy them.
137 ;;("\177" . scroll-down)
138 ;; Standard M-a is useful, so don't change M-A.
139 ;;("A" . diff-ediff-patch)
140 ;; Standard M-r is useful, so don't change M-r or M-R.
141 ;;("r" . diff-restrict-view)
142 ;;("R" . diff-reverse-direction)
144 "Basic keymap for `diff-mode', bound to various prefix keys.")
146 (easy-mmode-defmap diff-mode-map
147 `(("\e" . ,diff-mode-shared-map)
148 ;; From compilation-minor-mode.
149 ("\C-c\C-c" . diff-goto-source)
151 ("\C-c\C-a" . diff-apply-hunk)
152 ("\C-c\C-e" . diff-ediff-patch)
153 ("\C-c\C-n" . diff-restrict-view)
154 ("\C-c\C-r" . diff-reverse-direction)
155 ("\C-c\C-s" . diff-split-hunk)
156 ("\C-c\C-t" . diff-test-hunk)
157 ("\C-c\C-u" . diff-context->unified)
158 ;; `d' because it duplicates the context :-( --Stef
159 ("\C-c\C-d" . diff-unified->context)
160 ("\C-c\C-w" . diff-refine-hunk)
161 ("\C-c\C-f" . next-error-follow-minor-mode))
162 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
164 (easy-menu-define diff-mode-menu diff-mode-map
165 "Menu for `diff-mode'."
167 ["Jump to Source" diff-goto-source t]
168 ["Apply hunk" diff-apply-hunk t]
169 ["Test applying hunk" diff-test-hunk t]
170 ["Apply diff with Ediff" diff-ediff-patch t]
172 ["Reverse direction" diff-reverse-direction t]
173 ["Context -> Unified" diff-context->unified t]
174 ["Unified -> Context" diff-unified->context t]
175 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
177 ["Split hunk" diff-split-hunk t]
178 ["Refine hunk" diff-refine-hunk 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 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
355 (0 diff-header-face) (2 diff-file-header-face prepend))
356 ("^\\([-<]\\)\\(.*\n\\)"
357 (1 diff-indicator-removed-face) (2 diff-removed-face))
358 ("^\\([+>]\\)\\(.*\n\\)"
359 (1 diff-indicator-added-face) (2 diff-added-face))
360 ("^\\(!\\)\\(.*\n\\)"
361 (1 diff-indicator-changed-face) (2 diff-changed-face))
362 ("^Index: \\(.+\\).*\n"
363 (0 diff-header-face) (1 diff-index-face prepend))
364 ("^Only in .*\n" . diff-nonexistent-face)
366 (1 font-lock-comment-delimiter-face)
367 (2 font-lock-comment-face))
368 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
370 (defconst diff-font-lock-defaults
371 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
373 (defvar diff-imenu-generic-expression
374 ;; Prefer second name as first is most likely to be a backup or
375 ;; version-control name. The [\t\n] at the end of the unidiff pattern
376 ;; catches Debian source diff files (which lack the trailing date).
377 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
378 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
384 (defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
385 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
386 (defvar diff-narrowed-to nil)
388 (defun diff-end-of-hunk (&optional style)
389 (when (looking-at diff-hunk-header-re)
391 ;; Especially important for unified (because headers are ambiguous).
392 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
393 (goto-char (match-end 0)))
394 (let ((end (and (re-search-forward (case style
395 ;; A `unified' header is ambiguous.
396 (unified (concat "^[^-+# \\]\\|"
397 diff-file-header-re))
398 (context "^[^-+#! \\]")
402 (match-beginning 0))))
403 ;; The return value is used by easy-mmode-define-navigation.
404 (goto-char (or end (point-max)))))
406 (defun diff-beginning-of-hunk (&optional try-harder)
407 "Move back to beginning of hunk.
408 If TRY-HARDER is non-nil, try to cater to the case where we're not in a hunk
409 but in the file header instead, in which case move forward to the first hunk."
411 (unless (looking-at diff-hunk-header-re)
414 (re-search-backward diff-hunk-header-re)
417 (error "Can't find the beginning of the hunk")
418 (diff-beginning-of-file-and-junk)
419 (diff-hunk-next))))))
421 (defun diff-beginning-of-file ()
423 (unless (looking-at diff-file-header-re)
426 (re-search-backward diff-file-header-re)
427 (error (error "Can't find the beginning of the file")))))
429 (defun diff-end-of-file ()
430 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
431 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
433 (if (match-beginning 1)
434 (goto-char (match-beginning 1))
435 (beginning-of-line)))
437 ;; Define diff-{hunk,file}-{prev,next}
438 (easy-mmode-define-navigation
439 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
440 (easy-mmode-define-navigation
441 diff-file diff-file-header-re "file" diff-end-of-hunk)
443 (defun diff-restrict-view (&optional arg)
444 "Restrict the view to the current hunk.
445 If the prefix ARG is given, restrict the view to the current file instead."
448 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk 'try-harder))
449 (narrow-to-region (point)
450 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
452 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
455 (defun diff-hunk-kill ()
458 (diff-beginning-of-hunk)
459 (let* ((start (point))
460 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
461 (match-beginning 0)))
462 (firsthunk (ignore-errors
464 (diff-beginning-of-file) (diff-hunk-next) (point)))
465 (nextfile (ignore-errors (diff-file-next) (point)))
466 (inhibit-read-only t))
468 (if (and firsthunk (= firsthunk start)
470 (and nextfile (> nexthunk nextfile))))
471 ;; It's the only hunk for this file, so kill the file.
474 (kill-region start (point)))))
476 (defun diff-beginning-of-file-and-junk ()
477 "Go to the beginning of file-related diff-info.
478 This is like `diff-beginning-of-file' except it tries to skip back over leading
479 data such as \"Index: ...\" and such."
480 (let ((start (point))
481 (file (condition-case err (progn (diff-beginning-of-file) (point))
483 ;; prevhunk is one of the limits.
484 (prevhunk (save-excursion (ignore-errors (diff-hunk-prev) (point))))
487 ;; Presumably, we started before the file header, in the leading junk.
491 (let ((index (save-excursion
492 (forward-line 1) ;In case we're looking at "Index:".
493 (re-search-backward "^Index: " prevhunk t))))
494 (when index (setq file index))
497 ;; File starts *after* the starting point: we really weren't in
498 ;; a file diff but elsewhere.
500 (signal (car err) (cdr err))))))
502 (defun diff-file-kill ()
503 "Kill current file's hunks."
505 (diff-beginning-of-file-and-junk)
506 (let* ((start (point))
507 (inhibit-read-only t))
509 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
510 (kill-region start (point))))
512 (defun diff-kill-junk ()
513 "Kill spurious empty diffs."
516 (let ((inhibit-read-only t))
517 (goto-char (point-min))
518 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
519 "\\([^-+!* <>].*\n\\)*?"
520 "\\(\\(Index:\\) \\|"
521 diff-file-header-re "\\)")
523 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
525 (beginning-of-line)))))
527 (defun diff-count-matches (re start end)
531 (while (re-search-forward re end t) (incf n))
534 (defun diff-split-hunk ()
535 "Split the current (unified diff) hunk at point into two hunks."
539 (start (progn (diff-beginning-of-hunk) (point))))
540 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
541 (error "diff-split-hunk only works on unified context diffs"))
543 (let* ((start1 (string-to-number (match-string 1)))
544 (start2 (string-to-number (match-string 2)))
545 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
546 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
547 (inhibit-read-only t))
549 ;; Hopefully the after-change-function will not screw us over.
550 (insert "@@ -" (number-to-string newstart1) ",1 +"
551 (number-to-string newstart2) ",1 @@\n")
552 ;; Fix the original hunk-header.
553 (diff-fixup-modifs start pos))))
557 ;;;; jump to other buffers
560 (defvar diff-remembered-files-alist nil)
562 (defun diff-filename-drop-dir (file)
563 (when (string-match "/" file) (substring file (match-end 0))))
565 (defun diff-merge-strings (ancestor from to)
566 "Merge the diff between ANCESTOR and FROM into TO.
567 Returns the merged string if successful or nil otherwise.
568 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
569 If ANCESTOR = FROM, returns TO.
570 If ANCESTOR = TO, returns FROM.
571 The heuristic is simplistic and only really works for cases
572 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
574 ;; AMB ANB CMD -> CND
575 ;; but that's ambiguous if `foo' or `bar' is empty:
576 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
577 (let ((str (concat ancestor "\n" from "\n" to)))
578 (when (and (string-match (concat
579 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
581 "\\(.*\\(\\2\\).*\\)\\'") str)
582 (equal to (match-string 5 str)))
583 (concat (substring str (match-beginning 5) (match-beginning 6))
585 (substring str (match-end 6) (match-end 5))))))
587 (defun diff-tell-file-name (old name)
588 "Tell Emacs where the find the source file of the current hunk.
589 If the OLD prefix arg is passed, tell the file NAME of the old file."
591 (let* ((old current-prefix-arg)
592 (fs (diff-hunk-file-names current-prefix-arg)))
593 (unless fs (error "No file name to look for"))
594 (list old (read-file-name (format "File for %s: " (car fs))
595 nil (diff-find-file-name old) t))))
596 (let ((fs (diff-hunk-file-names old)))
597 (unless fs (error "No file name to look for"))
598 (push (cons fs name) diff-remembered-files-alist)))
600 (defun diff-hunk-file-names (&optional old)
601 "Give the list of file names textually mentioned for the current hunk."
603 (unless (looking-at diff-file-header-re)
604 (or (ignore-errors (diff-beginning-of-file))
605 (re-search-forward diff-file-header-re nil t)))
606 (let ((limit (save-excursion
608 (progn (diff-hunk-prev) (point))
609 (error (point-min)))))
611 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
612 (list (if old (match-string 1) (match-string 3))
613 (if old (match-string 3) (match-string 1)))
614 (forward-line 1) nil)))
619 (re-search-backward "^Index: \\(.+\\)" limit t)))
620 (list (match-string 1)))
622 (when (re-search-backward
623 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
625 (list (if old (match-string 2) (match-string 4))
626 (if old (match-string 4) (match-string 2)))))))))
628 (defun diff-find-file-name (&optional old prefix)
629 "Return the file corresponding to the current patch.
630 Non-nil OLD means that we want the old file.
631 PREFIX is only used internally: don't use it."
633 (unless (looking-at diff-file-header-re)
634 (or (ignore-errors (diff-beginning-of-file))
635 (re-search-forward diff-file-header-re nil t)))
636 (let ((fs (diff-hunk-file-names old)))
637 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
639 ;; use any previously used preference
640 (cdr (assoc fs diff-remembered-files-alist))
641 ;; try to be clever and use previous choices as an inspiration
642 (dolist (rf diff-remembered-files-alist)
643 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
644 (if (and newfile (file-exists-p newfile)) (return newfile))))
645 ;; look for each file in turn. If none found, try again but
646 ;; ignoring the first level of directory, ...
647 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
650 (setq file (do* ((files files (cdr files))
651 (file (car files) (car files)))
652 ;; Use file-regular-p to avoid
653 ;; /dev/null, directories, etc.
654 ((or (null file) (file-regular-p file))
657 ;; <foo>.rej patches implicitly apply to <foo>
658 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
659 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
660 (when (file-exists-p file) file)))
661 ;; If we haven't found the file, maybe it's because we haven't paid
662 ;; attention to the PCL-CVS hint.
664 (boundp 'cvs-pcl-cvs-dirchange-re)
666 (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
667 (diff-find-file-name old (match-string 1)))
668 ;; if all else fails, ask the user
669 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
670 nil (first fs) t (first fs))))
671 (set (make-local-variable 'diff-remembered-files-alist)
672 (cons (cons fs file) diff-remembered-files-alist))
676 (defun diff-ediff-patch ()
677 "Call `ediff-patch-file' on the current buffer."
680 (ediff-patch-file nil (current-buffer))
681 (wrong-number-of-arguments (ediff-patch-file))))
684 ;;;; Conversion functions
687 ;;(defvar diff-inhibit-after-change nil
688 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
690 (defun diff-unified->context (start end)
691 "Convert unified diffs to context diffs.
692 START and END are either taken from the region (if a prefix arg is given) or
693 else cover the whole buffer."
694 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
695 (list (region-beginning) (region-end))
696 (list (point-min) (point-max))))
697 (unless (markerp end) (setq end (copy-marker end t)))
698 (let (;;(diff-inhibit-after-change t)
699 (inhibit-read-only t))
702 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
704 (combine-after-change-calls
705 (if (match-beginning 2)
706 ;; we matched a file header
708 ;; use reverse order to make sure the indices are kept valid
709 (replace-match "---" t t nil 3)
710 (replace-match "***" t t nil 2))
711 ;; we matched a hunk header
712 (let ((line1 (match-string 4))
713 (lines1 (match-string 5))
714 (line2 (match-string 6))
715 (lines2 (match-string 7)))
717 (concat "***************\n*** " line1 ","
718 (number-to-string (+ (string-to-number line1)
719 (string-to-number lines1)
723 (narrow-to-region (point)
724 (progn (diff-end-of-hunk 'unified) (point)))
725 (let ((hunk (buffer-string)))
726 (goto-char (point-min))
727 (if (not (save-excursion (re-search-forward "^-" nil t)))
728 (delete-region (point) (point-max))
729 (goto-char (point-max))
730 (let ((modif nil) last-pt)
731 (while (progn (setq last-pt (point))
732 (= (forward-line -1) 0))
734 (?\s (insert " ") (setq modif nil) (backward-char 1))
735 (?+ (delete-region (point) last-pt) (setq modif t))
737 (progn (forward-char 1)
742 (?\\ (when (save-excursion (forward-line -1)
744 (delete-region (point) last-pt) (setq modif t)))
745 (t (setq modif nil))))))
746 (goto-char (point-max))
748 (insert "--- " line2 ","
749 (number-to-string (+ (string-to-number line2)
750 (string-to-number lines2)
751 -1)) " ----\n" hunk))
752 ;;(goto-char (point-min))
754 (if (not (save-excursion (re-search-forward "^+" nil t)))
755 (delete-region (point) (point-max))
756 (let ((modif nil) (delete nil))
759 (?\s (insert " ") (setq modif nil) (backward-char 1))
760 (?- (setq delete t) (setq modif t))
762 (progn (forward-char 1)
767 (?\\ (when (save-excursion (forward-line 1)
769 (setq delete t) (setq modif t)))
770 (t (setq modif nil)))
771 (let ((last-pt (point)))
774 (delete-region last-pt (point))
775 (setq delete nil)))))))))))))))
777 (defun diff-context->unified (start end &optional to-context)
778 "Convert context diffs to unified diffs.
779 START and END are either taken from the region
780 \(when it is highlighted) or else cover the whole buffer.
781 With a prefix argument, convert unified format to context format."
782 (interactive (if (and transient-mark-mode mark-active)
783 (list (region-beginning) (region-end) current-prefix-arg)
784 (list (point-min) (point-max) current-prefix-arg)))
786 (diff-unified->context start end)
787 (unless (markerp end) (setq end (copy-marker end t)))
788 (let ( ;;(diff-inhibit-after-change t)
789 (inhibit-read-only t))
792 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
794 (combine-after-change-calls
795 (if (match-beginning 2)
796 ;; we matched a file header
798 ;; use reverse order to make sure the indices are kept valid
799 (replace-match "+++" t t nil 3)
800 (replace-match "---" t t nil 2))
801 ;; we matched a hunk header
802 (let ((line1s (match-string 4))
803 (line1e (match-string 5))
804 (pt1 (match-beginning 0)))
806 (unless (re-search-forward
807 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
808 (error "Can't find matching `--- n1,n2 ----' line"))
809 (let ((line2s (match-string 1))
810 (line2e (match-string 2))
812 (delete-region (progn (beginning-of-line) (point))
813 (progn (forward-line 1) (point)))
817 (while (< (point) pt2)
819 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
820 (?\s ;merge with the other half of the chunk
823 (goto-char pt2) (forward-line 1) (point)))
824 (c (char-after pt2)))
828 (prog1 (buffer-substring (+ pt2 2) endline2)
829 (delete-region pt2 endline2))))
830 (?\s ;FIXME: check consistency
831 (delete-region pt2 endline2)
834 (?\\ (forward-line 1))
835 (t (delete-char 1) (forward-line 1)))))
836 (t (forward-line 1))))
837 (while (looking-at "[+! ] ")
838 (if (/= (char-after) ?!) (forward-char 1)
839 (delete-char 1) (insert "+"))
840 (delete-char 1) (forward-line 1))
843 (insert "@@ -" line1s ","
844 (number-to-string (- (string-to-number line1e)
845 (string-to-number line1s)
848 (number-to-string (- (string-to-number line2e)
849 (string-to-number line2s)
850 -1)) " @@")))))))))))
852 (defun diff-reverse-direction (start end)
853 "Reverse the direction of the diffs.
854 START and END are either taken from the region (if a prefix arg is given) or
855 else cover the whole buffer."
856 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
857 (list (region-beginning) (region-end))
858 (list (point-min) (point-max))))
859 (unless (markerp end) (setq end (copy-marker end t)))
860 (let (;;(diff-inhibit-after-change t)
861 (inhibit-read-only t))
864 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
866 (combine-after-change-calls
869 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
870 ;; a context-diff hunk header
872 (let ((pt-lines1 (match-beginning 6))
873 (lines1 (match-string 6)))
874 (replace-match "" nil nil nil 6)
876 (let ((half1s (point)))
877 (while (looking-at "[-! \\][ \t]\\|#")
878 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
880 (let ((half1 (delete-and-extract-region half1s (point))))
881 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
883 (error "Can't find matching `--- n1,n2 ----' line"))
884 (let ((str1 (match-string 1)))
885 (replace-match lines1 nil nil nil 1)
887 (let ((half2s (point)))
888 (while (looking-at "[!+ \\][ \t]\\|#")
889 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
891 (let ((half2 (delete-and-extract-region half2s (point))))
892 (insert (or half1 ""))
894 (insert (or half2 ""))))
895 (goto-char pt-lines1)
897 ;; a unified-diff hunk header
899 (replace-match "@@ -\\8 +\\7 @@" nil)
901 (let ((c (char-after)) first last)
902 (while (case (setq c (char-after))
903 (?- (setq first (or first (point)))
904 (delete-char 1) (insert "+") t)
905 (?+ (setq last (or last (point)))
906 (delete-char 1) (insert "-") t)
908 (t (when (and first last (< first last))
909 (insert (delete-and-extract-region first last)))
910 (setq first nil last nil)
912 (forward-line 1))))))))))
914 (defun diff-fixup-modifs (start end)
915 "Fixup the hunk headers (in case the buffer was modified).
916 START and END are either taken from the region (if a prefix arg is given) or
917 else cover the whole buffer."
918 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
919 (list (region-beginning) (region-end))
920 (list (point-min) (point-max))))
921 (let ((inhibit-read-only t))
923 (goto-char end) (diff-end-of-hunk)
924 (let ((plus 0) (minus 0) (space 0) (bang 0))
925 (while (and (= (forward-line -1) 0) (<= start (point)))
927 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
928 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
929 "\\|--- .+\n\\+\\+\\+ ")))
936 (t (setq space 0 plus 0 minus 0 bang 0)))
938 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
939 (let* ((old1 (match-string 1))
940 (old2 (match-string 2))
941 (new1 (number-to-string (+ space minus)))
942 (new2 (number-to-string (+ space plus))))
943 (unless (string= new2 old2) (replace-match new2 t t nil 2))
944 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
945 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
946 (when (> (+ space bang plus) 0)
947 (let* ((old1 (match-string 1))
948 (old2 (match-string 2))
949 (new (number-to-string
950 (+ space bang plus -1 (string-to-number old1)))))
951 (unless (string= new old2) (replace-match new t t nil 2)))))
952 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
953 (when (> (+ space bang minus) 0)
954 (let* ((old (match-string 1))
956 (concat "%0" (number-to-string (length old)) "d")
957 (+ space bang minus -1 (string-to-number old)))))
958 (unless (string= new old) (replace-match new t t nil 2))))))
959 (setq space 0 plus 0 minus 0 bang 0)))))))
965 (defun diff-write-contents-hooks ()
966 "Fixup hunk headers if necessary."
967 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
970 ;; It turns out that making changes in the buffer from within an
971 ;; *-change-function is asking for trouble, whereas making them
972 ;; from a post-command-hook doesn't pose much problems
973 (defvar diff-unhandled-changes nil)
974 (defun diff-after-change-function (beg end len)
975 "Remember to fixup the hunk header.
976 See `after-change-functions' for the meaning of BEG, END and LEN."
977 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
978 ;; incorrect, but it turns out that inhibit-read-only is normally not set
979 ;; inside editing commands, while it tends to be set when the buffer gets
980 ;; updated by an async process or by a conversion function, both of which
981 ;; would rather not be uselessly slowed down by this hook.
982 (when (and (not undo-in-progress) (not inhibit-read-only))
983 (if diff-unhandled-changes
984 (setq diff-unhandled-changes
985 (cons (min beg (car diff-unhandled-changes))
986 (max end (cdr diff-unhandled-changes))))
987 (setq diff-unhandled-changes (cons beg end)))))
989 (defun diff-post-command-hook ()
990 "Fixup hunk headers if necessary."
991 (when (consp diff-unhandled-changes)
994 (goto-char (car diff-unhandled-changes))
995 ;; Maybe we've cut the end of the hunk before point.
996 (if (and (bolp) (not (bobp))) (backward-char 1))
997 ;; We used to fixup modifs on all the changes, but it turns out
998 ;; that it's safer not to do it on big changes, for example
999 ;; when yanking a big diff, since we might then screw up perfectly
1000 ;; correct values. -stef
1001 ;; (unless (ignore-errors
1002 ;; (diff-beginning-of-hunk)
1004 ;; (diff-end-of-hunk)
1005 ;; (> (point) (car diff-unhandled-changes))))
1006 ;; (goto-char (car diff-unhandled-changes))
1007 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
1008 ;; (diff-beginning-of-hunk))
1009 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
1010 (diff-beginning-of-hunk)
1011 (when (save-excursion
1013 (>= (point) (cdr diff-unhandled-changes)))
1014 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
1015 (setq diff-unhandled-changes nil)))
1017 (defun diff-next-error (arg reset)
1018 ;; Select a window that displays the current buffer so that point
1019 ;; movements are reflected in that window. Otherwise, the user might
1020 ;; never see the hunk corresponding to the source she's jumping to.
1021 (pop-to-buffer (current-buffer))
1022 (if reset (goto-char (point-min)))
1023 (diff-hunk-next arg)
1027 (define-derived-mode diff-mode fundamental-mode "Diff"
1028 "Major mode for viewing/editing context diffs.
1029 Supports unified and context diffs as well as (to a lesser extent)
1032 When the buffer is read-only, the ESC prefix is not necessary.
1033 If you edit the buffer manually, diff-mode will try to update the hunk
1034 headers for you on-the-fly.
1036 You can also switch between context diff and unified diff with \\[diff-context->unified],
1037 or vice versa with \\[diff-unified->context] and you can also reverse the direction of
1038 a diff with \\[diff-reverse-direction].
1042 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1043 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
1044 (set (make-local-variable 'imenu-generic-expression)
1045 diff-imenu-generic-expression)
1046 ;; These are not perfect. They would be better done separately for
1047 ;; context diffs and unidiffs.
1048 ;; (set (make-local-variable 'paragraph-start)
1049 ;; (concat "@@ " ; unidiff hunk
1050 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1051 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1052 ;; ; start (first or second line)
1053 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1054 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1056 (set (make-local-variable 'next-error-function) 'diff-next-error)
1058 (setq buffer-read-only diff-default-read-only)
1059 ;; setup change hooks
1060 (if (not diff-update-on-the-fly)
1061 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1062 (make-local-variable 'diff-unhandled-changes)
1063 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1064 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1065 ;; Neat trick from Dave Love to add more bindings in read-only mode:
1066 (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
1067 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1068 ;; Turn off this little trick in case the buffer is put in view-mode.
1069 (add-hook 'view-mode-hook
1071 (setq minor-mode-overriding-map-alist
1072 (delq ro-bind minor-mode-overriding-map-alist)))
1075 (set (make-local-variable 'add-log-current-defun-function)
1076 'diff-current-defun)
1077 (set (make-local-variable 'add-log-buffer-file-name-function)
1078 'diff-find-file-name))
1081 (define-minor-mode diff-minor-mode
1082 "Minor mode for viewing/editing context diffs.
1083 \\{diff-minor-mode-map}"
1084 :group 'diff-mode :lighter " Diff"
1085 ;; FIXME: setup font-lock
1086 ;; setup change hooks
1087 (if (not diff-update-on-the-fly)
1088 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1089 (make-local-variable 'diff-unhandled-changes)
1090 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1091 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1093 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1095 (defun diff-delete-if-empty ()
1096 ;; An empty diff file means there's no more diffs to integrate, so we
1097 ;; can just remove the file altogether. Very handy for .rej files if we
1098 ;; remove hunks as we apply them.
1099 (when (and buffer-file-name
1100 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1101 (delete-file buffer-file-name)))
1103 (defun diff-delete-empty-files ()
1104 "Arrange for empty diff files to be removed."
1105 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1107 (defun diff-make-unified ()
1108 "Turn context diffs into unified diffs if applicable."
1110 (goto-char (point-min))
1111 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
1112 (let ((mod (buffer-modified-p)))
1114 (diff-context->unified (point-min) (point-max))
1115 (restore-buffer-modified-p mod)))))
1118 ;;; Misc operations that have proved useful at some point.
1121 (defun diff-next-complex-hunk ()
1122 "Jump to the next \"complex\" hunk.
1123 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1124 Only works for unified diffs."
1127 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1129 (equal (match-string 1) (match-string 2)))))
1131 (defun diff-sanity-check-context-hunk-half (lines)
1132 (let ((count lines))
1135 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1136 (memq (char-after (1+ (point))) '(?\s ?\t)))
1138 ((or (zerop count) (= count lines)) nil)
1139 ((memq (char-after) '(?! ?+ ?-))
1140 (if (not (and (eq (char-after (1+ (point))) ?\n)
1141 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1142 (error "End of hunk ambiguously marked")
1143 (forward-char 1) (insert " ") (forward-line -1) t))
1145 (error "End of hunk ambiguously marked"))
1146 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1148 ((eolp) (insert " ") (forward-line -1) t)
1149 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1152 (defun diff-sanity-check-hunk ()
1153 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1154 ;; OK to override a read-only setting.
1155 (inhibit-read-only t))
1158 ((not (looking-at diff-hunk-header-re))
1159 (error "Not recognizable hunk header"))
1162 ((eq (char-after) ?*)
1163 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\),\\([0-9]+\\) \\*\\*\\*\\*"))
1164 (error "Unrecognized context diff first hunk header format")
1166 (diff-sanity-check-context-hunk-half
1167 (1+ (- (string-to-number (match-string 2))
1168 (string-to-number (match-string 1)))))
1169 (if (not (looking-at "--- \\([0-9]+\\),\\([0-9]+\\) ----$"))
1170 (error "Unrecognized context diff second hunk header format")
1172 (diff-sanity-check-context-hunk-half
1173 (1+ (- (string-to-number (match-string 2))
1174 (string-to-number (match-string 1))))))))
1177 ((eq (char-after) ?@)
1178 (if (not (looking-at
1179 "@@ -[0-9]+,\\([0-9]+\\) \\+[0-9]+,\\([0-9]+\\) @@"))
1180 (error "Unrecognized unified diff hunk header format")
1181 (let ((before (string-to-number (match-string 1)))
1182 (after (string-to-number (match-string 2))))
1186 (?\s (decf before) (decf after) t)
1188 (if (and (looking-at diff-file-header-re)
1189 (zerop before) (zerop after))
1190 ;; No need to query: this is a case where two patches
1191 ;; are concatenated and only counting the lines will
1192 ;; give the right result. Let's just add an empty
1193 ;; line so that our code which doesn't count lines
1194 ;; will not get confused.
1195 (progn (save-excursion (insert "\n")) nil)
1200 ((and (zerop before) (zerop after)) nil)
1201 ((or (< before 0) (< after 0))
1202 (error (if (or (zerop before) (zerop after))
1203 "End of hunk ambiguously marked"
1204 "Hunk seriously messed up")))
1205 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1207 ((eolp) (insert " ") (forward-line -1) t)
1209 (delete-region (- (point) 2) (- (point) 1)) t))))
1217 (defun diff-hunk-text (hunk destp char-offset)
1218 "Return the literal source text from HUNK as (TEXT . OFFSET).
1219 If DESTP is nil, TEXT is the source, otherwise the destination text.
1220 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1221 char-offset in TEXT."
1224 (goto-char (point-min))
1229 ;; Set the following variables:
1230 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1231 ;; DST-POS buffer pos of the destination part of the hunk or nil
1232 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1233 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1234 (cond ((looking-at "^@@")
1236 (setq num-pfx-chars 1)
1238 (setq src-pos (point) dst-pos (point)))
1239 ((looking-at "^\\*\\*")
1242 (setq src-pos (point))
1243 (re-search-forward "^--- " nil t)
1245 (setq divider-pos (point))
1247 (setq dst-pos (point)))
1248 ((looking-at "^[0-9]+a[0-9,]+$")
1249 ;; normal diff, insert
1251 (setq dst-pos (point)))
1252 ((looking-at "^[0-9,]+d[0-9]+$")
1253 ;; normal diff, delete
1255 (setq src-pos (point)))
1256 ((looking-at "^[0-9,]+c[0-9,]+$")
1257 ;; normal diff, change
1259 (setq src-pos (point))
1260 (re-search-forward "^---$" nil t)
1262 (setq divider-pos (point))
1264 (setq dst-pos (point)))
1266 (error "Unknown diff hunk type")))
1268 (if (if destp (null dst-pos) (null src-pos))
1269 ;; Implied empty text
1270 (if char-offset '("" . 0) "")
1272 ;; For context diffs, either side can be empty, (if there's only
1273 ;; added or only removed text). We should then use the other side.
1274 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1275 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1277 (when char-offset (goto-char (+ (point-min) char-offset)))
1279 ;; Get rid of anything except the desired text.
1281 ;; Delete unused text region
1282 (let ((keep (if destp dst-pos src-pos)))
1283 (when (and divider-pos (> divider-pos keep))
1284 (delete-region divider-pos (point-max)))
1285 (delete-region (point-min) keep))
1286 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1287 (let ((kill-char (if destp ?- ?+)))
1288 (goto-char (point-min))
1290 (if (eq (char-after) kill-char)
1291 (delete-region (point) (progn (forward-line 1) (point)))
1292 (delete-char num-pfx-chars)
1293 (forward-line 1)))))
1295 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1296 (if char-offset (cons text (- (point) (point-min))) text))))))
1299 (defun diff-find-text (text)
1300 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1301 If TEXT isn't found, nil is returned."
1302 (let* ((orig (point))
1303 (forw (and (search-forward text nil t)
1304 (cons (match-beginning 0) (match-end 0))))
1305 (back (and (goto-char (+ orig (length text)))
1306 (search-backward text nil t)
1307 (cons (match-beginning 0) (match-end 0)))))
1308 ;; Choose the closest match.
1310 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1313 (defun diff-find-approx-text (text)
1314 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1315 Whitespace differences are ignored."
1316 (let* ((orig (point))
1317 (re (concat "^[ \t\n\f]*"
1318 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1320 (forw (and (re-search-forward re nil t)
1321 (cons (match-beginning 0) (match-end 0))))
1322 (back (and (goto-char (+ orig (length text)))
1323 (re-search-backward re nil t)
1324 (cons (match-beginning 0) (match-end 0)))))
1325 ;; Choose the closest match.
1327 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1330 (defsubst diff-xor (a b) (if a (not b) b))
1332 (defun diff-find-source-location (&optional other-file reverse)
1333 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1334 BUF is the buffer corresponding to the source file.
1335 LINE-OFFSET is the offset between the expected and actual positions
1336 of the text of the hunk or nil if the text was not found.
1337 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1338 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1339 SRC is the variant that was found in the buffer.
1340 SWITCHED is non-nil if the patch is already applied."
1342 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1343 (char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1345 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1346 ;; the user may disagree on what constitutes the hunk
1347 ;; (e.g. because an empty line truncates the hunk mid-course),
1348 ;; leading to potentially nasty surprises for the user.
1349 (_ (diff-sanity-check-hunk))
1350 (hunk (buffer-substring (point)
1351 (save-excursion (diff-end-of-hunk) (point))))
1352 (old (diff-hunk-text hunk reverse char-offset))
1353 (new (diff-hunk-text hunk (not reverse) char-offset))
1354 ;; Find the location specification.
1355 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1356 (error "Can't find the hunk header")
1357 (if other (match-string 1)
1358 (if (match-end 3) (match-string 3)
1359 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1360 (error "Can't find the hunk separator"))
1361 (match-string 1)))))
1362 (file (or (diff-find-file-name other) (error "Can't find the file")))
1363 (buf (find-file-noselect file)))
1364 ;; Update the user preference if he so wished.
1365 (when (> (prefix-numeric-value other-file) 8)
1366 (setq diff-jump-to-old-file other))
1367 (with-current-buffer buf
1368 (goto-line (string-to-number line))
1369 (let* ((orig-pos (point))
1371 ;; FIXME: Check for case where both OLD and NEW are found.
1372 (pos (or (diff-find-text (car old))
1373 (progn (setq switched t) (diff-find-text (car new)))
1374 (progn (setq switched nil)
1376 (diff-find-approx-text (car old))
1377 (invalid-regexp nil))) ;Regex too big.
1378 (progn (setq switched t)
1380 (diff-find-approx-text (car new))
1381 (invalid-regexp nil))) ;Regex too big.
1382 (progn (setq switched nil) nil))))
1386 (list (count-lines orig-pos (car pos)) pos)
1387 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1388 (if switched (list new old t) (list old new))))))))
1391 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1392 (let ((msg (if dry-run
1393 (if reversed "already applied" "not yet applied")
1394 (if reversed "undone" "applied"))))
1395 (message (cond ((null line-offset) "Hunk text not found")
1396 ((= line-offset 0) "Hunk %s")
1397 ((= line-offset 1) "Hunk %s at offset %d line")
1398 (t "Hunk %s at offset %d lines"))
1401 (defvar diff-apply-hunk-to-backup-file nil)
1403 (defun diff-apply-hunk (&optional reverse)
1404 "Apply the current hunk to the source file and go to the next.
1405 By default, the new source file is patched, but if the variable
1406 `diff-jump-to-old-file' is non-nil, then the old source file is
1407 patched instead (some commands, such as `diff-goto-source' can change
1408 the value of this variable when given an appropriate prefix argument).
1410 With a prefix argument, REVERSE the hunk."
1412 (destructuring-bind (buf line-offset pos old new &optional switched)
1413 ;; If REVERSE go to the new file, otherwise go to the old.
1414 (diff-find-source-location (not reverse) reverse)
1417 (error "Can't find the text to patch"))
1418 ((with-current-buffer buf
1419 (and buffer-file-name
1420 (backup-file-name-p buffer-file-name)
1421 (not diff-apply-hunk-to-backup-file)
1422 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1423 (yes-or-no-p (format "Really apply this hunk to %s? "
1424 (file-name-nondirectory
1425 buffer-file-name)))))))
1427 (substitute-command-keys
1428 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1429 (if (not reverse) "\\[universal-argument] ")))))
1431 ;; A reversed patch was detected, perhaps apply it in reverse.
1432 (not (save-window-excursion
1434 (goto-char (+ (car pos) (cdr old)))
1437 "Hunk hasn't been applied yet; apply it now? "
1438 "Hunk has already been applied; undo it? ")))))
1439 (message "(Nothing done)"))
1442 (with-current-buffer buf
1443 (goto-char (car pos))
1444 (delete-region (car pos) (cdr pos))
1446 ;; Display BUF in a window
1447 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1448 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1449 (when diff-advance-after-apply-hunk
1450 (diff-hunk-next))))))
1453 (defun diff-test-hunk (&optional reverse)
1454 "See whether it's possible to apply the current hunk.
1455 With a prefix argument, try to REVERSE the hunk."
1457 (destructuring-bind (buf line-offset pos src dst &optional switched)
1458 ;; If REVERSE go to the new file, otherwise go to the old.
1459 (diff-find-source-location (not reverse) reverse)
1460 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1461 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1464 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1466 (defun diff-goto-source (&optional other-file event)
1467 "Jump to the corresponding source line.
1468 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1469 is given) determines whether to jump to the old or the new file.
1470 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1471 then `diff-jump-to-old-file' is also set, for the next invocations."
1472 (interactive (list current-prefix-arg last-input-event))
1473 ;; When pointing at a removal line, we probably want to jump to
1474 ;; the old location, and else to the new (i.e. as if reverting).
1475 ;; This is a convenient detail when using smerge-diff.
1476 (if event (posn-set-point (event-end event)))
1477 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1478 (destructuring-bind (buf line-offset pos src dst &optional switched)
1479 (diff-find-source-location other-file rev)
1481 (goto-char (+ (car pos) (cdr src)))
1482 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1485 (defun diff-current-defun ()
1486 "Find the name of function at point.
1487 For use in `add-log-current-defun-function'."
1489 (when (looking-at diff-hunk-header-re)
1491 (re-search-forward "^[^ ]" nil t))
1492 (destructuring-bind (buf line-offset pos src dst &optional switched)
1493 (diff-find-source-location)
1495 (or (when (memq (char-after) '(?< ?-))
1496 ;; Cursor is pointing at removed text. This could be a removed
1497 ;; function, in which case, going to the source buffer will
1498 ;; not help since the function is now removed. Instead,
1499 ;; try to figure out the function name just from the code-fragment.
1500 (let ((old (if switched dst src)))
1503 (funcall (with-current-buffer buf major-mode))
1504 (goto-char (+ (point-min) (cdr old)))
1505 (add-log-current-defun))))
1506 (with-current-buffer buf
1507 (goto-char (+ (car pos) (cdr src)))
1508 (add-log-current-defun))))))
1510 (defun diff-refine-hunk ()
1511 "Refine the current hunk by ignoring space differences."
1513 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1515 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1516 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1517 (error "Can't find line number"))
1518 (string-to-number (match-string 1))))
1519 (hunk (delete-and-extract-region
1520 (point) (save-excursion (diff-end-of-hunk) (point))))
1521 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1522 (file1 (make-temp-file "diff1"))
1523 (file2 (make-temp-file "diff2"))
1524 (coding-system-for-read buffer-file-coding-system)
1525 (inhibit-read-only t)
1529 (setq old (diff-hunk-text hunk nil char-offset))
1530 (setq new (diff-hunk-text hunk t char-offset))
1531 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1532 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1535 (call-process diff-command nil t nil
1538 (0 nil) ;Nothing to reformat.
1539 (1 (goto-char (point-min))
1540 ;; Remove the file-header.
1541 (when (re-search-forward diff-hunk-header-re nil t)
1542 (delete-region (point-min) (match-beginning 0))))
1543 (t (goto-char (point-max))
1544 (unless (bolp) (insert "\n"))
1546 (setq hunk (buffer-string))
1547 (unless (memq status '(0 1))
1548 (error "Diff returned: %s" status)))))
1549 ;; Whatever happens, put back some equivalent text: either the new
1550 ;; one or the original one in case some error happened.
1553 (delete-file file2))))
1555 ;; provide the package
1556 (provide 'diff-mode)
1558 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1559 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1560 ;; (diff-mode-load-hook): dropped.
1561 ;; (auto-mode-alist): also catch *.diffs.
1562 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1563 ;; for *.rej files (that lack any file name indication).
1565 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1566 ;; added support for "\ No newline at end of file".
1568 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1569 ;; - added basic `compile' support.
1570 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1571 ;; - diff-kill-file now tries to kill the leading garbage as well.
1573 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1574 ;; - don't use CL in the autoloaded code
1575 ;; - accept diffs using -T
1577 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1578 ;; interface to ediff-patch
1580 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1581 ;; (ediff=patch-file): add bindings to call ediff-patch.
1582 ;; (diff-find-file-name): taken out of diff-goto-source.
1583 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1584 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1586 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1587 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1589 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1590 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1593 ;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
1594 ;;; diff-mode.el ends here