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