Specify missing group (and type, if simple) in defcustom.
[bpt/emacs.git] / lisp / diff-mode.el
CommitLineData
b532d575 1;;; diff-mode.el --- a mode for viewing/editing context diffs
610a6418 2
cfc80227
LK
3;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
4;; Free Software Foundation, Inc.
610a6418
SM
5
6;; Author: Stefan Monnier <monnier@cs.yale.edu>
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
13;; the Free Software Foundation; either version 2, or (at your option)
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
23;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24;; Boston, MA 02111-1307, USA.
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".
49;;
50;; - Refine hunk on a word-by-word basis.
51;;
027ac3f8 52;; - Handle `diff -b' output in context->unified.
610a6418
SM
53
54;;; Code:
55
56(eval-when-compile (require 'cl))
57
58
59(defgroup diff-mode ()
3cec9c57 60 "Major mode for viewing/editing diffs"
ccce6558 61 :version "21.1"
610a6418
SM
62 :group 'tools
63 :group 'diff)
64
22cd1973 65(defcustom diff-default-read-only nil
769dd0f1
SM
66 "If non-nil, `diff-mode' buffers default to being read-only."
67 :type 'boolean
68 :group 'diff-mode)
69
e8a1ed31 70(defcustom diff-jump-to-old-file nil
610a6418
SM
71 "*Non-nil means `diff-goto-source' jumps to the old file.
72Else, it jumps to the new file."
f5307782
JB
73 :type 'boolean
74 :group 'diff-mode)
610a6418 75
e8a1ed31 76(defcustom diff-update-on-the-fly t
610a6418
SM
77 "*Non-nil means hunk headers are kept up-to-date on-the-fly.
78When editing a diff file, the line numbers in the hunk headers
79need to be kept consistent with the actual diff. This can
80either be done on the fly (but this sometimes interacts poorly with the
81undo mechanism) or whenever the file is written (can be slow
82when editing big diffs)."
f5307782
JB
83 :type 'boolean
84 :group 'diff-mode)
610a6418 85
00df919e
MB
86(defcustom diff-advance-after-apply-hunk t
87 "*Non-nil means `diff-apply-hunk' will move to the next hunk after applying."
f5307782
JB
88 :type 'boolean
89 :group 'diff-mode)
00df919e
MB
90
91
22cd1973
SM
92(defcustom diff-mode-hook nil
93 "Run after setting up the `diff-mode' major mode."
94 :type 'hook
f5307782
JB
95 :options '(diff-delete-empty-files diff-make-unified)
96 :group 'diff-mode)
610a6418
SM
97
98(defvar diff-outline-regexp
99 "\\([*+][*+][*+] [^0-9]\\|@@ ...\\|\\*\\*\\* [0-9].\\|--- [0-9]..\\)")
100
cd632e57 101;;;;
610a6418 102;;;; keymap, menu, ...
cd632e57 103;;;;
610a6418 104
d87e5627 105(easy-mmode-defmap diff-mode-shared-map
027ac3f8 106 '(;; From Pavel Machek's patch-mode.
d87e5627
SM
107 ("n" . diff-hunk-next)
108 ("N" . diff-file-next)
109 ("p" . diff-hunk-prev)
110 ("P" . diff-file-prev)
111 ("k" . diff-hunk-kill)
112 ("K" . diff-file-kill)
027ac3f8 113 ;; From compilation-minor-mode.
d87e5627
SM
114 ("}" . diff-file-next)
115 ("{" . diff-file-prev)
610a6418 116 ("\C-m" . diff-goto-source)
a1e2d7f7 117 ([mouse-2] . diff-goto-source)
027ac3f8 118 ;; From XEmacs' diff-mode.
610a6418
SM
119 ("W" . widen)
120 ;;("." . diff-goto-source) ;display-buffer
121 ;;("f" . diff-goto-source) ;find-file
122 ("o" . diff-goto-source) ;other-window
123 ;;("w" . diff-goto-source) ;other-frame
124 ;;("N" . diff-narrow)
125 ;;("h" . diff-show-header)
126 ;;("j" . diff-show-difference) ;jump to Nth diff
127 ;;("q" . diff-quit)
128 (" " . scroll-up)
129 ("\177" . scroll-down)
027ac3f8 130 ;; Our very own bindings.
610a6418
SM
131 ("A" . diff-ediff-patch)
132 ("r" . diff-restrict-view)
133 ("R" . diff-reverse-direction)
134 ("U" . diff-context->unified)
c010ecfa
BR
135 ("C" . diff-unified->context)
136 ("q" . quit-window))
0b82e382 137 "Basic keymap for `diff-mode', bound to various prefix keys.")
610a6418 138
d87e5627 139(easy-mmode-defmap diff-mode-map
610a6418 140 `(("\e" . ,diff-mode-shared-map)
027ac3f8
SM
141 ;; From compilation-minor-mode.
142 ("\C-c\C-c" . diff-goto-source)
143 ;; Misc operations.
22cd1973 144 ("\C-c\C-r" . diff-refine-hunk)
cd632e57 145 ("\C-c\C-s" . diff-split-hunk)
3cec9c57 146 ("\C-c\C-a" . diff-apply-hunk)
b711788a 147 ("\C-c\C-t" . diff-test-hunk)
677c0382 148 ("\C-c\C-f" . next-error-follow-minor-mode))
610a6418
SM
149 "Keymap for `diff-mode'. See also `diff-mode-shared-map'.")
150
151(easy-menu-define diff-mode-menu diff-mode-map
152 "Menu for `diff-mode'."
153 '("Diff"
154 ["Jump to Source" diff-goto-source t]
cd632e57
SM
155 ["Apply hunk" diff-apply-hunk t]
156 ["Apply diff with Ediff" diff-ediff-patch t]
610a6418
SM
157 ["-----" nil nil]
158 ["Reverse direction" diff-reverse-direction t]
159 ["Context -> Unified" diff-context->unified t]
160 ["Unified -> Context" diff-unified->context t]
161 ;;["Fixup Headers" diff-fixup-modifs (not buffer-read-only)]
162 ))
163
3cec9c57 164(defcustom diff-minor-mode-prefix "\C-c="
0b82e382 165 "Prefix key for `diff-minor-mode' commands."
f5307782
JB
166 :type '(choice (string "\e") (string "C-c=") string)
167 :group 'diff-mode)
0b82e382 168
d87e5627
SM
169(easy-mmode-defmap diff-minor-mode-map
170 `((,diff-minor-mode-prefix . ,diff-mode-shared-map))
0b82e382
SM
171 "Keymap for `diff-minor-mode'. See also `diff-mode-shared-map'.")
172
610a6418 173
cd632e57 174;;;;
610a6418 175;;;; font-lock support
cd632e57 176;;;;
610a6418 177
c0aa75f7 178(defface diff-header-face
55f2eb7e 179 '((((class color) (min-colors 88) (background light))
4f815065 180 :background "grey85")
55f2eb7e 181 (((class color) (min-colors 88) (background dark))
4f815065 182 :background "grey45")
55f2eb7e 183 (((class color) (background light))
4f815065 184 :foreground "blue1" :weight bold)
55f2eb7e 185 (((class color) (background dark))
4f815065
SM
186 :foreground "green" :weight bold)
187 (t :weight bold))
1eabc5e6 188 "`diff-mode' face inherited by hunk and index header faces.")
c0aa75f7
SM
189(defvar diff-header-face 'diff-header-face)
190
610a6418 191(defface diff-file-header-face
55f2eb7e 192 '((((class color) (min-colors 88) (background light))
4f815065 193 :background "grey70" :weight bold)
55f2eb7e 194 (((class color) (min-colors 88) (background dark))
4f815065 195 :background "grey60" :weight bold)
55f2eb7e 196 (((class color) (background light))
4f815065 197 :foreground "yellow" :weight bold)
55f2eb7e 198 (((class color) (background dark))
4f815065
SM
199 :foreground "cyan" :weight bold)
200 (t :weight bold)) ; :height 1.3
1eabc5e6 201 "`diff-mode' face used to highlight file header lines.")
610a6418
SM
202(defvar diff-file-header-face 'diff-file-header-face)
203
204(defface diff-index-face
4f815065 205 '((t :inherit diff-file-header-face))
1eabc5e6 206 "`diff-mode' face used to highlight index header lines.")
610a6418
SM
207(defvar diff-index-face 'diff-index-face)
208
209(defface diff-hunk-header-face
4f815065 210 '((t :inherit diff-header-face))
1eabc5e6 211 "`diff-mode' face used to highlight hunk header lines.")
610a6418
SM
212(defvar diff-hunk-header-face 'diff-hunk-header-face)
213
214(defface diff-removed-face
4f815065 215 '((t :inherit diff-changed-face))
1eabc5e6 216 "`diff-mode' face used to highlight removed lines.")
610a6418
SM
217(defvar diff-removed-face 'diff-removed-face)
218
219(defface diff-added-face
4f815065 220 '((t :inherit diff-changed-face))
1eabc5e6 221 "`diff-mode' face used to highlight added lines.")
610a6418
SM
222(defvar diff-added-face 'diff-added-face)
223
224(defface diff-changed-face
86a27a3a 225 '((((type tty pc) (class color) (background light))
4f815065 226 :foreground "magenta" :weight bold :slant italic)
86a27a3a 227 (((type tty pc) (class color) (background dark))
4f815065 228 :foreground "yellow" :weight bold :slant italic))
1eabc5e6 229 "`diff-mode' face used to highlight changed lines.")
610a6418
SM
230(defvar diff-changed-face 'diff-changed-face)
231
34460354 232(defface diff-function-face
4f815065 233 '((t :inherit diff-context-face))
1eabc5e6 234 "`diff-mode' face used to highlight function names produced by \"diff -p\".")
34460354
EZ
235(defvar diff-function-face 'diff-function-face)
236
9244f2c7
SM
237(defface diff-context-face
238 '((((class color) (background light))
4f815065 239 :foreground "grey50")
9244f2c7 240 (((class color) (background dark))
4f815065 241 :foreground "grey70"))
1eabc5e6 242 "`diff-mode' face used to highlight context and other side-information.")
9244f2c7 243(defvar diff-context-face 'diff-context-face)
c0aa75f7 244
7dfb000f 245(defface diff-nonexistent-face
4f815065 246 '((t :inherit diff-file-header-face))
1eabc5e6 247 "`diff-mode' face used to highlight nonexistent files in recursive diffs.")
7dfb000f 248(defvar diff-nonexistent-face 'diff-nonexistent-face)
469fc0a2 249
22cd1973
SM
250(defconst diff-yank-handler '(diff-yank-function))
251(defun diff-yank-function (text)
1ec7bd14
SM
252 ;; FIXME: the yank-handler is now called separately on each piece of text
253 ;; with a yank-handler property, so the next-single-property-change call
254 ;; below will always return nil :-( --stef
22cd1973
SM
255 (let ((mixed (next-single-property-change 0 'yank-handler text))
256 (start (point)))
257 ;; First insert the text.
258 (insert text)
259 ;; If the text does not include any diff markers and if we're not
260 ;; yanking back into a diff-mode buffer, get rid of the prefixes.
261 (unless (or mixed (derived-mode-p 'diff-mode))
262 (undo-boundary) ; Just in case the user wanted the prefixes.
263 (let ((re (save-excursion
264 (if (re-search-backward "^[><!][ \t]" start t)
265 (if (eq (char-after) ?!)
266 "^[!+- ][ \t]" "^[<>][ \t]")
267 "^[ <>!+-]"))))
268 (save-excursion
269 (while (re-search-backward re start t)
270 (replace-match "" t t)))))))
cfc80227 271
22cd1973 272
610a6418 273(defvar diff-font-lock-keywords
22cd1973 274 `(("^\\(@@ -[0-9,]+ \\+[0-9,]+ @@\\)\\(.*\\)$" ;unified
19e713d8 275 (1 diff-hunk-header-face)
34460354 276 (2 diff-function-face))
469fc0a2 277 ("^--- .+ ----$" . diff-hunk-header-face) ;context
a62d56ab 278 ("^\\(\\*\\{15\\}\\)\\(.*\\)$" ;context
19e713d8 279 (1 diff-hunk-header-face)
34460354 280 (2 diff-function-face))
370d860c 281 ("^\\*\\*\\* .+ \\*\\*\\*\\*". diff-hunk-header-face) ;context
a6373340 282 ("^\\(---\\|\\+\\+\\+\\|\\*\\*\\*\\) \\(\\S-+\\)\\(.*[^*-]\\)?\n"
c0aa75f7 283 (0 diff-header-face) (2 diff-file-header-face prepend))
610a6418 284 ("^[0-9,]+[acd][0-9,]+$" . diff-hunk-header-face)
1ec7bd14
SM
285 ("^!.*\n" (0 diff-changed-face))
286 ("^[+>].*\n" (0 diff-added-face))
287 ("^[-<].*\n" (0 diff-removed-face))
c0aa75f7 288 ("^Index: \\(.+\\).*\n" (0 diff-header-face) (1 diff-index-face prepend))
7dfb000f 289 ("^Only in .*\n" . diff-nonexistent-face)
0e104800 290 ("^#.*" . font-lock-string-face)
1ec7bd14 291 ("^[^-=+*!<>].*\n" (0 diff-context-face))))
610a6418
SM
292
293(defconst diff-font-lock-defaults
0e104800 294 '(diff-font-lock-keywords t nil nil nil (font-lock-multiline . nil)))
610a6418 295
ccce6558
DL
296(defvar diff-imenu-generic-expression
297 ;; Prefer second name as first is most likely to be a backup or
824693e7
DL
298 ;; version-control name. The [\t\n] at the end of the unidiff pattern
299 ;; catches Debian source diff files (which lack the trailing date).
300 '((nil "\\+\\+\\+\\ \\([^\t\n]+\\)[\t\n]" 1) ; unidiffs
ccce6558
DL
301 (nil "^--- \\([^\t\n]+\\)\t.*\n\\*" 1))) ; context diffs
302
cd632e57 303;;;;
610a6418 304;;;; Movement
cd632e57 305;;;;
610a6418 306
c0078a04 307(defconst diff-hunk-header-re "^\\(@@ -[0-9,]+ \\+[0-9,]+ @@.*\\|\\*\\{15\\}.*\n\\*\\*\\* .+ \\*\\*\\*\\*\\|[0-9]+\\(,[0-9]+\\)?[acd][0-9]+\\(,[0-9]+\\)?\\)$")
bd9d7d76 308(defconst diff-file-header-re (concat "^\\(--- .+\n\\+\\+\\+ \\|\\*\\*\\* .+\n--- \\|[^-+!<>0-9@* ]\\).+\n" (substring diff-hunk-header-re 1)))
610a6418
SM
309(defvar diff-narrowed-to nil)
310
311(defun diff-end-of-hunk (&optional style)
996884b2
SM
312 (when (looking-at diff-hunk-header-re)
313 (unless style
314 ;; Especially important for unified (because headers are ambiguous).
315 (setq style (cdr (assq (char-after) '((?@ . unified) (?* . context))))))
316 (goto-char (match-end 0)))
0e104800 317 (let ((end (and (re-search-forward (case style
1eabc5e6
SM
318 ;; A `unified' header is ambiguous.
319 (unified (concat "^[^-+# \\]\\|"
320 diff-file-header-re))
0e104800
SM
321 (context "^[^-+#! \\]")
322 (normal "^[^<>#\\]")
323 (t "^[^-+#!<> \\]"))
324 nil t)
325 (match-beginning 0))))
326 ;; The return value is used by easy-mmode-define-navigation.
327 (goto-char (or end (point-max)))))
610a6418
SM
328
329(defun diff-beginning-of-hunk ()
330 (beginning-of-line)
331 (unless (looking-at diff-hunk-header-re)
332 (forward-line 1)
333 (condition-case ()
334 (re-search-backward diff-hunk-header-re)
335 (error (error "Can't find the beginning of the hunk")))))
336
337(defun diff-beginning-of-file ()
338 (beginning-of-line)
339 (unless (looking-at diff-file-header-re)
340 (forward-line 2)
341 (condition-case ()
342 (re-search-backward diff-file-header-re)
343 (error (error "Can't find the beginning of the file")))))
344
345(defun diff-end-of-file ()
0e104800 346 (re-search-forward "^[-+#!<>0-9@* \\]" nil t)
22cd1973
SM
347 (re-search-forward (concat "^[^-+#!<>0-9@* \\]\\|" diff-file-header-re)
348 nil 'move)
349 (if (match-beginning 1)
350 (goto-char (match-beginning 1))
351 (beginning-of-line)))
610a6418 352
d87e5627
SM
353;; Define diff-{hunk,file}-{prev,next}
354(easy-mmode-define-navigation
067b4094 355 diff-hunk diff-hunk-header-re "hunk" diff-end-of-hunk diff-restrict-view)
d87e5627
SM
356(easy-mmode-define-navigation
357 diff-file diff-file-header-re "file" diff-end-of-hunk)
610a6418
SM
358
359(defun diff-restrict-view (&optional arg)
360 "Restrict the view to the current hunk.
361If the prefix ARG is given, restrict the view to the current file instead."
362 (interactive "P")
363 (save-excursion
364 (if arg (diff-beginning-of-file) (diff-beginning-of-hunk))
365 (narrow-to-region (point)
366 (progn (if arg (diff-end-of-file) (diff-end-of-hunk))
367 (point)))
368 (set (make-local-variable 'diff-narrowed-to) (if arg 'file 'hunk))))
369
370
d87e5627 371(defun diff-hunk-kill ()
610a6418
SM
372 "Kill current hunk."
373 (interactive)
374 (diff-beginning-of-hunk)
1eabc5e6 375 (let* ((start (point))
22cd1973
SM
376 (nexthunk (when (re-search-forward diff-hunk-header-re nil t)
377 (match-beginning 0)))
1eabc5e6
SM
378 (firsthunk (ignore-errors
379 (goto-char start)
380 (diff-beginning-of-file) (diff-hunk-next) (point)))
381 (nextfile (ignore-errors (diff-file-next) (point))))
382 (goto-char start)
610a6418
SM
383 (if (and firsthunk (= firsthunk start)
384 (or (null nexthunk)
385 (and nextfile (> nexthunk nextfile))))
1eabc5e6 386 ;; It's the only hunk for this file, so kill the file.
d87e5627 387 (diff-file-kill)
610a6418
SM
388 (diff-end-of-hunk)
389 (kill-region start (point)))))
390
d87e5627 391(defun diff-file-kill ()
610a6418
SM
392 "Kill current file's hunks."
393 (interactive)
394 (diff-beginning-of-file)
395 (let* ((start (point))
396 (prevhunk (save-excursion
397 (ignore-errors
d87e5627 398 (diff-hunk-prev) (point))))
610a6418
SM
399 (index (save-excursion
400 (re-search-backward "^Index: " prevhunk t))))
401 (when index (setq start index))
402 (diff-end-of-file)
22cd1973 403 (if (looking-at "^\n") (forward-char 1)) ;`tla' generates such diffs.
610a6418
SM
404 (kill-region start (point))))
405
fef8c55b
SM
406(defun diff-kill-junk ()
407 "Kill spurious empty diffs."
408 (interactive)
409 (save-excursion
410 (let ((inhibit-read-only t))
411 (goto-char (point-min))
412 (while (re-search-forward (concat "^\\(Index: .*\n\\)"
413 "\\([^-+!* <>].*\n\\)*?"
414 "\\(\\(Index:\\) \\|"
415 diff-file-header-re "\\)")
416 nil t)
417 (delete-region (if (match-end 4) (match-beginning 0) (match-end 1))
418 (match-beginning 3))
419 (beginning-of-line)))))
420
cd632e57
SM
421(defun diff-count-matches (re start end)
422 (save-excursion
423 (let ((n 0))
424 (goto-char start)
425 (while (re-search-forward re end t) (incf n))
426 n)))
427
428(defun diff-split-hunk ()
429 "Split the current (unified diff) hunk at point into two hunks."
430 (interactive)
431 (beginning-of-line)
432 (let ((pos (point))
433 (start (progn (diff-beginning-of-hunk) (point))))
434 (unless (looking-at "@@ -\\([0-9]+\\),[0-9]+ \\+\\([0-9]+\\),[0-9]+ @@")
435 (error "diff-split-hunk only works on unified context diffs"))
436 (forward-line 1)
437 (let* ((start1 (string-to-number (match-string 1)))
438 (start2 (string-to-number (match-string 2)))
439 (newstart1 (+ start1 (diff-count-matches "^[- \t]" (point) pos)))
440 (newstart2 (+ start2 (diff-count-matches "^[+ \t]" (point) pos))))
441 (goto-char pos)
442 ;; Hopefully the after-change-function will not screw us over.
443 (insert "@@ -" (number-to-string newstart1) ",1 +"
444 (number-to-string newstart2) ",1 @@\n")
445 ;; Fix the original hunk-header.
446 (diff-fixup-modifs start pos))))
71296446 447
cd632e57 448
610a6418
SM
449;;;;
450;;;; jump to other buffers
451;;;;
452
0b82e382
SM
453(defvar diff-remembered-files-alist nil)
454
610a6418
SM
455(defun diff-filename-drop-dir (file)
456 (when (string-match "/" file) (substring file (match-end 0))))
457
0b82e382
SM
458(defun diff-merge-strings (ancestor from to)
459 "Merge the diff between ANCESTOR and FROM into TO.
460Returns the merged string if successful or nil otherwise.
d87e5627 461The strings are assumed not to contain any \"\\n\" (i.e. end of line).
0b82e382
SM
462If ANCESTOR = FROM, returns TO.
463If ANCESTOR = TO, returns FROM.
464The heuristic is simplistic and only really works for cases
465like \(diff-merge-strings \"b/foo\" \"b/bar\" \"/a/c/foo\")."
466 ;; Ideally, we want:
467 ;; AMB ANB CMD -> CND
468 ;; but that's ambiguous if `foo' or `bar' is empty:
469 ;; a/foo a/foo1 b/foo.c -> b/foo1.c but not 1b/foo.c or b/foo.c1
d87e5627 470 (let ((str (concat ancestor "\n" from "\n" to)))
0b82e382 471 (when (and (string-match (concat
d87e5627
SM
472 "\\`\\(.*?\\)\\(.*\\)\\(.*\\)\n"
473 "\\1\\(.*\\)\\3\n"
0b82e382
SM
474 "\\(.*\\(\\2\\).*\\)\\'") str)
475 (equal to (match-string 5 str)))
476 (concat (substring str (match-beginning 5) (match-beginning 6))
477 (match-string 4 str)
478 (substring str (match-end 6) (match-end 5))))))
479
22cd1973
SM
480(defun diff-tell-file-name (old name)
481 "Tell Emacs where the find the source file of the current hunk.
482If the OLD prefix arg is passed, tell the file NAME of the old file."
483 (interactive
484 (let* ((old current-prefix-arg)
485 (fs (diff-hunk-file-names current-prefix-arg)))
486 (unless fs (error "No file name to look for"))
487 (list old (read-file-name (format "File for %s: " (car fs))
488 nil (diff-find-file-name old) t))))
489 (let ((fs (diff-hunk-file-names old)))
490 (unless fs (error "No file name to look for"))
491 (push (cons fs name) diff-remembered-files-alist)))
cfc80227 492
22cd1973
SM
493(defun diff-hunk-file-names (&optional old)
494 "Give the list of file names textually mentioned for the current hunk."
610a6418
SM
495 (save-excursion
496 (unless (looking-at diff-file-header-re)
497 (or (ignore-errors (diff-beginning-of-file))
498 (re-search-forward diff-file-header-re nil t)))
22cd1973 499 (let ((limit (save-excursion
610a6418 500 (condition-case ()
d87e5627 501 (progn (diff-hunk-prev) (point))
610a6418 502 (error (point-min)))))
22cd1973
SM
503 (header-files
504 (if (looking-at "[-*][-*][-*] \\(\\S-+\\)\\(\\s-.*\\)?\n[-+][-+][-+] \\(\\S-+\\)")
505 (list (if old (match-string 1) (match-string 3))
506 (if old (match-string 3) (match-string 1)))
507 (forward-line 1) nil)))
508 (delq nil
509 (append
510 (when (and (not old)
511 (save-excursion
512 (re-search-backward "^Index: \\(.+\\)" limit t)))
513 (list (match-string 1)))
514 header-files
515 (when (re-search-backward
516 "^diff \\(-\\S-+ +\\)*\\(\\S-+\\)\\( +\\(\\S-+\\)\\)?"
517 nil t)
518 (list (if old (match-string 2) (match-string 4))
519 (if old (match-string 4) (match-string 2)))))))))
520
521(defun diff-find-file-name (&optional old)
522 "Return the file corresponding to the current patch.
523Non-nil OLD means that we want the old file."
524 (save-excursion
525 (unless (looking-at diff-file-header-re)
526 (or (ignore-errors (diff-beginning-of-file))
527 (re-search-forward diff-file-header-re nil t)))
528 (let ((fs (diff-hunk-file-names old)))
610a6418 529 (or
0b82e382
SM
530 ;; use any previously used preference
531 (cdr (assoc fs diff-remembered-files-alist))
532 ;; try to be clever and use previous choices as an inspiration
533 (dolist (rf diff-remembered-files-alist)
534 (let ((newfile (diff-merge-strings (caar rf) (car fs) (cdr rf))))
535 (if (and newfile (file-exists-p newfile)) (return newfile))))
536 ;; look for each file in turn. If none found, try again but
537 ;; ignoring the first level of directory, ...
538 (do* ((files fs (delq nil (mapcar 'diff-filename-drop-dir files)))
539 (file nil nil))
540 ((or (null files)
541 (setq file (do* ((files files (cdr files))
542 (file (car files) (car files)))
543 ((or (null file) (file-exists-p file))
544 file))))
545 file))
546 ;; <foo>.rej patches implicitly apply to <foo>
610a6418
SM
547 (and (string-match "\\.rej\\'" (or buffer-file-name ""))
548 (let ((file (substring buffer-file-name 0 (match-beginning 0))))
549 (when (file-exists-p file) file)))
0b82e382
SM
550 ;; if all else fails, ask the user
551 (let ((file (read-file-name (format "Use file %s: " (or (first fs) ""))
552 nil (first fs) t (first fs))))
553 (set (make-local-variable 'diff-remembered-files-alist)
554 (cons (cons fs file) diff-remembered-files-alist))
610a6418
SM
555 file)))))
556
1b1b5dae 557
610a6418
SM
558(defun diff-ediff-patch ()
559 "Call `ediff-patch-file' on the current buffer."
560 (interactive)
561 (condition-case err
0e104800 562 (ediff-patch-file nil (current-buffer))
610a6418
SM
563 (wrong-number-of-arguments (ediff-patch-file))))
564
71296446 565;;;;
610a6418 566;;;; Conversion functions
71296446 567;;;;
610a6418
SM
568
569;;(defvar diff-inhibit-after-change nil
570;; "Non-nil means inhibit `diff-mode's after-change functions.")
571
572(defun diff-unified->context (start end)
573 "Convert unified diffs to context diffs.
574START and END are either taken from the region (if a prefix arg is given) or
575else cover the whole bufer."
576 (interactive (if current-prefix-arg
577 (list (mark) (point))
578 (list (point-min) (point-max))))
579 (unless (markerp end) (setq end (copy-marker end)))
580 (let (;;(diff-inhibit-after-change t)
581 (inhibit-read-only t))
582 (save-excursion
583 (goto-char start)
c0078a04 584 (while (and (re-search-forward "^\\(\\(---\\) .+\n\\(\\+\\+\\+\\) .+\\|@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\\)$" nil t)
610a6418
SM
585 (< (point) end))
586 (combine-after-change-calls
587 (if (match-beginning 2)
0e104800 588 ;; we matched a file header
610a6418
SM
589 (progn
590 ;; use reverse order to make sure the indices are kept valid
591 (replace-match "---" t t nil 3)
592 (replace-match "***" t t nil 2))
593 ;; we matched a hunk header
594 (let ((line1 (match-string 4))
595 (lines1 (match-string 5))
596 (line2 (match-string 6))
597 (lines2 (match-string 7)))
598 (replace-match
599 (concat "***************\n*** " line1 ","
600 (number-to-string (+ (string-to-number line1)
601 (string-to-number lines1)
602 -1)) " ****"))
603 (forward-line 1)
604 (save-restriction
605 (narrow-to-region (point)
606 (progn (diff-end-of-hunk 'unified) (point)))
607 (let ((hunk (buffer-string)))
608 (goto-char (point-min))
609 (if (not (save-excursion (re-search-forward "^-" nil t)))
610 (delete-region (point) (point-max))
611 (goto-char (point-max))
612 (let ((modif nil) last-pt)
613 (while (progn (setq last-pt (point))
614 (= (forward-line -1) 0))
615 (case (char-after)
616 (? (insert " ") (setq modif nil) (backward-char 1))
617 (?+ (delete-region (point) last-pt) (setq modif t))
618 (?- (if (not modif)
619 (progn (forward-char 1)
620 (insert " "))
621 (delete-char 1)
622 (insert "! "))
623 (backward-char 2))
624 (?\\ (when (save-excursion (forward-line -1)
625 (= (char-after) ?+))
626 (delete-region (point) last-pt) (setq modif t)))
627 (t (setq modif nil))))))
628 (goto-char (point-max))
629 (save-excursion
630 (insert "--- " line2 ","
631 (number-to-string (+ (string-to-number line2)
632 (string-to-number lines2)
633 -1)) " ----\n" hunk))
634 ;;(goto-char (point-min))
635 (forward-line 1)
636 (if (not (save-excursion (re-search-forward "^+" nil t)))
637 (delete-region (point) (point-max))
638 (let ((modif nil) (delete nil))
639 (while (not (eobp))
640 (case (char-after)
641 (? (insert " ") (setq modif nil) (backward-char 1))
642 (?- (setq delete t) (setq modif t))
643 (?+ (if (not modif)
644 (progn (forward-char 1)
645 (insert " "))
646 (delete-char 1)
647 (insert "! "))
648 (backward-char 2))
649 (?\\ (when (save-excursion (forward-line 1)
650 (not (eobp)))
651 (setq delete t) (setq modif t)))
652 (t (setq modif nil)))
653 (let ((last-pt (point)))
654 (forward-line 1)
655 (when delete
656 (delete-region last-pt (point))
657 (setq delete nil)))))))))))))))
658
659(defun diff-context->unified (start end)
660 "Convert context diffs to unified diffs.
661START and END are either taken from the region (if a prefix arg is given) or
662else cover the whole bufer."
663 (interactive (if current-prefix-arg
664 (list (mark) (point))
665 (list (point-min) (point-max))))
666 (unless (markerp end) (setq end (copy-marker end)))
667 (let (;;(diff-inhibit-after-change t)
668 (inhibit-read-only t))
669 (save-excursion
670 (goto-char start)
c0078a04 671 (while (and (re-search-forward "^\\(\\(\\*\\*\\*\\) .+\n\\(---\\) .+\\|\\*\\{15\\}.*\n\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]+\\) \\*\\*\\*\\*\\)$" nil t)
610a6418
SM
672 (< (point) end))
673 (combine-after-change-calls
674 (if (match-beginning 2)
675 ;; we matched a file header
676 (progn
677 ;; use reverse order to make sure the indices are kept valid
678 (replace-match "+++" t t nil 3)
679 (replace-match "---" t t nil 2))
680 ;; we matched a hunk header
681 (let ((line1s (match-string 4))
682 (line1e (match-string 5))
683 (pt1 (match-beginning 0)))
684 (replace-match "")
685 (unless (re-search-forward
686 "^--- \\([0-9]+\\),\\(-?[0-9]+\\) ----$" nil t)
687 (error "Can't find matching `--- n1,n2 ----' line"))
688 (let ((line2s (match-string 1))
689 (line2e (match-string 2))
690 (pt2 (progn
691 (delete-region (progn (beginning-of-line) (point))
692 (progn (forward-line 1) (point)))
693 (point-marker))))
694 (goto-char pt1)
695 (forward-line 1)
696 (while (< (point) pt2)
697 (case (char-after)
698 ((?! ?-) (delete-char 2) (insert "-") (forward-line 1))
699 (?\ ;merge with the other half of the chunk
700 (let* ((endline2
701 (save-excursion
702 (goto-char pt2) (forward-line 1) (point)))
703 (c (char-after pt2)))
704 (case c
705 ((?! ?+)
706 (insert "+"
707 (prog1 (buffer-substring (+ pt2 2) endline2)
708 (delete-region pt2 endline2))))
709 (?\ ;FIXME: check consistency
710 (delete-region pt2 endline2)
711 (delete-char 1)
712 (forward-line 1))
713 (?\\ (forward-line 1))
714 (t (delete-char 1) (forward-line 1)))))
715 (t (forward-line 1))))
716 (while (looking-at "[+! ] ")
717 (if (/= (char-after) ?!) (forward-char 1)
718 (delete-char 1) (insert "+"))
719 (delete-char 1) (forward-line 1))
720 (save-excursion
721 (goto-char pt1)
722 (insert "@@ -" line1s ","
723 (number-to-string (- (string-to-number line1e)
724 (string-to-number line1s)
725 -1))
726 " +" line2s ","
727 (number-to-string (- (string-to-number line2e)
728 (string-to-number line2s)
729 -1)) " @@"))))))))))
730
731(defun diff-reverse-direction (start end)
732 "Reverse the direction of the diffs.
733START and END are either taken from the region (if a prefix arg is given) or
734else cover the whole bufer."
735 (interactive (if current-prefix-arg
736 (list (mark) (point))
737 (list (point-min) (point-max))))
738 (unless (markerp end) (setq end (copy-marker end)))
739 (let (;;(diff-inhibit-after-change t)
740 (inhibit-read-only t))
741 (save-excursion
742 (goto-char start)
c0078a04 743 (while (and (re-search-forward "^\\(\\([-*][-*][-*] \\)\\(.+\\)\n\\([-+][-+][-+] \\)\\(.+\\)\\|\\*\\{15\\}.*\n\\*\\*\\* \\(.+\\) \\*\\*\\*\\*\\|@@ -\\([0-9,]+\\) \\+\\([0-9,]+\\) @@.*\\)$" nil t)
610a6418
SM
744 (< (point) end))
745 (combine-after-change-calls
746 (cond
747 ;; a file header
748 ((match-beginning 2) (replace-match "\\2\\5\n\\4\\3" nil))
749 ;; a context-diff hunk header
750 ((match-beginning 6)
751 (let ((pt-lines1 (match-beginning 6))
752 (lines1 (match-string 6)))
753 (replace-match "" nil nil nil 6)
754 (forward-line 1)
755 (let ((half1s (point)))
0e104800 756 (while (looking-at "[-! \\][ \t]\\|#")
610a6418
SM
757 (when (= (char-after) ?-) (delete-char 1) (insert "+"))
758 (forward-line 1))
fef8c55b 759 (let ((half1 (delete-and-extract-region half1s (point))))
610a6418
SM
760 (unless (looking-at "^--- \\([0-9]+,-?[0-9]+\\) ----$")
761 (insert half1)
762 (error "Can't find matching `--- n1,n2 ----' line"))
763 (let ((str1 (match-string 1)))
764 (replace-match lines1 nil nil nil 1)
765 (forward-line 1)
766 (let ((half2s (point)))
0e104800 767 (while (looking-at "[!+ \\][ \t]\\|#")
610a6418
SM
768 (when (= (char-after) ?+) (delete-char 1) (insert "-"))
769 (forward-line 1))
fef8c55b 770 (let ((half2 (delete-and-extract-region half2s (point))))
0e104800 771 (insert (or half1 ""))
610a6418 772 (goto-char half1s)
0e104800 773 (insert (or half2 ""))))
610a6418
SM
774 (goto-char pt-lines1)
775 (insert str1))))))
776 ;; a unified-diff hunk header
777 ((match-beginning 7)
778 (replace-match "@@ -\\8 +\\7 @@" nil)
779 (forward-line 1)
780 (let ((c (char-after)) first last)
781 (while (case (setq c (char-after))
782 (?- (setq first (or first (point)))
783 (delete-char 1) (insert "+") t)
784 (?+ (setq last (or last (point)))
785 (delete-char 1) (insert "-") t)
0e104800 786 ((?\\ ?#) t)
610a6418 787 (t (when (and first last (< first last))
cb4e8176 788 (insert (delete-and-extract-region first last)))
610a6418
SM
789 (setq first nil last nil)
790 (equal ?\ c)))
791 (forward-line 1))))))))))
792
793(defun diff-fixup-modifs (start end)
794 "Fixup the hunk headers (in case the buffer was modified).
795START and END are either taken from the region (if a prefix arg is given) or
796else cover the whole bufer."
797 (interactive (if current-prefix-arg
798 (list (mark) (point))
799 (list (point-min) (point-max))))
800 (let ((inhibit-read-only t))
801 (save-excursion
802 (goto-char end) (diff-end-of-hunk)
803 (let ((plus 0) (minus 0) (space 0) (bang 0))
804 (while (and (= (forward-line -1) 0) (<= start (point)))
bd9d7d76
SM
805 (if (not (looking-at
806 (concat "@@ -[0-9,]+ \\+[0-9,]+ @@"
807 "\\|[-*][-*][-*] [0-9,]+ [-*][-*][-*][-*]$"
808 "\\|--- .+\n\\+\\+\\+ ")))
610a6418 809 (case (char-after)
bd9d7d76 810 (?\s (incf space))
610a6418
SM
811 (?+ (incf plus))
812 (?- (incf minus))
813 (?! (incf bang))
0e104800 814 ((?\\ ?#) nil)
610a6418
SM
815 (t (setq space 0 plus 0 minus 0 bang 0)))
816 (cond
c0078a04 817 ((looking-at "@@ -[0-9]+,\\([0-9]*\\) \\+[0-9]+,\\([0-9]*\\) @@.*$")
610a6418
SM
818 (let* ((old1 (match-string 1))
819 (old2 (match-string 2))
820 (new1 (number-to-string (+ space minus)))
821 (new2 (number-to-string (+ space plus))))
822 (unless (string= new2 old2) (replace-match new2 t t nil 2))
823 (unless (string= new1 old1) (replace-match new1 t t nil 1))))
824 ((looking-at "--- \\([0-9]+\\),\\([0-9]*\\) ----$")
825 (when (> (+ space bang plus) 0)
826 (let* ((old1 (match-string 1))
827 (old2 (match-string 2))
828 (new (number-to-string
829 (+ space bang plus -1 (string-to-number old1)))))
830 (unless (string= new old2) (replace-match new t t nil 2)))))
831 ((looking-at "\\*\\*\\* \\([0-9]+\\),\\(-?[0-9]*\\) \\*\\*\\*\\*$")
832 (when (> (+ space bang minus) 0)
833 (let* ((old (match-string 1))
834 (new (format
835 (concat "%0" (number-to-string (length old)) "d")
836 (+ space bang minus -1 (string-to-number old)))))
837 (unless (string= new old) (replace-match new t t nil 2))))))
838 (setq space 0 plus 0 minus 0 bang 0)))))))
839
71296446 840;;;;
610a6418 841;;;; Hooks
71296446 842;;;;
610a6418
SM
843
844(defun diff-write-contents-hooks ()
845 "Fixup hunk headers if necessary."
846 (if (buffer-modified-p) (diff-fixup-modifs (point-min) (point-max)))
847 nil)
848
610a6418
SM
849;; It turns out that making changes in the buffer from within an
850;; *-change-function is asking for trouble, whereas making them
851;; from a post-command-hook doesn't pose much problems
852(defvar diff-unhandled-changes nil)
853(defun diff-after-change-function (beg end len)
854 "Remember to fixup the hunk header.
855See `after-change-functions' for the meaning of BEG, END and LEN."
c0078a04
SM
856 ;; Ignoring changes when inhibit-read-only is set is strictly speaking
857 ;; incorrect, but it turns out that inhibit-read-only is normally not set
858 ;; inside editing commands, while it tends to be set when the buffer gets
859 ;; updated by an async process or by a conversion function, both of which
860 ;; would rather not be uselessly slowed down by this hook.
610a6418
SM
861 (when (and (not undo-in-progress) (not inhibit-read-only))
862 (if diff-unhandled-changes
863 (setq diff-unhandled-changes
864 (cons (min beg (car diff-unhandled-changes))
cb4e8176 865 (max end (cdr diff-unhandled-changes))))
610a6418
SM
866 (setq diff-unhandled-changes (cons beg end)))))
867
868(defun diff-post-command-hook ()
869 "Fixup hunk headers if necessary."
870 (when (consp diff-unhandled-changes)
871 (ignore-errors
872 (save-excursion
fef8c55b 873 (goto-char (car diff-unhandled-changes))
cb4e8176
SM
874 ;; Maybe we've cut the end of the hunk before point.
875 (if (and (bolp) (not (bobp))) (backward-char 1))
1eabc5e6
SM
876 ;; We used to fixup modifs on all the changes, but it turns out
877 ;; that it's safer not to do it on big changes, for example
878 ;; when yanking a big diff, since we might then screw up perfectly
879 ;; correct values. -stef
880 ;; (unless (ignore-errors
881 ;; (diff-beginning-of-hunk)
882 ;; (save-excursion
883 ;; (diff-end-of-hunk)
884 ;; (> (point) (car diff-unhandled-changes))))
885 ;; (goto-char (car diff-unhandled-changes))
886 ;; (re-search-forward diff-hunk-header-re (cdr diff-unhandled-changes))
887 ;; (diff-beginning-of-hunk))
888 ;; (diff-fixup-modifs (point) (cdr diff-unhandled-changes))
889 (diff-beginning-of-hunk)
890 (when (save-excursion
891 (diff-end-of-hunk)
cb4e8176 892 (>= (point) (cdr diff-unhandled-changes)))
1eabc5e6 893 (diff-fixup-modifs (point) (cdr diff-unhandled-changes)))))
610a6418
SM
894 (setq diff-unhandled-changes nil)))
895
6fc049f6
SM
896(defun diff-next-error (arg reset)
897 ;; Select a window that displays the current buffer so that point
898 ;; movements are reflected in that window. Otherwise, the user might
899 ;; never see the hunk corresponding to the source she's jumping to.
900 (pop-to-buffer (current-buffer))
901 (if reset (goto-char (point-min)))
902 (diff-hunk-next arg)
903 (diff-goto-source))
610a6418 904
610a6418 905;;;###autoload
d87e5627 906(define-derived-mode diff-mode fundamental-mode "Diff"
0b82e382 907 "Major mode for viewing/editing context diffs.
769dd0f1
SM
908Supports unified and context diffs as well as (to a lesser extent)
909normal diffs.
df52e0e7
SM
910When the buffer is read-only, the ESC prefix is not necessary.
911IF you edit the buffer manually, diff-mode will try to update the hunk
912headers for you on-the-fly.
913
914You can also switch between context diff and unified diff with \\[diff-context->unified],
915or vice versa with \\[diff-unified->context] and you can also revert the direction of
916a diff with \\[diff-reverse-direction]."
610a6418
SM
917 (set (make-local-variable 'font-lock-defaults) diff-font-lock-defaults)
918 (set (make-local-variable 'outline-regexp) diff-outline-regexp)
ccce6558
DL
919 (set (make-local-variable 'imenu-generic-expression)
920 diff-imenu-generic-expression)
19e713d8
DL
921 ;; These are not perfect. They would be better done separately for
922 ;; context diffs and unidiffs.
923 ;; (set (make-local-variable 'paragraph-start)
924 ;; (concat "@@ " ; unidiff hunk
925 ;; "\\|\\*\\*\\* " ; context diff hunk or file start
926 ;; "\\|--- [^\t]+\t")) ; context or unidiff file
927 ;; ; start (first or second line)
928 ;; (set (make-local-variable 'paragraph-separate) paragraph-start)
929 ;; (set (make-local-variable 'page-delimiter) "--- [^\t]+\t")
930 ;; compile support
6fc049f6 931 (set (make-local-variable 'next-error-function) 'diff-next-error)
cdbb79c1 932
769dd0f1 933 (when (and (> (point-max) (point-min)) diff-default-read-only)
2b960ac0 934 (toggle-read-only t))
769dd0f1 935 ;; setup change hooks
e8a1ed31 936 (if (not diff-update-on-the-fly)
3ccdb14e 937 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
610a6418 938 (make-local-variable 'diff-unhandled-changes)
3cec9c57
SM
939 (add-hook 'after-change-functions 'diff-after-change-function nil t)
940 (add-hook 'post-command-hook 'diff-post-command-hook nil t))
610a6418 941 ;; Neat trick from Dave Love to add more bindings in read-only mode:
22cd1973
SM
942 (let ((ro-bind (cons 'buffer-read-only diff-mode-shared-map)))
943 (add-to-list 'minor-mode-overriding-map-alist ro-bind)
944 ;; Turn off this little trick in case the buffer is put in view-mode.
945 (add-hook 'view-mode-hook
946 `(lambda ()
947 (setq minor-mode-overriding-map-alist
5c84686c 948 (delq ',ro-bind minor-mode-overriding-map-alist)))
22cd1973 949 nil t))
281096ed
SM
950 ;; add-log support
951 (set (make-local-variable 'add-log-current-defun-function)
952 'diff-current-defun)
1b1b5dae
SM
953 (set (make-local-variable 'add-log-buffer-file-name-function)
954 'diff-find-file-name))
610a6418
SM
955
956;;;###autoload
0b82e382
SM
957(define-minor-mode diff-minor-mode
958 "Minor mode for viewing/editing context diffs.
959\\{diff-minor-mode-map}"
cfc80227 960 :group 'diff-mode :lighter " Diff"
0b82e382 961 ;; FIXME: setup font-lock
fef8c55b 962 ;; setup change hooks
e8a1ed31 963 (if (not diff-update-on-the-fly)
3ccdb14e 964 (add-hook 'write-contents-functions 'diff-write-contents-hooks nil t)
fef8c55b 965 (make-local-variable 'diff-unhandled-changes)
3cec9c57
SM
966 (add-hook 'after-change-functions 'diff-after-change-function nil t)
967 (add-hook 'post-command-hook 'diff-post-command-hook nil t)))
0b82e382 968
22cd1973
SM
969;;; Handy hook functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
970
971(defun diff-delete-if-empty ()
972 ;; An empty diff file means there's no more diffs to integrate, so we
973 ;; can just remove the file altogether. Very handy for .rej files if we
974 ;; remove hunks as we apply them.
975 (when (and buffer-file-name
976 (eq 0 (nth 7 (file-attributes buffer-file-name))))
977 (delete-file buffer-file-name)))
978
979(defun diff-delete-empty-files ()
980 "Arrange for empty diff files to be removed."
981 (add-hook 'after-save-hook 'diff-delete-if-empty nil t))
982
983(defun diff-make-unified ()
984 "Turn context diffs into unified diffs if applicable."
985 (if (save-excursion
986 (goto-char (point-min))
4c174fb4 987 (and (looking-at diff-hunk-header-re) (eq (char-after) ?*)))
22cd1973
SM
988 (let ((mod (buffer-modified-p)))
989 (unwind-protect
990 (diff-context->unified (point-min) (point-max))
991 (restore-buffer-modified-p mod)))))
610a6418 992
027ac3f8
SM
993;;;
994;;; Misc operations that have proved useful at some point.
995;;;
996
997(defun diff-next-complex-hunk ()
998 "Jump to the next \"complex\" hunk.
999\"Complex\" is approximated by \"the hunk changes the number of lines\".
1000Only works for unified diffs."
1001 (interactive)
1002 (while
1003 (and (re-search-forward "^@@ [-0-9]+,\\([0-9]+\\) [+0-9]+,\\([0-9]+\\) @@"
1004 nil t)
1005 (equal (match-string 1) (match-string 2)))))
1006
1eabc5e6
SM
1007(defun diff-hunk-text (hunk destp char-offset)
1008 "Return the literal source text from HUNK as (TEXT . OFFSET).
1009if DESTP is nil TEXT is the source, otherwise the destination text.
1010CHAR-OFFSET is a char-offset in HUNK, and OFFSET is the corresponding
1011char-offset in TEXT."
3017133f 1012 (with-temp-buffer
6e4e8a3b
SM
1013 (insert hunk)
1014 (goto-char (point-min))
1015 (let ((src-pos nil)
1016 (dst-pos nil)
1017 (divider-pos nil)
1018 (num-pfx-chars 2))
1019 ;; Set the following variables:
1020 ;; SRC-POS buffer pos of the source part of the hunk or nil if none
1021 ;; DST-POS buffer pos of the destination part of the hunk or nil
1022 ;; DIVIDER-POS buffer pos of any divider line separating the src & dst
1023 ;; NUM-PFX-CHARS number of line-prefix characters used by this format"
1024 (cond ((looking-at "^@@")
1025 ;; unified diff
1026 (setq num-pfx-chars 1)
1027 (forward-line 1)
1028 (setq src-pos (point) dst-pos (point)))
1029 ((looking-at "^\\*\\*")
1030 ;; context diff
1031 (forward-line 2)
1032 (setq src-pos (point))
1033 (re-search-forward "^--- " nil t)
1034 (forward-line 0)
1035 (setq divider-pos (point))
1036 (forward-line 1)
1037 (setq dst-pos (point)))
1038 ((looking-at "^[0-9]+a[0-9,]+$")
1039 ;; normal diff, insert
1040 (forward-line 1)
1041 (setq dst-pos (point)))
1042 ((looking-at "^[0-9,]+d[0-9]+$")
1043 ;; normal diff, delete
1044 (forward-line 1)
1045 (setq src-pos (point)))
1046 ((looking-at "^[0-9,]+c[0-9,]+$")
1047 ;; normal diff, change
1048 (forward-line 1)
1049 (setq src-pos (point))
1050 (re-search-forward "^---$" nil t)
1051 (forward-line 0)
1052 (setq divider-pos (point))
1053 (forward-line 1)
1054 (setq dst-pos (point)))
1055 (t
1056 (error "Unknown diff hunk type")))
1057
1058 (if (if destp (null dst-pos) (null src-pos))
1059 ;; Implied empty text
1060 (if char-offset '("" . 0) "")
1061
1062 ;; For context diffs, either side can be empty, (if there's only
1063 ;; added or only removed text). We should then use the other side.
1064 (cond ((equal src-pos divider-pos) (setq src-pos dst-pos))
1065 ((equal dst-pos (point-max)) (setq dst-pos src-pos)))
1066
1067 (when char-offset (goto-char (+ (point-min) char-offset)))
1068
1069 ;; Get rid of anything except the desired text.
1070 (save-excursion
1071 ;; Delete unused text region
1072 (let ((keep (if destp dst-pos src-pos)))
1073 (when (and divider-pos (> divider-pos keep))
1074 (delete-region divider-pos (point-max)))
1075 (delete-region (point-min) keep))
1076 ;; Remove line-prefix characters, and unneeded lines (unified diffs).
1077 (let ((kill-char (if destp ?- ?+)))
1078 (goto-char (point-min))
1079 (while (not (eobp))
1080 (if (eq (char-after) kill-char)
1081 (delete-region (point) (progn (forward-line 1) (point)))
1082 (delete-char num-pfx-chars)
1083 (forward-line 1)))))
1084
1085 (let ((text (buffer-substring-no-properties (point-min) (point-max))))
1086 (if char-offset (cons text (- (point) (point-min))) text))))))
370d860c 1087
7530b6da 1088
c0aa75f7 1089(defun diff-find-text (text)
1eabc5e6 1090 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
7530b6da 1091If TEXT isn't found, nil is returned."
7530b6da
MB
1092 (let* ((orig (point))
1093 (forw (and (search-forward text nil t)
1eabc5e6 1094 (cons (match-beginning 0) (match-end 0))))
7530b6da
MB
1095 (back (and (goto-char (+ orig (length text)))
1096 (search-backward text nil t)
1eabc5e6
SM
1097 (cons (match-beginning 0) (match-end 0)))))
1098 ;; Choose the closest match.
1099 (if (and forw back)
1100 (if (> (- (car forw) orig) (- orig (car back))) back forw)
1101 (or back forw))))
1102
1103(defun diff-find-approx-text (text)
1104 "Return the buffer position (BEG . END) of the nearest occurrence of TEXT.
1105Whitespace differences are ignored."
1106 (let* ((orig (point))
1107 (re (concat "^[ \t\n\f]*"
1108 (mapconcat 'regexp-quote (split-string text) "[ \t\n\f]+")
1109 "[ \t\n\f]*\n"))
1110 (forw (and (re-search-forward re nil t)
1111 (cons (match-beginning 0) (match-end 0))))
1112 (back (and (goto-char (+ orig (length text)))
1113 (re-search-backward re nil t)
1114 (cons (match-beginning 0) (match-end 0)))))
1115 ;; Choose the closest match.
7530b6da 1116 (if (and forw back)
1eabc5e6 1117 (if (> (- (car forw) orig) (- orig (car back))) back forw)
7530b6da
MB
1118 (or back forw))))
1119
370d860c
SM
1120(defsubst diff-xor (a b) (if a (not b) b))
1121
d868b3bd 1122(defun diff-find-source-location (&optional other-file reverse)
1eabc5e6
SM
1123 "Find out (BUF LINE-OFFSET POS SRC DST SWITCHED).
1124BUF is the buffer corresponding to the source file.
1125LINE-OFFSET is the offset between the expected and actual positions
1126 of the text of the hunk or nil if the text was not found.
1127POS is a pair (BEG . END) indicating the position of the text in the buffer.
1128SRC and DST are the two variants of text as returned by `diff-hunk-text'.
1129 SRC is the variant that was found in the buffer.
1130SWITCHED is non-nil if the patch is already applied."
7b91e0f2 1131 (save-excursion
e8a1ed31 1132 (let* ((other (diff-xor other-file diff-jump-to-old-file))
370d860c
SM
1133 (char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1134 (hunk (buffer-substring (point)
1135 (save-excursion (diff-end-of-hunk) (point))))
1136 (old (diff-hunk-text hunk reverse char-offset))
1137 (new (diff-hunk-text hunk (not reverse) char-offset))
7b91e0f2 1138 ;; Find the location specification.
d868b3bd 1139 (line (if (not (looking-at "\\(?:\\*\\{15\\}.*\n\\)?[-@* ]*\\([0-9,]+\\)\\([ acd+]+\\([0-9,]+\\)\\)?"))
370d860c
SM
1140 (error "Can't find the hunk header")
1141 (if other (match-string 1)
1142 (if (match-end 3) (match-string 3)
1143 (unless (re-search-forward "^--- \\([0-9,]+\\)" nil t)
1144 (error "Can't find the hunk separator"))
1145 (match-string 1)))))
1146 (file (or (diff-find-file-name other) (error "Can't find the file")))
1147 (buf (find-file-noselect file)))
7b91e0f2
SM
1148 ;; Update the user preference if he so wished.
1149 (when (> (prefix-numeric-value other-file) 8)
e8a1ed31 1150 (setq diff-jump-to-old-file other))
d868b3bd
SM
1151 (with-current-buffer buf
1152 (goto-line (string-to-number line))
1153 (let* ((orig-pos (point))
1eabc5e6 1154 (switched nil)
22cd1973 1155 ;; FIXME: Check for case where both OLD and NEW are found.
1eabc5e6
SM
1156 (pos (or (diff-find-text (car old))
1157 (progn (setq switched t) (diff-find-text (car new)))
1158 (progn (setq switched nil)
22cd1973
SM
1159 (condition-case nil
1160 (diff-find-approx-text (car old))
1161 (invalid-regexp nil))) ;Regex too big.
1eabc5e6 1162 (progn (setq switched t)
22cd1973
SM
1163 (condition-case nil
1164 (diff-find-approx-text (car new))
1165 (invalid-regexp nil))) ;Regex too big.
1eabc5e6 1166 (progn (setq switched nil) nil))))
370d860c
SM
1167 (nconc
1168 (list buf)
1eabc5e6
SM
1169 (if pos
1170 (list (count-lines orig-pos (car pos)) pos)
1171 (list nil (cons orig-pos (+ orig-pos (length (car old))))))
370d860c
SM
1172 (if switched (list new old t) (list old new))))))))
1173
7b91e0f2 1174
370d860c
SM
1175(defun diff-hunk-status-msg (line-offset reversed dry-run)
1176 (let ((msg (if dry-run
1177 (if reversed "already applied" "not yet applied")
1178 (if reversed "undone" "applied"))))
1179 (message (cond ((null line-offset) "Hunk text not found")
1180 ((= line-offset 0) "Hunk %s")
1181 ((= line-offset 1) "Hunk %s at offset %d line")
1182 (t "Hunk %s at offset %d lines"))
1183 msg line-offset)))
1184
1185
1186(defun diff-apply-hunk (&optional reverse)
6e4e8a3b 1187 "Apply the current hunk to the source file and go to the next.
7530b6da 1188By default, the new source file is patched, but if the variable
e8a1ed31 1189`diff-jump-to-old-file' is non-nil, then the old source file is
7530b6da
MB
1190patched instead (some commands, such as `diff-goto-source' can change
1191the value of this variable when given an appropriate prefix argument).
1192
4eaa6852 1193With a prefix argument, REVERSE the hunk."
370d860c 1194 (interactive "P")
281096ed 1195 (destructuring-bind (buf line-offset pos old new &optional switched)
22cd1973
SM
1196 ;; If REVERSE go to the new file, otherwise go to the old.
1197 (diff-find-source-location (not reverse) reverse)
370d860c 1198 (cond
4eaa6852
MB
1199 ((null line-offset)
1200 (error "Can't find the text to patch"))
370d860c 1201 ((and switched
cdbb79c1 1202 ;; A reversed patch was detected, perhaps apply it in reverse.
370d860c
SM
1203 (not (save-window-excursion
1204 (pop-to-buffer buf)
1eabc5e6 1205 (goto-char (+ (car pos) (cdr old)))
370d860c
SM
1206 (y-or-n-p
1207 (if reverse
1208 "Hunk hasn't been applied yet; apply it now? "
1209 "Hunk has already been applied; undo it? ")))))
4eaa6852 1210 (message "(Nothing done)"))
370d860c 1211 (t
4eaa6852
MB
1212 ;; Apply the hunk
1213 (with-current-buffer buf
1eabc5e6
SM
1214 (goto-char (car pos))
1215 (delete-region (car pos) (cdr pos))
4eaa6852
MB
1216 (insert (car new)))
1217 ;; Display BUF in a window
1eabc5e6 1218 (set-window-point (display-buffer buf) (+ (car pos) (cdr new)))
4eaa6852
MB
1219 (diff-hunk-status-msg line-offset (diff-xor switched reverse) nil)
1220 (when diff-advance-after-apply-hunk
1221 (diff-hunk-next))))))
370d860c 1222
7530b6da 1223
7530b6da
MB
1224(defun diff-test-hunk (&optional reverse)
1225 "See whether it's possible to apply the current hunk.
4eaa6852 1226With a prefix argument, try to REVERSE the hunk."
7530b6da 1227 (interactive "P")
370d860c 1228 (destructuring-bind (buf line-offset pos src dst &optional switched)
22cd1973
SM
1229 ;; If REVERSE go to the new file, otherwise go to the old.
1230 (diff-find-source-location (not reverse) reverse)
1eabc5e6 1231 (set-window-point (display-buffer buf) (+ (car pos) (cdr src)))
4eaa6852 1232 (diff-hunk-status-msg line-offset (diff-xor reverse switched) t)))
370d860c 1233
7530b6da 1234
a1e2d7f7
SM
1235(defalias 'diff-mouse-goto-source 'diff-goto-source)
1236
1237(defun diff-goto-source (&optional other-file event)
7530b6da 1238 "Jump to the corresponding source line.
e8a1ed31 1239`diff-jump-to-old-file' (or its opposite if the OTHER-FILE prefix arg
281096ed 1240is given) determines whether to jump to the old or the new file.
7530b6da 1241If the prefix arg is bigger than 8 (for example with \\[universal-argument] \\[universal-argument])
e8a1ed31 1242 then `diff-jump-to-old-file' is also set, for the next invocations."
a1e2d7f7 1243 (interactive (list current-prefix-arg last-input-event))
a6373340
SM
1244 ;; When pointing at a removal line, we probably want to jump to
1245 ;; the old location, and else to the new (i.e. as if reverting).
1246 ;; This is a convenient detail when using smerge-diff.
a1e2d7f7 1247 (if event (posn-set-point (event-end event)))
a6373340
SM
1248 (let ((rev (not (save-excursion (beginning-of-line) (looking-at "[-<]")))))
1249 (destructuring-bind (buf line-offset pos src dst &optional switched)
1250 (diff-find-source-location other-file rev)
1251 (pop-to-buffer buf)
1eabc5e6 1252 (goto-char (+ (car pos) (cdr src)))
55d5d717 1253 (diff-hunk-status-msg line-offset (diff-xor rev switched) t))))
370d860c 1254
7530b6da 1255
281096ed 1256(defun diff-current-defun ()
370d860c
SM
1257 "Find the name of function at point.
1258For use in `add-log-current-defun-function'."
2f9edc8b
KG
1259 (save-excursion
1260 (when (looking-at diff-hunk-header-re)
1261 (forward-line 1)
4f815065 1262 (re-search-forward "^[^ ]" nil t))
2f9edc8b
KG
1263 (destructuring-bind (buf line-offset pos src dst &optional switched)
1264 (diff-find-source-location)
281096ed
SM
1265 (beginning-of-line)
1266 (or (when (memq (char-after) '(?< ?-))
370d860c
SM
1267 ;; Cursor is pointing at removed text. This could be a removed
1268 ;; function, in which case, going to the source buffer will
1269 ;; not help since the function is now removed. Instead,
1270 ;; try to figure out the function name just from the code-fragment.
281096ed
SM
1271 (let ((old (if switched dst src)))
1272 (with-temp-buffer
1273 (insert (car old))
281096ed 1274 (funcall (with-current-buffer buf major-mode))
cb4e8176 1275 (goto-char (+ (point-min) (cdr old)))
281096ed
SM
1276 (add-log-current-defun))))
1277 (with-current-buffer buf
1eabc5e6 1278 (goto-char (+ (car pos) (cdr src)))
281096ed 1279 (add-log-current-defun))))))
027ac3f8 1280
22cd1973
SM
1281(defun diff-refine-hunk ()
1282 "Refine the current hunk by ignoring space differences."
1283 (interactive)
1284 (let* ((char-offset (- (point) (progn (diff-beginning-of-hunk) (point))))
1285 (opts (case (char-after) (?@ "-bu") (?* "-bc") (t "-b")))
1286 (line-nb (and (or (looking-at "[^0-9]+\\([0-9]+\\)")
1287 (error "Can't find line number"))
1288 (string-to-number (match-string 1))))
1289 (hunk (delete-and-extract-region
1290 (point) (save-excursion (diff-end-of-hunk) (point))))
1291 (lead (make-string (1- line-nb) ?\n)) ;Line nums start at 1.
1292 (file1 (make-temp-file "diff1"))
1293 (file2 (make-temp-file "diff2"))
1294 (coding-system-for-read buffer-file-coding-system)
1295 old new)
1296 (unwind-protect
1297 (save-excursion
1298 (setq old (diff-hunk-text hunk nil char-offset))
1299 (setq new (diff-hunk-text hunk t char-offset))
1300 (write-region (concat lead (car old)) nil file1 nil 'nomessage)
1301 (write-region (concat lead (car new)) nil file2 nil 'nomessage)
1302 (with-temp-buffer
1303 (let ((status
1304 (call-process diff-command nil t nil
1305 opts file1 file2)))
1306 (case status
1307 (0 nil) ;Nothing to reformat.
1308 (1 (goto-char (point-min))
1309 ;; Remove the file-header.
1310 (when (re-search-forward diff-hunk-header-re nil t)
1311 (delete-region (point-min) (match-beginning 0))))
1312 (t (goto-char (point-max))
1313 (unless (bolp) (insert "\n"))
1314 (insert hunk)))
1315 (setq hunk (buffer-string))
1316 (unless (memq status '(0 1))
1317 (error "Diff returned: %s" status)))))
1318 ;; Whatever happens, put back some equivalent text: either the new
1319 ;; one or the original one in case some error happened.
1320 (insert hunk)
1321 (delete-file file1)
1322 (delete-file file2))))
1323
610a6418
SM
1324;; provide the package
1325(provide 'diff-mode)
1326
027ac3f8 1327;;; Old Change Log from when diff-mode wasn't part of Emacs:
610a6418
SM
1328;; Revision 1.11 1999/10/09 23:38:29 monnier
1329;; (diff-mode-load-hook): dropped.
1330;; (auto-mode-alist): also catch *.diffs.
1331;; (diff-find-file-name, diff-mode): add smarts to find the right file
1332;; for *.rej files (that lack any file name indication).
1333;;
1334;; Revision 1.10 1999/09/30 15:32:11 monnier
1335;; added support for "\ No newline at end of file".
1336;;
1337;; Revision 1.9 1999/09/15 00:01:13 monnier
1338;; - added basic `compile' support.
1339;; - have diff-kill-hunk call diff-kill-file if it's the only hunk.
1340;; - diff-kill-file now tries to kill the leading garbage as well.
1341;;
1342;; Revision 1.8 1999/09/13 21:10:09 monnier
1343;; - don't use CL in the autoloaded code
1344;; - accept diffs using -T
1345;;
1346;; Revision 1.7 1999/09/05 20:53:03 monnier
1347;; interface to ediff-patch
1348;;
1349;; Revision 1.6 1999/09/01 20:55:13 monnier
1350;; (ediff=patch-file): add bindings to call ediff-patch.
1351;; (diff-find-file-name): taken out of diff-goto-source.
1352;; (diff-unified->context, diff-context->unified, diff-reverse-direction,
1353;; diff-fixup-modifs): only use the region if a prefix arg is given.
1354;;
1355;; Revision 1.5 1999/08/31 19:18:52 monnier
1356;; (diff-beginning-of-file, diff-prev-file): fixed wrong parenthesis.
1357;;
1358;; Revision 1.4 1999/08/31 13:01:44 monnier
1359;; use `combine-after-change-calls' to minimize the slowdown of font-lock.
1360;;
1361
4f815065 1362;; arch-tag: 2571d7ff-bc28-4cf9-8585-42e21890be66
610a6418 1363;;; diff-mode.el ends here