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