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