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