LCOV - code coverage report
Current view: top level - lisp/vc - diff-mode.el (source / functions) Hit Total Coverage
Test: tramp-tests.info Lines: 0 1087 0.0 %
Date: 2017-08-27 09:44:50 Functions: 0 66 0.0 %

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

Generated by: LCOV version 1.12