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 '(;; 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's diff-mode.
126 ;;("." . diff-goto-source) ;display-buffer
127 ;;("f" . diff-goto-source) ;find-file
128 ("o" . diff-goto-source) ;other-window
129 ;;("w" . diff-goto-source) ;other-frame
130 ;;("N" . diff-narrow)
131 ;;("h" . diff-show-header)
132 ;;("j" . diff-show-difference) ;jump to Nth diff
134 ;; Not useful if you have to metafy them.
136 ;;("\177" . scroll-down)
137 ("A" . diff-ediff-patch)
138 ("r" . diff-restrict-view)
139 ("R" . diff-reverse-direction))
140 "Basic keymap for `diff-mode', bound to various prefix keys."
141 :inherit special-mode-map)
143 (easy-mmode-defmap diff-mode-map
144 `(("\e" . ,(let ((map (make-sparse-keymap)))
145 ;; We want to inherit most bindings from diff-mode-shared-map,
146 ;; but not all since they may hide useful M-<foo> global
147 ;; bindings when editing.
148 (set-keymap-parent map diff-mode-shared-map)
149 (dolist (key '("A" "r" "R" "g" "q" "W" "z"))
150 (define-key map key nil))
152 ;; From compilation-minor-mode.
153 ("\C-c\C-c" . diff-goto-source)
154 ;; By analogy with the global C-x 4 a binding.
155 ("\C-x4A" . diff-add-change-log-entries-other-window)
157 ("\C-c\C-a" . diff-apply-hunk)
158 ("\C-c\C-e" . diff-ediff-patch)
159 ("\C-c\C-n" . diff-restrict-view)
160 ("\C-c\C-s" . diff-split-hunk)
161 ("\C-c\C-t" . diff-test-hunk)
162 ("\C-c\C-r" . diff-reverse-direction)
163 ("\C-c\C-u" . diff-context->unified)
164 ;; `d' because it duplicates the context :-( --Stef
165 ("\C-c\C-d" . diff-unified->context)
166 ("\C-c\C-w" . diff-ignore-whitespace-hunk)
167 ("\C-c\C-b" . diff-refine-hunk) ;No reason for `b' :-(
168 ("\C-c\C-f" . next-error-follow-minor-mode))
169 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
171 (easy-menu-define diff-mode-menu diff-mode-map
172 "Menu for `diff-mode'."
174 ["Jump to Source" diff-goto-source
175 :help "Jump to the corresponding source line"]
176 ["Apply hunk" diff-apply-hunk
177 :help "Apply the current hunk to the source file and go to the next"]
178 ["Test applying hunk" diff-test-hunk
179 :help "See whether it's possible to apply the current hunk"]
180 ["Apply diff with Ediff" diff-ediff-patch
181 :help "Call `ediff-patch-file' on the current buffer"]
182 ["Create Change Log entries" diff-add-change-log-entries-other-window
183 :help "Create ChangeLog entries for the changes in the diff buffer"]
185 ["Reverse direction" diff-reverse-direction
186 :help "Reverse the direction of the diffs"]
187 ["Context -> Unified" diff-context->unified
188 :help "Convert context diffs to unified diffs"]
189 ["Unified -> Context" diff-unified->context
190 :help "Convert unified diffs to context diffs"]
191 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
192 ["Show trailing whitespace" whitespace-mode
193 :style toggle :selected (bound-and-true-p whitespace-mode)
194 :help "Show trailing whitespace in modified lines"]
196 ["Split hunk" diff-split-hunk
197 :active (diff-splittable-p)
198 :help "Split the current (unified diff) hunk at point into two hunks"]
199 ["Ignore whitespace changes" diff-ignore-whitespace-hunk
200 :help "Re-diff the current hunk, ignoring whitespace differences"]
201 ["Highlight fine changes" diff-refine-hunk
202 :help "Highlight changes of hunk at point at a finer granularity"]
203 ["Kill current hunk" diff-hunk-kill
204 :help "Kill current hunk"]
205 ["Kill current file's hunks" diff-file-kill
206 :help "Kill all current file's hunks"]
208 ["Previous Hunk" diff-hunk-prev
209 :help "Go to the previous count'th hunk"]
210 ["Next Hunk" diff-hunk-next
211 :help "Go to the next count'th hunk"]
212 ["Previous File" diff-file-prev
213 :help "Go to the previous count'th file"]
214 ["Next File" diff-file-next
215 :help "Go to the next count'th file"]
218 (defcustom diff-minor-mode-prefix "\C-c="
219 "Prefix key for `diff-minor-mode' commands."
220 :type '(choice (string "\e") (string "C-c=") string)
223 (easy-mmode-defmap diff-minor-mode-map
224 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
225 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
227 (define-minor-mode diff-auto-refine-mode
228 "Toggle automatic diff hunk highlighting (Diff Auto Refine mode).
229 With a prefix argument ARG, enable Diff Auto Refine mode if ARG
230 is positive, and disable it otherwise. If called from Lisp,
231 enable the mode if ARG is omitted or nil.
233 Diff Auto Refine mode is a buffer-local minor mode used with
234 `diff-mode'. When enabled, Emacs automatically highlights
235 changes in detail as the user visits hunks. When transitioning
236 from disabled to enabled, it tries to refine the current hunk, as
238 :group 'diff-mode :init-value t :lighter nil ;; " Auto-Refine"
239 (when diff-auto-refine-mode
240 (condition-case-unless-debug nil (diff-refine-hunk) (error nil))))
243 ;;;; font-lock support
247 '((((class color) (min-colors 88) (background light))
248 :background "grey80")
249 (((class color) (min-colors 88) (background dark))
250 :background "grey45")
251 (((class color) (background light))
252 :foreground "blue1" :weight bold)
253 (((class color) (background dark))
254 :foreground "green" :weight bold)
256 "`diff-mode' face inherited by hunk and index header faces."
258 (define-obsolete-face-alias 'diff-header-face 'diff-header "22.1")
259 (defvar diff-header-face 'diff-header)
261 (defface diff-file-header
262 '((((class color) (min-colors 88) (background light))
263 :background "grey70" :weight bold)
264 (((class color) (min-colors 88) (background dark))
265 :background "grey60" :weight bold)
266 (((class color) (background light))
267 :foreground "green" :weight bold)
268 (((class color) (background dark))
269 :foreground "cyan" :weight bold)
270 (t :weight bold)) ; :height 1.3
271 "`diff-mode' face used to highlight file header lines."
273 (define-obsolete-face-alias 'diff-file-header-face 'diff-file-header "22.1")
274 (defvar diff-file-header-face 'diff-file-header)
277 '((t :inherit diff-file-header))
278 "`diff-mode' face used to highlight index header lines."
280 (define-obsolete-face-alias 'diff-index-face 'diff-index "22.1")
281 (defvar diff-index-face 'diff-index)
283 (defface diff-hunk-header
284 '((t :inherit diff-header))
285 "`diff-mode' face used to highlight hunk header lines."
287 (define-obsolete-face-alias 'diff-hunk-header-face 'diff-hunk-header "22.1")
288 (defvar diff-hunk-header-face 'diff-hunk-header)
290 (defface diff-removed
291 '((t :inherit diff-changed))
292 "`diff-mode' face used to highlight removed lines."
294 (define-obsolete-face-alias 'diff-removed-face 'diff-removed "22.1")
295 (defvar diff-removed-face 'diff-removed)
298 '((t :inherit diff-changed))
299 "`diff-mode' face used to highlight added lines."
301 (define-obsolete-face-alias 'diff-added-face 'diff-added "22.1")
302 (defvar diff-added-face 'diff-added)
304 (defface diff-changed
305 ;; We normally apply a `shadow'-based face on the `diff-context'
306 ;; face, and keep `diff-changed' the default.
307 '((((class color grayscale) (min-colors 88)))
308 ;; If the terminal lacks sufficient colors for shadowing,
309 ;; highlight changed lines explicitly.
310 (((class color) (background light))
311 :foreground "magenta" :weight bold :slant italic)
312 (((class color) (background dark))
313 :foreground "yellow" :weight bold :slant italic))
314 "`diff-mode' face used to highlight changed lines."
316 (define-obsolete-face-alias 'diff-changed-face 'diff-changed "22.1")
317 (defvar diff-changed-face 'diff-changed)
319 (defface diff-indicator-removed
320 '((t :inherit diff-removed))
321 "`diff-mode' face used to highlight indicator of removed lines (-, <)."
324 (defvar diff-indicator-removed-face 'diff-indicator-removed)
326 (defface diff-indicator-added
327 '((t :inherit diff-added))
328 "`diff-mode' face used to highlight indicator of added lines (+, >)."
331 (defvar diff-indicator-added-face 'diff-indicator-added)
333 (defface diff-indicator-changed
334 '((t :inherit diff-changed))
335 "`diff-mode' face used to highlight indicator of changed lines."
338 (defvar diff-indicator-changed-face 'diff-indicator-changed)
340 (defface diff-function
341 '((t :inherit diff-header))
342 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
344 (define-obsolete-face-alias 'diff-function-face 'diff-function "22.1")
345 (defvar diff-function-face 'diff-function)
347 (defface diff-context
348 '((((class color grayscale) (min-colors 88)) :inherit shadow))
349 "`diff-mode' face used to highlight context and other side-information."
351 (define-obsolete-face-alias 'diff-context-face 'diff-context "22.1")
352 (defvar diff-context-face 'diff-context)
354 (defface diff-nonexistent
355 '((t :inherit diff-file-header))
356 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
358 (define-obsolete-face-alias 'diff-nonexistent-face 'diff-nonexistent "22.1")
359 (defvar diff-nonexistent-face 'diff-nonexistent)
361 (defconst diff-yank-handler '(diff-yank-function))
362 (defun diff-yank-function (text)
363 ;; FIXME: the yank-handler is now called separately on each piece of text
364 ;; with a yank-handler property, so the next-single-property-change call
365 ;; below will always return nil :-( --stef
366 (let ((mixed (next-single-property-change 0 'yank-handler text))
368 ;; First insert the text.
370 ;; If the text does not include any diff markers and if we're not
371 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
372 (unless (or mixed (derived-mode-p 'diff-mode))
373 (undo-boundary) ; Just in case the user wanted the prefixes.
374 (let ((re (save-excursion
375 (if (re-search-backward "^[><!][ \t]" start t)
376 (if (eq (char-after) ?!)
377 "^[!+- ][ \t]" "^[<>][ \t]")
380 (while (re-search-backward re start t)
381 (replace-match "" t t)))))))
383 (defconst diff-hunk-header-re-unified
384 "^@@ -\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\+\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? @@")
385 (defconst diff-context-mid-hunk-header-re
386 "--- \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? ----$")
388 (defvar diff-font-lock-keywords
389 `((,(concat "\\(" diff-hunk-header-re-unified "\\)\\(.*\\)$")
390 (1 diff-hunk-header-face) (6 diff-function-face))
391 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
392 (1 diff-hunk-header-face) (2 diff-function-face))
393 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
394 (,diff-context-mid-hunk-header-re . diff-hunk-header-face) ;context
395 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face) ;normal
396 ("^---$" . diff-hunk-header-face) ;normal
397 ;; For file headers, accept files with spaces, but be careful to rule
398 ;; out false-positives when matching hunk headers.
399 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\([^\t\n]+?\\)\\(?:\t.*\\| \\(\\*\\*\\*\\*\\|----\\)\\)?\n"
401 (2 (if (not (match-end 3)) diff-file-header-face) prepend))
402 ("^\\([-<]\\)\\(.*\n\\)"
403 (1 diff-indicator-removed-face) (2 diff-removed-face))
404 ("^\\([+>]\\)\\(.*\n\\)"
405 (1 diff-indicator-added-face) (2 diff-added-face))
406 ("^\\(!\\)\\(.*\n\\)"
407 (1 diff-indicator-changed-face) (2 diff-changed-face))
408 ("^Index: \\(.+\\).*\n"
409 (0 diff-header-face) (1 diff-index-face prepend))
410 ("^Only in .*\n" . diff-nonexistent-face)
412 (1 font-lock-comment-delimiter-face)
413 (2 font-lock-comment-face))
414 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
416 (defconst diff-font-lock-defaults
417 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
419 (defvar diff-imenu-generic-expression
420 ;; Prefer second name as first is most likely to be a backup or
421 ;; version-control name. The [\t\n] at the end of the unidiff pattern
422 ;; catches Debian source diff files (which lack the trailing date).
423 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
424 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
430 (defvar diff-valid-unified-empty-line t
431 "If non-nil, empty lines are valid in unified diffs.
432 Some versions of diff replace all-blank context lines in unified format with
433 empty lines. This makes the format less robust, but is tolerated.
434 See http://lists.gnu.org/archive/html/emacs-devel/2007-11/msg01990.html")
436 (defconst diff-hunk-header-re
437 (concat "^\\(?:" diff-hunk-header-re-unified ".*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$"))
438 (defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* \n]\\).+\n" (substring diff-hunk-header-re 1)))
439 (defvar diff-narrowed-to nil)
441 (defun diff-hunk-style (&optional style)
442 (when (looking-at diff-hunk-header-re)
443 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context)))))
444 (goto-char (match-end 0)))
447 (defun diff-end-of-hunk (&optional style donttrustheader)
449 (when (looking-at diff-hunk-header-re)
450 ;; Especially important for unified (because headers are ambiguous).
451 (setq style (diff-hunk-style style))
452 (goto-char (match-end 0))
453 (when (and (not donttrustheader) (match-end 2))
454 (let* ((nold (string-to-number (or (match-string 2) "1")))
455 (nnew (string-to-number (or (match-string 4) "1")))
458 (re-search-forward (if diff-valid-unified-empty-line
461 (line-beginning-position 2)))
463 ;; The hunk may end with a bunch of "+" lines, so the `end' is
464 ;; then further than computed above.
466 (re-search-forward (if diff-valid-unified-empty-line
469 (line-beginning-position 2))))
470 (setq end (max endold endnew)))))
471 ;; We may have a first evaluation of `end' thanks to the hunk header.
473 (setq end (and (re-search-forward
475 (unified (concat (if diff-valid-unified-empty-line
476 "^[^-+# \\\n]\\|" "^[^-+# \\]\\|")
477 ;; A `unified' header is ambiguous.
478 diff-file-header-re))
479 (context "^[^-+#! \\]")
483 (match-beginning 0)))
484 (when diff-valid-unified-empty-line
485 ;; While empty lines may be valid inside hunks, they are also likely
486 ;; to be unrelated to the hunk.
487 (goto-char (or end (point-max)))
488 (while (eq ?\n (char-before (1- (point))))
490 (setq end (point)))))
491 ;; The return value is used by easy-mmode-define-navigation.
492 (goto-char (or end (point-max)))))
494 (defun diff-beginning-of-hunk (&optional try-harder)
495 "Move back to beginning of hunk.
496 If TRY-HARDER is non-nil, try to cater to the case where we're not in a hunk
497 but in the file header instead, in which case move forward to the first hunk."
499 (unless (looking-at diff-hunk-header-re)
502 (re-search-backward diff-hunk-header-re)
505 (error "Can't find the beginning of the hunk")
506 (diff-beginning-of-file-and-junk)
507 (diff-hunk-next))))))
509 (defun diff-unified-hunk-p ()
512 (diff-beginning-of-hunk)
513 (looking-at "^@@"))))
515 (defun diff-beginning-of-file ()
517 (unless (looking-at diff-file-header-re)
518 (let ((start (point))
520 ;; diff-file-header-re may need to match up to 4 lines, so in case
521 ;; we're inside the header, we need to move up to 3 lines forward.
523 (if (and (setq res (re-search-backward diff-file-header-re nil t))
524 ;; Maybe the 3 lines forward were too much and we matched
525 ;; a file header after our starting point :-(
526 (or (<= (point) start)
527 (setq res (re-search-backward diff-file-header-re nil t))))
530 (error "Can't find the beginning of the file")))))
533 (defun diff-end-of-file ()
534 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
535 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
537 (if (match-beginning 1)
538 (goto-char (match-beginning 1))
539 (beginning-of-line)))
541 ;; Define diff-{hunk,file}-{prev,next}
542 (easy-mmode-define-navigation
543 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view
544 (if diff-auto-refine-mode
545 (condition-case-unless-debug nil (diff-refine-hunk) (error nil))))
547 (easy-mmode-define-navigation
548 diff-file diff-file-header-re "file" diff-end-of-hunk)
550 (defun diff-restrict-view (&optional arg)
551 "Restrict the view to the current hunk.
552 If the prefix ARG is given, restrict the view to the current file instead."
555 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk 'try-harder))
556 (narrow-to-region (point)
557 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
559 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
562 (defun diff-hunk-kill ()
565 (diff-beginning-of-hunk)
566 (let* ((start (point))
567 ;; Search the second match, since we're looking at the first.
568 (nexthunk (when (re-search-forward diff-hunk-header-re nil t 2)
569 (match-beginning 0)))
570 (firsthunk (ignore-errors
572 (diff-beginning-of-file) (diff-hunk-next) (point)))
573 (nextfile (ignore-errors (diff-file-next) (point)))
574 (inhibit-read-only t))
576 (if (and firsthunk (= firsthunk start)
578 (and nextfile (> nexthunk nextfile))))
579 ;; It's the only hunk for this file, so kill the file.
582 (kill-region start (point)))))
584 ;; "index ", "old mode", "new mode", "new file mode" and
585 ;; "deleted file mode" are output by git-diff.
586 (defconst diff-file-junk-re
587 "diff \\|index \\|\\(?:deleted file\\|new\\(?: file\\)?\\|old\\) mode")
589 (defun diff-beginning-of-file-and-junk ()
590 "Go to the beginning of file-related diff-info.
591 This is like `diff-beginning-of-file' except it tries to skip back over leading
592 data such as \"Index: ...\" and such."
593 (let* ((orig (point))
594 ;; Skip forward over what might be "leading junk" so as to get
595 ;; closer to the actual diff.
596 (_ (progn (beginning-of-line)
597 (while (looking-at diff-file-junk-re)
600 (prevfile (condition-case err
601 (save-excursion (diff-beginning-of-file) (point))
603 (err (if (consp prevfile) prevfile))
604 (nextfile (ignore-errors
606 (goto-char start) (diff-file-next) (point))))
607 ;; prevhunk is one of the limits.
608 (prevhunk (save-excursion
610 (if (numberp prevfile) (goto-char prevfile))
611 (diff-hunk-prev) (point))))
612 (previndex (save-excursion
613 (forward-line 1) ;In case we're looking at "Index:".
614 (re-search-backward "^Index: " prevhunk t))))
615 ;; If we're in the junk, we should use nextfile instead of prevfile.
616 (if (and (numberp nextfile)
617 (or (not (numberp prevfile))
618 (and previndex (> previndex prevfile))))
619 (setq prevfile nextfile))
620 (if (and previndex (numberp prevfile) (< previndex prevfile))
621 (setq prevfile previndex))
622 (if (and (numberp prevfile) (<= prevfile start))
625 ;; Now skip backward over the leading junk we may have before the
627 (while (save-excursion
628 (and (zerop (forward-line -1))
629 (looking-at diff-file-junk-re)))
631 ;; File starts *after* the starting point: we really weren't in
632 ;; a file diff but elsewhere.
634 (signal (car err) (cdr err)))))
636 (defun diff-file-kill ()
637 "Kill current file's hunks."
640 (start (progn (diff-beginning-of-file-and-junk) (point)))
641 (inhibit-read-only t))
643 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
644 (if (> orig (point)) (error "Not inside a file diff"))
645 (kill-region start (point))))
647 (defun diff-kill-junk ()
648 "Kill spurious empty diffs."
651 (let ((inhibit-read-only t))
652 (goto-char (point-min))
653 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
654 "\\([^-+!* <>].*\n\\)*?"
655 "\\(\\(Index:\\) \\|"
656 diff-file-header-re "\\)")
658 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
660 (beginning-of-line)))))
662 (defun diff-count-matches (re start end)
666 (while (re-search-forward re end t) (incf n))
669 (defun diff-splittable-p ()
672 (and (looking-at "^[-+ ]")
673 (progn (forward-line -1) (looking-at "^[-+ ]"))
674 (diff-unified-hunk-p))))
676 (defun diff-split-hunk ()
677 "Split the current (unified diff) hunk at point into two hunks."
681 (start (progn (diff-beginning-of-hunk) (point))))
682 (unless (looking-at diff-hunk-header-re-unified)
683 (error "diff-split-hunk only works on unified context diffs"))
685 (let* ((start1 (string-to-number (match-string 1)))
686 (start2 (string-to-number (match-string 3)))
687 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
688 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
689 (inhibit-read-only t))
691 ;; Hopefully the after-change-function will not screw us over.
692 (insert "@@ -" (number-to-string newstart1) ",1 +"
693 (number-to-string newstart2) ",1 @@\n")
694 ;; Fix the original hunk-header.
695 (diff-fixup-modifs start pos))))
699 ;;;; jump to other buffers
702 (defvar diff-remembered-files-alist nil)
703 (defvar diff-remembered-defdir nil)
705 (defun diff-filename-drop-dir (file)
706 (when (string-match "/" file) (substring file (match-end 0))))
708 (defun diff-merge-strings (ancestor from to)
709 "Merge the diff between ANCESTOR and FROM into TO.
710 Returns the merged string if successful or nil otherwise.
711 The strings are assumed not to contain any \"\\n\" (i.e. end of line).
712 If ANCESTOR = FROM, returns TO.
713 If ANCESTOR = TO, returns FROM.
714 The heuristic is simplistic and only really works for cases
715 like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
717 ;; AMB ANB CMD -> CND
718 ;; but that's ambiguous if `foo' or `bar' is empty:
719 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
720 (let ((str (concat ancestor "\n" from "\n" to)))
721 (when (and (string-match (concat
722 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
724 "\\(.*\\(\\2\\).*\\)\\'") str)
725 (equal to (match-string 5 str)))
726 (concat (substring str (match-beginning 5) (match-beginning 6))
728 (substring str (match-end 6) (match-end 5))))))
730 (defun diff-tell-file-name (old name)
731 "Tell Emacs where the find the source file of the current hunk.
732 If the OLD prefix arg is passed, tell the file NAME of the old file."
734 (let* ((old current-prefix-arg)
735 (fs (diff-hunk-file-names current-prefix-arg)))
736 (unless fs (error "No file name to look for"))
737 (list old (read-file-name (format "File for %s: " (car fs))
738 nil (diff-find-file-name old 'noprompt) t))))
739 (let ((fs (diff-hunk-file-names old)))
740 (unless fs (error "No file name to look for"))
741 (push (cons fs name) diff-remembered-files-alist)))
743 (defun diff-hunk-file-names (&optional old)
744 "Give the list of file names textually mentioned for the current hunk."
746 (unless (looking-at diff-file-header-re)
747 (or (ignore-errors (diff-beginning-of-file))
748 (re-search-forward diff-file-header-re nil t)))
749 (let ((limit (save-excursion
751 (progn (diff-hunk-prev) (point))
752 (error (point-min)))))
754 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
755 (list (if old (match-string 1) (match-string 3))
756 (if old (match-string 3) (match-string 1)))
757 (forward-line 1) nil)))
762 (re-search-backward "^Index: \\(.+\\)" limit t)))
763 (list (match-string 1)))
765 (when (re-search-backward
766 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
768 (list (if old (match-string 2) (match-string 4))
769 (if old (match-string 4) (match-string 2)))))))))
771 (defun diff-find-file-name (&optional old noprompt prefix)
772 "Return the file corresponding to the current patch.
773 Non-nil OLD means that we want the old file.
774 Non-nil NOPROMPT means to prefer returning nil than to prompt the user.
775 PREFIX is only used internally: don't use it."
776 (unless (equal diff-remembered-defdir default-directory)
777 ;; Flush diff-remembered-files-alist if the default-directory is changed.
778 (set (make-local-variable 'diff-remembered-defdir) default-directory)
779 (set (make-local-variable 'diff-remembered-files-alist) nil))
781 (unless (looking-at diff-file-header-re)
782 (or (ignore-errors (diff-beginning-of-file))
783 (re-search-forward diff-file-header-re nil t)))
784 (let ((fs (diff-hunk-file-names old)))
785 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
787 ;; use any previously used preference
788 (cdr (assoc fs diff-remembered-files-alist))
789 ;; try to be clever and use previous choices as an inspiration
790 (dolist (rf diff-remembered-files-alist)
791 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
792 (if (and newfile (file-exists-p newfile)) (return newfile))))
793 ;; look for each file in turn. If none found, try again but
794 ;; ignoring the first level of directory, ...
795 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
798 (setq file (do* ((files files (cdr files))
799 (file (car files) (car files)))
800 ;; Use file-regular-p to avoid
801 ;; /dev/null, directories, etc.
802 ((or (null file) (file-regular-p file))
805 ;; <foo>.rej patches implicitly apply to <foo>
806 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
807 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
808 (when (file-exists-p file) file)))
809 ;; If we haven't found the file, maybe it's because we haven't paid
810 ;; attention to the PCL-CVS hint.
812 (boundp 'cvs-pcl-cvs-dirchange-re)
814 (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
815 (diff-find-file-name old noprompt (match-string 1)))
816 ;; if all else fails, ask the user
818 (let ((file (expand-file-name (or (first fs) ""))))
820 (read-file-name (format "Use file %s: " file)
821 (file-name-directory file) file t
822 (file-name-nondirectory file)))
823 (set (make-local-variable 'diff-remembered-files-alist)
824 (cons (cons fs file) diff-remembered-files-alist))
828 (defun diff-ediff-patch ()
829 "Call `ediff-patch-file' on the current buffer."
832 (ediff-patch-file nil (current-buffer))
833 (wrong-number-of-arguments (ediff-patch-file))))
836 ;;;; Conversion functions
839 ;;(defvar diff-inhibit-after-change nil
840 ;; "Non-nil means inhibit `diff-mode's after-change functions.")
842 (defun diff-unified->context (start end)
843 "Convert unified diffs to context diffs.
844 START and END are either taken from the region (if a prefix arg is given) or
845 else cover the whole buffer."
846 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
847 (list (region-beginning) (region-end))
848 (list (point-min) (point-max))))
849 (unless (markerp end) (setq end (copy-marker end t)))
850 (let (;;(diff-inhibit-after-change t)
851 (inhibit-read-only t))
854 (while (and (re-search-forward
855 (concat "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|"
856 diff-hunk-header-re-unified ".*\\)$")
859 (combine-after-change-calls
860 (if (match-beginning 2)
861 ;; we matched a file header
863 ;; use reverse order to make sure the indices are kept valid
864 (replace-match "---" t t nil 3)
865 (replace-match "***" t t nil 2))
866 ;; we matched a hunk header
867 (let ((line1 (match-string 4))
868 (lines1 (or (match-string 5) "1"))
869 (line2 (match-string 6))
870 (lines2 (or (match-string 7) "1"))
871 ;; Variables to use the special undo function.
872 (old-undo buffer-undo-list)
873 (old-end (marker-position end))
874 (start (match-beginning 0))
877 (concat "***************\n*** " line1 ","
878 (number-to-string (+ (string-to-number line1)
879 (string-to-number lines1)
883 (narrow-to-region (line-beginning-position 2)
884 ;; Call diff-end-of-hunk from just before
885 ;; the hunk header so it can use the hunk
887 (progn (diff-end-of-hunk 'unified) (point)))
888 (let ((hunk (buffer-string)))
889 (goto-char (point-min))
890 (if (not (save-excursion (re-search-forward "^-" nil t)))
891 (delete-region (point) (point-max))
892 (goto-char (point-max))
893 (let ((modif nil) last-pt)
894 (while (progn (setq last-pt (point))
895 (= (forward-line -1) 0))
897 (?\s (insert " ") (setq modif nil) (backward-char 1))
898 (?+ (delete-region (point) last-pt) (setq modif t))
900 (progn (forward-char 1)
905 (?\\ (when (save-excursion (forward-line -1)
907 (delete-region (point) last-pt) (setq modif t)))
908 ;; diff-valid-unified-empty-line.
909 (?\n (insert " ") (setq modif nil) (backward-char 2))
910 (t (setq modif nil))))))
911 (goto-char (point-max))
913 (insert "--- " line2 ","
914 (number-to-string (+ (string-to-number line2)
915 (string-to-number lines2)
918 ;;(goto-char (point-min))
920 (if (not (save-excursion (re-search-forward "^+" nil t)))
921 (delete-region (point) (point-max))
922 (let ((modif nil) (delete nil))
923 (if (save-excursion (re-search-forward "^\\+.*\n-" nil t))
924 ;; Normally, lines in a substitution come with
925 ;; first the removals and then the additions, and
926 ;; the context->unified function follows this
927 ;; convention, of course. Yet, other alternatives
928 ;; are valid as well, but they preclude the use of
929 ;; context->unified as an undo command.
930 (setq reversible nil))
933 (?\s (insert " ") (setq modif nil) (backward-char 1))
934 (?- (setq delete t) (setq modif t))
936 (progn (forward-char 1)
941 (?\\ (when (save-excursion (forward-line 1)
943 (setq delete t) (setq modif t)))
944 ;; diff-valid-unified-empty-line.
945 (?\n (insert " ") (setq modif nil) (backward-char 2)
946 (setq reversible nil))
947 (t (setq modif nil)))
948 (let ((last-pt (point)))
951 (delete-region last-pt (point))
952 (setq delete nil)))))))
953 (unless (or (not reversible) (eq buffer-undo-list t))
954 ;; Drop the many undo entries and replace them with
955 ;; a single entry that uses diff-context->unified to do
957 (setq buffer-undo-list
958 (cons (list 'apply (- old-end end) start (point-max)
959 'diff-context->unified start (point-max))
962 (defun diff-context->unified (start end &optional to-context)
963 "Convert context diffs to unified diffs.
964 START and END are either taken from the region
965 \(when it is highlighted) or else cover the whole buffer.
966 With a prefix argument, convert unified format to context format."
967 (interactive (if (and transient-mark-mode mark-active)
968 (list (region-beginning) (region-end) current-prefix-arg)
969 (list (point-min) (point-max) current-prefix-arg)))
971 (diff-unified->context start end)
972 (unless (markerp end) (setq end (copy-marker end t)))
973 (let ( ;;(diff-inhibit-after-change t)
974 (inhibit-read-only t))
977 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
979 (combine-after-change-calls
980 (if (match-beginning 2)
981 ;; we matched a file header
983 ;; use reverse order to make sure the indices are kept valid
984 (replace-match "+++" t t nil 3)
985 (replace-match "---" t t nil 2))
986 ;; we matched a hunk header
987 (let ((line1s (match-string 4))
988 (line1e (match-string 5))
989 (pt1 (match-beginning 0))
990 ;; Variables to use the special undo function.
991 (old-undo buffer-undo-list)
992 (old-end (marker-position end))
995 (unless (re-search-forward
996 diff-context-mid-hunk-header-re nil t)
997 (error "Can't find matching `--- n1,n2 ----' line"))
998 (let ((line2s (match-string 1))
999 (line2e (match-string 2))
1001 (delete-region (progn (beginning-of-line) (point))
1002 (progn (forward-line 1) (point)))
1006 (while (< (point) pt2)
1008 (?! (delete-char 2) (insert "-") (forward-line 1))
1009 (?- (forward-char 1) (delete-char 1) (forward-line 1))
1010 (?\s ;merge with the other half of the chunk
1013 (goto-char pt2) (forward-line 1) (point))))
1014 (case (char-after pt2)
1017 (prog1 (buffer-substring (+ pt2 2) endline2)
1018 (delete-region pt2 endline2))))
1020 (unless (= (- endline2 pt2)
1021 (- (line-beginning-position 2) (point)))
1022 ;; If the two lines we're merging don't have the
1023 ;; same length (can happen with "diff -b"), then
1024 ;; diff-unified->context will not properly undo
1026 (setq reversible nil))
1027 (delete-region pt2 endline2)
1030 (?\\ (forward-line 1))
1031 (t (setq reversible nil)
1032 (delete-char 1) (forward-line 1)))))
1033 (t (setq reversible nil) (forward-line 1))))
1034 (while (looking-at "[+! ] ")
1035 (if (/= (char-after) ?!) (forward-char 1)
1036 (delete-char 1) (insert "+"))
1037 (delete-char 1) (forward-line 1))
1040 (insert "@@ -" line1s ","
1041 (number-to-string (- (string-to-number line1e)
1042 (string-to-number line1s)
1045 (number-to-string (- (string-to-number line2e)
1046 (string-to-number line2s)
1048 (set-marker pt2 nil)
1049 ;; The whole procedure succeeded, let's replace the myriad
1050 ;; of undo elements with just a single special one.
1051 (unless (or (not reversible) (eq buffer-undo-list t))
1052 (setq buffer-undo-list
1053 (cons (list 'apply (- old-end end) pt1 (point)
1054 'diff-unified->context pt1 (point))
1058 (defun diff-reverse-direction (start end)
1059 "Reverse the direction of the diffs.
1060 START and END are either taken from the region (if a prefix arg is given) or
1061 else cover the whole buffer."
1062 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
1063 (list (region-beginning) (region-end))
1064 (list (point-min) (point-max))))
1065 (unless (markerp end) (setq end (copy-marker end t)))
1066 (let (;;(diff-inhibit-after-change t)
1067 (inhibit-read-only t))
1070 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
1072 (combine-after-change-calls
1075 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
1076 ;; a context-diff hunk header
1077 ((match-beginning 6)
1078 (let ((pt-lines1 (match-beginning 6))
1079 (lines1 (match-string 6)))
1080 (replace-match "" nil nil nil 6)
1082 (let ((half1s (point)))
1083 (while (looking-at "[-! \\][ \t]\\|#")
1084 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
1086 (let ((half1 (delete-and-extract-region half1s (point))))
1087 (unless (looking-at diff-context-mid-hunk-header-re)
1089 (error "Can't find matching `--- n1,n2 ----' line"))
1090 (let* ((str1end (or (match-end 2) (match-end 1)))
1091 (str1 (buffer-substring (match-beginning 1) str1end)))
1094 (delete-region (match-beginning 1) str1end)
1096 (let ((half2s (point)))
1097 (while (looking-at "[!+ \\][ \t]\\|#")
1098 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
1100 (let ((half2 (delete-and-extract-region half2s (point))))
1101 (insert (or half1 ""))
1103 (insert (or half2 ""))))
1104 (goto-char pt-lines1)
1106 ;; a unified-diff hunk header
1107 ((match-beginning 7)
1108 (replace-match "@@ -\\8 +\\7 @@" nil)
1110 (let ((c (char-after)) first last)
1111 (while (case (setq c (char-after))
1112 (?- (setq first (or first (point)))
1113 (delete-char 1) (insert "+") t)
1114 (?+ (setq last (or last (point)))
1115 (delete-char 1) (insert "-") t)
1117 (t (when (and first last (< first last))
1118 (insert (delete-and-extract-region first last)))
1119 (setq first nil last nil)
1120 (memq c (if diff-valid-unified-empty-line
1121 '(?\s ?\n) '(?\s)))))
1122 (forward-line 1))))))))))
1124 (defun diff-fixup-modifs (start end)
1125 "Fixup the hunk headers (in case the buffer was modified).
1126 START and END are either taken from the region (if a prefix arg is given) or
1127 else cover the whole buffer."
1128 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
1129 (list (region-beginning) (region-end))
1130 (list (point-min) (point-max))))
1131 (let ((inhibit-read-only t))
1133 (goto-char end) (diff-end-of-hunk nil 'donttrustheader)
1134 (let ((plus 0) (minus 0) (space 0) (bang 0))
1135 (while (and (= (forward-line -1) 0) (<= start (point)))
1136 (if (not (looking-at
1137 (concat diff-hunk-header-re-unified
1138 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
1139 "\\|--- .+\n\\+\\+\\+ ")))
1146 (t (setq space 0 plus 0 minus 0 bang 0)))
1148 ((looking-at diff-hunk-header-re-unified)
1149 (let* ((old1 (match-string 2))
1150 (old2 (match-string 4))
1151 (new1 (number-to-string (+ space minus)))
1152 (new2 (number-to-string (+ space plus))))
1154 (unless (string= new2 old2) (replace-match new2 t t nil 4))
1155 (goto-char (match-end 3))
1158 (unless (string= new1 old1) (replace-match new1 t t nil 2))
1159 (goto-char (match-end 1))
1160 (insert "," new1))))
1161 ((looking-at diff-context-mid-hunk-header-re)
1162 (when (> (+ space bang plus) 0)
1163 (let* ((old1 (match-string 1))
1164 (old2 (match-string 2))
1165 (new (number-to-string
1166 (+ space bang plus -1 (string-to-number old1)))))
1167 (unless (string= new old2) (replace-match new t t nil 2)))))
1168 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
1169 (when (> (+ space bang minus) 0)
1170 (let* ((old (match-string 1))
1172 (concat "%0" (number-to-string (length old)) "d")
1173 (+ space bang minus -1 (string-to-number old)))))
1174 (unless (string= new old) (replace-match new t t nil 2))))))
1175 (setq space 0 plus 0 minus 0 bang 0)))))))
1181 (defun diff-write-contents-hooks ()
1182 "Fixup hunk headers if necessary."
1183 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
1186 ;; It turns out that making changes in the buffer from within an
1187 ;; *-change-function is asking for trouble, whereas making them
1188 ;; from a post-command-hook doesn't pose much problems
1189 (defvar diff-unhandled-changes nil)
1190 (defun diff-after-change-function (beg end _len)
1191 "Remember to fixup the hunk header.
1192 See `after-change-functions' for the meaning of BEG, END and LEN."
1193 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
1194 ;; incorrect, but it turns out that inhibit-read-only is normally not set
1195 ;; inside editing commands, while it tends to be set when the buffer gets
1196 ;; updated by an async process or by a conversion function, both of which
1197 ;; would rather not be uselessly slowed down by this hook.
1198 (when (and (not undo-in-progress) (not inhibit-read-only))
1199 (if diff-unhandled-changes
1200 (setq diff-unhandled-changes
1201 (cons (min beg (car diff-unhandled-changes))
1202 (max end (cdr diff-unhandled-changes))))
1203 (setq diff-unhandled-changes (cons beg end)))))
1205 (defun diff-post-command-hook ()
1206 "Fixup hunk headers if necessary."
1207 (when (consp diff-unhandled-changes)
1210 (goto-char (car diff-unhandled-changes))
1211 ;; Maybe we've cut the end of the hunk before point.
1212 (if (and (bolp) (not (bobp))) (backward-char 1))
1213 ;; We used to fixup modifs on all the changes, but it turns out that
1214 ;; it's safer not to do it on big changes, e.g. when yanking a big
1215 ;; diff, or when the user edits the header, since we might then
1216 ;; screw up perfectly correct values. --Stef
1217 (diff-beginning-of-hunk)
1218 (let* ((style (if (looking-at "\\*\\*\\*") 'context))
1219 (start (line-beginning-position (if (eq style 'context) 3 2)))
1220 (mid (if (eq style 'context)
1222 (re-search-forward diff-context-mid-hunk-header-re
1224 (when (and ;; Don't try to fixup changes in the hunk header.
1225 (> (car diff-unhandled-changes) start)
1226 ;; Don't try to fixup changes in the mid-hunk header either.
1228 (< (cdr diff-unhandled-changes) (match-beginning 0))
1229 (> (car diff-unhandled-changes) (match-end 0)))
1231 (diff-end-of-hunk nil 'donttrustheader)
1232 ;; Don't try to fixup changes past the end of the hunk.
1233 (>= (point) (cdr diff-unhandled-changes))))
1234 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
1235 (setq diff-unhandled-changes nil))))
1237 (defun diff-next-error (arg reset)
1238 ;; Select a window that displays the current buffer so that point
1239 ;; movements are reflected in that window. Otherwise, the user might
1240 ;; never see the hunk corresponding to the source she's jumping to.
1241 (pop-to-buffer (current-buffer))
1242 (if reset (goto-char (point-min)))
1243 (diff-hunk-next arg)
1246 (defvar whitespace-style)
1247 (defvar whitespace-trailing-regexp)
1250 (define-derived-mode diff-mode fundamental-mode "Diff"
1251 "Major mode for viewing/editing context diffs.
1252 Supports unified and context diffs as well as (to a lesser extent)
1255 When the buffer is read-only, the ESC prefix is not necessary.
1256 If you edit the buffer manually, diff-mode will try to update the hunk
1257 headers for you on-the-fly.
1259 You can also switch between context diff and unified diff with \\[diff-context->unified],
1260 or vice versa with \\[diff-unified->context] and you can also reverse the direction of
1261 a diff with \\[diff-reverse-direction].
1265 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1266 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
1267 (set (make-local-variable 'imenu-generic-expression)
1268 diff-imenu-generic-expression)
1269 ;; These are not perfect. They would be better done separately for
1270 ;; context diffs and unidiffs.
1271 ;; (set (make-local-variable 'paragraph-start)
1272 ;; (concat "@@ " ; unidiff hunk
1273 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1274 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1275 ;; ; start (first or second line)
1276 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1277 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1279 (set (make-local-variable 'next-error-function) 'diff-next-error)
1281 (set (make-local-variable 'beginning-of-defun-function)
1282 'diff-beginning-of-file-and-junk)
1283 (set (make-local-variable 'end-of-defun-function)
1286 ;; Set up `whitespace-mode' so that turning it on will show trailing
1287 ;; whitespace problems on the modified lines of the diff.
1288 (set (make-local-variable 'whitespace-style) '(face trailing))
1289 (set (make-local-variable 'whitespace-trailing-regexp)
1290 "^[-\+!<>].*?\\([\t ]+\\)$")
1292 (setq buffer-read-only diff-default-read-only)
1293 ;; setup change hooks
1294 (if (not diff-update-on-the-fly)
1295 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1296 (make-local-variable 'diff-unhandled-changes)
1297 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1298 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
1299 ;; Neat trick from Dave Love to add more bindings in read-only mode:
1300 (let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
1301 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1302 ;; Turn off this little trick in case the buffer is put in view-mode.
1303 (add-hook 'view-mode-hook
1305 (setq minor-mode-overriding-map-alist
1306 (delq ro-bind minor-mode-overriding-map-alist)))
1309 (set (make-local-variable 'add-log-current-defun-function)
1310 'diff-current-defun)
1311 (set (make-local-variable 'add-log-buffer-file-name-function)
1312 (lambda () (diff-find-file-name nil 'noprompt)))
1313 (unless (buffer-file-name)
1314 (hack-dir-local-variables-non-file-buffer)))
1317 (define-minor-mode diff-minor-mode
1318 "Toggle Diff minor mode.
1319 With a prefix argument ARG, enable Diff minor mode if ARG is
1320 positive, and disable it otherwise. If called from Lisp, enable
1321 the mode if ARG is omitted or nil.
1323 \\{diff-minor-mode-map}"
1324 :group 'diff-mode :lighter " Diff"
1325 ;; FIXME: setup font-lock
1326 ;; setup change hooks
1327 (if (not diff-update-on-the-fly)
1328 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
1329 (make-local-variable 'diff-unhandled-changes)
1330 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1331 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
1333 ;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1335 (defun diff-delete-if-empty ()
1336 ;; An empty diff file means there's no more diffs to integrate, so we
1337 ;; can just remove the file altogether. Very handy for .rej files if we
1338 ;; remove hunks as we apply them.
1339 (when (and buffer-file-name
1340 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1341 (delete-file buffer-file-name)))
1343 (defun diff-delete-empty-files ()
1344 "Arrange for empty diff files to be removed."
1345 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1347 (defun diff-make-unified ()
1348 "Turn context diffs into unified diffs if applicable."
1350 (goto-char (point-min))
1351 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
1352 (let ((mod (buffer-modified-p)))
1354 (diff-context->unified (point-min) (point-max))
1355 (restore-buffer-modified-p mod)))))
1358 ;;; Misc operations that have proved useful at some point.
1361 (defun diff-next-complex-hunk ()
1362 "Jump to the next \"complex\" hunk.
1363 \"Complex\" is approximated by \"the hunk changes the number of lines\".
1364 Only works for unified diffs."
1367 (and (re-search-forward diff-hunk-header-re-unified nil t)
1368 (equal (match-string 2) (match-string 4)))))
1370 (defun diff-sanity-check-context-hunk-half (lines)
1371 (let ((count lines))
1374 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1375 (memq (char-after (1+ (point))) '(?\s ?\t)))
1377 ((or (zerop count) (= count lines)) nil)
1378 ((memq (char-after) '(?! ?+ ?-))
1379 (if (not (and (eq (char-after (1+ (point))) ?\n)
1380 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1381 (error "End of hunk ambiguously marked")
1382 (forward-char 1) (insert " ") (forward-line -1) t))
1384 (error "End of hunk ambiguously marked"))
1385 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1387 ((eolp) (insert " ") (forward-line -1) t)
1388 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1391 (defun diff-sanity-check-hunk ()
1392 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1393 ;; OK to override a read-only setting.
1394 (inhibit-read-only t))
1397 ((not (looking-at diff-hunk-header-re))
1398 (error "Not recognizable hunk header"))
1401 ((eq (char-after) ?*)
1402 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\*\\*\\*\\*"))
1403 (error "Unrecognized context diff first hunk header format")
1405 (diff-sanity-check-context-hunk-half
1407 (1+ (- (string-to-number (match-string 2))
1408 (string-to-number (match-string 1))))
1410 (if (not (looking-at diff-context-mid-hunk-header-re))
1411 (error "Unrecognized context diff second hunk header format")
1413 (diff-sanity-check-context-hunk-half
1415 (1+ (- (string-to-number (match-string 2))
1416 (string-to-number (match-string 1))))
1420 ((eq (char-after) ?@)
1421 (if (not (looking-at diff-hunk-header-re-unified))
1422 (error "Unrecognized unified diff hunk header format")
1423 (let ((before (string-to-number (or (match-string 2) "1")))
1424 (after (string-to-number (or (match-string 4) "1"))))
1428 (?\s (decf before) (decf after) t)
1430 (if (and (looking-at diff-file-header-re)
1431 (zerop before) (zerop after))
1432 ;; No need to query: this is a case where two patches
1433 ;; are concatenated and only counting the lines will
1434 ;; give the right result. Let's just add an empty
1435 ;; line so that our code which doesn't count lines
1436 ;; will not get confused.
1437 (progn (save-excursion (insert "\n")) nil)
1442 ((and diff-valid-unified-empty-line
1443 ;; Not just (eolp) so we don't infloop at eob.
1444 (eq (char-after) ?\n)
1445 (> before 0) (> after 0))
1446 (decf before) (decf after) t)
1447 ((and (zerop before) (zerop after)) nil)
1448 ((or (< before 0) (< after 0))
1449 (error (if (or (zerop before) (zerop after))
1450 "End of hunk ambiguously marked"
1451 "Hunk seriously messed up")))
1452 ((not (y-or-n-p (concat "Try to auto-fix " (if (eolp) "whitespace loss" "word-wrap damage") "? ")))
1454 ((eolp) (insert " ") (forward-line -1) t)
1456 (delete-region (- (point) 2) (- (point) 1)) t))))
1464 (defun diff-hunk-text (hunk destp char-offset)
1465 "Return the literal source text from HUNK as (TEXT . OFFSET).
1466 If DESTP is nil, TEXT is the source, otherwise the destination text.
1467 CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1468 char-offset in TEXT."
1471 (goto-char (point-min))
1476 ;; Set the following variables:
1477 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1478 ;; DST-POS buffer pos of the destination part of the hunk or nil
1479 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1480 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1481 (cond ((looking-at "^@@")
1483 (setq num-pfx-chars 1)
1485 (setq src-pos (point) dst-pos (point)))
1486 ((looking-at "^\\*\\*")
1489 (setq src-pos (point))
1490 (re-search-forward diff-context-mid-hunk-header-re nil t)
1492 (setq divider-pos (point))
1494 (setq dst-pos (point)))
1495 ((looking-at "^[0-9]+a[0-9,]+$")
1496 ;; normal diff, insert
1498 (setq dst-pos (point)))
1499 ((looking-at "^[0-9,]+d[0-9]+$")
1500 ;; normal diff, delete
1502 (setq src-pos (point)))
1503 ((looking-at "^[0-9,]+c[0-9,]+$")
1504 ;; normal diff, change
1506 (setq src-pos (point))
1507 (re-search-forward "^---$" nil t)
1509 (setq divider-pos (point))
1511 (setq dst-pos (point)))
1513 (error "Unknown diff hunk type")))
1515 (if (if destp (null dst-pos) (null src-pos))
1516 ;; Implied empty text
1517 (if char-offset '("" . 0) "")
1519 ;; For context diffs, either side can be empty, (if there's only
1520 ;; added or only removed text). We should then use the other side.
1521 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1522 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1524 (when char-offset (goto-char (+ (point-min) char-offset)))
1526 ;; Get rid of anything except the desired text.
1528 ;; Delete unused text region
1529 (let ((keep (if destp dst-pos src-pos)))
1530 (when (and divider-pos (> divider-pos keep))
1531 (delete-region divider-pos (point-max)))
1532 (delete-region (point-min) keep))
1533 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1534 (let ((kill-char (if destp ?- ?+)))
1535 (goto-char (point-min))
1537 (if (eq (char-after) kill-char)
1538 (delete-region (point) (progn (forward-line 1) (point)))
1539 (delete-char num-pfx-chars)
1540 (forward-line 1)))))
1542 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1543 (if char-offset (cons text (- (point) (point-min))) text))))))
1546 (defun diff-find-text (text)
1547 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1548 If TEXT isn't found, nil is returned."
1549 (let* ((orig (point))
1550 (forw (and (search-forward text nil t)
1551 (cons (match-beginning 0) (match-end 0))))
1552 (back (and (goto-char (+ orig (length text)))
1553 (search-backward text nil t)
1554 (cons (match-beginning 0) (match-end 0)))))
1555 ;; Choose the closest match.
1557 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1560 (defun diff-find-approx-text (text)
1561 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1562 Whitespace differences are ignored."
1563 (let* ((orig (point))
1564 (re (concat "^[ \t\n\f]*"
1565 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1567 (forw (and (re-search-forward re nil t)
1568 (cons (match-beginning 0) (match-end 0))))
1569 (back (and (goto-char (+ orig (length text)))
1570 (re-search-backward re nil t)
1571 (cons (match-beginning 0) (match-end 0)))))
1572 ;; Choose the closest match.
1574 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1577 (defsubst diff-xor (a b) (if a (if (not b) a) b))
1579 (defun diff-find-source-location (&optional other-file reverse noprompt)
1580 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1581 BUF is the buffer corresponding to the source file.
1582 LINE-OFFSET is the offset between the expected and actual positions
1583 of the text of the hunk or nil if the text was not found.
1584 POS is a pair (BEG . END) indicating the position of the text in the buffer.
1585 SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1586 SRC is the variant that was found in the buffer.
1587 SWITCHED is non-nil if the patch is already applied.
1588 NOPROMPT, if non-nil, means not to prompt the user."
1590 (let* ((other (diff-xor other-file diff-jump-to-old-file))
1591 (char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1593 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1594 ;; the user may disagree on what constitutes the hunk
1595 ;; (e.g. because an empty line truncates the hunk mid-course),
1596 ;; leading to potentially nasty surprises for the user.
1598 ;; Suppress check when NOPROMPT is non-nil (Bug#3033).
1599 (_ (unless noprompt (diff-sanity-check-hunk)))
1600 (hunk (buffer-substring
1601 (point) (save-excursion (diff-end-of-hunk) (point))))
1602 (old (diff-hunk-text hunk reverse char-offset))
1603 (new (diff-hunk-text hunk (not reverse) char-offset))
1604 ;; Find the location specification.
1605 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
1606 (error "Can't find the hunk header")
1607 (if other (match-string 1)
1608 (if (match-end 3) (match-string 3)
1609 (unless (re-search-forward
1610 diff-context-mid-hunk-header-re nil t)
1611 (error "Can't find the hunk separator"))
1612 (match-string 1)))))
1613 (file (or (diff-find-file-name other noprompt)
1614 (error "Can't find the file")))
1615 (buf (find-file-noselect file)))
1616 ;; Update the user preference if he so wished.
1617 (when (> (prefix-numeric-value other-file) 8)
1618 (setq diff-jump-to-old-file other))
1619 (with-current-buffer buf
1620 (goto-char (point-min)) (forward-line (1- (string-to-number line)))
1621 (let* ((orig-pos (point))
1623 ;; FIXME: Check for case where both OLD and NEW are found.
1624 (pos (or (diff-find-text (car old))
1625 (progn (setq switched t) (diff-find-text (car new)))
1626 (progn (setq switched nil)
1628 (diff-find-approx-text (car old))
1629 (invalid-regexp nil))) ;Regex too big.
1630 (progn (setq switched t)
1632 (diff-find-approx-text (car new))
1633 (invalid-regexp nil))) ;Regex too big.
1634 (progn (setq switched nil) nil))))
1638 (list (count-lines orig-pos (car pos)) pos)
1639 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
1640 (if switched (list new old t) (list old new))))))))
1643 (defun diff-hunk-status-msg (line-offset reversed dry-run)
1644 (let ((msg (if dry-run
1645 (if reversed "already applied" "not yet applied")
1646 (if reversed "undone" "applied"))))
1647 (message (cond ((null line-offset) "Hunk text not found")
1648 ((= line-offset 0) "Hunk %s")
1649 ((= line-offset 1) "Hunk %s at offset %d line")
1650 (t "Hunk %s at offset %d lines"))
1653 (defvar diff-apply-hunk-to-backup-file nil)
1655 (defun diff-apply-hunk (&optional reverse)
1656 "Apply the current hunk to the source file and go to the next.
1657 By default, the new source file is patched, but if the variable
1658 `diff-jump-to-old-file' is non-nil, then the old source file is
1659 patched instead (some commands, such as `diff-goto-source' can change
1660 the value of this variable when given an appropriate prefix argument).
1662 With a prefix argument, REVERSE the hunk."
1664 (destructuring-bind (buf line-offset pos old new &optional switched)
1665 ;; Sometimes we'd like to have the following behavior: if REVERSE go
1666 ;; to the new file, otherwise go to the old. But that means that by
1667 ;; default we use the old file, which is the opposite of the default
1668 ;; for diff-goto-source, and is thus confusing. Also when you don't
1669 ;; know about it it's pretty surprising.
1670 ;; TODO: make it possible to ask explicitly for this behavior.
1672 ;; This is duplicated in diff-test-hunk.
1673 (diff-find-source-location nil reverse)
1676 (error "Can't find the text to patch"))
1677 ((with-current-buffer buf
1678 (and buffer-file-name
1679 (backup-file-name-p buffer-file-name)
1680 (not diff-apply-hunk-to-backup-file)
1681 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1682 (yes-or-no-p (format "Really apply this hunk to %s? "
1683 (file-name-nondirectory
1684 buffer-file-name)))))))
1686 (substitute-command-keys
1687 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1688 (if (not reverse) "\\[universal-argument] ")))))
1690 ;; A reversed patch was detected, perhaps apply it in reverse.
1691 (not (save-window-excursion
1693 (goto-char (+ (car pos) (cdr old)))
1696 "Hunk hasn't been applied yet; apply it now? "
1697 "Hunk has already been applied; undo it? ")))))
1698 (message "(Nothing done)"))
1701 (with-current-buffer buf
1702 (goto-char (car pos))
1703 (delete-region (car pos) (cdr pos))
1705 ;; Display BUF in a window
1706 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
1707 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1708 (when diff-advance-after-apply-hunk
1709 (diff-hunk-next))))))
1712 (defun diff-test-hunk (&optional reverse)
1713 "See whether it's possible to apply the current hunk.
1714 With a prefix argument, try to REVERSE the hunk."
1716 (destructuring-bind (buf line-offset pos src _dst &optional switched)
1717 (diff-find-source-location nil reverse)
1718 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
1719 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
1722 (defalias 'diff-mouse-goto-source 'diff-goto-source)
1724 (defun diff-goto-source (&optional other-file event)
1725 "Jump to the corresponding source line.
1726 `diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
1727 is given) determines whether to jump to the old or the new file.
1728 If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
1729 then `diff-jump-to-old-file' is also set, for the next invocations."
1730 (interactive (list current-prefix-arg last-input-event))
1731 ;; When pointing at a removal line, we probably want to jump to
1732 ;; the old location, and else to the new (i.e. as if reverting).
1733 ;; This is a convenient detail when using smerge-diff.
1734 (if event (posn-set-point (event-end event)))
1735 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1736 (destructuring-bind (buf line-offset pos src _dst &optional switched)
1737 (diff-find-source-location other-file rev)
1739 (goto-char (+ (car pos) (cdr src)))
1740 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
1743 (defun diff-current-defun ()
1744 "Find the name of function at point.
1745 For use in `add-log-current-defun-function'."
1746 ;; Kill change-log-default-name so it gets recomputed each time, since
1747 ;; each hunk may belong to another file which may belong to another
1748 ;; directory and hence have a different ChangeLog file.
1749 (kill-local-variable 'change-log-default-name)
1751 (when (looking-at diff-hunk-header-re)
1753 (re-search-forward "^[^ ]" nil t))
1754 (destructuring-bind (&optional buf _line-offset pos src dst switched)
1755 ;; Use `noprompt' since this is used in which-func-mode and such.
1756 (ignore-errors ;Signals errors in place of prompting.
1757 (diff-find-source-location nil nil 'noprompt))
1760 (or (when (memq (char-after) '(?< ?-))
1761 ;; Cursor is pointing at removed text. This could be a removed
1762 ;; function, in which case, going to the source buffer will
1763 ;; not help since the function is now removed. Instead,
1764 ;; try to figure out the function name just from the
1766 (let ((old (if switched dst src)))
1769 (funcall (buffer-local-value 'major-mode buf))
1770 (goto-char (+ (point-min) (cdr old)))
1771 (add-log-current-defun))))
1772 (with-current-buffer buf
1773 (goto-char (+ (car pos) (cdr src)))
1774 (add-log-current-defun)))))))
1776 (defun diff-ignore-whitespace-hunk ()
1777 "Re-diff the current hunk, ignoring whitespace differences."
1779 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1781 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1782 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1783 (error "Can't find line number"))
1784 (string-to-number (match-string 1))))
1785 (inhibit-read-only t)
1786 (hunk (delete-and-extract-region
1787 (point) (save-excursion (diff-end-of-hunk) (point))))
1788 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1789 (file1 (make-temp-file "diff1"))
1790 (file2 (make-temp-file "diff2"))
1791 (coding-system-for-read buffer-file-coding-system)
1795 (setq old (diff-hunk-text hunk nil char-offset))
1796 (setq new (diff-hunk-text hunk t char-offset))
1797 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1798 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1801 (call-process diff-command nil t nil
1804 (0 nil) ;Nothing to reformat.
1805 (1 (goto-char (point-min))
1806 ;; Remove the file-header.
1807 (when (re-search-forward diff-hunk-header-re nil t)
1808 (delete-region (point-min) (match-beginning 0))))
1809 (t (goto-char (point-max))
1810 (unless (bolp) (insert "\n"))
1812 (setq hunk (buffer-string))
1813 (unless (memq status '(0 1))
1814 (error "Diff returned: %s" status)))))
1815 ;; Whatever happens, put back some equivalent text: either the new
1816 ;; one or the original one in case some error happened.
1819 (delete-file file2))))
1821 ;;; Fine change highlighting.
1823 (defface diff-refine-change
1824 '((((class color) (min-colors 88) (background light))
1825 :background "grey85")
1826 (((class color) (min-colors 88) (background dark))
1827 :background "grey60")
1828 (((class color) (background light))
1829 :background "yellow")
1830 (((class color) (background dark))
1831 :background "green")
1833 "Face used for char-based changes shown by `diff-refine-hunk'."
1836 (defun diff-refine-preproc ()
1837 (while (re-search-forward "^[+>]" nil t)
1838 ;; Remove spurious changes due to the fact that one side of the hunk is
1839 ;; marked with leading + or > and the other with leading - or <.
1840 ;; We used to replace all the prefix chars with " " but this only worked
1841 ;; when we did char-based refinement (or when using
1842 ;; smerge-refine-weight-hack) since otherwise, the `forward' motion done
1843 ;; in chopup do not necessarily do the same as the ones in highlight
1844 ;; since the "_" is not treated the same as " ".
1845 (replace-match (cdr (assq (char-before) '((?+ . "-") (?> . "<"))))))
1848 (declare-function smerge-refine-subst "smerge-mode"
1849 (beg1 end1 beg2 end2 props &optional preproc))
1851 (defun diff-refine-hunk ()
1852 "Highlight changes of hunk at point at a finer granularity."
1854 (require 'smerge-mode)
1856 (diff-beginning-of-hunk 'try-harder)
1857 (let* ((start (point))
1858 (style (diff-hunk-style)) ;Skips the hunk header as well.
1860 (props '((diff-mode . fine) (face diff-refine-change)))
1861 ;; Be careful to go back to `start' so diff-end-of-hunk gets
1862 ;; to read the hunk header's line info.
1863 (end (progn (goto-char start) (diff-end-of-hunk) (point))))
1865 (remove-overlays beg end 'diff-mode 'fine)
1870 (while (re-search-forward "^\\(?:-.*\n\\)+\\(\\)\\(?:\\+.*\n\\)+"
1872 (smerge-refine-subst (match-beginning 0) (match-end 1)
1873 (match-end 1) (match-end 0)
1874 props 'diff-refine-preproc)))
1876 (let* ((middle (save-excursion (re-search-forward "^---")))
1878 (while (re-search-forward "^\\(?:!.*\n\\)+" middle t)
1879 (smerge-refine-subst (match-beginning 0) (match-end 0)
1882 (re-search-forward "^\\(?:!.*\n\\)+" end)
1883 (setq other (match-end 0))
1884 (match-beginning 0))
1886 props 'diff-refine-preproc))))
1888 (let ((beg1 (1+ (point))))
1889 (when (re-search-forward "^---.*\n" end t)
1890 ;; It's a combined add&remove, so there's something to do.
1891 (smerge-refine-subst beg1 (match-beginning 0)
1893 props 'diff-refine-preproc))))))))
1896 (defun diff-add-change-log-entries-other-window ()
1897 "Iterate through the current diff and create ChangeLog entries.
1898 I.e. like `add-change-log-entry-other-window' but applied to all hunks."
1900 ;; XXX: Currently add-change-log-entry-other-window is only called
1901 ;; once per hunk. Some hunks have multiple changes, it would be
1902 ;; good to call it for each change.
1904 (goto-char (point-min))
1906 ;; Call add-change-log-entry-other-window for each hunk in
1910 ;; Move to where the changes are,
1911 ;; `add-change-log-entry-other-window' works better in
1915 ;; If the hunk is a context hunk with an empty first
1916 ;; half, recognize the "--- NNN,MMM ----" line
1917 "\\(-- [0-9]+\\(,[0-9]+\\)? ----\n"
1918 ;; and skip to the next non-context line.
1919 "\\( .*\n\\)*[+]\\)?")
1922 ;; FIXME: this pops up windows of all the buffers.
1923 (add-change-log-entry nil nil t nil t)))
1924 ;; When there's no more hunks, diff-hunk-next signals an error.
1927 ;; provide the package
1928 (provide 'diff-mode)
1930 ;;; Old Change Log from when diff-mode wasn't part of Emacs:
1931 ;; Revision 1.11 1999/10/09 23:38:29 monnier
1932 ;; (diff-mode-load-hook): dropped.
1933 ;; (auto-mode-alist): also catch *.diffs.
1934 ;; (diff-find-file-name, diff-mode): add smarts to find the right file
1935 ;; for *.rej files (that lack any file name indication).
1937 ;; Revision 1.10 1999/09/30 15:32:11 monnier
1938 ;; added support for "\ No newline at end of file".
1940 ;; Revision 1.9 1999/09/15 00:01:13 monnier
1941 ;; - added basic `compile' support.
1942 ;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1943 ;; - diff-kill-file now tries to kill the leading garbage as well.
1945 ;; Revision 1.8 1999/09/13 21:10:09 monnier
1946 ;; - don't use CL in the autoloaded code
1947 ;; - accept diffs using -T
1949 ;; Revision 1.7 1999/09/05 20:53:03 monnier
1950 ;; interface to ediff-patch
1952 ;; Revision 1.6 1999/09/01 20:55:13 monnier
1953 ;; (ediff=patch-file): add bindings to call ediff-patch.
1954 ;; (diff-find-file-name): taken out of diff-goto-source.
1955 ;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1956 ;; diff-fixup-modifs): only use the region if a prefix arg is given.
1958 ;; Revision 1.5 1999/08/31 19:18:52 monnier
1959 ;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1961 ;; Revision 1.4 1999/08/31 13:01:44 monnier
1962 ;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1965 ;;; diff-mode.el ends here