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