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