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