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