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