diff-mode.el 88 KB

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