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