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