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