* term/x-win.el (x-gtk-stock-map, icon-map-list)
[bpt/emacs.git] / lisp / diff-mode.el
CommitLineData
b532d575 1;;; diff-mode.el --- a mode for viewing/editing context diffs
610a6418 2
0d30b337 3;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3a349573 4;; 2005, 2006, 2007 Free Software Foundation, Inc.
610a6418 5
cc1eecfd 6;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
b532d575 7;; Keywords: convenience patch diff
610a6418
SM
8
9;; This file is part of GNU Emacs.
10
11;; GNU Emacs is free software; you can redistribute it and/or modify
12;; it under the terms of the GNU General Public License as published by
b4aa6026 13;; the Free Software Foundation; either version 3, or (at your option)
610a6418
SM
14;; any later version.
15
16;; GNU Emacs is distributed in the hope that it will be useful,
17;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19;; GNU General Public License for more details.
20
21;; You should have received a copy of the GNU General Public License
22;; along with GNU Emacs; see the file COPYING. If not, write to the
086add15
LK
23;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24;; Boston, MA 02110-1301, USA.
610a6418
SM
25
26;;; Commentary:
27
cdbb79c1 28;; Provides support for font-lock, outline, navigation
610a6418
SM
29;; commands, editing and various conversions as well as jumping
30;; to the corresponding source file.
31
3ccdb14e 32;; Inspired by Pavel Machek's patch-mode.el (<pavel@@atrey.karlin.mff.cuni.cz>)
b532d575 33;; Some efforts were spent to have it somewhat compatible with XEmacs'
610a6418
SM
34;; diff-mode as well as with compilation-minor-mode
35
610a6418
SM
36;; Bugs:
37
027ac3f8 38;; - Reverse doesn't work with normal diffs.
610a6418
SM
39
40;; Todo:
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:
610a6418
SM
56(eval-when-compile (require 'cl))
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
610a6418
SM
79 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
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
MB
88(defcustom diff-advance-after-apply-hunk t
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
2659df68
SM
93(defcustom diff-auto-refine t
94 "Automatically highlight changes in detail as the user visits hunks."
97546017
DN
95 :type 'boolean
96 :group 'diff-mode)
00df919e 97
22cd1973
SM
98(defcustom diff-mode-hook nil
99 "Run after setting up the `diff-mode' major mode."
100 :type 'hook
f5307782
JB
101 :options '(diff-delete-empty-files diff-make-unified)
102 :group 'diff-mode)
610a6418
SM
103
104(defvar diff-outline-regexp
105 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
106
cd632e57 107;;;;
610a6418 108;;;; keymap, menu, ...
cd632e57 109;;;;
610a6418 110
d87e5627 111(easy-mmode-defmap diff-mode-shared-map
027ac3f8 112 '(;; From Pavel Machek's patch-mode.
d87e5627
SM
113 ("n" . diff-hunk-next)
114 ("N" . diff-file-next)
115 ("p" . diff-hunk-prev)
116 ("P" . diff-file-prev)
25edda53
DN
117 ("\t" . diff-hunk-next)
118 ([backtab] . diff-hunk-prev)
d87e5627
SM
119 ("k" . diff-hunk-kill)
120 ("K" . diff-file-kill)
027ac3f8 121 ;; From compilation-minor-mode.
d87e5627
SM
122 ("}" . diff-file-next)
123 ("{" . diff-file-prev)
610a6418 124 ("\C-m" . diff-goto-source)
a1e2d7f7 125 ([mouse-2] . diff-goto-source)
027ac3f8 126 ;; From XEmacs' diff-mode.
fe39af99
SM
127 ;; Standard M-w is useful, so don't change M-W.
128 ;;("W" . widen)
610a6418
SM
129 ;;("." . diff-goto-source) ;display-buffer
130 ;;("f" . diff-goto-source) ;find-file
131 ("o" . diff-goto-source) ;other-window
132 ;;("w" . diff-goto-source) ;other-frame
133 ;;("N" . diff-narrow)
134 ;;("h" . diff-show-header)
135 ;;("j" . diff-show-difference) ;jump to Nth diff
136 ;;("q" . diff-quit)
e78cf8e5
SM
137 ;; Not useful if you have to metafy them.
138 ;;(" " . scroll-up)
139 ;;("\177" . scroll-down)
140 ;; Standard M-a is useful, so don't change M-A.
141 ;;("A" . diff-ediff-patch)
142 ;; Standard M-r is useful, so don't change M-r or M-R.
143 ;;("r" . diff-restrict-view)
144 ;;("R" . diff-reverse-direction)
c010ecfa 145 ("q" . quit-window))
0b82e382 146 "Basic keymap for `diff-mode', bound to various prefix keys.")
610a6418 147
d87e5627 148(easy-mmode-defmap diff-mode-map
610a6418 149 `(("\e" . ,diff-mode-shared-map)
027ac3f8
SM
150 ;; From compilation-minor-mode.
151 ("\C-c\C-c" . diff-goto-source)
152 ;; Misc operations.
3cec9c57 153 ("\C-c\C-a" . diff-apply-hunk)
28408bfd
RS
154 ("\C-c\C-e" . diff-ediff-patch)
155 ("\C-c\C-n" . diff-restrict-view)
28408bfd 156 ("\C-c\C-s" . diff-split-hunk)
b711788a 157 ("\C-c\C-t" . diff-test-hunk)
2659df68 158 ("\C-c\C-r" . diff-reverse-direction)
28408bfd 159 ("\C-c\C-u" . diff-context->unified)
fe39af99
SM
160 ;; `d' because it duplicates the context :-( --Stef
161 ("\C-c\C-d" . diff-unified->context)
2659df68
SM
162 ("\C-c\C-w" . diff-ignore-whitespace-hunk)
163 ("\C-c\C-b" . diff-refine-hunk) ;No reason for `b' :-(
677c0382 164 ("\C-c\C-f" . next-error-follow-minor-mode))
610a6418
SM
165 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
166
167(easy-menu-define diff-mode-menu diff-mode-map
168 "Menu for `diff-mode'."
169 '("Diff"
170 ["Jump to Source" diff-goto-source t]
cd632e57 171 ["Apply hunk" diff-apply-hunk t]
8f2d38de 172 ["Test applying hunk" diff-test-hunk t]
cd632e57 173 ["Apply diff with Ediff" diff-ediff-patch t]
8f2d38de 174 "-----"
610a6418
SM
175 ["Reverse direction" diff-reverse-direction t]
176 ["Context -> Unified" diff-context->unified t]
177 ["Unified -> Context" diff-unified->context t]
178 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
8f2d38de 179 "-----"
f151b310 180 ["Split hunk" diff-split-hunk (diff-splittable-p)]
2659df68
SM
181 ["Ignore whitespace changes" diff-ignore-whitespace-hunk t]
182 ["Highlight fine changes" diff-refine-hunk t]
8f2d38de
SM
183 ["Kill current hunk" diff-hunk-kill t]
184 ["Kill current file's hunks" diff-file-kill t]
185 "-----"
186 ["Previous Hunk" diff-hunk-prev t]
187 ["Next Hunk" diff-hunk-next t]
188 ["Previous File" diff-file-prev t]
189 ["Next File" diff-file-next t]
610a6418
SM
190 ))
191
3cec9c57 192(defcustom diff-minor-mode-prefix "\C-c="
0b82e382 193 "Prefix key for `diff-minor-mode' commands."
f5307782
JB
194 :type '(choice (string "\e") (string "C-c=") string)
195 :group 'diff-mode)
0b82e382 196
d87e5627
SM
197(easy-mmode-defmap diff-minor-mode-map
198 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
0b82e382
SM
199 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
200
610a6418 201
cd632e57 202;;;;
610a6418 203;;;; font-lock support
cd632e57 204;;;;
610a6418 205
221711eb 206(defface diff-header
55f2eb7e 207 '((((class color) (min-colors 88) (background light))
4f815065 208 :background "grey85")
55f2eb7e 209 (((class color) (min-colors 88) (background dark))
4f815065 210 :background "grey45")
55f2eb7e 211 (((class color) (background light))
4f815065 212 :foreground "blue1" :weight bold)
55f2eb7e 213 (((class color) (background dark))
4f815065
SM
214 :foreground "green" :weight bold)
215 (t :weight bold))
d676819e
LK
216 "`diff-mode' face inherited by hunk and index header faces."
217 :group 'diff-mode)
221711eb
MB
218;; backward-compatibility alias
219(put 'diff-header-face 'face-alias 'diff-header)
220(defvar diff-header-face 'diff-header)
c0aa75f7 221
221711eb 222(defface diff-file-header
55f2eb7e 223 '((((class color) (min-colors 88) (background light))
4f815065 224 :background "grey70" :weight bold)
55f2eb7e 225 (((class color) (min-colors 88) (background dark))
4f815065 226 :background "grey60" :weight bold)
55f2eb7e 227 (((class color) (background light))
f3abba99 228 :foreground "green" :weight bold)
55f2eb7e 229 (((class color) (background dark))
4f815065
SM
230 :foreground "cyan" :weight bold)
231 (t :weight bold)) ; :height 1.3
d676819e
LK
232 "`diff-mode' face used to highlight file header lines."
233 :group 'diff-mode)
221711eb
MB
234;; backward-compatibility alias
235(put 'diff-file-header-face 'face-alias 'diff-file-header)
236(defvar diff-file-header-face 'diff-file-header)
610a6418 237
221711eb
MB
238(defface diff-index
239 '((t :inherit diff-file-header))
d676819e
LK
240 "`diff-mode' face used to highlight index header lines."
241 :group 'diff-mode)
221711eb
MB
242;; backward-compatibility alias
243(put 'diff-index-face 'face-alias 'diff-index)
244(defvar diff-index-face 'diff-index)
610a6418 245
221711eb
MB
246(defface diff-hunk-header
247 '((t :inherit diff-header))
d676819e
LK
248 "`diff-mode' face used to highlight hunk header lines."
249 :group 'diff-mode)
221711eb
MB
250;; backward-compatibility alias
251(put 'diff-hunk-header-face 'face-alias 'diff-hunk-header)
252(defvar diff-hunk-header-face 'diff-hunk-header)
610a6418 253
221711eb
MB
254(defface diff-removed
255 '((t :inherit diff-changed))
d676819e
LK
256 "`diff-mode' face used to highlight removed lines."
257 :group 'diff-mode)
221711eb
MB
258;; backward-compatibility alias
259(put 'diff-removed-face 'face-alias 'diff-removed)
260(defvar diff-removed-face 'diff-removed)
610a6418 261
221711eb
MB
262(defface diff-added
263 '((t :inherit diff-changed))
d676819e
LK
264 "`diff-mode' face used to highlight added lines."
265 :group 'diff-mode)
221711eb
MB
266;; backward-compatibility alias
267(put 'diff-added-face 'face-alias 'diff-added)
268(defvar diff-added-face 'diff-added)
610a6418 269
221711eb 270(defface diff-changed
86a27a3a 271 '((((type tty pc) (class color) (background light))
4f815065 272 :foreground "magenta" :weight bold :slant italic)
86a27a3a 273 (((type tty pc) (class color) (background dark))
4f815065 274 :foreground "yellow" :weight bold :slant italic))
d676819e
LK
275 "`diff-mode' face used to highlight changed lines."
276 :group 'diff-mode)
221711eb
MB
277;; backward-compatibility alias
278(put 'diff-changed-face 'face-alias 'diff-changed)
279(defvar diff-changed-face 'diff-changed)
610a6418 280
f3abba99
JL
281(defface diff-indicator-removed
282 '((t :inherit diff-removed))
283 "`diff-mode' face used to highlight indicator of removed lines (-, <)."
284 :group 'diff-mode
285 :version "22.1")
286(defvar diff-indicator-removed-face 'diff-indicator-removed)
287
288(defface diff-indicator-added
289 '((t :inherit diff-added))
290 "`diff-mode' face used to highlight indicator of added lines (+, >)."
291 :group 'diff-mode
292 :version "22.1")
293(defvar diff-indicator-added-face 'diff-indicator-added)
294
295(defface diff-indicator-changed
296 '((t :inherit diff-changed))
297 "`diff-mode' face used to highlight indicator of changed lines."
298 :group 'diff-mode
299 :version "22.1")
300(defvar diff-indicator-changed-face 'diff-indicator-changed)
301
221711eb 302(defface diff-function
ea5d66db 303 '((t :inherit diff-header))
d676819e
LK
304 "`diff-mode' face used to highlight function names produced by \"diff -p\"."
305 :group 'diff-mode)
221711eb
MB
306;; backward-compatibility alias
307(put 'diff-function-face 'face-alias 'diff-function)
308(defvar diff-function-face 'diff-function)
34460354 309
221711eb 310(defface diff-context
f3abba99 311 '((((class color grayscale) (min-colors 88)) :inherit shadow))
d676819e
LK
312 "`diff-mode' face used to highlight context and other side-information."
313 :group 'diff-mode)
221711eb
MB
314;; backward-compatibility alias
315(put 'diff-context-face 'face-alias 'diff-context)
316(defvar diff-context-face 'diff-context)
c0aa75f7 317
221711eb
MB
318(defface diff-nonexistent
319 '((t :inherit diff-file-header))
d676819e
LK
320 "`diff-mode' face used to highlight nonexistent files in recursive diffs."
321 :group 'diff-mode)
221711eb
MB
322;; backward-compatibility alias
323(put 'diff-nonexistent-face 'face-alias 'diff-nonexistent)
324(defvar diff-nonexistent-face 'diff-nonexistent)
469fc0a2 325
22cd1973
SM
326(defconst diff-yank-handler '(diff-yank-function))
327(defun diff-yank-function (text)
1ec7bd14
SM
328 ;; FIXME: the yank-handler is now called separately on each piece of text
329 ;; with a yank-handler property, so the next-single-property-change call
330 ;; below will always return nil :-( --stef
22cd1973
SM
331 (let ((mixed (next-single-property-change 0 'yank-handler text))
332 (start (point)))
333 ;; First insert the text.
334 (insert text)
335 ;; If the text does not include any diff markers and if we're not
336 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
337 (unless (or mixed (derived-mode-p 'diff-mode))
338 (undo-boundary) ; Just in case the user wanted the prefixes.
339 (let ((re (save-excursion
340 (if (re-search-backward "^[><!][ \t]" start t)
341 (if (eq (char-after) ?!)
342 "^[!+- ][ \t]" "^[<>][ \t]")
343 "^[ <>!+-]"))))
344 (save-excursion
345 (while (re-search-backward re start t)
346 (replace-match "" t t)))))))
cfc80227 347
22cd1973 348
610a6418 349(defvar diff-font-lock-keywords
f3abba99
JL
350 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
351 (1 diff-hunk-header-face) (2 diff-function-face))
352 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
353 (1 diff-hunk-header-face) (2 diff-function-face))
370d860c 354 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
f3abba99
JL
355 ("^--- .+ ----$" . diff-hunk-header-face) ;context
356 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face) ;normal
357 ("^---$" . diff-hunk-header-face) ;normal
4c969f97
SM
358 ;; For file headers, accept files with spaces, but be careful to rule
359 ;; out false-positives when matching hunk headers.
360 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\([^\t\n]+?\\)\\(?:\t.*\\| \\(\\*\\*\\*\\*\\|----\\)\\)?\n"
361 (0 diff-header-face)
362 (2 (if (not (match-end 3)) diff-file-header-face) prepend))
f3abba99
JL
363 ("^\\([-<]\\)\\(.*\n\\)"
364 (1 diff-indicator-removed-face) (2 diff-removed-face))
365 ("^\\([+>]\\)\\(.*\n\\)"
366 (1 diff-indicator-added-face) (2 diff-added-face))
367 ("^\\(!\\)\\(.*\n\\)"
368 (1 diff-indicator-changed-face) (2 diff-changed-face))
369 ("^Index: \\(.+\\).*\n"
370 (0 diff-header-face) (1 diff-index-face prepend))
7dfb000f 371 ("^Only in .*\n" . diff-nonexistent-face)
f3abba99 372 ("^\\(#\\)\\(.*\\)"
050dcc13
JL
373 (1 font-lock-comment-delimiter-face)
374 (2 font-lock-comment-face))
f3abba99 375 ("^[^-=+*!<>#].*\n" (0 diff-context-face))))
610a6418
SM
376
377(defconst diff-font-lock-defaults
0e104800 378 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
610a6418 379
ccce6558
DL
380(defvar diff-imenu-generic-expression
381 ;; Prefer second name as first is most likely to be a backup or
824693e7
DL
382 ;; version-control name. The [\t\n] at the end of the unidiff pattern
383 ;; catches Debian source diff files (which lack the trailing date).
384 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
ccce6558
DL
385 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
386
cd632e57 387;;;;
610a6418 388;;;; Movement
cd632e57 389;;;;
610a6418 390
c0078a04 391(defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
bd9d7d76 392(defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
610a6418
SM
393(defvar diff-narrowed-to nil)
394
be36f934 395(defun diff-hunk-style (&optional style)
996884b2 396 (when (looking-at diff-hunk-header-re)
be36f934 397 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context)))))
996884b2 398 (goto-char (match-end 0)))
be36f934
SM
399 style)
400
401(defun diff-end-of-hunk (&optional style)
402 ;; Especially important for unified (because headers are ambiguous).
403 (setq style (diff-hunk-style style))
0e104800 404 (let ((end (and (re-search-forward (case style
1eabc5e6
SM
405 ;; A `unified' header is ambiguous.
406 (unified (concat "^[^-+# \\]\\|"
407 diff-file-header-re))
0e104800
SM
408 (context "^[^-+#! \\]")
409 (normal "^[^<>#\\]")
410 (t "^[^-+#!<> \\]"))
411 nil t)
412 (match-beginning 0))))
413 ;; The return value is used by easy-mmode-define-navigation.
414 (goto-char (or end (point-max)))))
610a6418 415
fd691799
SM
416(defun diff-beginning-of-hunk (&optional try-harder)
417 "Move back to beginning of hunk.
418If TRY-HARDER is non-nil, try to cater to the case where we're not in a hunk
419but in the file header instead, in which case move forward to the first hunk."
610a6418
SM
420 (beginning-of-line)
421 (unless (looking-at diff-hunk-header-re)
422 (forward-line 1)
423 (condition-case ()
424 (re-search-backward diff-hunk-header-re)
fd691799
SM
425 (error
426 (if (not try-harder)
427 (error "Can't find the beginning of the hunk")
428 (diff-beginning-of-file-and-junk)
429 (diff-hunk-next))))))
610a6418 430
f151b310
SM
431(defun diff-unified-hunk-p ()
432 (save-excursion
433 (ignore-errors
434 (diff-beginning-of-hunk)
435 (looking-at "^@@"))))
436
610a6418
SM
437(defun diff-beginning-of-file ()
438 (beginning-of-line)
439 (unless (looking-at diff-file-header-re)
4c969f97
SM
440 (let ((start (point))
441 res)
442 ;; diff-file-header-re may need to match up to 4 lines, so in case
443 ;; we're inside the header, we need to move up to 3 lines forward.
444 (forward-line 3)
445 (if (and (setq res (re-search-backward diff-file-header-re nil t))
446 ;; Maybe the 3 lines forward were too much and we matched
447 ;; a file header after our starting point :-(
448 (or (<= (point) start)
449 (setq res (re-search-backward diff-file-header-re nil t))))
450 res
451 (goto-char start)
452 (error "Can't find the beginning of the file")))))
453
610a6418
SM
454
455(defun diff-end-of-file ()
0e104800 456 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
22cd1973
SM
457 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
458 nil 'move)
459 (if (match-beginning 1)
460 (goto-char (match-beginning 1))
461 (beginning-of-line)))
610a6418 462
d87e5627
SM
463;; Define diff-{hunk,file}-{prev,next}
464(easy-mmode-define-navigation
2659df68
SM
465 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view
466 (if diff-auto-refine
467 (condition-case-no-debug nil (diff-refine-hunk) (error nil))))
468
d87e5627
SM
469(easy-mmode-define-navigation
470 diff-file diff-file-header-re "file" diff-end-of-hunk)
610a6418
SM
471
472(defun diff-restrict-view (&optional arg)
473 "Restrict the view to the current hunk.
474If the prefix ARG is given, restrict the view to the current file instead."
475 (interactive "P")
476 (save-excursion
fd691799 477 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk 'try-harder))
610a6418
SM
478 (narrow-to-region (point)
479 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
480 (point)))
481 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
482
483
d87e5627 484(defun diff-hunk-kill ()
610a6418
SM
485 "Kill current hunk."
486 (interactive)
487 (diff-beginning-of-hunk)
1eabc5e6 488 (let* ((start (point))
22cd1973
SM
489 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
490 (match-beginning 0)))
1eabc5e6
SM
491 (firsthunk (ignore-errors
492 (goto-char start)
493 (diff-beginning-of-file) (diff-hunk-next) (point)))
dd24cb37
CY
494 (nextfile (ignore-errors (diff-file-next) (point)))
495 (inhibit-read-only t))
1eabc5e6 496 (goto-char start)
610a6418
SM
497 (if (and firsthunk (= firsthunk start)
498 (or (null nexthunk)
499 (and nextfile (> nexthunk nextfile))))
1eabc5e6 500 ;; It's the only hunk for this file, so kill the file.
d87e5627 501 (diff-file-kill)
610a6418
SM
502 (diff-end-of-hunk)
503 (kill-region start (point)))))
504
fd691799
SM
505(defun diff-beginning-of-file-and-junk ()
506 "Go to the beginning of file-related diff-info.
507This is like `diff-beginning-of-file' except it tries to skip back over leading
508data such as \"Index: ...\" and such."
4c969f97
SM
509 (let* ((start (point))
510 (prevfile (condition-case err
511 (save-excursion (diff-beginning-of-file) (point))
512 (error err)))
513 (err (if (consp prevfile) prevfile))
514 (nextfile (ignore-errors
515 (save-excursion
516 (goto-char start) (diff-file-next) (point))))
517 ;; prevhunk is one of the limits.
518 (prevhunk (save-excursion
519 (ignore-errors
520 (if (numberp prevfile) (goto-char prevfile))
521 (diff-hunk-prev) (point))))
522 (previndex (save-excursion
523 (re-search-backward "^Index: " prevhunk t))))
524 ;; If we're in the junk, we should use nextfile instead of prevfile.
525 (if (and (numberp nextfile)
526 (or (not (numberp prevfile))
527 (and previndex (> previndex prevfile))))
528 (setq prevfile nextfile))
529 (if (and previndex (numberp prevfile) (< previndex prevfile))
530 (setq prevfile previndex))
531 (if (and (numberp prevfile) (<= prevfile start))
532 (goto-char prevfile)
533 ;; File starts *after* the starting point: we really weren't in
534 ;; a file diff but elsewhere.
535 (goto-char start)
536 (signal (car err) (cdr err)))))
fd691799 537
d87e5627 538(defun diff-file-kill ()
610a6418
SM
539 "Kill current file's hunks."
540 (interactive)
fd691799 541 (diff-beginning-of-file-and-junk)
610a6418 542 (let* ((start (point))
dd24cb37 543 (inhibit-read-only t))
610a6418 544 (diff-end-of-file)
22cd1973 545 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
610a6418
SM
546 (kill-region start (point))))
547
fef8c55b
SM
548(defun diff-kill-junk ()
549 "Kill spurious empty diffs."
550 (interactive)
551 (save-excursion
552 (let ((inhibit-read-only t))
553 (goto-char (point-min))
554 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
555 "\\([^-+!* <>].*\n\\)*?"
556 "\\(\\(Index:\\) \\|"
557 diff-file-header-re "\\)")
558 nil t)
559 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
560 (match-beginning 3))
561 (beginning-of-line)))))
562
cd632e57
SM
563(defun diff-count-matches (re start end)
564 (save-excursion
565 (let ((n 0))
566 (goto-char start)
567 (while (re-search-forward re end t) (incf n))
568 n)))
569
f151b310
SM
570(defun diff-splittable-p ()
571 (save-excursion
572 (beginning-of-line)
573 (and (looking-at "^[-+ ]")
574 (progn (forward-line -1) (looking-at "^[-+ ]"))
575 (diff-unified-hunk-p))))
576
cd632e57
SM
577(defun diff-split-hunk ()
578 "Split the current (unified diff) hunk at point into two hunks."
579 (interactive)
580 (beginning-of-line)
581 (let ((pos (point))
582 (start (progn (diff-beginning-of-hunk) (point))))
583 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
584 (error "diff-split-hunk only works on unified context diffs"))
585 (forward-line 1)
586 (let* ((start1 (string-to-number (match-string 1)))
587 (start2 (string-to-number (match-string 2)))
588 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
dd24cb37
CY
589 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos)))
590 (inhibit-read-only t))
cd632e57
SM
591 (goto-char pos)
592 ;; Hopefully the after-change-function will not screw us over.
593 (insert "@@ -" (number-to-string newstart1) ",1 +"
594 (number-to-string newstart2) ",1 @@\n")
595 ;; Fix the original hunk-header.
596 (diff-fixup-modifs start pos))))
71296446 597
cd632e57 598
610a6418
SM
599;;;;
600;;;; jump to other buffers
601;;;;
602
0b82e382
SM
603(defvar diff-remembered-files-alist nil)
604
610a6418
SM
605(defun diff-filename-drop-dir (file)
606 (when (string-match "/" file) (substring file (match-end 0))))
607
0b82e382
SM
608(defun diff-merge-strings (ancestor from to)
609 "Merge the diff between ANCESTOR and FROM into TO.
610Returns the merged string if successful or nil otherwise.
d87e5627 611The strings are assumed not to contain any \"\\n\" (i.e. end of line).
0b82e382
SM
612If ANCESTOR = FROM, returns TO.
613If ANCESTOR = TO, returns FROM.
614The heuristic is simplistic and only really works for cases
615like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
616 ;; Ideally, we want:
617 ;; AMB ANB CMD -> CND
618 ;; but that's ambiguous if `foo' or `bar' is empty:
619 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
d87e5627 620 (let ((str (concat ancestor "\n" from "\n" to)))
0b82e382 621 (when (and (string-match (concat
d87e5627
SM
622 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
623 "\\1\\(.*\\)\\3\n"
0b82e382
SM
624 "\\(.*\\(\\2\\).*\\)\\'") str)
625 (equal to (match-string 5 str)))
626 (concat (substring str (match-beginning 5) (match-beginning 6))
627 (match-string 4 str)
628 (substring str (match-end 6) (match-end 5))))))
629
22cd1973
SM
630(defun diff-tell-file-name (old name)
631 "Tell Emacs where the find the source file of the current hunk.
632If the OLD prefix arg is passed, tell the file NAME of the old file."
633 (interactive
634 (let* ((old current-prefix-arg)
635 (fs (diff-hunk-file-names current-prefix-arg)))
636 (unless fs (error "No file name to look for"))
637 (list old (read-file-name (format "File for %s: " (car fs))
638 nil (diff-find-file-name old) t))))
639 (let ((fs (diff-hunk-file-names old)))
640 (unless fs (error "No file name to look for"))
641 (push (cons fs name) diff-remembered-files-alist)))
cfc80227 642
22cd1973
SM
643(defun diff-hunk-file-names (&optional old)
644 "Give the list of file names textually mentioned for the current hunk."
610a6418
SM
645 (save-excursion
646 (unless (looking-at diff-file-header-re)
647 (or (ignore-errors (diff-beginning-of-file))
648 (re-search-forward diff-file-header-re nil t)))
22cd1973 649 (let ((limit (save-excursion
610a6418 650 (condition-case ()
d87e5627 651 (progn (diff-hunk-prev) (point))
610a6418 652 (error (point-min)))))
22cd1973
SM
653 (header-files
654 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
655 (list (if old (match-string 1) (match-string 3))
656 (if old (match-string 3) (match-string 1)))
657 (forward-line 1) nil)))
658 (delq nil
659 (append
660 (when (and (not old)
661 (save-excursion
662 (re-search-backward "^Index: \\(.+\\)" limit t)))
663 (list (match-string 1)))
664 header-files
665 (when (re-search-backward
666 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
667 nil t)
668 (list (if old (match-string 2) (match-string 4))
669 (if old (match-string 4) (match-string 2)))))))))
670
e4456fdf 671(defun diff-find-file-name (&optional old batch prefix)
22cd1973 672 "Return the file corresponding to the current patch.
e78cf8e5 673Non-nil OLD means that we want the old file.
e4456fdf
SM
674Non-nil BATCH means to prefer returning an incorrect answer than to prompt
675the user.
e78cf8e5 676PREFIX is only used internally: don't use it."
22cd1973
SM
677 (save-excursion
678 (unless (looking-at diff-file-header-re)
679 (or (ignore-errors (diff-beginning-of-file))
680 (re-search-forward diff-file-header-re nil t)))
681 (let ((fs (diff-hunk-file-names old)))
e78cf8e5 682 (if prefix (setq fs (mapcar (lambda (f) (concat prefix f)) fs)))
610a6418 683 (or
0b82e382
SM
684 ;; use any previously used preference
685 (cdr (assoc fs diff-remembered-files-alist))
686 ;; try to be clever and use previous choices as an inspiration
687 (dolist (rf diff-remembered-files-alist)
688 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
689 (if (and newfile (file-exists-p newfile)) (return newfile))))
690 ;; look for each file in turn. If none found, try again but
691 ;; ignoring the first level of directory, ...
692 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
693 (file nil nil))
694 ((or (null files)
695 (setq file (do* ((files files (cdr files))
696 (file (car files) (car files)))
f9274544
GM
697 ;; Use file-regular-p to avoid
698 ;; /dev/null, directories, etc.
699 ((or (null file) (file-regular-p file))
0b82e382
SM
700 file))))
701 file))
702 ;; <foo>.rej patches implicitly apply to <foo>
610a6418
SM
703 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
704 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
705 (when (file-exists-p file) file)))
e78cf8e5
SM
706 ;; If we haven't found the file, maybe it's because we haven't paid
707 ;; attention to the PCL-CVS hint.
708 (and (not prefix)
709 (boundp 'cvs-pcl-cvs-dirchange-re)
710 (save-excursion
711 (re-search-backward cvs-pcl-cvs-dirchange-re nil t))
e4456fdf
SM
712 (diff-find-file-name old batch (match-string 1)))
713 ;; Invent something, if necessary.
714 (when batch
715 (or (car fs) default-directory))
0b82e382
SM
716 ;; if all else fails, ask the user
717 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
718 nil (first fs) t (first fs))))
719 (set (make-local-variable 'diff-remembered-files-alist)
720 (cons (cons fs file) diff-remembered-files-alist))
610a6418
SM
721 file)))))
722
1b1b5dae 723
610a6418
SM
724(defun diff-ediff-patch ()
725 "Call `ediff-patch-file' on the current buffer."
726 (interactive)
727 (condition-case err
0e104800 728 (ediff-patch-file nil (current-buffer))
610a6418
SM
729 (wrong-number-of-arguments (ediff-patch-file))))
730
71296446 731;;;;
610a6418 732;;;; Conversion functions
71296446 733;;;;
610a6418
SM
734
735;;(defvar diff-inhibit-after-change nil
736;; "Non-nil means inhibit `diff-mode's after-change functions.")
737
738(defun diff-unified->context (start end)
739 "Convert unified diffs to context diffs.
740START and END are either taken from the region (if a prefix arg is given) or
dfbd373d 741else cover the whole buffer."
a70b0ff8
JL
742 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
743 (list (region-beginning) (region-end))
610a6418 744 (list (point-min) (point-max))))
e78cf8e5 745 (unless (markerp end) (setq end (copy-marker end t)))
610a6418
SM
746 (let (;;(diff-inhibit-after-change t)
747 (inhibit-read-only t))
748 (save-excursion
749 (goto-char start)
c0078a04 750 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
610a6418
SM
751 (< (point) end))
752 (combine-after-change-calls
753 (if (match-beginning 2)
0e104800 754 ;; we matched a file header
610a6418
SM
755 (progn
756 ;; use reverse order to make sure the indices are kept valid
757 (replace-match "---" t t nil 3)
758 (replace-match "***" t t nil 2))
759 ;; we matched a hunk header
760 (let ((line1 (match-string 4))
761 (lines1 (match-string 5))
762 (line2 (match-string 6))
3dc04e83
SM
763 (lines2 (match-string 7))
764 ;; Variables to use the special undo function.
765 (old-undo buffer-undo-list)
766 (old-end (marker-position end))
767 (start (match-beginning 0))
768 (reversible t))
610a6418
SM
769 (replace-match
770 (concat "***************\n*** " line1 ","
771 (number-to-string (+ (string-to-number line1)
772 (string-to-number lines1)
773 -1)) " ****"))
774 (forward-line 1)
775 (save-restriction
776 (narrow-to-region (point)
777 (progn (diff-end-of-hunk 'unified) (point)))
778 (let ((hunk (buffer-string)))
779 (goto-char (point-min))
780 (if (not (save-excursion (re-search-forward "^-" nil t)))
781 (delete-region (point) (point-max))
782 (goto-char (point-max))
783 (let ((modif nil) last-pt)
784 (while (progn (setq last-pt (point))
785 (= (forward-line -1) 0))
786 (case (char-after)
bdad2e31 787 (?\s (insert " ") (setq modif nil) (backward-char 1))
610a6418
SM
788 (?+ (delete-region (point) last-pt) (setq modif t))
789 (?- (if (not modif)
790 (progn (forward-char 1)
791 (insert " "))
792 (delete-char 1)
793 (insert "! "))
794 (backward-char 2))
795 (?\\ (when (save-excursion (forward-line -1)
796 (= (char-after) ?+))
797 (delete-region (point) last-pt) (setq modif t)))
798 (t (setq modif nil))))))
799 (goto-char (point-max))
800 (save-excursion
801 (insert "--- " line2 ","
802 (number-to-string (+ (string-to-number line2)
803 (string-to-number lines2)
804 -1)) " ----\n" hunk))
805 ;;(goto-char (point-min))
806 (forward-line 1)
807 (if (not (save-excursion (re-search-forward "^+" nil t)))
808 (delete-region (point) (point-max))
809 (let ((modif nil) (delete nil))
3dc04e83
SM
810 (if (save-excursion (re-search-forward "^\\+.*\n-" nil t))
811 ;; Normally, lines in a substitution come with
812 ;; first the removals and then the additions, and
813 ;; the context->unified function follows this
814 ;; convention, of course. Yet, other alternatives
815 ;; are valid as well, but they preclude the use of
816 ;; context->unified as an undo command.
817 (setq reversible nil))
610a6418
SM
818 (while (not (eobp))
819 (case (char-after)
bdad2e31 820 (?\s (insert " ") (setq modif nil) (backward-char 1))
610a6418
SM
821 (?- (setq delete t) (setq modif t))
822 (?+ (if (not modif)
823 (progn (forward-char 1)
824 (insert " "))
825 (delete-char 1)
826 (insert "! "))
827 (backward-char 2))
828 (?\\ (when (save-excursion (forward-line 1)
829 (not (eobp)))
830 (setq delete t) (setq modif t)))
831 (t (setq modif nil)))
832 (let ((last-pt (point)))
833 (forward-line 1)
834 (when delete
835 (delete-region last-pt (point))
3dc04e83
SM
836 (setq delete nil)))))))
837 (unless (or (not reversible) (eq buffer-undo-list t))
838 ;; Drop the many undo entries and replace them with
839 ;; a single entry that uses diff-context->unified to do
840 ;; the work.
841 (setq buffer-undo-list
842 (cons (list 'apply (- old-end end) start (point-max)
843 'diff-context->unified start (point-max))
844 old-undo)))))))))))
610a6418 845
28408bfd 846(defun diff-context->unified (start end &optional to-context)
610a6418 847 "Convert context diffs to unified diffs.
28408bfd
RS
848START and END are either taken from the region
849\(when it is highlighted) or else cover the whole buffer.
850With a prefix argument, convert unified format to context format."
851 (interactive (if (and transient-mark-mode mark-active)
a70b0ff8 852 (list (region-beginning) (region-end) current-prefix-arg)
28408bfd
RS
853 (list (point-min) (point-max) current-prefix-arg)))
854 (if to-context
855 (diff-unified->context start end)
e78cf8e5 856 (unless (markerp end) (setq end (copy-marker end t)))
28408bfd 857 (let ( ;;(diff-inhibit-after-change t)
be36f934 858 (inhibit-read-only t))
28408bfd 859 (save-excursion
be36f934
SM
860 (goto-char start)
861 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
862 (< (point) end))
863 (combine-after-change-calls
864 (if (match-beginning 2)
865 ;; we matched a file header
866 (progn
867 ;; use reverse order to make sure the indices are kept valid
868 (replace-match "+++" t t nil 3)
869 (replace-match "---" t t nil 2))
870 ;; we matched a hunk header
871 (let ((line1s (match-string 4))
872 (line1e (match-string 5))
873 (pt1 (match-beginning 0))
874 ;; Variables to use the special undo function.
875 (old-undo buffer-undo-list)
876 (old-end (marker-position end))
877 (reversible t))
878 (replace-match "")
879 (unless (re-search-forward
880 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
881 (error "Can't find matching `--- n1,n2 ----' line"))
882 (let ((line2s (match-string 1))
883 (line2e (match-string 2))
884 (pt2 (progn
885 (delete-region (progn (beginning-of-line) (point))
886 (progn (forward-line 1) (point)))
887 (point-marker))))
888 (goto-char pt1)
889 (forward-line 1)
890 (while (< (point) pt2)
891 (case (char-after)
892 (?! (delete-char 2) (insert "-") (forward-line 1))
893 (?- (forward-char 1) (delete-char 1) (forward-line 1))
894 (?\s ;merge with the other half of the chunk
895 (let* ((endline2
896 (save-excursion
897 (goto-char pt2) (forward-line 1) (point))))
898 (case (char-after pt2)
899 ((?! ?+)
900 (insert "+"
901 (prog1 (buffer-substring (+ pt2 2) endline2)
902 (delete-region pt2 endline2))))
903 (?\s
904 (unless (= (- endline2 pt2)
905 (- (line-beginning-position 2) (point)))
906 ;; If the two lines we're merging don't have the
907 ;; same length (can happen with "diff -b"), then
908 ;; diff-unified->context will not properly undo
909 ;; this operation.
910 (setq reversible nil))
911 (delete-region pt2 endline2)
912 (delete-char 1)
913 (forward-line 1))
914 (?\\ (forward-line 1))
915 (t (setq reversible nil)
916 (delete-char 1) (forward-line 1)))))
917 (t (setq reversible nil) (forward-line 1))))
918 (while (looking-at "[+! ] ")
919 (if (/= (char-after) ?!) (forward-char 1)
920 (delete-char 1) (insert "+"))
921 (delete-char 1) (forward-line 1))
922 (save-excursion
923 (goto-char pt1)
924 (insert "@@ -" line1s ","
925 (number-to-string (- (string-to-number line1e)
926 (string-to-number line1s)
927 -1))
928 " +" line2s ","
929 (number-to-string (- (string-to-number line2e)
930 (string-to-number line2s)
931 -1)) " @@"))
932 (set-marker pt2 nil)
933 ;; The whole procedure succeeded, let's replace the myriad
934 ;; of undo elements with just a single special one.
935 (unless (or (not reversible) (eq buffer-undo-list t))
936 (setq buffer-undo-list
937 (cons (list 'apply (- old-end end) pt1 (point)
938 'diff-unified->context pt1 (point))
939 old-undo)))
940 )))))))))
610a6418
SM
941
942(defun diff-reverse-direction (start end)
943 "Reverse the direction of the diffs.
944START and END are either taken from the region (if a prefix arg is given) or
dfbd373d 945else cover the whole buffer."
a70b0ff8
JL
946 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
947 (list (region-beginning) (region-end))
610a6418 948 (list (point-min) (point-max))))
e78cf8e5 949 (unless (markerp end) (setq end (copy-marker end t)))
610a6418
SM
950 (let (;;(diff-inhibit-after-change t)
951 (inhibit-read-only t))
952 (save-excursion
953 (goto-char start)
c0078a04 954 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
610a6418
SM
955 (< (point) end))
956 (combine-after-change-calls
957 (cond
958 ;; a file header
959 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
960 ;; a context-diff hunk header
961 ((match-beginning 6)
962 (let ((pt-lines1 (match-beginning 6))
963 (lines1 (match-string 6)))
964 (replace-match "" nil nil nil 6)
965 (forward-line 1)
966 (let ((half1s (point)))
0e104800 967 (while (looking-at "[-! \\][ \t]\\|#")
610a6418
SM
968 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
969 (forward-line 1))
fef8c55b 970 (let ((half1 (delete-and-extract-region half1s (point))))
610a6418
SM
971 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
972 (insert half1)
973 (error "Can't find matching `--- n1,n2 ----' line"))
974 (let ((str1 (match-string 1)))
975 (replace-match lines1 nil nil nil 1)
976 (forward-line 1)
977 (let ((half2s (point)))
0e104800 978 (while (looking-at "[!+ \\][ \t]\\|#")
610a6418
SM
979 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
980 (forward-line 1))
fef8c55b 981 (let ((half2 (delete-and-extract-region half2s (point))))
0e104800 982 (insert (or half1 ""))
610a6418 983 (goto-char half1s)
0e104800 984 (insert (or half2 ""))))
610a6418
SM
985 (goto-char pt-lines1)
986 (insert str1))))))
987 ;; a unified-diff hunk header
988 ((match-beginning 7)
989 (replace-match "@@ -\\8 +\\7 @@" nil)
990 (forward-line 1)
991 (let ((c (char-after)) first last)
992 (while (case (setq c (char-after))
993 (?- (setq first (or first (point)))
994 (delete-char 1) (insert "+") t)
995 (?+ (setq last (or last (point)))
996 (delete-char 1) (insert "-") t)
0e104800 997 ((?\\ ?#) t)
610a6418 998 (t (when (and first last (< first last))
cb4e8176 999 (insert (delete-and-extract-region first last)))
610a6418 1000 (setq first nil last nil)
aa753196 1001 (equal ?\s c)))
610a6418
SM
1002 (forward-line 1))))))))))
1003
1004(defun diff-fixup-modifs (start end)
1005 "Fixup the hunk headers (in case the buffer was modified).
1006START and END are either taken from the region (if a prefix arg is given) or
dfbd373d 1007else cover the whole buffer."
a70b0ff8
JL
1008 (interactive (if (or current-prefix-arg (and transient-mark-mode mark-active))
1009 (list (region-beginning) (region-end))
610a6418
SM
1010 (list (point-min) (point-max))))
1011 (let ((inhibit-read-only t))
1012 (save-excursion
1013 (goto-char end) (diff-end-of-hunk)
1014 (let ((plus 0) (minus 0) (space 0) (bang 0))
1015 (while (and (= (forward-line -1) 0) (<= start (point)))
bd9d7d76
SM
1016 (if (not (looking-at
1017 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
1018 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
1019 "\\|--- .+\n\\+\\+\\+ ")))
610a6418 1020 (case (char-after)
bd9d7d76 1021 (?\s (incf space))
610a6418
SM
1022 (?+ (incf plus))
1023 (?- (incf minus))
1024 (?! (incf bang))
0e104800 1025 ((?\\ ?#) nil)
610a6418
SM
1026 (t (setq space 0 plus 0 minus 0 bang 0)))
1027 (cond
c0078a04 1028 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
610a6418
SM
1029 (let* ((old1 (match-string 1))
1030 (old2 (match-string 2))
1031 (new1 (number-to-string (+ space minus)))
1032 (new2 (number-to-string (+ space plus))))
1033 (unless (string= new2 old2) (replace-match new2 t t nil 2))
1034 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
1035 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
1036 (when (> (+ space bang plus) 0)
1037 (let* ((old1 (match-string 1))
1038 (old2 (match-string 2))
1039 (new (number-to-string
1040 (+ space bang plus -1 (string-to-number old1)))))
1041 (unless (string= new old2) (replace-match new t t nil 2)))))
1042 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
1043 (when (> (+ space bang minus) 0)
1044 (let* ((old (match-string 1))
1045 (new (format
1046 (concat "%0" (number-to-string (length old)) "d")
1047 (+ space bang minus -1 (string-to-number old)))))
1048 (unless (string= new old) (replace-match new t t nil 2))))))
1049 (setq space 0 plus 0 minus 0 bang 0)))))))
1050
71296446 1051;;;;
610a6418 1052;;;; Hooks
71296446 1053;;;;
610a6418
SM
1054
1055(defun diff-write-contents-hooks ()
1056 "Fixup hunk headers if necessary."
1057 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
1058 nil)
1059
610a6418
SM
1060;; It turns out that making changes in the buffer from within an
1061;; *-change-function is asking for trouble, whereas making them
1062;; from a post-command-hook doesn't pose much problems
1063(defvar diff-unhandled-changes nil)
1064(defun diff-after-change-function (beg end len)
1065 "Remember to fixup the hunk header.
1066See `after-change-functions' for the meaning of BEG, END and LEN."
c0078a04
SM
1067 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
1068 ;; incorrect, but it turns out that inhibit-read-only is normally not set
1069 ;; inside editing commands, while it tends to be set when the buffer gets
1070 ;; updated by an async process or by a conversion function, both of which
1071 ;; would rather not be uselessly slowed down by this hook.
610a6418
SM
1072 (when (and (not undo-in-progress) (not inhibit-read-only))
1073 (if diff-unhandled-changes
1074 (setq diff-unhandled-changes
1075 (cons (min beg (car diff-unhandled-changes))
cb4e8176 1076 (max end (cdr diff-unhandled-changes))))
610a6418
SM
1077 (setq diff-unhandled-changes (cons beg end)))))
1078
1079(defun diff-post-command-hook ()
1080 "Fixup hunk headers if necessary."
1081 (when (consp diff-unhandled-changes)
1082 (ignore-errors
1083 (save-excursion
fef8c55b 1084 (goto-char (car diff-unhandled-changes))
cb4e8176
SM
1085 ;; Maybe we've cut the end of the hunk before point.
1086 (if (and (bolp) (not (bobp))) (backward-char 1))
1eabc5e6
SM
1087 ;; We used to fixup modifs on all the changes, but it turns out
1088 ;; that it's safer not to do it on big changes, for example
1089 ;; when yanking a big diff, since we might then screw up perfectly
1090 ;; correct values. -stef
1091 ;; (unless (ignore-errors
1092 ;; (diff-beginning-of-hunk)
1093 ;; (save-excursion
1094 ;; (diff-end-of-hunk)
1095 ;; (> (point) (car diff-unhandled-changes))))
1096 ;; (goto-char (car diff-unhandled-changes))
1097 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
1098 ;; (diff-beginning-of-hunk))
1099 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
1100 (diff-beginning-of-hunk)
1101 (when (save-excursion
1102 (diff-end-of-hunk)
cb4e8176 1103 (>= (point) (cdr diff-unhandled-changes)))
1eabc5e6 1104 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
610a6418
SM
1105 (setq diff-unhandled-changes nil)))
1106
6fc049f6
SM
1107(defun diff-next-error (arg reset)
1108 ;; Select a window that displays the current buffer so that point
1109 ;; movements are reflected in that window. Otherwise, the user might
1110 ;; never see the hunk corresponding to the source she's jumping to.
1111 (pop-to-buffer (current-buffer))
1112 (if reset (goto-char (point-min)))
1113 (diff-hunk-next arg)
1114 (diff-goto-source))
610a6418 1115
610a6418 1116;;;###autoload
d87e5627 1117(define-derived-mode diff-mode fundamental-mode "Diff"
0b82e382 1118 "Major mode for viewing/editing context diffs.
769dd0f1 1119Supports unified and context diffs as well as (to a lesser extent)
6035b97e 1120normal diffs.
b64d66b5 1121
df52e0e7 1122When the buffer is read-only, the ESC prefix is not necessary.
3b696504 1123If you edit the buffer manually, diff-mode will try to update the hunk
df52e0e7
SM
1124headers for you on-the-fly.
1125
1126You can also switch between context diff and unified diff with \\[diff-context->unified],
72147c53 1127or vice versa with \\[diff-unified->context] and you can also reverse the direction of
e78cf8e5 1128a diff with \\[diff-reverse-direction].
b64d66b5 1129
b64d66b5
RS
1130 \\{diff-mode-map}"
1131
610a6418
SM
1132 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
1133 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
ccce6558
DL
1134 (set (make-local-variable 'imenu-generic-expression)
1135 diff-imenu-generic-expression)
19e713d8
DL
1136 ;; These are not perfect. They would be better done separately for
1137 ;; context diffs and unidiffs.
1138 ;; (set (make-local-variable 'paragraph-start)
1139 ;; (concat "@@ " ; unidiff hunk
1140 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
1141 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
1142 ;; ; start (first or second line)
1143 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
1144 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
1145 ;; compile support
6fc049f6 1146 (set (make-local-variable 'next-error-function) 'diff-next-error)
cdbb79c1 1147
53dd481c 1148 (setq buffer-read-only diff-default-read-only)
769dd0f1 1149 ;; setup change hooks
e8a1ed31 1150 (if (not diff-update-on-the-fly)
3ccdb14e 1151 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
610a6418 1152 (make-local-variable 'diff-unhandled-changes)
3cec9c57
SM
1153 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1154 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
610a6418 1155 ;; Neat trick from Dave Love to add more bindings in read-only mode:
e78cf8e5 1156 (lexical-let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
22cd1973
SM
1157 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
1158 ;; Turn off this little trick in case the buffer is put in view-mode.
1159 (add-hook 'view-mode-hook
e78cf8e5
SM
1160 (lambda ()
1161 (setq minor-mode-overriding-map-alist
1162 (delq ro-bind minor-mode-overriding-map-alist)))
22cd1973 1163 nil t))
281096ed
SM
1164 ;; add-log support
1165 (set (make-local-variable 'add-log-current-defun-function)
1166 'diff-current-defun)
1b1b5dae
SM
1167 (set (make-local-variable 'add-log-buffer-file-name-function)
1168 'diff-find-file-name))
610a6418
SM
1169
1170;;;###autoload
0b82e382
SM
1171(define-minor-mode diff-minor-mode
1172 "Minor mode for viewing/editing context diffs.
1173\\{diff-minor-mode-map}"
cfc80227 1174 :group 'diff-mode :lighter " Diff"
0b82e382 1175 ;; FIXME: setup font-lock
fef8c55b 1176 ;; setup change hooks
e8a1ed31 1177 (if (not diff-update-on-the-fly)
3ccdb14e 1178 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
fef8c55b 1179 (make-local-variable 'diff-unhandled-changes)
3cec9c57
SM
1180 (add-hook 'after-change-functions 'diff-after-change-function nil t)
1181 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
0b82e382 1182
e78cf8e5 1183;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22cd1973
SM
1184
1185(defun diff-delete-if-empty ()
1186 ;; An empty diff file means there's no more diffs to integrate, so we
1187 ;; can just remove the file altogether. Very handy for .rej files if we
1188 ;; remove hunks as we apply them.
1189 (when (and buffer-file-name
1190 (eq 0 (nth 7 (file-attributes buffer-file-name))))
1191 (delete-file buffer-file-name)))
1192
1193(defun diff-delete-empty-files ()
1194 "Arrange for empty diff files to be removed."
1195 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
1196
1197(defun diff-make-unified ()
1198 "Turn context diffs into unified diffs if applicable."
1199 (if (save-excursion
1200 (goto-char (point-min))
4c174fb4 1201 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
22cd1973
SM
1202 (let ((mod (buffer-modified-p)))
1203 (unwind-protect
1204 (diff-context->unified (point-min) (point-max))
1205 (restore-buffer-modified-p mod)))))
610a6418 1206
027ac3f8
SM
1207;;;
1208;;; Misc operations that have proved useful at some point.
1209;;;
1210
1211(defun diff-next-complex-hunk ()
1212 "Jump to the next \"complex\" hunk.
1213\"Complex\" is approximated by \"the hunk changes the number of lines\".
1214Only works for unified diffs."
1215 (interactive)
1216 (while
1217 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1218 nil t)
1219 (equal (match-string 1) (match-string 2)))))
1220
3a349573
SM
1221(defun diff-sanity-check-context-hunk-half (lines)
1222 (let ((count lines))
1223 (while
1224 (cond
1225 ((and (memq (char-after) '(?\s ?! ?+ ?-))
1226 (memq (char-after (1+ (point))) '(?\s ?\t)))
1227 (decf count) t)
1228 ((or (zerop count) (= count lines)) nil)
1229 ((memq (char-after) '(?! ?+ ?-))
1230 (if (not (and (eq (char-after (1+ (point))) ?\n)
1231 (y-or-n-p "Try to auto-fix whitespace loss damage? ")))
1232 (error "End of hunk ambiguously marked")
1233 (forward-char 1) (insert " ") (forward-line -1) t))
1234 ((< lines 0)
1235 (error "End of hunk ambiguously marked"))
1236 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1237 (error "Abort!"))
1238 ((eolp) (insert " ") (forward-line -1) t)
1239 (t (insert " ") (delete-region (- (point) 2) (- (point) 1)) t))
1240 (forward-line))))
1241
1242(defun diff-sanity-check-hunk ()
1243 (let (;; Every modification is protected by a y-or-n-p, so it's probably
1244 ;; OK to override a read-only setting.
1245 (inhibit-read-only t))
1246 (save-excursion
1247 (cond
1248 ((not (looking-at diff-hunk-header-re))
1249 (error "Not recognizable hunk header"))
1250
1251 ;; A context diff.
1252 ((eq (char-after) ?*)
7fb6ce6e 1253 (if (not (looking-at "\\*\\{15\\}\\(?: .*\\)?\n\\*\\*\\* \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? \\*\\*\\*\\*"))
3a349573
SM
1254 (error "Unrecognized context diff first hunk header format")
1255 (forward-line 2)
1256 (diff-sanity-check-context-hunk-half
7fb6ce6e
TTN
1257 (if (match-string 2)
1258 (1+ (- (string-to-number (match-string 2))
1259 (string-to-number (match-string 1))))
1260 1))
1261 (if (not (looking-at "--- \\([0-9]+\\)\\(?:,\\([0-9]+\\)\\)? ----$"))
3a349573
SM
1262 (error "Unrecognized context diff second hunk header format")
1263 (forward-line)
1264 (diff-sanity-check-context-hunk-half
7fb6ce6e
TTN
1265 (if (match-string 2)
1266 (1+ (- (string-to-number (match-string 2))
1267 (string-to-number (match-string 1))))
1268 1)))))
3a349573
SM
1269
1270 ;; A unified diff.
1271 ((eq (char-after) ?@)
1272 (if (not (looking-at
7fb6ce6e 1273 "@@ -[0-9]+\\(?:,\\([0-9]+\\)\\)? \\+[0-9]+\\(?:,\\([0-9]+\\)\\)? @@"))
3a349573 1274 (error "Unrecognized unified diff hunk header format")
7fb6ce6e
TTN
1275 (let ((before (if (match-string 1) (string-to-number (match-string 1)) 1))
1276 (after (if (match-string 2) (string-to-number (match-string 2)) 1)))
3a349573
SM
1277 (forward-line)
1278 (while
1279 (case (char-after)
1280 (?\s (decf before) (decf after) t)
80a01d97
SM
1281 (?-
1282 (if (and (looking-at diff-file-header-re)
1283 (zerop before) (zerop after))
1284 ;; No need to query: this is a case where two patches
1285 ;; are concatenated and only counting the lines will
1286 ;; give the right result. Let's just add an empty
1287 ;; line so that our code which doesn't count lines
1288 ;; will not get confused.
1289 (progn (save-excursion (insert "\n")) nil)
1290 (decf before) t))
3a349573
SM
1291 (?+ (decf after) t)
1292 (t
1293 (cond
1294 ((and (zerop before) (zerop after)) nil)
1295 ((or (< before 0) (< after 0))
1296 (error (if (or (zerop before) (zerop after))
1297 "End of hunk ambiguously marked"
1298 "Hunk seriously messed up")))
1299 ((not (y-or-n-p "Try to auto-fix whitespace loss and word-wrap damage? "))
1300 (error "Abort!"))
1301 ((eolp) (insert " ") (forward-line -1) t)
1302 (t (insert " ")
1303 (delete-region (- (point) 2) (- (point) 1)) t))))
1304 (forward-line)))))
1305
1306 ;; A plain diff.
1307 (t
1308 ;; TODO.
1309 )))))
1310
1eabc5e6
SM
1311(defun diff-hunk-text (hunk destp char-offset)
1312 "Return the literal source text from HUNK as (TEXT . OFFSET).
a70b0ff8 1313If DESTP is nil, TEXT is the source, otherwise the destination text.
1eabc5e6
SM
1314CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1315char-offset in TEXT."
3017133f 1316 (with-temp-buffer
6e4e8a3b
SM
1317 (insert hunk)
1318 (goto-char (point-min))
1319 (let ((src-pos nil)
1320 (dst-pos nil)
1321 (divider-pos nil)
1322 (num-pfx-chars 2))
1323 ;; Set the following variables:
1324 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1325 ;; DST-POS buffer pos of the destination part of the hunk or nil
1326 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1327 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1328 (cond ((looking-at "^@@")
1329 ;; unified diff
1330 (setq num-pfx-chars 1)
1331 (forward-line 1)
1332 (setq src-pos (point) dst-pos (point)))
1333 ((looking-at "^\\*\\*")
1334 ;; context diff
1335 (forward-line 2)
1336 (setq src-pos (point))
1337 (re-search-forward "^--- " nil t)
1338 (forward-line 0)
1339 (setq divider-pos (point))
1340 (forward-line 1)
1341 (setq dst-pos (point)))
1342 ((looking-at "^[0-9]+a[0-9,]+$")
1343 ;; normal diff, insert
1344 (forward-line 1)
1345 (setq dst-pos (point)))
1346 ((looking-at "^[0-9,]+d[0-9]+$")
1347 ;; normal diff, delete
1348 (forward-line 1)
1349 (setq src-pos (point)))
1350 ((looking-at "^[0-9,]+c[0-9,]+$")
1351 ;; normal diff, change
1352 (forward-line 1)
1353 (setq src-pos (point))
1354 (re-search-forward "^---$" nil t)
1355 (forward-line 0)
1356 (setq divider-pos (point))
1357 (forward-line 1)
1358 (setq dst-pos (point)))
1359 (t
1360 (error "Unknown diff hunk type")))
1361
1362 (if (if destp (null dst-pos) (null src-pos))
1363 ;; Implied empty text
1364 (if char-offset '("" . 0) "")
1365
1366 ;; For context diffs, either side can be empty, (if there's only
1367 ;; added or only removed text). We should then use the other side.
1368 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1369 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1370
1371 (when char-offset (goto-char (+ (point-min) char-offset)))
1372
1373 ;; Get rid of anything except the desired text.
1374 (save-excursion
1375 ;; Delete unused text region
1376 (let ((keep (if destp dst-pos src-pos)))
1377 (when (and divider-pos (> divider-pos keep))
1378 (delete-region divider-pos (point-max)))
1379 (delete-region (point-min) keep))
1380 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1381 (let ((kill-char (if destp ?- ?+)))
1382 (goto-char (point-min))
1383 (while (not (eobp))
1384 (if (eq (char-after) kill-char)
1385 (delete-region (point) (progn (forward-line 1) (point)))
1386 (delete-char num-pfx-chars)
1387 (forward-line 1)))))
1388
1389 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1390 (if char-offset (cons text (- (point) (point-min))) text))))))
370d860c 1391
7530b6da 1392
c0aa75f7 1393(defun diff-find-text (text)
1eabc5e6 1394 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
7530b6da 1395If TEXT isn't found, nil is returned."
7530b6da
MB
1396 (let* ((orig (point))
1397 (forw (and (search-forward text nil t)
1eabc5e6 1398 (cons (match-beginning 0) (match-end 0))))
7530b6da
MB
1399 (back (and (goto-char (+ orig (length text)))
1400 (search-backward text nil t)
1eabc5e6
SM
1401 (cons (match-beginning 0) (match-end 0)))))
1402 ;; Choose the closest match.
1403 (if (and forw back)
1404 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1405 (or back forw))))
1406
1407(defun diff-find-approx-text (text)
1408 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1409Whitespace differences are ignored."
1410 (let* ((orig (point))
1411 (re (concat "^[ \t\n\f]*"
1412 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1413 "[ \t\n\f]*\n"))
1414 (forw (and (re-search-forward re nil t)
1415 (cons (match-beginning 0) (match-end 0))))
1416 (back (and (goto-char (+ orig (length text)))
1417 (re-search-backward re nil t)
1418 (cons (match-beginning 0) (match-end 0)))))
1419 ;; Choose the closest match.
7530b6da 1420 (if (and forw back)
1eabc5e6 1421 (if (> (- (car forw) orig) (- orig (car back))) back forw)
7530b6da
MB
1422 (or back forw))))
1423
44a07c5a 1424(defsubst diff-xor (a b) (if a (if (not b) a) b))
370d860c 1425
d868b3bd 1426(defun diff-find-source-location (&optional other-file reverse)
1eabc5e6
SM
1427 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1428BUF is the buffer corresponding to the source file.
1429LINE-OFFSET is the offset between the expected and actual positions
1430 of the text of the hunk or nil if the text was not found.
1431POS is a pair (BEG . END) indicating the position of the text in the buffer.
1432SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1433 SRC is the variant that was found in the buffer.
1434SWITCHED is non-nil if the patch is already applied."
7b91e0f2 1435 (save-excursion
e8a1ed31 1436 (let* ((other (diff-xor other-file diff-jump-to-old-file))
fd691799
SM
1437 (char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1438 (point))))
3a349573
SM
1439 ;; Check that the hunk is well-formed. Otherwise diff-mode and
1440 ;; the user may disagree on what constitutes the hunk
1441 ;; (e.g. because an empty line truncates the hunk mid-course),
1442 ;; leading to potentially nasty surprises for the user.
1443 (_ (diff-sanity-check-hunk))
370d860c
SM
1444 (hunk (buffer-substring (point)
1445 (save-excursion (diff-end-of-hunk) (point))))
1446 (old (diff-hunk-text hunk reverse char-offset))
1447 (new (diff-hunk-text hunk (not reverse) char-offset))
7b91e0f2 1448 ;; Find the location specification.
d868b3bd 1449 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
370d860c
SM
1450 (error "Can't find the hunk header")
1451 (if other (match-string 1)
1452 (if (match-end 3) (match-string 3)
1453 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1454 (error "Can't find the hunk separator"))
1455 (match-string 1)))))
1456 (file (or (diff-find-file-name other) (error "Can't find the file")))
1457 (buf (find-file-noselect file)))
7b91e0f2
SM
1458 ;; Update the user preference if he so wished.
1459 (when (> (prefix-numeric-value other-file) 8)
e8a1ed31 1460 (setq diff-jump-to-old-file other))
d868b3bd
SM
1461 (with-current-buffer buf
1462 (goto-line (string-to-number line))
1463 (let* ((orig-pos (point))
1eabc5e6 1464 (switched nil)
22cd1973 1465 ;; FIXME: Check for case where both OLD and NEW are found.
1eabc5e6
SM
1466 (pos (or (diff-find-text (car old))
1467 (progn (setq switched t) (diff-find-text (car new)))
1468 (progn (setq switched nil)
22cd1973
SM
1469 (condition-case nil
1470 (diff-find-approx-text (car old))
1471 (invalid-regexp nil))) ;Regex too big.
1eabc5e6 1472 (progn (setq switched t)
22cd1973
SM
1473 (condition-case nil
1474 (diff-find-approx-text (car new))
1475 (invalid-regexp nil))) ;Regex too big.
1eabc5e6 1476 (progn (setq switched nil) nil))))
370d860c
SM
1477 (nconc
1478 (list buf)
1eabc5e6
SM
1479 (if pos
1480 (list (count-lines orig-pos (car pos)) pos)
1481 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
370d860c
SM
1482 (if switched (list new old t) (list old new))))))))
1483
7b91e0f2 1484
370d860c
SM
1485(defun diff-hunk-status-msg (line-offset reversed dry-run)
1486 (let ((msg (if dry-run
1487 (if reversed "already applied" "not yet applied")
1488 (if reversed "undone" "applied"))))
1489 (message (cond ((null line-offset) "Hunk text not found")
1490 ((= line-offset 0) "Hunk %s")
1491 ((= line-offset 1) "Hunk %s at offset %d line")
1492 (t "Hunk %s at offset %d lines"))
1493 msg line-offset)))
1494
cb9a30c8 1495(defvar diff-apply-hunk-to-backup-file nil)
370d860c
SM
1496
1497(defun diff-apply-hunk (&optional reverse)
6e4e8a3b 1498 "Apply the current hunk to the source file and go to the next.
7530b6da 1499By default, the new source file is patched, but if the variable
e8a1ed31 1500`diff-jump-to-old-file' is non-nil, then the old source file is
7530b6da
MB
1501patched instead (some commands, such as `diff-goto-source' can change
1502the value of this variable when given an appropriate prefix argument).
1503
4eaa6852 1504With a prefix argument, REVERSE the hunk."
370d860c 1505 (interactive "P")
281096ed 1506 (destructuring-bind (buf line-offset pos old new &optional switched)
44a07c5a
SM
1507 ;; Sometimes we'd like to have the following behavior: if REVERSE go
1508 ;; to the new file, otherwise go to the old. But that means that by
1509 ;; default we use the old file, which is the opposite of the default
1510 ;; for diff-goto-source, and is thus confusing. Also when you don't
1511 ;; know about it it's pretty surprising.
1512 ;; TODO: make it possible to ask explicitly for this behavior.
1513 ;;
1514 ;; This is duplicated in diff-test-hunk.
1515 (diff-find-source-location nil reverse)
370d860c 1516 (cond
4eaa6852
MB
1517 ((null line-offset)
1518 (error "Can't find the text to patch"))
cb9a30c8
SM
1519 ((with-current-buffer buf
1520 (and buffer-file-name
1521 (backup-file-name-p buffer-file-name)
1522 (not diff-apply-hunk-to-backup-file)
1523 (not (set (make-local-variable 'diff-apply-hunk-to-backup-file)
1524 (yes-or-no-p (format "Really apply this hunk to %s? "
1525 (file-name-nondirectory
1526 buffer-file-name)))))))
593b4fa8
AS
1527 (error "%s"
1528 (substitute-command-keys
cb9a30c8
SM
1529 (format "Use %s\\[diff-apply-hunk] to apply it to the other file"
1530 (if (not reverse) "\\[universal-argument] ")))))
370d860c 1531 ((and switched
cdbb79c1 1532 ;; A reversed patch was detected, perhaps apply it in reverse.
370d860c
SM
1533 (not (save-window-excursion
1534 (pop-to-buffer buf)
1eabc5e6 1535 (goto-char (+ (car pos) (cdr old)))
370d860c
SM
1536 (y-or-n-p
1537 (if reverse
1538 "Hunk hasn't been applied yet; apply it now? "
1539 "Hunk has already been applied; undo it? ")))))
4eaa6852 1540 (message "(Nothing done)"))
370d860c 1541 (t
4eaa6852
MB
1542 ;; Apply the hunk
1543 (with-current-buffer buf
1eabc5e6
SM
1544 (goto-char (car pos))
1545 (delete-region (car pos) (cdr pos))
4eaa6852
MB
1546 (insert (car new)))
1547 ;; Display BUF in a window
1eabc5e6 1548 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
4eaa6852
MB
1549 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1550 (when diff-advance-after-apply-hunk
1551 (diff-hunk-next))))))
370d860c 1552
7530b6da 1553
7530b6da
MB
1554(defun diff-test-hunk (&optional reverse)
1555 "See whether it's possible to apply the current hunk.
4eaa6852 1556With a prefix argument, try to REVERSE the hunk."
7530b6da 1557 (interactive "P")
370d860c 1558 (destructuring-bind (buf line-offset pos src dst &optional switched)
44a07c5a 1559 (diff-find-source-location nil reverse)
1eabc5e6 1560 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
4eaa6852 1561 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
370d860c 1562
7530b6da 1563
a1e2d7f7
SM
1564(defalias 'diff-mouse-goto-source 'diff-goto-source)
1565
1566(defun diff-goto-source (&optional other-file event)
7530b6da 1567 "Jump to the corresponding source line.
e8a1ed31 1568`diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
281096ed 1569is given) determines whether to jump to the old or the new file.
7530b6da 1570If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
a70b0ff8 1571then `diff-jump-to-old-file' is also set, for the next invocations."
a1e2d7f7 1572 (interactive (list current-prefix-arg last-input-event))
a6373340
SM
1573 ;; When pointing at a removal line, we probably want to jump to
1574 ;; the old location, and else to the new (i.e. as if reverting).
1575 ;; This is a convenient detail when using smerge-diff.
a1e2d7f7 1576 (if event (posn-set-point (event-end event)))
a6373340
SM
1577 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1578 (destructuring-bind (buf line-offset pos src dst &optional switched)
1579 (diff-find-source-location other-file rev)
1580 (pop-to-buffer buf)
1eabc5e6 1581 (goto-char (+ (car pos) (cdr src)))
55d5d717 1582 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
370d860c 1583
7530b6da 1584
281096ed 1585(defun diff-current-defun ()
370d860c
SM
1586 "Find the name of function at point.
1587For use in `add-log-current-defun-function'."
ef63ea1c
SM
1588 ;; Kill change-log-default-name so it gets recomputed each time, since
1589 ;; each hunk may belong to another file which may belong to another
1590 ;; directory and hence have a different ChangeLog file.
1591 (kill-local-variable 'change-log-default-name)
2f9edc8b
KG
1592 (save-excursion
1593 (when (looking-at diff-hunk-header-re)
1594 (forward-line 1)
4f815065 1595 (re-search-forward "^[^ ]" nil t))
2f9edc8b
KG
1596 (destructuring-bind (buf line-offset pos src dst &optional switched)
1597 (diff-find-source-location)
281096ed
SM
1598 (beginning-of-line)
1599 (or (when (memq (char-after) '(?< ?-))
370d860c
SM
1600 ;; Cursor is pointing at removed text. This could be a removed
1601 ;; function, in which case, going to the source buffer will
1602 ;; not help since the function is now removed. Instead,
1603 ;; try to figure out the function name just from the code-fragment.
281096ed
SM
1604 (let ((old (if switched dst src)))
1605 (with-temp-buffer
1606 (insert (car old))
281096ed 1607 (funcall (with-current-buffer buf major-mode))
cb4e8176 1608 (goto-char (+ (point-min) (cdr old)))
281096ed
SM
1609 (add-log-current-defun))))
1610 (with-current-buffer buf
1eabc5e6 1611 (goto-char (+ (car pos) (cdr src)))
281096ed 1612 (add-log-current-defun))))))
027ac3f8 1613
2659df68
SM
1614(defun diff-ignore-whitespace-hunk ()
1615 "Re-diff the current hunk, ignoring whitespace differences."
22cd1973 1616 (interactive)
fd691799
SM
1617 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk 'try-harder)
1618 (point))))
22cd1973
SM
1619 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1620 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1621 (error "Can't find line number"))
1622 (string-to-number (match-string 1))))
1623 (hunk (delete-and-extract-region
1624 (point) (save-excursion (diff-end-of-hunk) (point))))
1625 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1626 (file1 (make-temp-file "diff1"))
1627 (file2 (make-temp-file "diff2"))
1628 (coding-system-for-read buffer-file-coding-system)
dd24cb37 1629 (inhibit-read-only t)
22cd1973
SM
1630 old new)
1631 (unwind-protect
1632 (save-excursion
1633 (setq old (diff-hunk-text hunk nil char-offset))
1634 (setq new (diff-hunk-text hunk t char-offset))
1635 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1636 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1637 (with-temp-buffer
1638 (let ((status
1639 (call-process diff-command nil t nil
1640 opts file1 file2)))
1641 (case status
1642 (0 nil) ;Nothing to reformat.
1643 (1 (goto-char (point-min))
1644 ;; Remove the file-header.
1645 (when (re-search-forward diff-hunk-header-re nil t)
1646 (delete-region (point-min) (match-beginning 0))))
1647 (t (goto-char (point-max))
1648 (unless (bolp) (insert "\n"))
1649 (insert hunk)))
1650 (setq hunk (buffer-string))
1651 (unless (memq status '(0 1))
1652 (error "Diff returned: %s" status)))))
1653 ;; Whatever happens, put back some equivalent text: either the new
1654 ;; one or the original one in case some error happened.
1655 (insert hunk)
1656 (delete-file file1)
1657 (delete-file file2))))
1658
be36f934
SM
1659;;; Fine change highlighting.
1660
2659df68
SM
1661(defface diff-refine-change
1662 '((((class color) (min-colors 88) (background light))
1663 :background "grey90")
1664 (((class color) (min-colors 88) (background dark))
1665 :background "grey40")
1666 (((class color) (background light))
1667 :background "yellow")
1668 (((class color) (background dark))
1669 :background "green")
1670 (t :weight bold))
1671 "Face used for char-based changes shown by `diff-refine-hunk'."
5eee3c95 1672 :group 'diff-mode)
be36f934 1673
2659df68 1674(defun diff-refine-preproc ()
8872469d
SM
1675 (while (re-search-forward "^[+>]" nil t)
1676 ;; Remove spurious changes due to the fact that one side of the hunk is
1677 ;; marked with leading + or > and the other with leading - or <.
1678 ;; We used to replace all the prefix chars with " " but this only worked
1679 ;; when we did char-based refinement (or when using
1680 ;; smerge-refine-weight-hack) since otherwise, the `forward' motion done
1681 ;; in chopup do not necessarily do the same as the ones in highlight
1682 ;; since the "_" is not treated the same as " ".
1683 (replace-match (cdr (assq (char-before) '((?+ . "-") (?> . "<"))))))
1684 )
be36f934 1685
2659df68 1686(defun diff-refine-hunk ()
be36f934
SM
1687 "Highlight changes of hunk at point at a finer granularity."
1688 (interactive)
1689 (require 'smerge-mode)
8872469d
SM
1690 (save-excursion
1691 (diff-beginning-of-hunk 'try-harder)
1692 (let* ((style (diff-hunk-style)) ;Skips the hunk header as well.
1693 (beg (point))
2659df68 1694 (props '((diff-mode . fine) (face diff-refine-change)))
8872469d
SM
1695 (end (progn (diff-end-of-hunk) (point))))
1696
1697 (remove-overlays beg end 'diff-mode 'fine)
1698
1699 (goto-char beg)
1700 (case style
1701 (unified
1702 (while (re-search-forward "^\\(?:-.*\n\\)+\\(\\)\\(?:\\+.*\n\\)+"
1703 end t)
1704 (smerge-refine-subst (match-beginning 0) (match-end 1)
1705 (match-end 1) (match-end 0)
2659df68 1706 props 'diff-refine-preproc)))
8872469d
SM
1707 (context
1708 (let* ((middle (save-excursion (re-search-forward "^---")))
1709 (other middle))
1710 (while (re-search-forward "^\\(?:!.*\n\\)+" middle t)
1711 (smerge-refine-subst (match-beginning 0) (match-end 0)
1712 (save-excursion
1713 (goto-char other)
1714 (re-search-forward "^\\(?:!.*\n\\)+" end)
1715 (setq other (match-end 0))
1716 (match-beginning 0))
1717 other
2659df68 1718 props 'diff-refine-preproc))))
8872469d
SM
1719 (t ;; Normal diffs.
1720 (let ((beg1 (1+ (point))))
1721 (when (re-search-forward "^---.*\n" end t)
1722 ;; It's a combined add&remove, so there's something to do.
1723 (smerge-refine-subst beg1 (match-beginning 0)
1724 (match-end 0) end
2659df68 1725 props 'diff-refine-preproc))))))))
be36f934
SM
1726
1727
610a6418
SM
1728;; provide the package
1729(provide 'diff-mode)
1730
027ac3f8 1731;;; Old Change Log from when diff-mode wasn't part of Emacs:
610a6418
SM
1732;; Revision 1.11 1999/10/09 23:38:29 monnier
1733;; (diff-mode-load-hook): dropped.
1734;; (auto-mode-alist): also catch *.diffs.
1735;; (diff-find-file-name, diff-mode): add smarts to find the right file
1736;; for *.rej files (that lack any file name indication).
1737;;
1738;; Revision 1.10 1999/09/30 15:32:11 monnier
1739;; added support for "\ No newline at end of file".
1740;;
1741;; Revision 1.9 1999/09/15 00:01:13 monnier
1742;; - added basic `compile' support.
1743;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1744;; - diff-kill-file now tries to kill the leading garbage as well.
1745;;
1746;; Revision 1.8 1999/09/13 21:10:09 monnier
1747;; - don't use CL in the autoloaded code
1748;; - accept diffs using -T
1749;;
1750;; Revision 1.7 1999/09/05 20:53:03 monnier
1751;; interface to ediff-patch
1752;;
1753;; Revision 1.6 1999/09/01 20:55:13 monnier
1754;; (ediff=patch-file): add bindings to call ediff-patch.
1755;; (diff-find-file-name): taken out of diff-goto-source.
1756;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1757;; diff-fixup-modifs): only use the region if a prefix arg is given.
1758;;
1759;; Revision 1.5 1999/08/31 19:18:52 monnier
1760;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1761;;
1762;; Revision 1.4 1999/08/31 13:01:44 monnier
1763;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1764;;
1765
4f815065 1766;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
610a6418 1767;;; diff-mode.el ends here