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