(no commit message)
[bpt/emacs.git] / lisp / vc / diff-mode.el
CommitLineData
a9de04fa 1;;; diff-mode.el --- a mode for viewing/editing context diffs -*- lexical-binding: t -*-
610a6418 2
44e97401 3;; Copyright (C) 1998-2012 Free Software Foundation, Inc.
610a6418 4
cc1eecfd 5;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
9766adfb 6;; Keywords: convenience patch diff vc
610a6418
SM
7
8;; This file is part of GNU Emacs.
9
eb3fa2cf 10;; GNU Emacs is free software: you can redistribute it and/or modify
610a6418 11;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
610a6418
SM
14
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.
19
20;; You should have received a copy of the GNU General Public License
eb3fa2cf 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
610a6418
SM
22
23;;; Commentary:
24
cdbb79c1 25;; Provides support for font-lock, outline, navigation
610a6418
SM
26;; commands, editing and various conversions as well as jumping
27;; to the corresponding source file.
28
3ccdb14e 29;; Inspired by Pavel Machek's patch-mode.el (<pavel@@atrey.karlin.mff.cuni.cz>)
44e97401 30;; Some efforts were spent to have it somewhat compatible with XEmacs's
610a6418
SM
31;; diff-mode as well as with compilation-minor-mode
32
610a6418
SM
33;; Bugs:
34
027ac3f8 35;; - Reverse doesn't work with normal diffs.
610a6418
SM
36
37;; Todo:
38
8330c175
SM
39;; - Improve `diff-add-change-log-entries-other-window',
40;; it is very simplistic now.
9201cc28 41;;
22cd1973
SM
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.
44;;
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".
e78cf8e5 49;; Maybe just use `wiggle' (by Neil Brown) to do it for us.
22cd1973 50;;
e78cf8e5
SM
51;; - in diff-apply-hunk, strip context in replace-match to better
52;; preserve markers and spacing.
027ac3f8 53;; - Handle `diff -b' output in context->unified.
610a6418
SM
54
55;;; Code:
f58e0fd5 56(eval-when-compile (require 'cl-lib))
610a6418 57
6e0f362c
JB
58(defvar add-log-buffer-file-name-function)
59
610a6418
SM
60
61(defgroup diff-mode ()
aa753196 62 "Major mode for viewing/editing diffs."
ccce6558 63 :version "21.1"
610a6418
SM
64 :group 'tools
65 :group 'diff)
66
22cd1973 67(defcustom diff-default-read-only nil
769dd0f1
SM
68 "If non-nil, `diff-mode' buffers default to being read-only."
69 :type 'boolean
70 :group 'diff-mode)
71
e8a1ed31 72(defcustom diff-jump-to-old-file nil
44a07c5a 73 "Non-nil means `diff-goto-source' jumps to the old file.
610a6418 74Else, it jumps to the new file."
f5307782
JB
75 :type 'boolean
76 :group 'diff-mode)
610a6418 77
e8a1ed31 78(defcustom diff-update-on-the-fly t
9201cc28 79 "Non-nil means hunk headers are kept up-to-date on-the-fly.
610a6418
SM
80When editing a diff file, the line numbers in the hunk headers
81need to be kept consistent with the actual diff. This can
82either be done on the fly (but this sometimes interacts poorly with the
83undo mechanism) or whenever the file is written (can be slow
84when editing big diffs)."
f5307782
JB
85 :type 'boolean
86 :group 'diff-mode)
610a6418 87
00df919e 88(defcustom diff-advance-after-apply-hunk t
9201cc28 89 "Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
f5307782
JB
90 :type 'boolean
91 :group 'diff-mode)
00df919e 92
22cd1973
SM
93(defcustom diff-mode-hook nil
94 "Run after setting up the `diff-mode' major mode."
95 :type 'hook
f5307782
JB
96 :options '(diff-delete-empty-files diff-make-unified)
97 :group 'diff-mode)
610a6418 98
a2f043d3
CY
99(defvar diff-vc-backend nil
100 "The VC backend that created the current Diff buffer, if any.")
101
610a6418
SM
102(defvar diff-outline-regexp
103 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
104
cd632e57 105;;;;
610a6418 106;;;; keymap, menu, ...
cd632e57 107;;;;
610a6418 108
d87e5627 109(easy-mmode-defmap diff-mode-shared-map
8b71081d 110 '(("n" . diff-hunk-next)
d87e5627
SM
111 ("N" . diff-file-next)
112 ("p" . diff-hunk-prev)
113 ("P" . diff-file-prev)
25edda53
DN
114 ("\t" . diff-hunk-next)
115 ([backtab] . diff-hunk-prev)
d87e5627
SM
116 ("k" . diff-hunk-kill)
117 ("K" . diff-file-kill)
8b71081d 118 ("}" . diff-file-next) ; From compilation-minor-mode.
d87e5627 119 ("{" . diff-file-prev)
610a6418 120 ("\C-m" . diff-goto-source)
a1e2d7f7 121 ([mouse-2] . diff-goto-source)
a904a09a 122 ("W" . widen)
8b71081d 123 ("o" . diff-goto-source) ; other-window
a904a09a
SM
124 ("A" . diff-ediff-patch)
125 ("r" . diff-restrict-view)
8b71081d
CY
126 ("R" . diff-reverse-direction)
127 ("/" . diff-undo)
128 ([remap undo] . diff-undo))
abef340a
SS
129 "Basic keymap for `diff-mode', bound to various prefix keys."
130 :inherit special-mode-map)
610a6418 131
d87e5627 132(easy-mmode-defmap diff-mode-map
a904a09a
SM
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)
c60c3703 138 (dolist (key '("A" "r" "R" "g" "q" "W" "z"))
a904a09a
SM
139 (define-key map key nil))
140 map))
027ac3f8
SM
141 ;; From compilation-minor-mode.
142 ("\C-c\C-c" . diff-goto-source)
8330c175
SM
143 ;; By analogy with the global C-x 4 a binding.
144 ("\C-x4A" . diff-add-change-log-entries-other-window)
027ac3f8 145 ;; Misc operations.
3cec9c57 146 ("\C-c\C-a" . diff-apply-hunk)
28408bfd
RS
147 ("\C-c\C-e" . diff-ediff-patch)
148 ("\C-c\C-n" . diff-restrict-view)
28408bfd 149 ("\C-c\C-s" . diff-split-hunk)
b711788a 150 ("\C-c\C-t" . diff-test-hunk)
2659df68 151 ("\C-c\C-r" . diff-reverse-direction)
28408bfd 152 ("\C-c\C-u" . diff-context->unified)
fe39af99
SM
153 ;; `d' because it duplicates the context :-( --Stef
154 ("\C-c\C-d" . diff-unified->context)
2659df68
SM
155 ("\C-c\C-w" . diff-ignore-whitespace-hunk)
156 ("\C-c\C-b" . diff-refine-hunk) ;No reason for `b' :-(
677c0382 157 ("\C-c\C-f" . next-error-follow-minor-mode))
610a6418
SM
158 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
159
160(easy-menu-define diff-mode-menu diff-mode-map
161 "Menu for `diff-mode'."
162 '("Diff"
fb4dfdd2
DN
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"]
8330c175 171 ["Create Change Log entries" diff-add-change-log-entries-other-window
8a72c7f8 172 :help "Create ChangeLog entries for the changes in the diff buffer"]
8f2d38de 173 "-----"
fb4dfdd2
DN
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"]
610a6418 180 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
9d9e48d9 181 ["Remove trailing whitespace" diff-delete-trailing-whitespace
0780c517 182 :help "Remove trailing whitespace problems introduced by the diff"]
ac7020b3 183 ["Show trailing whitespace" whitespace-mode
4c6de5a5 184 :style toggle :selected (bound-and-true-p whitespace-mode)
ac7020b3 185 :help "Show trailing whitespace in modified lines"]
8f2d38de 186 "-----"
fb4dfdd2
DN
187 ["Split hunk" diff-split-hunk
188 :active (diff-splittable-p)
189 :help "Split the current (unified diff) hunk at point into two hunks"]
190 ["Ignore whitespace changes" diff-ignore-whitespace-hunk
191 :help "Re-diff the current hunk, ignoring whitespace differences"]
192 ["Highlight fine changes" diff-refine-hunk
193 :help "Highlight changes of hunk at point at a finer granularity"]
194 ["Kill current hunk" diff-hunk-kill
195 :help "Kill current hunk"]
196 ["Kill current file's hunks" diff-file-kill
197 :help "Kill all current file's hunks"]
8f2d38de 198 "-----"
fb4dfdd2
DN
199 ["Previous Hunk" diff-hunk-prev
200 :help "Go to the previous count'th hunk"]
201 ["Next Hunk" diff-hunk-next
202 :help "Go to the next count'th hunk"]
203 ["Previous File" diff-file-prev
204 :help "Go to the previous count'th file"]
205 ["Next File" diff-file-next
206 :help "Go to the next count'th file"]
610a6418
SM
207 ))
208
3cec9c57 209(defcustom diff-minor-mode-prefix "\C-c="
0b82e382 210 "Prefix key for `diff-minor-mode' commands."
f5307782
JB
211 :type '(choice (string "\e") (string "C-c=") string)
212 :group 'diff-mode)
0b82e382 213
d87e5627
SM
214(easy-mmode-defmap diff-minor-mode-map
215 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
0b82e382
SM
216 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
217
7381be9d 218(define-minor-mode diff-auto-refine-mode
ac6c8639
CY
219 "Toggle automatic diff hunk highlighting (Diff Auto Refine mode).
220With a prefix argument ARG, enable Diff Auto Refine mode if ARG
221is positive, and disable it otherwise. If called from Lisp,
222enable the mode if ARG is omitted or nil.
223
224Diff Auto Refine mode is a buffer-local minor mode used with
225`diff-mode'. When enabled, Emacs automatically highlights
226changes in detail as the user visits hunks. When transitioning
227from disabled to enabled, it tries to refine the current hunk, as
228well."
4542adfb 229 :group 'diff-mode :init-value t :lighter nil ;; " Auto-Refine"
7381be9d 230 (when diff-auto-refine-mode
1be3ca5a 231 (condition-case-unless-debug nil (diff-refine-hunk) (error nil))))
610a6418 232
cd632e57 233;;;;
610a6418 234;;;; font-lock support
cd632e57 235;;;;
610a6418 236
221711eb 237(defface diff-header
55f2eb7e 238 '((((class color) (min-colors 88) (background light))
9f4e4f5b 239 :background "grey80")
55f2eb7e 240 (((class color) (min-colors 88) (background dark))
4f815065 241 :background "grey45")
bc1b21bb 242 (((class color))
4f815065 243 :foreground "blue1" :weight bold)
4f815065 244 (t :weight bold))
d676819e
LK
245 "`diff-mode' face inherited by hunk and index header faces."
246 :group 'diff-mode)
c4f6e489 247(define-obsolete-face-alias 'diff-header-face 'diff-header "22.1")
221711eb 248(defvar diff-header-face 'diff-header)
c0aa75f7 249
221711eb 250(defface diff-file-header
55f2eb7e 251 '((((class color) (min-colors 88) (background light))
4f815065 252 :background "grey70" :weight bold)
55f2eb7e 253 (((class color) (min-colors 88) (background dark))
4f815065 254 :background "grey60" :weight bold)
bc1b21bb 255 (((class color))
4f815065
SM
256 :foreground "cyan" :weight bold)
257 (t :weight bold)) ; :height 1.3
d676819e
LK
258 "`diff-mode' face used to highlight file header lines."
259 :group 'diff-mode)
c4f6e489 260(define-obsolete-face-alias 'diff-file-header-face 'diff-file-header "22.1")
221711eb 261(defvar diff-file-header-face 'diff-file-header)
610a6418 262
221711eb
MB
263(defface diff-index
264 '((t :inherit diff-file-header))
d676819e
LK
265 "`diff-mode' face used to highlight index header lines."
266 :group 'diff-mode)
c4f6e489 267(define-obsolete-face-alias 'diff-index-face 'diff-index "22.1")
221711eb 268(defvar diff-index-face 'diff-index)
610a6418 269
221711eb
MB
270(defface diff-hunk-header
271 '((t :inherit diff-header))
d676819e
LK
272 "`diff-mode' face used to highlight hunk header lines."
273 :group 'diff-mode)
c4f6e489 274(define-obsolete-face-alias 'diff-hunk-header-face 'diff-hunk-header "22.1")
221711eb 275(defvar diff-hunk-header-face 'diff-hunk-header)
610a6418 276
221711eb 277(defface diff-removed
bc1b21bb
JL
278 '((default
279 :inherit diff-changed)
280 (((class color) (min-colors 88) (background light))
281 :background "#ffdddd")
282 (((class color) (min-colors 88) (background dark))
283 :background "#553333")
284 (((class color))
285 :foreground "red"))
d676819e
LK
286 "`diff-mode' face used to highlight removed lines."
287 :group 'diff-mode)
c4f6e489 288(define-obsolete-face-alias 'diff-removed-face 'diff-removed "22.1")
221711eb 289(defvar diff-removed-face 'diff-removed)
610a6418 290
221711eb 291(defface diff-added
bc1b21bb
JL
292 '((default
293 :inherit diff-changed)
294 (((class color) (min-colors 88) (background light))
295 :background "#ddffdd")
296 (((class color) (min-colors 88) (background dark))
297 :background "#335533")
298 (((class color))
299 :foreground "green"))
d676819e
LK
300 "`diff-mode' face used to highlight added lines."
301 :group 'diff-mode)
c4f6e489 302(define-obsolete-face-alias 'diff-added-face 'diff-added "22.1")
221711eb 303(defvar diff-added-face 'diff-added)
610a6418 304
221711eb 305(defface diff-changed
d5b44c93
CY
306 ;; We normally apply a `shadow'-based face on the `diff-context'
307 ;; face, and keep `diff-changed' the default.
308 '((((class color grayscale) (min-colors 88)))
309 ;; If the terminal lacks sufficient colors for shadowing,
310 ;; highlight changed lines explicitly.
bc1b21bb
JL
311 (((class color))
312 :foreground "yellow"))
d676819e
LK
313 "`diff-mode' face used to highlight changed lines."
314 :group 'diff-mode)
c4f6e489 315(define-obsolete-face-alias 'diff-changed-face 'diff-changed "22.1")
221711eb 316(defvar diff-changed-face 'diff-changed)
610a6418 317
f3abba99
JL
318(defface diff-indicator-removed
319 '((t :inherit diff-removed))
320 "`diff-mode' face used to highlight indicator of removed lines (-, <)."
321 :group 'diff-mode
322 :version "22.1")
323(defvar diff-indicator-removed-face 'diff-indicator-removed)
324
325(defface diff-indicator-added
326 '((t :inherit diff-added))
327 "`diff-mode' face used to highlight indicator of added lines (+, >)."
328 :group 'diff-mode
329 :version "22.1")
330(defvar diff-indicator-added-face 'diff-indicator-added)
331
332(defface diff-indicator-changed
333 '((t :inherit diff-changed))
334 "`diff-mode' face used to highlight indicator of changed lines."
335 :group 'diff-mode
336 :version "22.1")
337(defvar diff-indicator-changed-face 'diff-indicator-changed)
338
221711eb 339(defface diff-function
ea5d66db 340 '((t :inherit diff-header))
d676819e
LK
341 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
342 :group 'diff-mode)
c4f6e489 343(define-obsolete-face-alias 'diff-function-face 'diff-function "22.1")
221711eb 344(defvar diff-function-face 'diff-function)
34460354 345
221711eb 346(defface diff-context
f3abba99 347 '((((class color grayscale) (min-colors 88)) :inherit shadow))
d676819e
LK
348 "`diff-mode' face used to highlight context and other side-information."
349 :group 'diff-mode)
c4f6e489 350(define-obsolete-face-alias 'diff-context-face 'diff-context "22.1")
221711eb 351(defvar diff-context-face 'diff-context)
c0aa75f7 352
221711eb
MB
353(defface diff-nonexistent
354 '((t :inherit diff-file-header))
d676819e
LK
355 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
356 :group 'diff-mode)
c4f6e489 357(define-obsolete-face-alias 'diff-nonexistent-face 'diff-nonexistent "22.1")
221711eb 358(defvar diff-nonexistent-face 'diff-nonexistent)
469fc0a2 359
22cd1973
SM
360(defconst diff-yank-handler '(diff-yank-function))
361(defun diff-yank-function (text)
1ec7bd14
SM
362 ;; FIXME: the yank-handler is now called separately on each piece of text
363 ;; with a yank-handler property, so the next-single-property-change call
364 ;; below will always return nil :-( --stef
22cd1973
SM
365 (let ((mixed (next-single-property-change 0 'yank-handler text))
366 (start (point)))
367 ;; First insert the text.
368 (insert text)
369 ;; If the text does not include any diff markers and if we're not
370 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
371 (unless (or mixed (derived-mode-p 'diff-mode))
372 (undo-boundary) ; Just in case the user wanted the prefixes.
373 (let ((re (save-excursion
374 (if (re-search-backward "^[><!][ \t]" start t)
375 (if (eq (char-after) ?!)
376 "^[!+- ][ \t]" "^[<>][ \t]")
377 "^[ <>!+-]"))))
378 (save-excursion
379 (while (re-search-backward re start t)
380 (replace-match "" t t)))))))
cfc80227 381
f52d2f9c 382(defconst diff-hunk-header-re-unified
43392d12 383 "^@@ -\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\+\\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? @@")
bf6970a5
SM
384(defconst diff-context-mid-hunk-header-re
385 "--- \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? ----$")
22cd1973 386
bc1b21bb
JL
387(defvar diff-use-changed-face (and (face-differs-from-default-p diff-changed-face)
388 (not (face-equal diff-changed-face diff-added-face))
389 (not (face-equal diff-changed-face diff-removed-face)))
390 "If non-nil, use the face `diff-changed' for changed lines in context diffs.
391Otherwise, use the face `diff-removed' for removed lines,
392and the face `diff-added' for added lines.")
393
610a6418 394(defvar diff-font-lock-keywords
f52d2f9c
SM
395 `((,(concat "\\(" diff-hunk-header-re-unified "\\)\\(.*\\)$")
396 (1 diff-hunk-header-face) (6 diff-function-face))
f3abba99
JL
397 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
398 (1 diff-hunk-header-face) (2 diff-function-face))
370d860c 399 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
bf6970a5 400 (,diff-context-mid-hunk-header-re . diff-hunk-header-face) ;context
f3abba99
JL
401 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face) ;normal
402 ("^---$" . diff-hunk-header-face) ;normal
4c969f97
SM
403 ;; For file headers, accept files with spaces, but be careful to rule
404 ;; out false-positives when matching hunk headers.
405 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\([^\t\n]+?\\)\\(?:\t.*\\| \\(\\*\\*\\*\\*\\|----\\)\\)?\n"
406 (0 diff-header-face)
407 (2 (if (not (match-end 3)) diff-file-header-face) prepend))
f3abba99
JL
408 ("^\\([-<]\\)\\(.*\n\\)"
409 (1 diff-indicator-removed-face) (2 diff-removed-face))
410 ("^\\([+>]\\)\\(.*\n\\)"
411 (1 diff-indicator-added-face) (2 diff-added-face))
412 ("^\\(!\\)\\(.*\n\\)"
bc1b21bb
JL
413 (1 (if diff-use-changed-face
414 diff-indicator-changed-face
415 ;; Otherwise, search for `diff-context-mid-hunk-header-re' and
416 ;; if the line of context diff is above, use `diff-removed-face';
417 ;; if below, use `diff-added-face'.
418 (save-match-data
419 (let ((limit (save-excursion (diff-beginning-of-hunk))))
420 (if (save-excursion (re-search-backward diff-context-mid-hunk-header-re limit t))
421 diff-indicator-added-face
422 diff-indicator-removed-face)))))
423 (2 (if diff-use-changed-face
424 diff-changed-face
425 ;; Otherwise, use the same method as above.
426 (save-match-data
427 (let ((limit (save-excursion (diff-beginning-of-hunk))))
428 (if (save-excursion (re-search-backward diff-context-mid-hunk-header-re limit t))
429 diff-added-face
430 diff-removed-face))))))
431 ("^\\(?:Index\\|revno\\): \\(.+\\).*\n"
f3abba99 432 (0 diff-header-face) (1 diff-index-face prepend))
7dfb000f 433 ("^Only in .*\n" . diff-nonexistent-face)
f3abba99 434 ("^\\(#\\)\\(.*\\)"
050dcc13
JL
435 (1 font-lock-comment-delimiter-face)
436 (2 font-lock-comment-face))
f3abba99 437 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
610a6418
SM
438
439(defconst diff-font-lock-defaults
0e104800 440 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
610a6418 441
ccce6558
DL
442(defvar diff-imenu-generic-expression
443 ;; Prefer second name as first is most likely to be a backup or
824693e7
DL
444 ;; version-control name. The [\t\n] at the end of the unidiff pattern
445 ;; catches Debian source diff files (which lack the trailing date).
446 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
ccce6558
DL
447 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
448
cd632e57 449;;;;
610a6418 450;;;; Movement
cd632e57 451;;;;
610a6418 452
f52d2f9c
SM
453(defvar diff-valid-unified-empty-line t
454 "If non-nil, empty lines are valid in unified diffs.
455Some versions of diff replace all-blank context lines in unified format with
456empty lines. This makes the format less robust, but is tolerated.
457See http://lists.gnu.org/archive/html/emacs-devel/2007-11/msg01990.html")
458
459(defconst diff-hunk-header-re
460 (concat "^\\(?:" diff-hunk-header-re-unified ".*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$"))
365bdf63 461(defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* \n]\\).+\n" (substring diff-hunk-header-re 1)))
610a6418
SM
462(defvar diff-narrowed-to nil)
463
be36f934 464(defun diff-hunk-style (&optional style)
996884b2 465 (when (looking-at diff-hunk-header-re)
be36f934 466 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context)))))
996884b2 467 (goto-char (match-end 0)))
be36f934
SM
468 style)
469
f52d2f9c 470(defun diff-end-of-hunk (&optional style donttrustheader)
cb3e7ae0 471 "Advance to the end of the current hunk, and return its position."
f52d2f9c
SM
472 (let (end)
473 (when (looking-at diff-hunk-header-re)
474 ;; Especially important for unified (because headers are ambiguous).
475 (setq style (diff-hunk-style style))
476 (goto-char (match-end 0))
477 (when (and (not donttrustheader) (match-end 2))
43392d12
SM
478 (let* ((nold (string-to-number (or (match-string 2) "1")))
479 (nnew (string-to-number (or (match-string 4) "1")))
aec1ef07 480 (endold
a2be0357
SM
481 (save-excursion
482 (re-search-forward (if diff-valid-unified-empty-line
483 "^[- \n]" "^[- ]")
aec1ef07 484 nil t nold)
a2be0357
SM
485 (line-beginning-position
486 ;; Skip potential "\ No newline at end of file".
487 (if (looking-at ".*\n\\\\") 3 2))))
aec1ef07
SM
488 (endnew
489 ;; The hunk may end with a bunch of "+" lines, so the `end' is
490 ;; then further than computed above.
491 (save-excursion
492 (re-search-forward (if diff-valid-unified-empty-line
493 "^[+ \n]" "^[+ ]")
494 nil t nnew)
a2be0357
SM
495 (line-beginning-position
496 ;; Skip potential "\ No newline at end of file".
497 (if (looking-at ".*\n\\\\") 3 2)))))
aec1ef07 498 (setq end (max endold endnew)))))
f52d2f9c
SM
499 ;; We may have a first evaluation of `end' thanks to the hunk header.
500 (unless end
501 (setq end (and (re-search-forward
f58e0fd5
SM
502 (pcase style
503 (`unified
504 (concat (if diff-valid-unified-empty-line
505 "^[^-+# \\\n]\\|" "^[^-+# \\]\\|")
506 ;; A `unified' header is ambiguous.
507 diff-file-header-re))
508 (`context "^[^-+#! \\]")
509 (`normal "^[^<>#\\]")
510 (_ "^[^-+#!<> \\]"))
f52d2f9c
SM
511 nil t)
512 (match-beginning 0)))
513 (when diff-valid-unified-empty-line
514 ;; While empty lines may be valid inside hunks, they are also likely
515 ;; to be unrelated to the hunk.
516 (goto-char (or end (point-max)))
517 (while (eq ?\n (char-before (1- (point))))
518 (forward-char -1)
519 (setq end (point)))))
0e104800
SM
520 ;; The return value is used by easy-mmode-define-navigation.
521 (goto-char (or end (point-max)))))
610a6418 522
fd691799 523(defun diff-beginning-of-hunk (&optional try-harder)
cb3e7ae0
CY
524 "Move back to the previous hunk beginning, and return its position.
525If point is in a file header rather than a hunk, advance to the
526next hunk if TRY-HARDER is non-nil; otherwise signal an error."
610a6418 527 (beginning-of-line)
cb3e7ae0
CY
528 (if (looking-at diff-hunk-header-re)
529 (point)
610a6418
SM
530 (forward-line 1)
531 (condition-case ()
532 (re-search-backward diff-hunk-header-re)
fd691799 533 (error
cb3e7ae0
CY
534 (unless try-harder
535 (error "Can't find the beginning of the hunk"))
536 (diff-beginning-of-file-and-junk)
537 (diff-hunk-next)
538 (point)))))
610a6418 539
f151b310
SM
540(defun diff-unified-hunk-p ()
541 (save-excursion
542 (ignore-errors
543 (diff-beginning-of-hunk)
544 (looking-at "^@@"))))
545
610a6418
SM
546(defun diff-beginning-of-file ()
547 (beginning-of-line)
548 (unless (looking-at diff-file-header-re)
4c969f97
SM
549 (let ((start (point))
550 res)
551 ;; diff-file-header-re may need to match up to 4 lines, so in case
552 ;; we're inside the header, we need to move up to 3 lines forward.
553 (forward-line 3)
554 (if (and (setq res (re-search-backward diff-file-header-re nil t))
555 ;; Maybe the 3 lines forward were too much and we matched
556 ;; a file header after our starting point :-(
557 (or (<= (point) start)
558 (setq res (re-search-backward diff-file-header-re nil t))))
559 res
560 (goto-char start)
561 (error "Can't find the beginning of the file")))))
9201cc28 562
610a6418
SM
563
564(defun diff-end-of-file ()
0e104800 565 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
22cd1973
SM
566 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
567 nil 'move)
568 (if (match-beginning 1)
569 (goto-char (match-beginning 1))
570 (beginning-of-line)))
610a6418 571
6be9197e
SM
572(defvar diff--auto-refine-data nil)
573
d87e5627
SM
574;; Define diff-{hunk,file}-{prev,next}
575(easy-mmode-define-navigation
2659df68 576 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view
6be9197e 577 (when diff-auto-refine-mode
1000d895
SM
578 (unless (prog1 diff--auto-refine-data
579 (setq diff--auto-refine-data
580 (cons (current-buffer) (point-marker))))
581 (run-at-time 0.0 nil
582 (lambda ()
583 (when diff--auto-refine-data
584 (let ((buffer (car diff--auto-refine-data))
585 (point (cdr diff--auto-refine-data)))
586 (setq diff--auto-refine-data nil)
587 (with-local-quit
588 (when (buffer-live-p buffer)
589 (with-current-buffer buffer
590 (save-excursion
591 (goto-char point)
592 (diff-refine-hunk))))))))))))
2659df68 593
d87e5627 594(easy-mmode-define-navigation
d65c9521 595 diff-file diff-file-header-re "file" diff-end-of-file)
610a6418 596
cb3e7ae0
CY
597(defun diff-bounds-of-hunk ()
598 "Return the bounds of the diff hunk at point.
599The return value is a list (BEG END), which are the hunk's start
600and end positions. Signal an error if no hunk is found. If
601point is in a file header, return the bounds of the next hunk."
602 (save-excursion
603 (let ((pos (point))
604 (beg (diff-beginning-of-hunk t))
605 (end (diff-end-of-hunk)))
606 (cond ((>= end pos)
607 (list beg end))
608 ;; If this hunk ends above POS, consider the next hunk.
609 ((re-search-forward diff-hunk-header-re nil t)
610 (list (match-beginning 0) (diff-end-of-hunk)))
611 (t (error "No hunk found"))))))
612
613(defun diff-bounds-of-file ()
614 "Return the bounds of the file segment at point.
615The return value is a list (BEG END), which are the segment's
616start and end positions."
617 (save-excursion
618 (let ((pos (point))
619 (beg (progn (diff-beginning-of-file-and-junk)
620 (point))))
621 (diff-end-of-file)
622 ;; bzr puts a newline after the last hunk.
623 (while (looking-at "^\n")
624 (forward-char 1))
625 (if (> pos (point))
626 (error "Not inside a file diff"))
627 (list beg (point)))))
628
610a6418
SM
629(defun diff-restrict-view (&optional arg)
630 "Restrict the view to the current hunk.
631If the prefix ARG is given, restrict the view to the current file instead."
632 (interactive "P")
cb3e7ae0
CY
633 (apply 'narrow-to-region
634 (if arg (diff-bounds-of-file) (diff-bounds-of-hunk)))
635 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk)))
610a6418 636
d87e5627 637(defun diff-hunk-kill ()
cb3e7ae0 638 "Kill the hunk at point."
610a6418 639 (interactive)
cb3e7ae0
CY
640 (let* ((hunk-bounds (diff-bounds-of-hunk))
641 (file-bounds (ignore-errors (diff-bounds-of-file)))
642 ;; If the current hunk is the only one for its file, kill the
643 ;; file header too.
644 (bounds (if (and file-bounds
645 (progn (goto-char (car file-bounds))
646 (= (progn (diff-hunk-next) (point))
647 (car hunk-bounds)))
648 (progn (goto-char (cadr hunk-bounds))
649 ;; bzr puts a newline after the last hunk.
650 (while (looking-at "^\n")
651 (forward-char 1))
652 (= (point) (cadr file-bounds))))
653 file-bounds
654 hunk-bounds))
dd24cb37 655 (inhibit-read-only t))
cb3e7ae0
CY
656 (apply 'kill-region bounds)
657 (goto-char (car bounds))))
610a6418 658
8d73b84e
DN
659;; "index ", "old mode", "new mode", "new file mode" and
660;; "deleted file mode" are output by git-diff.
9201cc28 661(defconst diff-file-junk-re
cb3e7ae0 662 "diff \\|index \\|\\(?:deleted file\\|new\\(?: file\\)?\\|old\\) mode\\|=== modified file")
f52d2f9c 663
fd691799
SM
664(defun diff-beginning-of-file-and-junk ()
665 "Go to the beginning of file-related diff-info.
666This is like `diff-beginning-of-file' except it tries to skip back over leading
667data such as \"Index: ...\" and such."
f52d2f9c
SM
668 (let* ((orig (point))
669 ;; Skip forward over what might be "leading junk" so as to get
670 ;; closer to the actual diff.
671 (_ (progn (beginning-of-line)
672 (while (looking-at diff-file-junk-re)
673 (forward-line 1))))
674 (start (point))
4c969f97
SM
675 (prevfile (condition-case err
676 (save-excursion (diff-beginning-of-file) (point))
677 (error err)))
678 (err (if (consp prevfile) prevfile))
679 (nextfile (ignore-errors
680 (save-excursion
681 (goto-char start) (diff-file-next) (point))))
682 ;; prevhunk is one of the limits.
683 (prevhunk (save-excursion
684 (ignore-errors
685 (if (numberp prevfile) (goto-char prevfile))
686 (diff-hunk-prev) (point))))
687 (previndex (save-excursion
f52d2f9c 688 (forward-line 1) ;In case we're looking at "Index:".
4c969f97
SM
689 (re-search-backward "^Index: " prevhunk t))))
690 ;; If we're in the junk, we should use nextfile instead of prevfile.
691 (if (and (numberp nextfile)
692 (or (not (numberp prevfile))
693 (and previndex (> previndex prevfile))))
694 (setq prevfile nextfile))
695 (if (and previndex (numberp prevfile) (< previndex prevfile))
696 (setq prevfile previndex))
697 (if (and (numberp prevfile) (<= prevfile start))
f52d2f9c
SM
698 (progn
699 (goto-char prevfile)
700 ;; Now skip backward over the leading junk we may have before the
701 ;; diff itself.
702 (while (save-excursion
703 (and (zerop (forward-line -1))
704 (looking-at diff-file-junk-re)))
705 (forward-line -1)))
4c969f97
SM
706 ;; File starts *after* the starting point: we really weren't in
707 ;; a file diff but elsewhere.
f52d2f9c 708 (goto-char orig)
4c969f97 709 (signal (car err) (cdr err)))))
9201cc28 710
d87e5627 711(defun diff-file-kill ()
610a6418
SM
712 "Kill current file's hunks."
713 (interactive)
cb3e7ae0
CY
714 (let ((inhibit-read-only t))
715 (apply 'kill-region (diff-bounds-of-file))))
610a6418 716
fef8c55b
SM
717(defun diff-kill-junk ()
718 "Kill spurious empty diffs."
719 (interactive)
720 (save-excursion
721 (let ((inhibit-read-only t))
722 (goto-char (point-min))
723 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
724 "\\([^-+!* <>].*\n\\)*?"
725 "\\(\\(Index:\\) \\|"
726 diff-file-header-re "\\)")
727 nil t)
728 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
729 (match-beginning 3))
730 (beginning-of-line)))))
731
cd632e57
SM
732(defun diff-count-matches (re start end)
733 (save-excursion
734 (let ((n 0))
735 (goto-char start)
f58e0fd5 736 (while (re-search-forward re end t) (cl-incf n))
cd632e57
SM
737 n)))
738
f151b310
SM
739(defun diff-splittable-p ()
740 (save-excursion
741 (beginning-of-line)
742 (and (looking-at "^[-+ ]")
743 (progn (forward-line -1) (looking-at "^[-+ ]"))
744 (diff-unified-hunk-p))))
745
cd632e57
SM
746(defun diff-split-hunk ()
747 "Split the current (unified diff) hunk at point into two hunks."
748 (interactive)
749 (beginning-of-line)
750 (let ((pos (point))
cb3e7ae0 751 (start (diff-beginning-of-hunk)))
f52d2f9c 752 (unless (looking-at diff-hunk-header-re-unified)
cd632e57
SM
753 (error "diff-split-hunk only works on unified context diffs"))
754 (forward-line 1)
755 (let* ((start1 (string-to-number (match-string 1)))
f52d2f9c 756 (start2 (string-to-number (match-string 3)))
cd632e57 757 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
dd24cb37
CY
758 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
759 (inhibit-read-only t))
cd632e57
SM
760 (goto-char pos)
761 ;; Hopefully the after-change-function will not screw us over.
762 (insert "@@ -" (number-to-string newstart1) ",1 +"
763 (number-to-string newstart2) ",1 @@\n")
764 ;; Fix the original hunk-header.
765 (diff-fixup-modifs start pos))))
71296446 766
cd632e57 767
610a6418
SM
768;;;;
769;;;; jump to other buffers
770;;;;
771
0b82e382 772(defvar diff-remembered-files-alist nil)
adf4cc7e 773(defvar diff-remembered-defdir nil)
0b82e382 774
610a6418
SM
775(defun diff-filename-drop-dir (file)
776 (when (string-match "/" file) (substring file (match-end 0))))
777
0b82e382
SM
778(defun diff-merge-strings (ancestor from to)
779 "Merge the diff between ANCESTOR and FROM into TO.
780Returns the merged string if successful or nil otherwise.
d87e5627 781The strings are assumed not to contain any \"\\n\" (i.e. end of line).
0b82e382
SM
782If ANCESTOR = FROM, returns TO.
783If ANCESTOR = TO, returns FROM.
784The heuristic is simplistic and only really works for cases
785like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
786 ;; Ideally, we want:
787 ;; AMB ANB CMD -> CND
788 ;; but that's ambiguous if `foo' or `bar' is empty:
789 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
d87e5627 790 (let ((str (concat ancestor "\n" from "\n" to)))
0b82e382 791 (when (and (string-match (concat
d87e5627
SM
792 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
793 "\\1\\(.*\\)\\3\n"
0b82e382
SM
794 "\\(.*\\(\\2\\).*\\)\\'") str)
795 (equal to (match-string 5 str)))
796 (concat (substring str (match-beginning 5) (match-beginning 6))
797 (match-string 4 str)
798 (substring str (match-end 6) (match-end 5))))))
799
22cd1973
SM
800(defun diff-tell-file-name (old name)
801 "Tell Emacs where the find the source file of the current hunk.
802If the OLD prefix arg is passed, tell the file NAME of the old file."
803 (interactive
804 (let* ((old current-prefix-arg)
805 (fs (diff-hunk-file-names current-prefix-arg)))
806 (unless fs (error "No file name to look for"))
807 (list old (read-file-name (format "File for %s: " (car fs))
68035b97 808 nil (diff-find-file-name old 'noprompt) t))))
22cd1973
SM
809 (let ((fs (diff-hunk-file-names old)))
810 (unless fs (error "No file name to look for"))
811 (push (cons fs name) diff-remembered-files-alist)))
cfc80227 812
22cd1973
SM
813(defun diff-hunk-file-names (&optional old)
814 "Give the list of file names textually mentioned for the current hunk."
610a6418
SM
815 (save-excursion
816 (unless (looking-at diff-file-header-re)
817 (or (ignore-errors (diff-beginning-of-file))
818 (re-search-forward diff-file-header-re nil t)))
22cd1973 819 (let ((limit (save-excursion
610a6418 820 (condition-case ()
d87e5627 821 (progn (diff-hunk-prev) (point))
610a6418 822 (error (point-min)))))
22cd1973
SM
823 (header-files
824 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
825 (list (if old (match-string 1) (match-string 3))
826 (if old (match-string 3) (match-string 1)))
827 (forward-line 1) nil)))
828 (delq nil
829 (append
830 (when (and (not old)
831 (save-excursion
832 (re-search-backward "^Index: \\(.+\\)" limit t)))
833 (list (match-string 1)))
834 header-files
835 (when (re-search-backward
836 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
837 nil t)
838 (list (if old (match-string 2) (match-string 4))
839 (if old (match-string 4) (match-string 2)))))))))
840
68035b97 841(defun diff-find-file-name (&optional old noprompt prefix)
22cd1973 842 "Return the file corresponding to the current patch.
e78cf8e5 843Non-nil OLD means that we want the old file.
68035b97 844Non-nil NOPROMPT means to prefer returning nil than to prompt the user.
e78cf8e5 845PREFIX is only used internally: don't use it."
adf4cc7e
SM
846 (unless (equal diff-remembered-defdir default-directory)
847 ;; Flush diff-remembered-files-alist if the default-directory is changed.
848 (set (make-local-variable 'diff-remembered-defdir) default-directory)
849 (set (make-local-variable 'diff-remembered-files-alist) nil))
22cd1973
SM
850 (save-excursion
851 (unless (looking-at diff-file-header-re)
852 (or (ignore-errors (diff-beginning-of-file))
853 (re-search-forward diff-file-header-re nil t)))
854 (let ((fs (diff-hunk-file-names old)))
e78cf8e5 855 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
610a6418 856 (or
0b82e382
SM
857 ;; use any previously used preference
858 (cdr (assoc fs diff-remembered-files-alist))
859 ;; try to be clever and use previous choices as an inspiration
f58e0fd5 860 (cl-dolist (rf diff-remembered-files-alist)
0b82e382 861 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
f58e0fd5 862 (if (and newfile (file-exists-p newfile)) (cl-return newfile))))
0b82e382
SM
863 ;; look for each file in turn. If none found, try again but
864 ;; ignoring the first level of directory, ...
f58e0fd5
SM
865 (cl-do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
866 (file nil nil))
0b82e382 867 ((or (null files)
f58e0fd5
SM
868 (setq file (cl-do* ((files files (cdr files))
869 (file (car files) (car files)))
f9274544
GM
870 ;; Use file-regular-p to avoid
871 ;; /dev/null, directories, etc.
872 ((or (null file) (file-regular-p file))
0b82e382
SM
873 file))))
874 file))
875 ;; <foo>.rej patches implicitly apply to <foo>
610a6418
SM
876 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
877 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
878 (when (file-exists-p file) file)))
e78cf8e5
SM
879 ;; If we haven't found the file, maybe it's because we haven't paid
880 ;; attention to the PCL-CVS hint.
881 (and (not prefix)
882 (boundp 'cvs-pcl-cvs-dirchange-re)
883 (save-excursion
884 (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
68035b97 885 (diff-find-file-name old noprompt (match-string 1)))
0b82e382 886 ;; if all else fails, ask the user
68035b97 887 (unless noprompt
f58e0fd5 888 (let ((file (expand-file-name (or (car fs) ""))))
f3af92b7
MA
889 (setq file
890 (read-file-name (format "Use file %s: " file)
891 (file-name-directory file) file t
892 (file-name-nondirectory file)))
68035b97
SM
893 (set (make-local-variable 'diff-remembered-files-alist)
894 (cons (cons fs file) diff-remembered-files-alist))
895 file))))))
610a6418 896
1b1b5dae 897
610a6418
SM
898(defun diff-ediff-patch ()
899 "Call `ediff-patch-file' on the current buffer."
900 (interactive)
ba83908c 901 (condition-case nil
0e104800 902 (ediff-patch-file nil (current-buffer))
610a6418
SM
903 (wrong-number-of-arguments (ediff-patch-file))))
904
71296446 905;;;;
610a6418 906;;;; Conversion functions
71296446 907;;;;
610a6418
SM
908
909;;(defvar diff-inhibit-after-change nil
910;; "Non-nil means inhibit `diff-mode's after-change functions.")
911
912(defun diff-unified->context (start end)
913 "Convert unified diffs to context diffs.
914START and END are either taken from the region (if a prefix arg is given) or
dfbd373d 915else cover the whole buffer."
d7f9cc85 916 (interactive (if (or current-prefix-arg (use-region-p))
a70b0ff8 917 (list (region-beginning) (region-end))
610a6418 918 (list (point-min) (point-max))))
e78cf8e5 919 (unless (markerp end) (setq end (copy-marker end t)))
610a6418
SM
920 (let (;;(diff-inhibit-after-change t)
921 (inhibit-read-only t))
922 (save-excursion
923 (goto-char start)
f52d2f9c
SM
924 (while (and (re-search-forward
925 (concat "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|"
926 diff-hunk-header-re-unified ".*\\)$")
927 nil t)
610a6418
SM
928 (< (point) end))
929 (combine-after-change-calls
930 (if (match-beginning 2)
0e104800 931 ;; we matched a file header
610a6418
SM
932 (progn
933 ;; use reverse order to make sure the indices are kept valid
934 (replace-match "---" t t nil 3)
935 (replace-match "***" t t nil 2))
936 ;; we matched a hunk header
937 (let ((line1 (match-string 4))
43392d12 938 (lines1 (or (match-string 5) "1"))
610a6418 939 (line2 (match-string 6))
341dd15a 940 (lines2 (or (match-string 7) "1"))
3dc04e83
SM
941 ;; Variables to use the special undo function.
942 (old-undo buffer-undo-list)
943 (old-end (marker-position end))
944 (start (match-beginning 0))
945 (reversible t))
610a6418
SM
946 (replace-match
947 (concat "***************\n*** " line1 ","
948 (number-to-string (+ (string-to-number line1)
949 (string-to-number lines1)
341dd15a
MB
950 -1))
951 " ****"))
610a6418 952 (save-restriction
f52d2f9c
SM
953 (narrow-to-region (line-beginning-position 2)
954 ;; Call diff-end-of-hunk from just before
955 ;; the hunk header so it can use the hunk
956 ;; header info.
610a6418
SM
957 (progn (diff-end-of-hunk 'unified) (point)))
958 (let ((hunk (buffer-string)))
959 (goto-char (point-min))
960 (if (not (save-excursion (re-search-forward "^-" nil t)))
961 (delete-region (point) (point-max))
962 (goto-char (point-max))
963 (let ((modif nil) last-pt)
964 (while (progn (setq last-pt (point))
965 (= (forward-line -1) 0))
f58e0fd5 966 (pcase (char-after)
bdad2e31 967 (?\s (insert " ") (setq modif nil) (backward-char 1))
610a6418
SM
968 (?+ (delete-region (point) last-pt) (setq modif t))
969 (?- (if (not modif)
f58e0fd5
SM
970 (progn (forward-char 1)
971 (insert " "))
972 (delete-char 1)
973 (insert "! "))
974 (backward-char 2))
610a6418 975 (?\\ (when (save-excursion (forward-line -1)
f58e0fd5
SM
976 (= (char-after) ?+))
977 (delete-region (point) last-pt)
978 (setq modif t)))
f52d2f9c 979 ;; diff-valid-unified-empty-line.
f58e0fd5
SM
980 (?\n (insert " ") (setq modif nil)
981 (backward-char 2))
982 (_ (setq modif nil))))))
610a6418
SM
983 (goto-char (point-max))
984 (save-excursion
985 (insert "--- " line2 ","
986 (number-to-string (+ (string-to-number line2)
987 (string-to-number lines2)
341dd15a 988 -1))
f52d2f9c 989 " ----\n" hunk))
610a6418
SM
990 ;;(goto-char (point-min))
991 (forward-line 1)
992 (if (not (save-excursion (re-search-forward "^+" nil t)))
993 (delete-region (point) (point-max))
994 (let ((modif nil) (delete nil))
f58e0fd5
SM
995 (if (save-excursion (re-search-forward "^\\+.*\n-"
996 nil t))
3dc04e83
SM
997 ;; Normally, lines in a substitution come with
998 ;; first the removals and then the additions, and
999 ;; the context->unified function follows this
1000 ;; convention, of course. Yet, other alternatives
1001 ;; are valid as well, but they preclude the use of
1002 ;; context->unified as an undo command.
1003 (setq reversible nil))
610a6418 1004 (while (not (eobp))
f58e0fd5 1005 (pcase (char-after)
bdad2e31 1006 (?\s (insert " ") (setq modif nil) (backward-char 1))
610a6418
SM
1007 (?- (setq delete t) (setq modif t))
1008 (?+ (if (not modif)
f58e0fd5
SM
1009 (progn (forward-char 1)
1010 (insert " "))
1011 (delete-char 1)
1012 (insert "! "))
1013 (backward-char 2))
610a6418 1014 (?\\ (when (save-excursion (forward-line 1)
f58e0fd5
SM
1015 (not (eobp)))
1016 (setq delete t) (setq modif t)))
f52d2f9c
SM
1017 ;; diff-valid-unified-empty-line.
1018 (?\n (insert " ") (setq modif nil) (backward-char 2)
1019 (setq reversible nil))
f58e0fd5 1020 (_ (setq modif nil)))
610a6418
SM
1021 (let ((last-pt (point)))
1022 (forward-line 1)
1023 (when delete
1024 (delete-region last-pt (point))
3dc04e83
SM
1025 (setq delete nil)))))))
1026 (unless (or (not reversible) (eq buffer-undo-list t))
1027 ;; Drop the many undo entries and replace them with
1028 ;; a single entry that uses diff-context->unified to do
1029 ;; the work.
1030 (setq buffer-undo-list
1031 (cons (list 'apply (- old-end end) start (point-max)
1032 'diff-context->unified start (point-max))
1033 old-undo)))))))))))
610a6418 1034
28408bfd 1035(defun diff-context->unified (start end &optional to-context)
610a6418 1036 "Convert context diffs to unified diffs.
28408bfd
RS
1037START and END are either taken from the region
1038\(when it is highlighted) or else cover the whole buffer.
1039With a prefix argument, convert unified format to context format."
d7f9cc85 1040 (interactive (if (use-region-p)
a70b0ff8 1041 (list (region-beginning) (region-end) current-prefix-arg)
28408bfd
RS
1042 (list (point-min) (point-max) current-prefix-arg)))
1043 (if to-context
1044 (diff-unified->context start end)
e78cf8e5 1045 (unless (markerp end) (setq end (copy-marker end t)))
28408bfd 1046 (let ( ;;(diff-inhibit-after-change t)
be36f934 1047 (inhibit-read-only t))
28408bfd 1048 (save-excursion
be36f934 1049 (goto-char start)
d7f9cc85 1050 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)\\(?: \\(.*\\)\\|$\\)" nil t)
be36f934
SM
1051 (< (point) end))
1052 (combine-after-change-calls
1053 (if (match-beginning 2)
1054 ;; we matched a file header
1055 (progn
1056 ;; use reverse order to make sure the indices are kept valid
1057 (replace-match "+++" t t nil 3)
1058 (replace-match "---" t t nil 2))
1059 ;; we matched a hunk header
1060 (let ((line1s (match-string 4))
1061 (line1e (match-string 5))
1062 (pt1 (match-beginning 0))
1063 ;; Variables to use the special undo function.
1064 (old-undo buffer-undo-list)
1065 (old-end (marker-position end))
d7f9cc85
SM
1066 ;; We currently throw away the comment that can follow
1067 ;; the hunk header. FIXME: Preserve it instead!
1068 (reversible (not (match-end 6))))
be36f934
SM
1069 (replace-match "")
1070 (unless (re-search-forward
bf6970a5 1071 diff-context-mid-hunk-header-re nil t)
be36f934
SM
1072 (error "Can't find matching `--- n1,n2 ----' line"))
1073 (let ((line2s (match-string 1))
1074 (line2e (match-string 2))
1075 (pt2 (progn
1076 (delete-region (progn (beginning-of-line) (point))
1077 (progn (forward-line 1) (point)))
1078 (point-marker))))
1079 (goto-char pt1)
1080 (forward-line 1)
1081 (while (< (point) pt2)
f58e0fd5 1082 (pcase (char-after)
be36f934
SM
1083 (?! (delete-char 2) (insert "-") (forward-line 1))
1084 (?- (forward-char 1) (delete-char 1) (forward-line 1))
f58e0fd5 1085 (?\s ;merge with the other half of the chunk
be36f934
SM
1086 (let* ((endline2
1087 (save-excursion
1088 (goto-char pt2) (forward-line 1) (point))))
f58e0fd5
SM
1089 (pcase (char-after pt2)
1090 ((or ?! ?+)
be36f934 1091 (insert "+"
f58e0fd5
SM
1092 (prog1
1093 (buffer-substring (+ pt2 2) endline2)
be36f934
SM
1094 (delete-region pt2 endline2))))
1095 (?\s
1096 (unless (= (- endline2 pt2)
1097 (- (line-beginning-position 2) (point)))
1098 ;; If the two lines we're merging don't have the
1099 ;; same length (can happen with "diff -b"), then
1100 ;; diff-unified->context will not properly undo
1101 ;; this operation.
1102 (setq reversible nil))
1103 (delete-region pt2 endline2)
1104 (delete-char 1)
1105 (forward-line 1))
1106 (?\\ (forward-line 1))
f58e0fd5 1107 (_ (setq reversible nil)
be36f934 1108 (delete-char 1) (forward-line 1)))))
f58e0fd5 1109 (_ (setq reversible nil) (forward-line 1))))
be36f934
SM
1110 (while (looking-at "[+! ] ")
1111 (if (/= (char-after) ?!) (forward-char 1)
1112 (delete-char 1) (insert "+"))
1113 (delete-char 1) (forward-line 1))
1114 (save-excursion
1115 (goto-char pt1)
1116 (insert "@@ -" line1s ","
1117 (number-to-string (- (string-to-number line1e)
1118 (string-to-number line1s)
1119 -1))
1120 " +" line2s ","
1121 (number-to-string (- (string-to-number line2e)
1122 (string-to-number line2s)
1123 -1)) " @@"))
1124 (set-marker pt2 nil)
1125 ;; The whole procedure succeeded, let's replace the myriad
1126 ;; of undo elements with just a single special one.
1127 (unless (or (not reversible) (eq buffer-undo-list t))
1128 (setq buffer-undo-list
1129 (cons (list 'apply (- old-end end) pt1 (point)
1130 'diff-unified->context pt1 (point))
1131 old-undo)))
1132 )))))))))
610a6418
SM
1133
1134(defun diff-reverse-direction (start end)
1135 "Reverse the direction of the diffs.
1136START and END are either taken from the region (if a prefix arg is given) or
dfbd373d 1137else cover the whole buffer."
d7f9cc85 1138 (interactive (if (or current-prefix-arg (use-region-p))
a70b0ff8 1139 (list (region-beginning) (region-end))
610a6418 1140 (list (point-min) (point-max))))
e78cf8e5 1141 (unless (markerp end) (setq end (copy-marker end t)))
610a6418
SM
1142 (let (;;(diff-inhibit-after-change t)
1143 (inhibit-read-only t))
1144 (save-excursion
1145 (goto-char start)
c0078a04 1146 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
610a6418
SM
1147 (< (point) end))
1148 (combine-after-change-calls
1149 (cond
1150 ;; a file header
1151 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
1152 ;; a context-diff hunk header
1153 ((match-beginning 6)
1154 (let ((pt-lines1 (match-beginning 6))
1155 (lines1 (match-string 6)))
1156 (replace-match "" nil nil nil 6)
1157 (forward-line 1)
1158 (let ((half1s (point)))
0e104800 1159 (while (looking-at "[-! \\][ \t]\\|#")
610a6418
SM
1160 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
1161 (forward-line 1))
fef8c55b 1162 (let ((half1 (delete-and-extract-region half1s (point))))
bf6970a5 1163 (unless (looking-at diff-context-mid-hunk-header-re)
610a6418
SM
1164 (insert half1)
1165 (error "Can't find matching `--- n1,n2 ----' line"))
bf6970a5
SM
1166 (let* ((str1end (or (match-end 2) (match-end 1)))
1167 (str1 (buffer-substring (match-beginning 1) str1end)))
1168 (goto-char str1end)
1169 (insert lines1)
1170 (delete-region (match-beginning 1) str1end)
610a6418
SM
1171 (forward-line 1)
1172 (let ((half2s (point)))
0e104800 1173 (while (looking-at "[!+ \\][ \t]\\|#")
610a6418
SM
1174 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
1175 (forward-line 1))
fef8c55b 1176 (let ((half2 (delete-and-extract-region half2s (point))))
0e104800 1177 (insert (or half1 ""))
610a6418 1178 (goto-char half1s)
0e104800 1179 (insert (or half2 ""))))
610a6418
SM
1180 (goto-char pt-lines1)
1181 (insert str1))))))
1182 ;; a unified-diff hunk header
1183 ((match-beginning 7)
1184 (replace-match "@@ -\\8 +\\7 @@" nil)
1185 (forward-line 1)
1186 (let ((c (char-after)) first last)
f58e0fd5 1187 (while (pcase (setq c (char-after))
610a6418 1188 (?- (setq first (or first (point)))
f58e0fd5 1189 (delete-char 1) (insert "+") t)
610a6418 1190 (?+ (setq last (or last (point)))
f58e0fd5
SM
1191 (delete-char 1) (insert "-") t)
1192 ((or ?\\ ?#) t)
1193 (_ (when (and first last (< first last))
cb4e8176 1194 (insert (delete-and-extract-region first last)))
610a6418 1195 (setq first nil last nil)
f52d2f9c
SM
1196 (memq c (if diff-valid-unified-empty-line
1197 '(?\s ?\n) '(?\s)))))
610a6418
SM
1198 (forward-line 1))))))))))
1199
1200(defun diff-fixup-modifs (start end)
1201 "Fixup the hunk headers (in case the buffer was modified).
1202START and END are either taken from the region (if a prefix arg is given) or
dfbd373d 1203else cover the whole buffer."
d7f9cc85 1204 (interactive (if (or current-prefix-arg (use-region-p))
a70b0ff8 1205 (list (region-beginning) (region-end))
610a6418
SM
1206 (list (point-min) (point-max))))
1207 (let ((inhibit-read-only t))
1208 (save-excursion
f52d2f9c 1209 (goto-char end) (diff-end-of-hunk nil 'donttrustheader)
610a6418 1210 (let ((plus 0) (minus 0) (space 0) (bang 0))
1aba75c2 1211 (while (and (= (forward-line -1) 0) (<= start (point)))
165fd2df
AS
1212 (if (not (looking-at
1213 (concat diff-hunk-header-re-unified
1214 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
1215 "\\|--- .+\n\\+\\+\\+ ")))
f58e0fd5
SM
1216 (pcase (char-after)
1217 (?\s (cl-incf space))
1218 (?+ (cl-incf plus))
1219 (?- (cl-incf minus))
1220 (?! (cl-incf bang))
1221 ((or ?\\ ?#) nil)
1222 (_ (setq space 0 plus 0 minus 0 bang 0)))
165fd2df
AS
1223 (cond
1224 ((looking-at diff-hunk-header-re-unified)
1225 (let* ((old1 (match-string 2))
1226 (old2 (match-string 4))
1227 (new1 (number-to-string (+ space minus)))
1228 (new2 (number-to-string (+ space plus))))
1229 (if old2
1230 (unless (string= new2 old2) (replace-match new2 t t nil 4))
1231 (goto-char (match-end 3))
1232 (insert "," new2))
1233 (if old1
1234 (unless (string= new1 old1) (replace-match new1 t t nil 2))
1235 (goto-char (match-end 1))
1236 (insert "," new1))))
1237 ((looking-at diff-context-mid-hunk-header-re)
1238 (when (> (+ space bang plus) 0)
1239 (let* ((old1 (match-string 1))
1240 (old2 (match-string 2))
1241 (new (number-to-string
1242 (+ space bang plus -1 (string-to-number old1)))))
1243 (unless (string= new old2) (replace-match new t t nil 2)))))
1244 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
1245 (when (> (+ space bang minus) 0)
1246 (let* ((old (match-string 1))
1247 (new (format
1248 (concat "%0" (number-to-string (length old)) "d")
1249 (+ space bang minus -1 (string-to-number old)))))
1250 (unless (string= new old) (replace-match new t t nil 2))))))
1251 (setq space 0 plus 0 minus 0 bang 0)))))))
610a6418 1252
71296446 1253;;;;
610a6418 1254;;;; Hooks
71296446 1255;;;;
610a6418
SM
1256
1257(defun diff-write-contents-hooks ()
1258 "Fixup hunk headers if necessary."
1259 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
1260 nil)
1261
610a6418
SM
1262;; It turns out that making changes in the buffer from within an
1263;; *-change-function is asking for trouble, whereas making them
1264;; from a post-command-hook doesn't pose much problems
1265(defvar diff-unhandled-changes nil)
ba83908c 1266(defun diff-after-change-function (beg end _len)
610a6418
SM
1267 "Remember to fixup the hunk header.
1268See `after-change-functions' for the meaning of BEG, END and LEN."
c0078a04
SM
1269 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
1270 ;; incorrect, but it turns out that inhibit-read-only is normally not set
1271 ;; inside editing commands, while it tends to be set when the buffer gets
1272 ;; updated by an async process or by a conversion function, both of which
1273 ;; would rather not be uselessly slowed down by this hook.
610a6418
SM
1274 (when (and (not undo-in-progress) (not inhibit-read-only))
1275 (if diff-unhandled-changes
1276 (setq diff-unhandled-changes
1277 (cons (min beg (car diff-unhandled-changes))
cb4e8176 1278 (max end (cdr diff-unhandled-changes))))
610a6418
SM
1279 (setq diff-unhandled-changes (cons beg end)))))
1280
1281(defun diff-post-command-hook ()
1282 "Fixup hunk headers if necessary."
1283 (when (consp diff-unhandled-changes)
1284 (ignore-errors
1285 (save-excursion
fef8c55b 1286 (goto-char (car diff-unhandled-changes))
cb4e8176
SM
1287 ;; Maybe we've cut the end of the hunk before point.
1288 (if (and (bolp) (not (bobp))) (backward-char 1))
bf6970a5
SM
1289 ;; We used to fixup modifs on all the changes, but it turns out that
1290 ;; it's safer not to do it on big changes, e.g. when yanking a big
1291 ;; diff, or when the user edits the header, since we might then
1292 ;; screw up perfectly correct values. --Stef
1eabc5e6 1293 (diff-beginning-of-hunk)
bf6970a5
SM
1294 (let* ((style (if (looking-at "\\*\\*\\*") 'context))
1295 (start (line-beginning-position (if (eq style 'context) 3 2)))
1296 (mid (if (eq style 'context)
1297 (save-excursion
1298 (re-search-forward diff-context-mid-hunk-header-re
1299 nil t)))))
1300 (when (and ;; Don't try to fixup changes in the hunk header.
1301 (> (car diff-unhandled-changes) start)
1302 ;; Don't try to fixup changes in the mid-hunk header either.
1303 (or (not mid)
1304 (< (cdr diff-unhandled-changes) (match-beginning 0))
1305 (> (car diff-unhandled-changes) (match-end 0)))
1306 (save-excursion
f52d2f9c 1307 (diff-end-of-hunk nil 'donttrustheader)
bf6970a5
SM
1308 ;; Don't try to fixup changes past the end of the hunk.
1309 (>= (point) (cdr diff-unhandled-changes))))
1eabc5e6 1310 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
bf6970a5 1311 (setq diff-unhandled-changes nil))))
610a6418 1312
6fc049f6
SM
1313(defun diff-next-error (arg reset)
1314 ;; Select a window that displays the current buffer so that point
1315 ;; movements are reflected in that window. Otherwise, the user might
1316 ;; never see the hunk corresponding to the source she's jumping to.
1317 (pop-to-buffer (current-buffer))
1318 (if reset (goto-char (point-min)))
1319 (diff-hunk-next arg)
1320 (diff-goto-source))
610a6418 1321
e8f642e7
GM
1322(defvar whitespace-style)
1323(defvar whitespace-trailing-regexp)
1324
610a6418 1325;;;###autoload
d87e5627 1326(define-derived-mode diff-mode fundamental-mode "Diff"
0b82e382 1327 "Major mode for viewing/editing context diffs.
769dd0f1 1328Supports unified and context diffs as well as (to a lesser extent)
6035b97e 1329normal diffs.
b64d66b5 1330
df52e0e7 1331When the buffer is read-only, the ESC prefix is not necessary.
3b696504 1332If you edit the buffer manually, diff-mode will try to update the hunk
df52e0e7
SM
1333headers for you on-the-fly.
1334
1335You can also switch between context diff and unified diff with \\[diff-context->unified],
72147c53 1336or vice versa with \\[diff-unified->context] and you can also reverse the direction of
e78cf8e5 1337a diff with \\[diff-reverse-direction].
b64d66b5 1338
b64d66b5
RS
1339 \\{diff-mode-map}"
1340
610a6418 1341 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
6be9197e
SM
1342 (add-hook 'font-lock-mode-hook
1343 (lambda () (remove-overlays nil nil 'diff-mode 'fine))
1344 nil 'local)
610a6418 1345 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
ccce6558
DL
1346 (set (make-local-variable 'imenu-generic-expression)
1347 diff-imenu-generic-expression)
19e713d8
DL
1348 ;; These are not perfect. They would be better done separately for
1349 ;; context diffs and unidiffs.
1350 ;; (set (make-local-variable 'paragraph-start)
1351 ;; (concat "@@ " ; unidiff hunk
1352 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1353 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1354 ;; ; start (first or second line)
1355 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1356 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1357 ;; compile support
6fc049f6 1358 (set (make-local-variable 'next-error-function) 'diff-next-error)
cdbb79c1 1359
19446c41
DN
1360 (set (make-local-variable 'beginning-of-defun-function)
1361 'diff-beginning-of-file-and-junk)
1362 (set (make-local-variable 'end-of-defun-function)
1363 'diff-end-of-file)
1364
07875ee7 1365 (diff-setup-whitespace)
ac7020b3 1366
53dd481c 1367 (setq buffer-read-only diff-default-read-only)
769dd0f1 1368 ;; setup change hooks
e8a1ed31 1369 (if (not diff-update-on-the-fly)
3ccdb14e 1370 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
610a6418 1371 (make-local-variable 'diff-unhandled-changes)
3cec9c57
SM
1372 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1373 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
610a6418 1374 ;; Neat trick from Dave Love to add more bindings in read-only mode:
a9de04fa 1375 (let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
22cd1973
SM
1376 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1377 ;; Turn off this little trick in case the buffer is put in view-mode.
1378 (add-hook 'view-mode-hook
e78cf8e5
SM
1379 (lambda ()
1380 (setq minor-mode-overriding-map-alist
1381 (delq ro-bind minor-mode-overriding-map-alist)))
22cd1973 1382 nil t))
281096ed
SM
1383 ;; add-log support
1384 (set (make-local-variable 'add-log-current-defun-function)
1385 'diff-current-defun)
1b1b5dae 1386 (set (make-local-variable 'add-log-buffer-file-name-function)
8117868f
DN
1387 (lambda () (diff-find-file-name nil 'noprompt)))
1388 (unless (buffer-file-name)
1389 (hack-dir-local-variables-non-file-buffer)))
610a6418
SM
1390
1391;;;###autoload
0b82e382 1392(define-minor-mode diff-minor-mode
ac6c8639
CY
1393 "Toggle Diff minor mode.
1394With a prefix argument ARG, enable Diff minor mode if ARG is
1395positive, and disable it otherwise. If called from Lisp, enable
1396the mode if ARG is omitted or nil.
1397
0b82e382 1398\\{diff-minor-mode-map}"
cfc80227 1399 :group 'diff-mode :lighter " Diff"
0b82e382 1400 ;; FIXME: setup font-lock
fef8c55b 1401 ;; setup change hooks
e8a1ed31 1402 (if (not diff-update-on-the-fly)
3ccdb14e 1403 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
fef8c55b 1404 (make-local-variable 'diff-unhandled-changes)
3cec9c57
SM
1405 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1406 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
0b82e382 1407
e78cf8e5 1408;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22cd1973 1409
07875ee7
CY
1410(defun diff-setup-whitespace ()
1411 "Set up Whitespace mode variables for the current Diff mode buffer.
1412This sets `whitespace-style' and `whitespace-trailing-regexp' so
1413that Whitespace mode shows trailing whitespace problems on the
1414modified lines of the diff."
1415 (set (make-local-variable 'whitespace-style) '(face trailing))
1416 (let ((style (save-excursion
1417 (goto-char (point-min))
6be9197e
SM
1418 ;; FIXME: For buffers filled from async processes, this search
1419 ;; will simply fail because the buffer is still empty :-(
07875ee7
CY
1420 (when (re-search-forward diff-hunk-header-re nil t)
1421 (goto-char (match-beginning 0))
1422 (diff-hunk-style)))))
1423 (set (make-local-variable 'whitespace-trailing-regexp)
1424 (if (eq style 'context)
1425 "^[-\+!] .*?\\([\t ]+\\)$"
1426 "^[-\+!<>].*?\\([\t ]+\\)$"))))
1427
22cd1973
SM
1428(defun diff-delete-if-empty ()
1429 ;; An empty diff file means there's no more diffs to integrate, so we
1430 ;; can just remove the file altogether. Very handy for .rej files if we
1431 ;; remove hunks as we apply them.
1432 (when (and buffer-file-name
1433 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1434 (delete-file buffer-file-name)))
1435
1436(defun diff-delete-empty-files ()
1437 "Arrange for empty diff files to be removed."
1438 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1439
1440(defun diff-make-unified ()
1441 "Turn context diffs into unified diffs if applicable."
1442 (if (save-excursion
1443 (goto-char (point-min))
4c174fb4 1444 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
22cd1973
SM
1445 (let ((mod (buffer-modified-p)))
1446 (unwind-protect
1447 (diff-context->unified (point-min) (point-max))
1448 (restore-buffer-modified-p mod)))))
610a6418 1449
027ac3f8
SM
1450;;;
1451;;; Misc operations that have proved useful at some point.
1452;;;
1453
1454(defun diff-next-complex-hunk ()
1455 "Jump to the next \"complex\" hunk.
1456\"Complex\" is approximated by \"the hunk changes the number of lines\".
1457Only works for unified diffs."
1458 (interactive)
1459 (while
f52d2f9c
SM
1460 (and (re-search-forward diff-hunk-header-re-unified nil t)
1461 (equal (match-string 2) (match-string 4)))))
027ac3f8 1462
3a349573
SM
1463(defun diff-sanity-check-context-hunk-half (lines)
1464 (let ((count lines))
1465 (while
1466 (cond
1467 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1468 (memq (char-after (1+ (point))) '(?\s ?\t)))
f58e0fd5 1469 (cl-decf count) t)
3a349573
SM
1470 ((or (zerop count) (= count lines)) nil)
1471 ((memq (char-after) '(?! ?+ ?-))
1472 (if (not (and (eq (char-after (1+ (point))) ?\n)
1473 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1474 (error "End of hunk ambiguously marked")
1475 (forward-char 1) (insert " ") (forward-line -1) t))
1476 ((< lines 0)
1477 (error "End of hunk ambiguously marked"))
1478 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1479 (error "Abort!"))
1480 ((eolp) (insert " ") (forward-line -1) t)
1481 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1482 (forward-line))))
1483
1484(defun diff-sanity-check-hunk ()
1485 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1486 ;; OK to override a read-only setting.
1487 (inhibit-read-only t))
1488 (save-excursion
1489 (cond
1490 ((not (looking-at diff-hunk-header-re))
1491 (error "Not recognizable hunk header"))
1492
1493 ;; A context diff.
1494 ((eq (char-after) ?*)
7fb6ce6e 1495 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\*\\*\\*\\*"))
3a349573
SM
1496 (error "Unrecognized context diff first hunk header format")
1497 (forward-line 2)
1498 (diff-sanity-check-context-hunk-half
f52d2f9c 1499 (if (match-end 2)
7fb6ce6e
TTN
1500 (1+ (- (string-to-number (match-string 2))
1501 (string-to-number (match-string 1))))
1502 1))
bf6970a5 1503 (if (not (looking-at diff-context-mid-hunk-header-re))
3a349573
SM
1504 (error "Unrecognized context diff second hunk header format")
1505 (forward-line)
1506 (diff-sanity-check-context-hunk-half
f52d2f9c 1507 (if (match-end 2)
7fb6ce6e
TTN
1508 (1+ (- (string-to-number (match-string 2))
1509 (string-to-number (match-string 1))))
1510 1)))))
3a349573
SM
1511
1512 ;; A unified diff.
1513 ((eq (char-after) ?@)
f52d2f9c 1514 (if (not (looking-at diff-hunk-header-re-unified))
3a349573 1515 (error "Unrecognized unified diff hunk header format")
43392d12
SM
1516 (let ((before (string-to-number (or (match-string 2) "1")))
1517 (after (string-to-number (or (match-string 4) "1"))))
3a349573
SM
1518 (forward-line)
1519 (while
f58e0fd5
SM
1520 (pcase (char-after)
1521 (?\s (cl-decf before) (cl-decf after) t)
80a01d97
SM
1522 (?-
1523 (if (and (looking-at diff-file-header-re)
1524 (zerop before) (zerop after))
1525 ;; No need to query: this is a case where two patches
1526 ;; are concatenated and only counting the lines will
1527 ;; give the right result. Let's just add an empty
1528 ;; line so that our code which doesn't count lines
1529 ;; will not get confused.
1530 (progn (save-excursion (insert "\n")) nil)
f58e0fd5
SM
1531 (cl-decf before) t))
1532 (?+ (cl-decf after) t)
1533 (_
3a349573 1534 (cond
f52d2f9c
SM
1535 ((and diff-valid-unified-empty-line
1536 ;; Not just (eolp) so we don't infloop at eob.
79fd6168
SM
1537 (eq (char-after) ?\n)
1538 (> before 0) (> after 0))
f58e0fd5 1539 (cl-decf before) (cl-decf after) t)
3a349573
SM
1540 ((and (zerop before) (zerop after)) nil)
1541 ((or (< before 0) (< after 0))
1542 (error (if (or (zerop before) (zerop after))
1543 "End of hunk ambiguously marked"
1544 "Hunk seriously messed up")))
f52d2f9c 1545 ((not (y-or-n-p (concat "Try to auto-fix " (if (eolp) "whitespace loss" "word-wrap damage") "? ")))
3a349573
SM
1546 (error "Abort!"))
1547 ((eolp) (insert " ") (forward-line -1) t)
1548 (t (insert " ")
1549 (delete-region (- (point) 2) (- (point) 1)) t))))
1550 (forward-line)))))
1551
1552 ;; A plain diff.
1553 (t
1554 ;; TODO.
1555 )))))
1556
1eabc5e6
SM
1557(defun diff-hunk-text (hunk destp char-offset)
1558 "Return the literal source text from HUNK as (TEXT . OFFSET).
a70b0ff8 1559If DESTP is nil, TEXT is the source, otherwise the destination text.
1eabc5e6
SM
1560CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1561char-offset in TEXT."
3017133f 1562 (with-temp-buffer
6e4e8a3b
SM
1563 (insert hunk)
1564 (goto-char (point-min))
1565 (let ((src-pos nil)
1566 (dst-pos nil)
1567 (divider-pos nil)
1568 (num-pfx-chars 2))
1569 ;; Set the following variables:
1570 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1571 ;; DST-POS buffer pos of the destination part of the hunk or nil
1572 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1573 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1574 (cond ((looking-at "^@@")
1575 ;; unified diff
1576 (setq num-pfx-chars 1)
1577 (forward-line 1)
1578 (setq src-pos (point) dst-pos (point)))
1579 ((looking-at "^\\*\\*")
1580 ;; context diff
1581 (forward-line 2)
1582 (setq src-pos (point))
bf6970a5 1583 (re-search-forward diff-context-mid-hunk-header-re nil t)
6e4e8a3b
SM
1584 (forward-line 0)
1585 (setq divider-pos (point))
1586 (forward-line 1)
1587 (setq dst-pos (point)))
1588 ((looking-at "^[0-9]+a[0-9,]+$")
1589 ;; normal diff, insert
1590 (forward-line 1)
1591 (setq dst-pos (point)))
1592 ((looking-at "^[0-9,]+d[0-9]+$")
1593 ;; normal diff, delete
1594 (forward-line 1)
1595 (setq src-pos (point)))
1596 ((looking-at "^[0-9,]+c[0-9,]+$")
1597 ;; normal diff, change
1598 (forward-line 1)
1599 (setq src-pos (point))
1600 (re-search-forward "^---$" nil t)
1601 (forward-line 0)
1602 (setq divider-pos (point))
1603 (forward-line 1)
1604 (setq dst-pos (point)))
1605 (t
1606 (error "Unknown diff hunk type")))
1607
1608 (if (if destp (null dst-pos) (null src-pos))
1609 ;; Implied empty text
1610 (if char-offset '("" . 0) "")
1611
1612 ;; For context diffs, either side can be empty, (if there's only
1613 ;; added or only removed text). We should then use the other side.
1614 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1615 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1616
1617 (when char-offset (goto-char (+ (point-min) char-offset)))
1618
1619 ;; Get rid of anything except the desired text.
1620 (save-excursion
1621 ;; Delete unused text region
1622 (let ((keep (if destp dst-pos src-pos)))
1623 (when (and divider-pos (> divider-pos keep))
1624 (delete-region divider-pos (point-max)))
1625 (delete-region (point-min) keep))
1626 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1627 (let ((kill-char (if destp ?- ?+)))
1628 (goto-char (point-min))
1629 (while (not (eobp))
1630 (if (eq (char-after) kill-char)
1631 (delete-region (point) (progn (forward-line 1) (point)))
1632 (delete-char num-pfx-chars)
1633 (forward-line 1)))))
1634
1635 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1636 (if char-offset (cons text (- (point) (point-min))) text))))))
370d860c 1637
7530b6da 1638
c0aa75f7 1639(defun diff-find-text (text)
1eabc5e6 1640 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
7530b6da 1641If TEXT isn't found, nil is returned."
7530b6da
MB
1642 (let* ((orig (point))
1643 (forw (and (search-forward text nil t)
1eabc5e6 1644 (cons (match-beginning 0) (match-end 0))))
7530b6da
MB
1645 (back (and (goto-char (+ orig (length text)))
1646 (search-backward text nil t)
1eabc5e6
SM
1647 (cons (match-beginning 0) (match-end 0)))))
1648 ;; Choose the closest match.
1649 (if (and forw back)
1650 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1651 (or back forw))))
1652
1653(defun diff-find-approx-text (text)
1654 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1655Whitespace differences are ignored."
1656 (let* ((orig (point))
1657 (re (concat "^[ \t\n\f]*"
1658 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1659 "[ \t\n\f]*\n"))
1660 (forw (and (re-search-forward re nil t)
1661 (cons (match-beginning 0) (match-end 0))))
1662 (back (and (goto-char (+ orig (length text)))
1663 (re-search-backward re nil t)
1664 (cons (match-beginning 0) (match-end 0)))))
1665 ;; Choose the closest match.
7530b6da 1666 (if (and forw back)
1eabc5e6 1667 (if (> (- (car forw) orig) (- orig (car back))) back forw)
7530b6da
MB
1668 (or back forw))))
1669
44a07c5a 1670(defsubst diff-xor (a b) (if a (if (not b) a) b))
370d860c 1671
68035b97 1672(defun diff-find-source-location (&optional other-file reverse noprompt)
1eabc5e6
SM
1673 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1674BUF is the buffer corresponding to the source file.
1675LINE-OFFSET is the offset between the expected and actual positions
1676 of the text of the hunk or nil if the text was not found.
1677POS is a pair (BEG . END) indicating the position of the text in the buffer.
1678SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1679 SRC is the variant that was found in the buffer.
68035b97
SM
1680SWITCHED is non-nil if the patch is already applied.
1681NOPROMPT, if non-nil, means not to prompt the user."
7b91e0f2 1682 (save-excursion
e8a1ed31 1683 (let* ((other (diff-xor other-file diff-jump-to-old-file))
cb3e7ae0 1684 (char-offset (- (point) (diff-beginning-of-hunk t)))
3a349573
SM
1685 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1686 ;; the user may disagree on what constitutes the hunk
1687 ;; (e.g. because an empty line truncates the hunk mid-course),
1688 ;; leading to potentially nasty surprises for the user.
5dadb083 1689 ;;
19a4c504 1690 ;; Suppress check when NOPROMPT is non-nil (Bug#3033).
5dadb083 1691 (_ (unless noprompt (diff-sanity-check-hunk)))
68035b97
SM
1692 (hunk (buffer-substring
1693 (point) (save-excursion (diff-end-of-hunk) (point))))
370d860c
SM
1694 (old (diff-hunk-text hunk reverse char-offset))
1695 (new (diff-hunk-text hunk (not reverse) char-offset))
7b91e0f2 1696 ;; Find the location specification.
d868b3bd 1697 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
370d860c
SM
1698 (error "Can't find the hunk header")
1699 (if other (match-string 1)
1700 (if (match-end 3) (match-string 3)
bf6970a5
SM
1701 (unless (re-search-forward
1702 diff-context-mid-hunk-header-re nil t)
370d860c
SM
1703 (error "Can't find the hunk separator"))
1704 (match-string 1)))))
68035b97
SM
1705 (file (or (diff-find-file-name other noprompt)
1706 (error "Can't find the file")))
370d860c 1707 (buf (find-file-noselect file)))
7b91e0f2
SM
1708 ;; Update the user preference if he so wished.
1709 (when (> (prefix-numeric-value other-file) 8)
e8a1ed31 1710 (setq diff-jump-to-old-file other))
d868b3bd 1711 (with-current-buffer buf
88421f3e 1712 (goto-char (point-min)) (forward-line (1- (string-to-number line)))
d868b3bd 1713 (let* ((orig-pos (point))
1eabc5e6 1714 (switched nil)
22cd1973 1715 ;; FIXME: Check for case where both OLD and NEW are found.
1eabc5e6
SM
1716 (pos (or (diff-find-text (car old))
1717 (progn (setq switched t) (diff-find-text (car new)))
1718 (progn (setq switched nil)
22cd1973
SM
1719 (condition-case nil
1720 (diff-find-approx-text (car old))
1721 (invalid-regexp nil))) ;Regex too big.
1eabc5e6 1722 (progn (setq switched t)
22cd1973
SM
1723 (condition-case nil
1724 (diff-find-approx-text (car new))
1725 (invalid-regexp nil))) ;Regex too big.
1eabc5e6 1726 (progn (setq switched nil) nil))))
370d860c
SM
1727 (nconc
1728 (list buf)
1eabc5e6
SM
1729 (if pos
1730 (list (count-lines orig-pos (car pos)) pos)
1731 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
370d860c
SM
1732 (if switched (list new old t) (list old new))))))))
1733
7b91e0f2 1734
370d860c
SM
1735(defun diff-hunk-status-msg (line-offset reversed dry-run)
1736 (let ((msg (if dry-run
1737 (if reversed "already applied" "not yet applied")
1738 (if reversed "undone" "applied"))))
1739 (message (cond ((null line-offset) "Hunk text not found")
1740 ((= line-offset 0) "Hunk %s")
1741 ((= line-offset 1) "Hunk %s at offset %d line")
1742 (t "Hunk %s at offset %d lines"))
1743 msg line-offset)))
1744
cb9a30c8 1745(defvar diff-apply-hunk-to-backup-file nil)
370d860c
SM
1746
1747(defun diff-apply-hunk (&optional reverse)
6e4e8a3b 1748 "Apply the current hunk to the source file and go to the next.
7530b6da 1749By default, the new source file is patched, but if the variable
e8a1ed31 1750`diff-jump-to-old-file' is non-nil, then the old source file is
7530b6da
MB
1751patched instead (some commands, such as `diff-goto-source' can change
1752the value of this variable when given an appropriate prefix argument).
1753
4eaa6852 1754With a prefix argument, REVERSE the hunk."
370d860c 1755 (interactive "P")
f58e0fd5
SM
1756 (pcase-let ((`(,buf ,line-offset ,pos ,old ,new ,switched)
1757 ;; Sometimes we'd like to have the following behavior: if
1758 ;; REVERSE go to the new file, otherwise go to the old.
1759 ;; But that means that by default we use the old file, which is
1760 ;; the opposite of the default for diff-goto-source, and is thus
1761 ;; confusing. Also when you don't know about it it's
1762 ;; pretty surprising.
1763 ;; TODO: make it possible to ask explicitly for this behavior.
1764 ;;
1765 ;; This is duplicated in diff-test-hunk.
1766 (diff-find-source-location nil reverse)))
370d860c 1767 (cond
4eaa6852
MB
1768 ((null line-offset)
1769 (error "Can't find the text to patch"))
cb9a30c8
SM
1770 ((with-current-buffer buf
1771 (and buffer-file-name
1772 (backup-file-name-p buffer-file-name)
1773 (not diff-apply-hunk-to-backup-file)
1774 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1775 (yes-or-no-p (format "Really apply this hunk to %s? "
1776 (file-name-nondirectory
1777 buffer-file-name)))))))
593b4fa8
AS
1778 (error "%s"
1779 (substitute-command-keys
cb9a30c8
SM
1780 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1781 (if (not reverse) "\\[universal-argument] ")))))
370d860c 1782 ((and switched
cdbb79c1 1783 ;; A reversed patch was detected, perhaps apply it in reverse.
370d860c
SM
1784 (not (save-window-excursion
1785 (pop-to-buffer buf)
1eabc5e6 1786 (goto-char (+ (car pos) (cdr old)))
370d860c
SM
1787 (y-or-n-p
1788 (if reverse
1789 "Hunk hasn't been applied yet; apply it now? "
1790 "Hunk has already been applied; undo it? ")))))
4eaa6852 1791 (message "(Nothing done)"))
370d860c 1792 (t
4eaa6852
MB
1793 ;; Apply the hunk
1794 (with-current-buffer buf
1eabc5e6
SM
1795 (goto-char (car pos))
1796 (delete-region (car pos) (cdr pos))
4eaa6852
MB
1797 (insert (car new)))
1798 ;; Display BUF in a window
1eabc5e6 1799 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
4eaa6852
MB
1800 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1801 (when diff-advance-after-apply-hunk
1802 (diff-hunk-next))))))
370d860c 1803
7530b6da 1804
7530b6da
MB
1805(defun diff-test-hunk (&optional reverse)
1806 "See whether it's possible to apply the current hunk.
4eaa6852 1807With a prefix argument, try to REVERSE the hunk."
7530b6da 1808 (interactive "P")
f58e0fd5
SM
1809 (pcase-let ((`(,buf ,line-offset ,pos ,src ,_dst ,switched)
1810 (diff-find-source-location nil reverse)))
1eabc5e6 1811 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
4eaa6852 1812 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
370d860c 1813
7530b6da 1814
a1e2d7f7
SM
1815(defalias 'diff-mouse-goto-source 'diff-goto-source)
1816
1817(defun diff-goto-source (&optional other-file event)
7530b6da 1818 "Jump to the corresponding source line.
e8a1ed31 1819`diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
281096ed 1820is given) determines whether to jump to the old or the new file.
7530b6da 1821If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
a70b0ff8 1822then `diff-jump-to-old-file' is also set, for the next invocations."
a1e2d7f7 1823 (interactive (list current-prefix-arg last-input-event))
a6373340
SM
1824 ;; When pointing at a removal line, we probably want to jump to
1825 ;; the old location, and else to the new (i.e. as if reverting).
1826 ;; This is a convenient detail when using smerge-diff.
a1e2d7f7 1827 (if event (posn-set-point (event-end event)))
a6373340 1828 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
f58e0fd5
SM
1829 (pcase-let ((`(,buf ,line-offset ,pos ,src ,_dst ,switched)
1830 (diff-find-source-location other-file rev)))
a6373340 1831 (pop-to-buffer buf)
1eabc5e6 1832 (goto-char (+ (car pos) (cdr src)))
55d5d717 1833 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
370d860c 1834
7530b6da 1835
281096ed 1836(defun diff-current-defun ()
370d860c
SM
1837 "Find the name of function at point.
1838For use in `add-log-current-defun-function'."
ef63ea1c
SM
1839 ;; Kill change-log-default-name so it gets recomputed each time, since
1840 ;; each hunk may belong to another file which may belong to another
1841 ;; directory and hence have a different ChangeLog file.
1842 (kill-local-variable 'change-log-default-name)
2f9edc8b
KG
1843 (save-excursion
1844 (when (looking-at diff-hunk-header-re)
1845 (forward-line 1)
4f815065 1846 (re-search-forward "^[^ ]" nil t))
f58e0fd5
SM
1847 (pcase-let ((`(,buf ,_line-offset ,pos ,src ,dst ,switched)
1848 (ignore-errors ;Signals errors in place of prompting.
1849 ;; Use `noprompt' since this is used in which-func-mode
1850 ;; and such.
1851 (diff-find-source-location nil nil 'noprompt))))
68035b97
SM
1852 (when buf
1853 (beginning-of-line)
1854 (or (when (memq (char-after) '(?< ?-))
1855 ;; Cursor is pointing at removed text. This could be a removed
1856 ;; function, in which case, going to the source buffer will
1857 ;; not help since the function is now removed. Instead,
1858 ;; try to figure out the function name just from the
1859 ;; code-fragment.
1860 (let ((old (if switched dst src)))
1861 (with-temp-buffer
1862 (insert (car old))
1863 (funcall (buffer-local-value 'major-mode buf))
1864 (goto-char (+ (point-min) (cdr old)))
1865 (add-log-current-defun))))
1866 (with-current-buffer buf
1867 (goto-char (+ (car pos) (cdr src)))
1868 (add-log-current-defun)))))))
027ac3f8 1869
2659df68
SM
1870(defun diff-ignore-whitespace-hunk ()
1871 "Re-diff the current hunk, ignoring whitespace differences."
22cd1973 1872 (interactive)
cb3e7ae0 1873 (let* ((char-offset (- (point) (diff-beginning-of-hunk t)))
f58e0fd5 1874 (opts (pcase (char-after) (?@ "-bu") (?* "-bc") (_ "-b")))
22cd1973
SM
1875 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1876 (error "Can't find line number"))
1877 (string-to-number (match-string 1))))
14cf0430 1878 (inhibit-read-only t)
22cd1973
SM
1879 (hunk (delete-and-extract-region
1880 (point) (save-excursion (diff-end-of-hunk) (point))))
1881 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1882 (file1 (make-temp-file "diff1"))
1883 (file2 (make-temp-file "diff2"))
1884 (coding-system-for-read buffer-file-coding-system)
1885 old new)
1886 (unwind-protect
1887 (save-excursion
1888 (setq old (diff-hunk-text hunk nil char-offset))
1889 (setq new (diff-hunk-text hunk t char-offset))
1890 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1891 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1892 (with-temp-buffer
1893 (let ((status
1894 (call-process diff-command nil t nil
1895 opts file1 file2)))
f58e0fd5
SM
1896 (pcase status
1897 (0 nil) ;Nothing to reformat.
22cd1973 1898 (1 (goto-char (point-min))
f58e0fd5
SM
1899 ;; Remove the file-header.
1900 (when (re-search-forward diff-hunk-header-re nil t)
1901 (delete-region (point-min) (match-beginning 0))))
1902 (_ (goto-char (point-max))
22cd1973
SM
1903 (unless (bolp) (insert "\n"))
1904 (insert hunk)))
1905 (setq hunk (buffer-string))
1906 (unless (memq status '(0 1))
1907 (error "Diff returned: %s" status)))))
1908 ;; Whatever happens, put back some equivalent text: either the new
1909 ;; one or the original one in case some error happened.
1910 (insert hunk)
1911 (delete-file file1)
1912 (delete-file file2))))
1913
be36f934
SM
1914;;; Fine change highlighting.
1915
2659df68
SM
1916(defface diff-refine-change
1917 '((((class color) (min-colors 88) (background light))
bc1b21bb 1918 :background "#ffff55")
2659df68 1919 (((class color) (min-colors 88) (background dark))
bc1b21bb
JL
1920 :background "#aaaa22")
1921 (t :inverse-video t))
2659df68 1922 "Face used for char-based changes shown by `diff-refine-hunk'."
5eee3c95 1923 :group 'diff-mode)
be36f934 1924
bc1b21bb
JL
1925(defface diff-refine-removed
1926 '((default
1927 :inherit diff-refine-change)
1928 (((class color) (min-colors 88) (background light))
d80d54b2 1929 :background "#ffbbbb")
bc1b21bb
JL
1930 (((class color) (min-colors 88) (background dark))
1931 :background "#aa2222"))
1932 "Face used for removed characters shown by `diff-refine-hunk'."
1933 :group 'diff-mode
2a1e2476 1934 :version "24.3")
bc1b21bb
JL
1935
1936(defface diff-refine-added
1937 '((default
1938 :inherit diff-refine-change)
1939 (((class color) (min-colors 88) (background light))
1940 :background "#aaffaa")
1941 (((class color) (min-colors 88) (background dark))
1942 :background "#22aa22"))
1943 "Face used for added characters shown by `diff-refine-hunk'."
1944 :group 'diff-mode
2a1e2476 1945 :version "24.3")
bc1b21bb 1946
2659df68 1947(defun diff-refine-preproc ()
8872469d
SM
1948 (while (re-search-forward "^[+>]" nil t)
1949 ;; Remove spurious changes due to the fact that one side of the hunk is
1950 ;; marked with leading + or > and the other with leading - or <.
1951 ;; We used to replace all the prefix chars with " " but this only worked
1952 ;; when we did char-based refinement (or when using
1953 ;; smerge-refine-weight-hack) since otherwise, the `forward' motion done
1954 ;; in chopup do not necessarily do the same as the ones in highlight
1955 ;; since the "_" is not treated the same as " ".
1956 (replace-match (cdr (assq (char-before) '((?+ . "-") (?> . "<"))))))
1957 )
be36f934 1958
60f884b2 1959(declare-function smerge-refine-subst "smerge-mode"
bc1b21bb 1960 (beg1 end1 beg2 end2 props-c &optional preproc props-r props-a))
60f884b2 1961
2659df68 1962(defun diff-refine-hunk ()
be36f934
SM
1963 "Highlight changes of hunk at point at a finer granularity."
1964 (interactive)
60f884b2 1965 (require 'smerge-mode)
8872469d 1966 (save-excursion
cb3e7ae0 1967 (diff-beginning-of-hunk t)
b1816a74
SM
1968 (let* ((start (point))
1969 (style (diff-hunk-style)) ;Skips the hunk header as well.
8872469d 1970 (beg (point))
bc1b21bb
JL
1971 (props-c '((diff-mode . fine) (face diff-refine-change)))
1972 (props-r '((diff-mode . fine) (face diff-refine-removed)))
1973 (props-a '((diff-mode . fine) (face diff-refine-added)))
b1816a74
SM
1974 ;; Be careful to go back to `start' so diff-end-of-hunk gets
1975 ;; to read the hunk header's line info.
1976 (end (progn (goto-char start) (diff-end-of-hunk) (point))))
8872469d
SM
1977
1978 (remove-overlays beg end 'diff-mode 'fine)
1979
1980 (goto-char beg)
f58e0fd5
SM
1981 (pcase style
1982 (`unified
a2be0357
SM
1983 (while (re-search-forward
1984 (eval-when-compile
1985 (let ((no-LF-at-eol-re "\\(?:\\\\.*\n\\)?"))
1986 (concat "^\\(?:-.*\n\\)+" no-LF-at-eol-re
1987 "\\(\\)"
1988 "\\(?:\\+.*\n\\)+" no-LF-at-eol-re)))
1989 end t)
8872469d
SM
1990 (smerge-refine-subst (match-beginning 0) (match-end 1)
1991 (match-end 1) (match-end 0)
bc1b21bb 1992 nil 'diff-refine-preproc props-r props-a)))
f58e0fd5 1993 (`context
8872469d
SM
1994 (let* ((middle (save-excursion (re-search-forward "^---")))
1995 (other middle))
1996 (while (re-search-forward "^\\(?:!.*\n\\)+" middle t)
1997 (smerge-refine-subst (match-beginning 0) (match-end 0)
1998 (save-excursion
1999 (goto-char other)
2000 (re-search-forward "^\\(?:!.*\n\\)+" end)
2001 (setq other (match-end 0))
2002 (match-beginning 0))
2003 other
bc1b21bb
JL
2004 (if diff-use-changed-face props-c)
2005 'diff-refine-preproc
2006 (unless diff-use-changed-face props-r)
2007 (unless diff-use-changed-face props-a)))))
f58e0fd5 2008 (_ ;; Normal diffs.
8872469d
SM
2009 (let ((beg1 (1+ (point))))
2010 (when (re-search-forward "^---.*\n" end t)
2011 ;; It's a combined add&remove, so there's something to do.
2012 (smerge-refine-subst beg1 (match-beginning 0)
2013 (match-end 0) end
bc1b21bb 2014 nil 'diff-refine-preproc props-r props-a))))))))
be36f934 2015
8b71081d
CY
2016(defun diff-undo (&optional arg)
2017 "Perform `undo', ignoring the buffer's read-only status."
2018 (interactive "P")
2019 (let ((inhibit-read-only t))
2020 (undo arg)))
be36f934 2021
8330c175
SM
2022(defun diff-add-change-log-entries-other-window ()
2023 "Iterate through the current diff and create ChangeLog entries.
2024I.e. like `add-change-log-entry-other-window' but applied to all hunks."
8a72c7f8
DN
2025 (interactive)
2026 ;; XXX: Currently add-change-log-entry-other-window is only called
2027 ;; once per hunk. Some hunks have multiple changes, it would be
2028 ;; good to call it for each change.
2029 (save-excursion
2030 (goto-char (point-min))
ba83908c
SM
2031 (condition-case nil
2032 ;; Call add-change-log-entry-other-window for each hunk in
2033 ;; the diff buffer.
2034 (while (progn
2035 (diff-hunk-next)
2036 ;; Move to where the changes are,
2037 ;; `add-change-log-entry-other-window' works better in
2038 ;; that case.
2039 (re-search-forward
2040 (concat "\n[!+-<>]"
2041 ;; If the hunk is a context hunk with an empty first
2042 ;; half, recognize the "--- NNN,MMM ----" line
2043 "\\(-- [0-9]+\\(,[0-9]+\\)? ----\n"
2044 ;; and skip to the next non-context line.
2045 "\\( .*\n\\)*[+]\\)?")
2046 nil t))
2047 (save-excursion
2048 ;; FIXME: this pops up windows of all the buffers.
2049 (add-change-log-entry nil nil t nil t)))
2050 ;; When there's no more hunks, diff-hunk-next signals an error.
2051 (error nil))))
8a72c7f8 2052
9d9e48d9
CY
2053(defun diff-delete-trailing-whitespace (&optional other-file)
2054 "Remove trailing whitespace from lines modified in this diff.
2055This edits both the current Diff mode buffer and the patched
2056source file(s). If `diff-jump-to-old-file' is non-nil, edit the
2057original (unpatched) source file instead. With a prefix argument
2058OTHER-FILE, flip the choice of which source file to edit.
2059
2060If a file referenced in the diff has no buffer and needs to be
2061fixed, visit it in a buffer."
2062 (interactive "P")
2063 (save-excursion
2064 (goto-char (point-min))
2065 (let* ((other (diff-xor other-file diff-jump-to-old-file))
2066 (modified-buffers nil)
2067 (style (save-excursion
2068 (when (re-search-forward diff-hunk-header-re nil t)
2069 (goto-char (match-beginning 0))
2070 (diff-hunk-style))))
2071 (regexp (concat "^[" (if other "-<" "+>") "!]"
2072 (if (eq style 'context) " " "")
2073 ".*?\\([ \t]+\\)$"))
2074 (inhibit-read-only t)
2075 (end-marker (make-marker))
2076 hunk-end)
2077 ;; Move to the first hunk.
2078 (re-search-forward diff-hunk-header-re nil 1)
2079 (while (progn (save-excursion
2080 (re-search-forward diff-hunk-header-re nil 1)
2081 (setq hunk-end (point)))
2082 (< (point) hunk-end))
2083 ;; For context diffs, search only in the appropriate half of
2084 ;; the hunk. For other diffs, search within the entire hunk.
2085 (if (not (eq style 'context))
2086 (set-marker end-marker hunk-end)
2087 (let ((mid-hunk
2088 (save-excursion
2089 (re-search-forward diff-context-mid-hunk-header-re hunk-end)
2090 (point))))
2091 (if other
2092 (set-marker end-marker mid-hunk)
2093 (goto-char mid-hunk)
2094 (set-marker end-marker hunk-end))))
2095 (while (re-search-forward regexp end-marker t)
2096 (let ((match-data (match-data)))
2097 (pcase-let ((`(,buf ,line-offset ,pos ,src ,_dst ,_switched)
2098 (diff-find-source-location other-file)))
2099 (when line-offset
2100 ;; Remove the whitespace in the Diff mode buffer.
2101 (set-match-data match-data)
2102 (replace-match "" t t nil 1)
2103 ;; Remove the whitespace in the source buffer.
2104 (with-current-buffer buf
2105 (save-excursion
2106 (goto-char (+ (car pos) (cdr src)))
2107 (beginning-of-line)
2108 (when (re-search-forward "\\([ \t]+\\)$" (line-end-position) t)
2109 (unless (memq buf modified-buffers)
2110 (push buf modified-buffers))
2111 (replace-match ""))))))))
2112 (goto-char hunk-end))
2113 (if modified-buffers
2114 (message "Deleted trailing whitespace from %s."
2115 (mapconcat (lambda (buf) (concat "`" (buffer-name buf) "'"))
2116 modified-buffers ", "))
2117 (message "No trailing whitespace to delete.")))))
2c2d9c9c 2118
610a6418
SM
2119;; provide the package
2120(provide 'diff-mode)
2121
027ac3f8 2122;;; Old Change Log from when diff-mode wasn't part of Emacs:
610a6418
SM
2123;; Revision 1.11 1999/10/09 23:38:29 monnier
2124;; (diff-mode-load-hook): dropped.
2125;; (auto-mode-alist): also catch *.diffs.
2126;; (diff-find-file-name, diff-mode): add smarts to find the right file
2127;; for *.rej files (that lack any file name indication).
2128;;
2129;; Revision 1.10 1999/09/30 15:32:11 monnier
2130;; added support for "\ No newline at end of file".
2131;;
2132;; Revision 1.9 1999/09/15 00:01:13 monnier
2133;; - added basic `compile' support.
2134;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
2135;; - diff-kill-file now tries to kill the leading garbage as well.
2136;;
2137;; Revision 1.8 1999/09/13 21:10:09 monnier
2138;; - don't use CL in the autoloaded code
2139;; - accept diffs using -T
2140;;
2141;; Revision 1.7 1999/09/05 20:53:03 monnier
2142;; interface to ediff-patch
2143;;
2144;; Revision 1.6 1999/09/01 20:55:13 monnier
2145;; (ediff=patch-file): add bindings to call ediff-patch.
2146;; (diff-find-file-name): taken out of diff-goto-source.
2147;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
2148;; diff-fixup-modifs): only use the region if a prefix arg is given.
2149;;
2150;; Revision 1.5 1999/08/31 19:18:52 monnier
2151;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
2152;;
2153;; Revision 1.4 1999/08/31 13:01:44 monnier
2154;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
2155;;
2156
2157;;; diff-mode.el ends here