WmlComparer.Private.Methods.ProduceDocument.cs 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239
  1. // Copyright (c) Microsoft. All rights reserved.
  2. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.IO.Packaging;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Xml.Linq;
  10. using DocumentFormat.OpenXml.Packaging;
  11. using OpenXmlPowerTools.Previous;
  12. namespace OpenXmlPowerTools
  13. {
  14. public static partial class WmlComparer
  15. {
  16. private static WmlDocument ProduceDocumentWithTrackedRevisions(
  17. WmlComparerSettings settings,
  18. WmlDocument wmlResult,
  19. WordprocessingDocument wDoc1,
  20. WordprocessingDocument wDoc2)
  21. {
  22. // save away sectPr so that can set in the newly produced document.
  23. XElement savedSectPr = wDoc1
  24. .MainDocumentPart
  25. .GetXDocument()
  26. .Root?
  27. .Element(W.body)?
  28. .Element(W.sectPr);
  29. XElement contentParent1 = wDoc1.MainDocumentPart.GetXDocument().Root?.Element(W.body);
  30. AddSha1HashToBlockLevelContent(wDoc1.MainDocumentPart, contentParent1, settings);
  31. XElement contentParent2 = wDoc2.MainDocumentPart.GetXDocument().Root?.Element(W.body);
  32. AddSha1HashToBlockLevelContent(wDoc2.MainDocumentPart, contentParent2, settings);
  33. ComparisonUnitAtom[] cal1 = CreateComparisonUnitAtomList(
  34. wDoc1.MainDocumentPart,
  35. wDoc1.MainDocumentPart.GetXDocument().Root?.Element(W.body),
  36. settings);
  37. if (False)
  38. {
  39. var sb = new StringBuilder();
  40. foreach (ComparisonUnitAtom item in cal1)
  41. sb.Append(item + Environment.NewLine);
  42. string sbs = sb.ToString();
  43. TestUtil.NotePad(sbs);
  44. }
  45. ComparisonUnit[] cus1 = GetComparisonUnitList(cal1, settings);
  46. if (False)
  47. {
  48. string sbs = ComparisonUnit.ComparisonUnitListToString(cus1);
  49. TestUtil.NotePad(sbs);
  50. }
  51. ComparisonUnitAtom[] cal2 = CreateComparisonUnitAtomList(
  52. wDoc2.MainDocumentPart,
  53. wDoc2.MainDocumentPart.GetXDocument().Root?.Element(W.body),
  54. settings);
  55. if (False)
  56. {
  57. var sb = new StringBuilder();
  58. foreach (ComparisonUnitAtom item in cal2)
  59. sb.Append(item + Environment.NewLine);
  60. string sbs = sb.ToString();
  61. TestUtil.NotePad(sbs);
  62. }
  63. ComparisonUnit[] cus2 = GetComparisonUnitList(cal2, settings);
  64. if (False)
  65. {
  66. string sbs = ComparisonUnit.ComparisonUnitListToString(cus2);
  67. TestUtil.NotePad(sbs);
  68. }
  69. if (False)
  70. {
  71. var sb3 = new StringBuilder();
  72. sb3.Append("ComparisonUnitList 1 =====" + Environment.NewLine + Environment.NewLine);
  73. sb3.Append(ComparisonUnit.ComparisonUnitListToString(cus1));
  74. sb3.Append(Environment.NewLine);
  75. sb3.Append("ComparisonUnitList 2 =====" + Environment.NewLine + Environment.NewLine);
  76. sb3.Append(ComparisonUnit.ComparisonUnitListToString(cus2));
  77. string sbs3 = sb3.ToString();
  78. TestUtil.NotePad(sbs3);
  79. }
  80. List<CorrelatedSequence> correlatedSequence = Lcs(cus1, cus2, settings);
  81. if (False)
  82. {
  83. var sb = new StringBuilder();
  84. foreach (CorrelatedSequence item in correlatedSequence)
  85. {
  86. sb.Append(item + Environment.NewLine);
  87. }
  88. string sbs = sb.ToString();
  89. TestUtil.NotePad(sbs);
  90. }
  91. // for any deleted or inserted rows, we go into the w:trPr properties, and add the appropriate w:ins or
  92. // w:del element, and therefore when generating the document, the appropriate row will be marked as deleted
  93. // or inserted.
  94. MarkRowsAsDeletedOrInserted(settings, correlatedSequence);
  95. // the following gets a flattened list of ComparisonUnitAtoms, with status indicated in each
  96. // ComparisonUnitAtom: Deleted, Inserted, or Equal
  97. List<ComparisonUnitAtom> listOfComparisonUnitAtoms = FlattenToComparisonUnitAtomList(correlatedSequence, settings);
  98. if (False)
  99. {
  100. var sb = new StringBuilder();
  101. foreach (ComparisonUnitAtom item in listOfComparisonUnitAtoms)
  102. {
  103. sb.Append(item + Environment.NewLine);
  104. }
  105. string sbs = sb.ToString();
  106. TestUtil.NotePad(sbs);
  107. }
  108. // note - we don't want to do the hack until after flattening all of the groups. At the end of the
  109. // flattening, we should simply have a list of ComparisonUnitAtoms, appropriately marked as equal,
  110. // inserted, or deleted.
  111. // the table id will be hacked in the normal course of events.
  112. // in the case where a row is deleted, not necessary to hack - the deleted row ID will do.
  113. // in the case where a row is inserted, not necessary to hack - the inserted row ID will do as well.
  114. AssembleAncestorUnidsInOrderToRebuildXmlTreeProperly(listOfComparisonUnitAtoms);
  115. if (False)
  116. {
  117. var sb = new StringBuilder();
  118. foreach (ComparisonUnitAtom item in listOfComparisonUnitAtoms)
  119. sb.Append(item.ToStringAncestorUnids() + Environment.NewLine);
  120. string sbs = sb.ToString();
  121. TestUtil.NotePad(sbs);
  122. }
  123. // and then finally can generate the document with revisions
  124. using (var ms = new MemoryStream())
  125. {
  126. ms.Write(wmlResult.DocumentByteArray, 0, wmlResult.DocumentByteArray.Length);
  127. using (WordprocessingDocument wDocWithRevisions = WordprocessingDocument.Open(ms, true))
  128. {
  129. XDocument xDoc = wDocWithRevisions.MainDocumentPart.GetXDocument();
  130. List<XAttribute> rootNamespaceAttributes = xDoc
  131. .Root?
  132. .Attributes()
  133. .Where(a => a.IsNamespaceDeclaration || a.Name.Namespace == MC.mc)
  134. .ToList();
  135. // ======================================
  136. // The following produces a new valid WordprocessingML document from the listOfComparisonUnitAtoms
  137. object newBodyChildren = ProduceNewWmlMarkupFromCorrelatedSequence(
  138. wDocWithRevisions.MainDocumentPart,
  139. listOfComparisonUnitAtoms,
  140. settings);
  141. var newXDoc = new XDocument();
  142. newXDoc.Add(
  143. new XElement(W.document,
  144. rootNamespaceAttributes,
  145. new XElement(W.body, newBodyChildren)));
  146. MarkContentAsDeletedOrInserted(newXDoc, settings);
  147. CoalesceAdjacentRunsWithIdenticalFormatting(newXDoc);
  148. IgnorePt14Namespace(newXDoc.Root);
  149. ProcessFootnoteEndnote(settings,
  150. listOfComparisonUnitAtoms,
  151. wDoc1.MainDocumentPart,
  152. wDoc2.MainDocumentPart,
  153. newXDoc);
  154. RectifyFootnoteEndnoteIds(
  155. wDoc1.MainDocumentPart,
  156. wDoc2.MainDocumentPart,
  157. wDocWithRevisions.MainDocumentPart,
  158. newXDoc,
  159. settings);
  160. ConjoinDeletedInsertedParagraphMarks(wDocWithRevisions.MainDocumentPart, newXDoc);
  161. FixUpRevisionIds(wDocWithRevisions, newXDoc);
  162. // little bit of cleanup
  163. MoveLastSectPrToChildOfBody(newXDoc);
  164. var newXDoc2Root = (XElement) WordprocessingMLUtil.WmlOrderElementsPerStandard(newXDoc.Root);
  165. xDoc.Root?.ReplaceWith(newXDoc2Root);
  166. /**********************************************************************************************/
  167. // temporary code to remove sections. When remove this code, get validation errors for some ITU documents.
  168. // Note: This is a no-go for use cases in which documents have multiple sections, e.g., for title pages,
  169. // front matter, and body matter. Another example is where you have to switch between portrait and
  170. // landscape orientation, which requires sections.
  171. // TODO: Revisit
  172. xDoc.Root?.Descendants(W.sectPr).Remove();
  173. // move w:sectPr from source document into newly generated document.
  174. if (savedSectPr != null)
  175. {
  176. XDocument xd = wDocWithRevisions.MainDocumentPart.GetXDocument();
  177. // add everything but headers/footers
  178. var clonedSectPr = new XElement(W.sectPr,
  179. savedSectPr.Attributes(),
  180. savedSectPr.Element(W.type),
  181. savedSectPr.Element(W.pgSz),
  182. savedSectPr.Element(W.pgMar),
  183. savedSectPr.Element(W.cols),
  184. savedSectPr.Element(W.titlePg));
  185. xd.Root?.Element(W.body)?.Add(clonedSectPr);
  186. }
  187. /**********************************************************************************************/
  188. wDocWithRevisions.MainDocumentPart.PutXDocument();
  189. FixUpFootnotesEndnotesWithCustomMarkers(wDocWithRevisions);
  190. FixUpRevMarkIds(wDocWithRevisions);
  191. FixUpDocPrIds(wDocWithRevisions);
  192. FixUpShapeIds(wDocWithRevisions);
  193. FixUpShapeTypeIds(wDocWithRevisions);
  194. AddFootnotesEndnotesStyles(wDocWithRevisions);
  195. CopyMissingStylesFromOneDocToAnother(wDoc2, wDocWithRevisions);
  196. DeleteFootnotePropertiesInSettings(wDocWithRevisions);
  197. }
  198. foreach (OpenXmlPart part in wDoc1.ContentParts())
  199. {
  200. part.PutXDocument();
  201. }
  202. foreach (OpenXmlPart part in wDoc2.ContentParts())
  203. {
  204. part.PutXDocument();
  205. }
  206. var updatedWmlResult = new WmlDocument("Dummy.docx", ms.ToArray());
  207. return updatedWmlResult;
  208. }
  209. }
  210. private static void AddSha1HashToBlockLevelContent(OpenXmlPart part, XElement contentParent, WmlComparerSettings settings)
  211. {
  212. IEnumerable<XElement> blockLevelContentToAnnotate = contentParent
  213. .Descendants()
  214. .Where(d => ElementsToHaveSha1Hash.Contains(d.Name));
  215. foreach (XElement blockLevelContent in blockLevelContentToAnnotate)
  216. {
  217. var cloneBlockLevelContentForHashing =
  218. (XElement) CloneBlockLevelContentForHashing(part, blockLevelContent, true, settings);
  219. string shaString = cloneBlockLevelContentForHashing.ToString(SaveOptions.DisableFormatting)
  220. .Replace(" xmlns=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"", "");
  221. string sha1Hash = PtUtils.SHA1HashStringForUTF8String(shaString);
  222. blockLevelContent.Add(new XAttribute(PtOpenXml.SHA1Hash, sha1Hash));
  223. if (blockLevelContent.Name == W.tbl ||
  224. blockLevelContent.Name == W.tr)
  225. {
  226. var clonedForStructureHash = (XElement) CloneForStructureHash(cloneBlockLevelContentForHashing);
  227. // this is a convenient place to look at why tables are being compared as different.
  228. //if (blockLevelContent.Name == W.tbl)
  229. // Console.WriteLine();
  230. string shaString2 = clonedForStructureHash.ToString(SaveOptions.DisableFormatting)
  231. .Replace(" xmlns=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"", "");
  232. string sha1Hash2 = PtUtils.SHA1HashStringForUTF8String(shaString2);
  233. blockLevelContent.Add(new XAttribute(PtOpenXml.StructureSHA1Hash, sha1Hash2));
  234. }
  235. }
  236. }
  237. private static List<CorrelatedSequence> Lcs(ComparisonUnit[] cu1, ComparisonUnit[] cu2, WmlComparerSettings settings)
  238. {
  239. // set up initial state - one CorrelatedSequence, UnKnown, contents == entire sequences (both)
  240. var cs = new CorrelatedSequence
  241. {
  242. CorrelationStatus = CorrelationStatus.Unknown,
  243. ComparisonUnitArray1 = cu1,
  244. ComparisonUnitArray2 = cu2
  245. };
  246. var csList = new List<CorrelatedSequence>
  247. {
  248. cs
  249. };
  250. while (true)
  251. {
  252. if (False)
  253. {
  254. var sb = new StringBuilder();
  255. foreach (CorrelatedSequence item in csList)
  256. sb.Append(item).Append(Environment.NewLine);
  257. string sbs = sb.ToString();
  258. TestUtil.NotePad(sbs);
  259. }
  260. CorrelatedSequence unknown = csList
  261. .FirstOrDefault(z => z.CorrelationStatus == CorrelationStatus.Unknown);
  262. if (unknown != null)
  263. {
  264. // if unknown consists of a single group of the same type in each side, then can set some Unids in the 'after' document.
  265. // if the unknown is a pair of single tables, then can set table Unid.
  266. // if the unknown is a pair of single rows, then can set table and rows Unids.
  267. // if the unknown is a pair of single cells, then can set table, row, and cell Unids.
  268. // if the unknown is a pair of paragraphs, then can set paragraph (and all ancestor) Unids.
  269. SetAfterUnids(unknown);
  270. if (False)
  271. {
  272. var sb = new StringBuilder();
  273. sb.Append(unknown);
  274. string sbs = sb.ToString();
  275. TestUtil.NotePad(sbs);
  276. }
  277. List<CorrelatedSequence> newSequence = ProcessCorrelatedHashes(unknown, settings);
  278. if (newSequence == null)
  279. {
  280. newSequence = FindCommonAtBeginningAndEnd(unknown, settings);
  281. if (newSequence == null)
  282. {
  283. newSequence = DoLcsAlgorithm(unknown, settings);
  284. }
  285. }
  286. int indexOfUnknown = csList.IndexOf(unknown);
  287. csList.Remove(unknown);
  288. newSequence.Reverse();
  289. foreach (CorrelatedSequence item in newSequence)
  290. csList.Insert(indexOfUnknown, item);
  291. continue;
  292. }
  293. return csList;
  294. }
  295. }
  296. private static void MarkRowsAsDeletedOrInserted(WmlComparerSettings settings, List<CorrelatedSequence> correlatedSequence)
  297. {
  298. foreach (CorrelatedSequence dcs in correlatedSequence.Where(cs =>
  299. cs.CorrelationStatus == CorrelationStatus.Deleted || cs.CorrelationStatus == CorrelationStatus.Inserted))
  300. {
  301. // iterate through all deleted/inserted items in dcs.ComparisonUnitArray1/ComparisonUnitArray2
  302. ComparisonUnit[] toIterateThrough = dcs.ComparisonUnitArray1;
  303. if (dcs.CorrelationStatus == CorrelationStatus.Inserted)
  304. toIterateThrough = dcs.ComparisonUnitArray2;
  305. foreach (ComparisonUnit ca in toIterateThrough)
  306. {
  307. var cug = ca as ComparisonUnitGroup;
  308. // this works because we will never see a table in this list, only rows. If tables were in this list, would need to recursively
  309. // go into children, but tables are always flattened in the LCS process.
  310. // when we have a row, it is only necessary to find the first content atom of the row, then find the row ancestor, and then tweak
  311. // the w:trPr
  312. if (cug != null && cug.ComparisonUnitGroupType == ComparisonUnitGroupType.Row)
  313. {
  314. ComparisonUnitAtom firstContentAtom = cug.DescendantContentAtoms().FirstOrDefault();
  315. if (firstContentAtom == null)
  316. throw new OpenXmlPowerToolsException("Internal error");
  317. XElement tr = firstContentAtom
  318. .AncestorElements
  319. .Reverse()
  320. .FirstOrDefault(a => a.Name == W.tr);
  321. if (tr == null)
  322. throw new OpenXmlPowerToolsException("Internal error");
  323. XElement trPr = tr.Element(W.trPr);
  324. if (trPr == null)
  325. {
  326. trPr = new XElement(W.trPr);
  327. tr.AddFirst(trPr);
  328. }
  329. XName revTrackElementName = null;
  330. if (dcs.CorrelationStatus == CorrelationStatus.Deleted)
  331. revTrackElementName = W.del;
  332. else if (dcs.CorrelationStatus == CorrelationStatus.Inserted)
  333. revTrackElementName = W.ins;
  334. trPr.Add(new XElement(revTrackElementName,
  335. new XAttribute(W.author, settings.AuthorForRevisions),
  336. new XAttribute(W.id, _maxId++),
  337. new XAttribute(W.date, settings.DateTimeForRevisions)));
  338. }
  339. }
  340. }
  341. }
  342. private static List<ComparisonUnitAtom> FlattenToComparisonUnitAtomList(
  343. List<CorrelatedSequence> correlatedSequence,
  344. WmlComparerSettings settings)
  345. {
  346. List<ComparisonUnitAtom> listOfComparisonUnitAtoms = correlatedSequence
  347. .Select(cs =>
  348. {
  349. // need to write some code here to find out if we are assembling a paragraph (or anything) that contains the following unid.
  350. // why do are we dropping content???????
  351. //string searchFor = "0ecb9184";
  352. if (cs.CorrelationStatus == CorrelationStatus.Equal)
  353. {
  354. IEnumerable<ComparisonUnitAtom> contentAtomsBefore = cs
  355. .ComparisonUnitArray1
  356. .Select(ca => ca.DescendantContentAtoms())
  357. .SelectMany(m => m);
  358. IEnumerable<ComparisonUnitAtom> contentAtomsAfter = cs
  359. .ComparisonUnitArray2
  360. .Select(ca => ca.DescendantContentAtoms())
  361. .SelectMany(m => m);
  362. List<ComparisonUnitAtom> comparisonUnitAtomList = contentAtomsBefore
  363. .Zip(contentAtomsAfter,
  364. (before, after) => new ComparisonUnitAtom(
  365. after.ContentElement,
  366. after.AncestorElements,
  367. after.Part,
  368. settings)
  369. {
  370. CorrelationStatus = CorrelationStatus.Equal,
  371. ContentElementBefore = before.ContentElement,
  372. ComparisonUnitAtomBefore = before
  373. })
  374. .ToList();
  375. return comparisonUnitAtomList;
  376. }
  377. if (cs.CorrelationStatus == CorrelationStatus.Deleted)
  378. {
  379. IEnumerable<ComparisonUnitAtom> comparisonUnitAtomList = cs
  380. .ComparisonUnitArray1
  381. .Select(ca => ca.DescendantContentAtoms())
  382. .SelectMany(m => m)
  383. .Select(ca =>
  384. new ComparisonUnitAtom(ca.ContentElement, ca.AncestorElements, ca.Part, settings)
  385. {
  386. CorrelationStatus = CorrelationStatus.Deleted
  387. });
  388. return comparisonUnitAtomList;
  389. }
  390. if (cs.CorrelationStatus == CorrelationStatus.Inserted)
  391. {
  392. IEnumerable<ComparisonUnitAtom> comparisonUnitAtomList = cs
  393. .ComparisonUnitArray2
  394. .Select(ca => ca.DescendantContentAtoms())
  395. .SelectMany(m => m)
  396. .Select(ca =>
  397. new ComparisonUnitAtom(ca.ContentElement, ca.AncestorElements, ca.Part, settings)
  398. {
  399. CorrelationStatus = CorrelationStatus.Inserted
  400. });
  401. return comparisonUnitAtomList;
  402. }
  403. throw new OpenXmlPowerToolsException("Internal error");
  404. })
  405. .SelectMany(m => m)
  406. .ToList();
  407. if (False)
  408. {
  409. var sb = new StringBuilder();
  410. foreach (ComparisonUnitAtom item in listOfComparisonUnitAtoms)
  411. sb.Append(item).Append(Environment.NewLine);
  412. string sbs = sb.ToString();
  413. TestUtil.NotePad(sbs);
  414. }
  415. return listOfComparisonUnitAtoms;
  416. }
  417. /// Here is the crux of the fix to the algorithm. After assembling the entire list of ComparisonUnitAtoms, we do the following:
  418. /// - First, figure out the maximum hierarchy depth, considering only paragraphs, txbx, txbxContent, tables, rows, cells, and content controls.
  419. /// - For documents that do not contain tables, nor text boxes, this maximum hierarchy depth will always be 1.
  420. /// - For atoms within a table, the depth will be 4. The first level is the table, the second level is row, third is cell, fourth is paragraph.
  421. /// - For atoms within a nested table, the depth will be 7: Table / Row / Cell / Table / Row / Cell / Paragraph
  422. /// - For atoms within a text box, the depth will be 3: Paragraph / txbxContent / Paragraph
  423. /// - For atoms within a table in a text box, the depth will be 5: Paragraph / txbxContent / Table / Row / Cell / Paragraph
  424. /// In any case, we figure out the maximum depth.
  425. ///
  426. /// Then we iterate through the list of content atoms backwards. We do this n times, where n is the maximum depth.
  427. ///
  428. /// At each level, we find a paragraph mark, and working backwards, we set the guids in the hierarchy so that the content will be assembled together correctly.
  429. ///
  430. /// For each iteration, we only set unids at the level that we are working at.
  431. ///
  432. /// So first we will set all unids at level 1. When we find a paragraph mark, we get the unid for that level, and then working backwards, until we find another
  433. /// paragraph mark, we set all unids at level 1 to the same unid as level 1 of the paragraph mark.
  434. ///
  435. /// Then we set all unids at level 2. When we find a paragraph mark, we get the unid for that level, and then working backwards, until we find another paragraph
  436. /// mark, we set all unids at level 2 to the same unid as level 2 of the paragraph mark. At some point, we will find a paragraph mark with no level 2. This is
  437. /// not a problem. We stop setting anything until we find another paragraph mark that has a level 2, at which point we resume setting values at level 2.
  438. ///
  439. /// Same process for level 3, and so on, until we have processed to the maximum depth of the hierarchy.
  440. ///
  441. /// At the end of this process, we will be able to do the coalsce recurse algorithm, and the content atom list will be put back together into a beautiful tree,
  442. /// where every element is correctly positioned in the hierarchy.
  443. ///
  444. /// This should also properly assemble the test where just the paragraph marks have been deleted for a range of paragraphs.
  445. ///
  446. /// There is an interesting thought - it is possible that I have set two runs of text that were initially in the same paragraph, but then after
  447. /// processing, they match up to text in different paragraphs. Therefore this will not work. We need to actually keep a list of reconstructed ancestor
  448. /// Unids, because the same paragraph would get set to two different IDs - two ComparisonUnitAtoms need to be in separate paragraphs in the reconstructed
  449. /// document, but their ancestors actually point to the same paragraph.
  450. ///
  451. /// Fix this in the algorithm, and also keep the appropriate list in ComparisonUnitAtom class.
  452. private static void AssembleAncestorUnidsInOrderToRebuildXmlTreeProperly(List<ComparisonUnitAtom> comparisonUnitAtomList)
  453. {
  454. if (False)
  455. {
  456. var sb = new StringBuilder();
  457. foreach (ComparisonUnitAtom item in comparisonUnitAtomList)
  458. sb.Append(item).Append(Environment.NewLine);
  459. string sbs = sb.ToString();
  460. TestUtil.NotePad(sbs);
  461. }
  462. // the following loop sets all ancestor unids in the after document to the unids in the before document for all pPr where the status is equal.
  463. // this should always be true.
  464. // one additional modification to make to this loop - where we find a pPr in a text box, we want to do this as well, regardless of whether the status is equal, inserted, or deleted.
  465. // reason being that this module does not support insertion / deletion of text boxes themselves. If a text box is in the before or after document, it will be in the document that
  466. // contains deltas. It may have inserted or deleted text, but regardless, it will be in the result document.
  467. foreach (ComparisonUnitAtom cua in comparisonUnitAtomList)
  468. {
  469. var doSet = false;
  470. if (cua.ContentElement.Name == W.pPr)
  471. {
  472. if (cua.AncestorElements.Any(ae => ae.Name == W.txbxContent))
  473. doSet = true;
  474. if (cua.CorrelationStatus == CorrelationStatus.Equal)
  475. doSet = true;
  476. }
  477. if (doSet)
  478. {
  479. ComparisonUnitAtom cuaBefore = cua.ComparisonUnitAtomBefore;
  480. XElement[] ancestorsAfter = cua.AncestorElements;
  481. if (cuaBefore != null)
  482. {
  483. XElement[] ancestorsBefore = cuaBefore.AncestorElements;
  484. if (ancestorsAfter.Length == ancestorsBefore.Length)
  485. {
  486. var zipped = ancestorsBefore.Zip(ancestorsAfter, (b, a) =>
  487. new
  488. {
  489. After = a,
  490. Before = b
  491. });
  492. foreach (var z in zipped)
  493. {
  494. XAttribute afterUnidAtt = z.After.Attribute(PtOpenXml.Unid);
  495. XAttribute beforeUnidAtt = z.Before.Attribute(PtOpenXml.Unid);
  496. if (afterUnidAtt != null && beforeUnidAtt != null)
  497. afterUnidAtt.Value = beforeUnidAtt.Value;
  498. }
  499. }
  500. }
  501. }
  502. }
  503. if (False)
  504. {
  505. var sb = new StringBuilder();
  506. foreach (ComparisonUnitAtom item in comparisonUnitAtomList)
  507. sb.Append(item).Append(Environment.NewLine);
  508. string sbs = sb.ToString();
  509. TestUtil.NotePad(sbs);
  510. }
  511. List<ComparisonUnitAtom> rComparisonUnitAtomList =
  512. ((IEnumerable<ComparisonUnitAtom>) comparisonUnitAtomList).Reverse().ToList();
  513. // the following should always succeed, because there will always be at least one element in
  514. // rComparisonUnitAtomList, and there will always be at least one ancestor in AncestorElements
  515. XElement deepestAncestor = rComparisonUnitAtomList.First().AncestorElements.First();
  516. XName deepestAncestorName = deepestAncestor.Name;
  517. string deepestAncestorUnid = null;
  518. if (deepestAncestorName == W.footnote || deepestAncestorName == W.endnote)
  519. {
  520. deepestAncestorUnid = (string) deepestAncestor.Attribute(PtOpenXml.Unid);
  521. }
  522. // If the following loop finds a pPr that is in a text box, then continue on, processing the pPr and all of its contents as though it were
  523. // content in the containing text box. This is going to leave it after this loop where the AncestorUnids for the content in the text box will be
  524. // incomplete. We then will need to go through the rComparisonUnitAtomList a second time, processing all of the text boxes.
  525. // Note that this makes the basic assumption that a text box can't be nested inside of a text box, which, as far as I know, is a good assumption.
  526. // This also makes the basic assumption that an endnote / footnote can't contain a text box, which I believe is a good assumption.
  527. string[] currentAncestorUnids = null;
  528. foreach (ComparisonUnitAtom cua in rComparisonUnitAtomList)
  529. {
  530. if (cua.ContentElement.Name == W.pPr)
  531. {
  532. bool pPr_inTextBox = cua
  533. .AncestorElements
  534. .Any(ae => ae.Name == W.txbxContent);
  535. if (!pPr_inTextBox)
  536. {
  537. // this will collect the ancestor unids for the paragraph.
  538. // my hypothesis is that these ancestor unids should be the same for all content unit atoms within that paragraph.
  539. currentAncestorUnids = cua
  540. .AncestorElements
  541. .Select(ae =>
  542. {
  543. var thisUnid = (string) ae.Attribute(PtOpenXml.Unid);
  544. if (thisUnid == null)
  545. throw new OpenXmlPowerToolsException("Internal error");
  546. return thisUnid;
  547. })
  548. .ToArray();
  549. cua.AncestorUnids = currentAncestorUnids;
  550. if (deepestAncestorUnid != null)
  551. cua.AncestorUnids[0] = deepestAncestorUnid;
  552. continue;
  553. }
  554. }
  555. int thisDepth = cua.AncestorElements.Length;
  556. IEnumerable<string> additionalAncestorUnids = cua
  557. .AncestorElements
  558. .Skip(currentAncestorUnids.Length)
  559. .Select(ae =>
  560. {
  561. var thisUnid = (string) ae.Attribute(PtOpenXml.Unid);
  562. if (thisUnid == null)
  563. Guid.NewGuid().ToString().Replace("-", "");
  564. return thisUnid;
  565. });
  566. string[] thisAncestorUnids = currentAncestorUnids
  567. .Concat(additionalAncestorUnids)
  568. .ToArray();
  569. cua.AncestorUnids = thisAncestorUnids;
  570. if (deepestAncestorUnid != null)
  571. cua.AncestorUnids[0] = deepestAncestorUnid;
  572. }
  573. if (False)
  574. {
  575. var sb = new StringBuilder();
  576. foreach (ComparisonUnitAtom item in comparisonUnitAtomList)
  577. sb.Append(item).Append(Environment.NewLine);
  578. string sbs = sb.ToString();
  579. TestUtil.NotePad(sbs);
  580. }
  581. // this is the second loop that processes all text boxes.
  582. currentAncestorUnids = null;
  583. var skipUntilNextPpr = false;
  584. foreach (ComparisonUnitAtom cua in rComparisonUnitAtomList)
  585. {
  586. if (currentAncestorUnids != null && cua.AncestorElements.Length < currentAncestorUnids.Length)
  587. {
  588. skipUntilNextPpr = true;
  589. currentAncestorUnids = null;
  590. continue;
  591. }
  592. if (cua.ContentElement.Name == W.pPr)
  593. {
  594. //if (s_True)
  595. //{
  596. // var sb = new StringBuilder();
  597. // foreach (var item in comparisonUnitAtomList)
  598. // sb.Append(item.ToString()).Append(Environment.NewLine);
  599. // var sbs = sb.ToString();
  600. // TestUtil.NotePad(sbs);
  601. //}
  602. bool pPr_inTextBox = cua
  603. .AncestorElements
  604. .Any(ae => ae.Name == W.txbxContent);
  605. if (!pPr_inTextBox)
  606. {
  607. skipUntilNextPpr = true;
  608. currentAncestorUnids = null;
  609. continue;
  610. }
  611. skipUntilNextPpr = false;
  612. currentAncestorUnids = cua
  613. .AncestorElements
  614. .Select(ae =>
  615. {
  616. var thisUnid = (string) ae.Attribute(PtOpenXml.Unid);
  617. if (thisUnid == null)
  618. throw new OpenXmlPowerToolsException("Internal error");
  619. return thisUnid;
  620. })
  621. .ToArray();
  622. cua.AncestorUnids = currentAncestorUnids;
  623. continue;
  624. }
  625. if (skipUntilNextPpr)
  626. continue;
  627. int thisDepth = cua.AncestorElements.Length;
  628. IEnumerable<string> additionalAncestorUnids = cua
  629. .AncestorElements
  630. .Skip(currentAncestorUnids.Length)
  631. .Select(ae =>
  632. {
  633. var thisUnid = (string) ae.Attribute(PtOpenXml.Unid);
  634. if (thisUnid == null)
  635. Guid.NewGuid().ToString().Replace("-", "");
  636. return thisUnid;
  637. });
  638. string[] thisAncestorUnids = currentAncestorUnids
  639. .Concat(additionalAncestorUnids)
  640. .ToArray();
  641. cua.AncestorUnids = thisAncestorUnids;
  642. }
  643. if (False)
  644. {
  645. var sb = new StringBuilder();
  646. foreach (ComparisonUnitAtom item in comparisonUnitAtomList)
  647. sb.Append(item.ToStringAncestorUnids()).Append(Environment.NewLine);
  648. string sbs = sb.ToString();
  649. TestUtil.NotePad(sbs);
  650. }
  651. }
  652. private static object ProduceNewWmlMarkupFromCorrelatedSequence(
  653. OpenXmlPart part,
  654. IEnumerable<ComparisonUnitAtom> comparisonUnitAtomList,
  655. WmlComparerSettings settings)
  656. {
  657. // fabricate new MainDocumentPart from correlatedSequence
  658. _maxId = 0;
  659. object newBodyChildren = CoalesceRecurse(part, comparisonUnitAtomList, 0, settings);
  660. return newBodyChildren;
  661. }
  662. private static void MarkContentAsDeletedOrInserted(XDocument newXDoc, WmlComparerSettings settings)
  663. {
  664. object newRoot = MarkContentAsDeletedOrInsertedTransform(newXDoc.Root, settings);
  665. newXDoc.Root?.ReplaceWith(newRoot);
  666. }
  667. private static object MarkContentAsDeletedOrInsertedTransform(XNode node, WmlComparerSettings settings)
  668. {
  669. if (node is XElement element)
  670. {
  671. if (element.Name == W.r)
  672. {
  673. List<string> statusList = element
  674. .DescendantsTrimmed(W.txbxContent)
  675. .Where(d => d.Name == W.t || d.Name == W.delText || AllowableRunChildren.Contains(d.Name))
  676. .Attributes(PtOpenXml.Status)
  677. .Select(a => (string) a)
  678. .Distinct()
  679. .ToList();
  680. if (statusList.Count() > 1)
  681. {
  682. throw new OpenXmlPowerToolsException(
  683. "Internal error - have both deleted and inserted text elements in the same run.");
  684. }
  685. if (statusList.Count == 0)
  686. {
  687. return new XElement(W.r,
  688. element.Attributes(),
  689. element.Nodes().Select(n => MarkContentAsDeletedOrInsertedTransform(n, settings)));
  690. }
  691. if (statusList.First() == "Deleted")
  692. {
  693. return new XElement(W.del,
  694. new XAttribute(W.author, settings.AuthorForRevisions),
  695. new XAttribute(W.id, _maxId++),
  696. new XAttribute(W.date, settings.DateTimeForRevisions),
  697. new XElement(W.r,
  698. element.Attributes(),
  699. element.Nodes().Select(n => MarkContentAsDeletedOrInsertedTransform(n, settings))));
  700. }
  701. if (statusList.First() == "Inserted")
  702. {
  703. return new XElement(W.ins,
  704. new XAttribute(W.author, settings.AuthorForRevisions),
  705. new XAttribute(W.id, _maxId++),
  706. new XAttribute(W.date, settings.DateTimeForRevisions),
  707. new XElement(W.r,
  708. element.Attributes(),
  709. element.Nodes().Select(n => MarkContentAsDeletedOrInsertedTransform(n, settings))));
  710. }
  711. }
  712. if (element.Name == W.pPr)
  713. {
  714. var status = (string) element.Attribute(PtOpenXml.Status);
  715. if (status == null)
  716. return new XElement(W.pPr,
  717. element.Attributes(),
  718. element.Nodes().Select(n => MarkContentAsDeletedOrInsertedTransform(n, settings)));
  719. var pPr = new XElement(element);
  720. if (status == "Deleted")
  721. {
  722. XElement rPr = pPr.Element(W.rPr);
  723. if (rPr == null)
  724. rPr = new XElement(W.rPr);
  725. rPr.Add(new XElement(W.del,
  726. new XAttribute(W.author, settings.AuthorForRevisions),
  727. new XAttribute(W.id, _maxId++),
  728. new XAttribute(W.date, settings.DateTimeForRevisions)));
  729. if (pPr.Element(W.rPr) != null)
  730. pPr.Element(W.rPr).ReplaceWith(rPr);
  731. else
  732. pPr.AddFirst(rPr);
  733. }
  734. else if (status == "Inserted")
  735. {
  736. XElement rPr = pPr.Element(W.rPr);
  737. if (rPr == null)
  738. rPr = new XElement(W.rPr);
  739. rPr.Add(new XElement(W.ins,
  740. new XAttribute(W.author, settings.AuthorForRevisions),
  741. new XAttribute(W.id, _maxId++),
  742. new XAttribute(W.date, settings.DateTimeForRevisions)));
  743. if (pPr.Element(W.rPr) != null)
  744. pPr.Element(W.rPr).ReplaceWith(rPr);
  745. else
  746. pPr.AddFirst(rPr);
  747. }
  748. else
  749. {
  750. throw new OpenXmlPowerToolsException("Internal error");
  751. }
  752. return pPr;
  753. }
  754. return new XElement(element.Name,
  755. element.Attributes(),
  756. element.Nodes().Select(n => MarkContentAsDeletedOrInsertedTransform(n, settings)));
  757. }
  758. return node;
  759. }
  760. private static void CoalesceAdjacentRunsWithIdenticalFormatting(XDocument xDoc)
  761. {
  762. IEnumerable<XElement> paras = xDoc.Root.DescendantsTrimmed(W.txbxContent).Where(d => d.Name == W.p);
  763. foreach (XElement para in paras)
  764. {
  765. XElement newPara = WordprocessingMLUtil.CoalesceAdjacentRunsWithIdenticalFormatting(para);
  766. para.ReplaceNodes(newPara.Nodes());
  767. }
  768. }
  769. private static void IgnorePt14Namespace(XElement root)
  770. {
  771. if (root.Attribute(XNamespace.Xmlns + "pt14") == null)
  772. {
  773. root.Add(new XAttribute(XNamespace.Xmlns + "pt14", PtOpenXml.pt.NamespaceName));
  774. }
  775. var ignorable = (string) root.Attribute(MC.Ignorable);
  776. if (ignorable != null)
  777. {
  778. string[] list = ignorable.Split(' ');
  779. if (!list.Contains("pt14"))
  780. {
  781. ignorable += " pt14";
  782. root.Attribute(MC.Ignorable).Value = ignorable;
  783. }
  784. }
  785. else
  786. {
  787. root.Add(new XAttribute(MC.Ignorable, "pt14"));
  788. }
  789. }
  790. private static void ProcessFootnoteEndnote(
  791. WmlComparerSettings settings,
  792. List<ComparisonUnitAtom> listOfComparisonUnitAtoms,
  793. MainDocumentPart mainDocumentPartBefore,
  794. MainDocumentPart mainDocumentPartAfter,
  795. XDocument mainDocumentXDoc)
  796. {
  797. FootnotesPart footnotesPartBefore = mainDocumentPartBefore.FootnotesPart;
  798. EndnotesPart endnotesPartBefore = mainDocumentPartBefore.EndnotesPart;
  799. FootnotesPart footnotesPartAfter = mainDocumentPartAfter.FootnotesPart;
  800. EndnotesPart endnotesPartAfter = mainDocumentPartAfter.EndnotesPart;
  801. XDocument footnotesPartBeforeXDoc = null;
  802. if (footnotesPartBefore != null)
  803. footnotesPartBeforeXDoc = footnotesPartBefore.GetXDocument();
  804. XDocument footnotesPartAfterXDoc = null;
  805. if (footnotesPartAfter != null)
  806. footnotesPartAfterXDoc = footnotesPartAfter.GetXDocument();
  807. XDocument endnotesPartBeforeXDoc = null;
  808. if (endnotesPartBefore != null)
  809. endnotesPartBeforeXDoc = endnotesPartBefore.GetXDocument();
  810. XDocument endnotesPartAfterXDoc = null;
  811. if (endnotesPartAfter != null)
  812. endnotesPartAfterXDoc = endnotesPartAfter.GetXDocument();
  813. List<ComparisonUnitAtom> possiblyModifiedFootnotesEndNotes = listOfComparisonUnitAtoms
  814. .Where(cua =>
  815. cua.ContentElement.Name == W.footnoteReference ||
  816. cua.ContentElement.Name == W.endnoteReference)
  817. .ToList();
  818. foreach (ComparisonUnitAtom fn in possiblyModifiedFootnotesEndNotes)
  819. {
  820. string beforeId = null;
  821. if (fn.ContentElementBefore != null)
  822. beforeId = (string) fn.ContentElementBefore.Attribute(W.id);
  823. var afterId = (string) fn.ContentElement.Attribute(W.id);
  824. XElement footnoteEndnoteBefore = null;
  825. XElement footnoteEndnoteAfter = null;
  826. OpenXmlPart partToUseBefore = null;
  827. OpenXmlPart partToUseAfter = null;
  828. XDocument partToUseBeforeXDoc = null;
  829. XDocument partToUseAfterXDoc = null;
  830. if (fn.CorrelationStatus == CorrelationStatus.Equal)
  831. {
  832. if (fn.ContentElement.Name == W.footnoteReference)
  833. {
  834. footnoteEndnoteBefore = footnotesPartBeforeXDoc
  835. .Root
  836. .Elements()
  837. .FirstOrDefault(fnn => (string) fnn.Attribute(W.id) == beforeId);
  838. footnoteEndnoteAfter = footnotesPartAfterXDoc
  839. .Root
  840. .Elements()
  841. .FirstOrDefault(fnn => (string) fnn.Attribute(W.id) == afterId);
  842. partToUseBefore = footnotesPartBefore;
  843. partToUseAfter = footnotesPartAfter;
  844. partToUseBeforeXDoc = footnotesPartBeforeXDoc;
  845. partToUseAfterXDoc = footnotesPartAfterXDoc;
  846. }
  847. else
  848. {
  849. footnoteEndnoteBefore = endnotesPartBeforeXDoc
  850. .Root
  851. .Elements()
  852. .FirstOrDefault(fnn => (string) fnn.Attribute(W.id) == beforeId);
  853. footnoteEndnoteAfter = endnotesPartAfterXDoc
  854. .Root
  855. .Elements()
  856. .FirstOrDefault(fnn => (string) fnn.Attribute(W.id) == afterId);
  857. partToUseBefore = endnotesPartBefore;
  858. partToUseAfter = endnotesPartAfter;
  859. partToUseBeforeXDoc = endnotesPartBeforeXDoc;
  860. partToUseAfterXDoc = endnotesPartAfterXDoc;
  861. }
  862. AddSha1HashToBlockLevelContent(partToUseBefore, footnoteEndnoteBefore, settings);
  863. AddSha1HashToBlockLevelContent(partToUseAfter, footnoteEndnoteAfter, settings);
  864. ComparisonUnitAtom[] fncal1 = CreateComparisonUnitAtomList(partToUseBefore, footnoteEndnoteBefore, settings);
  865. ComparisonUnit[] fncus1 = GetComparisonUnitList(fncal1, settings);
  866. ComparisonUnitAtom[] fncal2 = CreateComparisonUnitAtomList(partToUseAfter, footnoteEndnoteAfter, settings);
  867. ComparisonUnit[] fncus2 = GetComparisonUnitList(fncal2, settings);
  868. if (!(fncus1.Length == 0 && fncus2.Length == 0))
  869. {
  870. List<CorrelatedSequence> fnCorrelatedSequence = Lcs(fncus1, fncus2, settings);
  871. if (False)
  872. {
  873. var sb = new StringBuilder();
  874. foreach (CorrelatedSequence item in fnCorrelatedSequence)
  875. sb.Append(item).Append(Environment.NewLine);
  876. string sbs = sb.ToString();
  877. TestUtil.NotePad(sbs);
  878. }
  879. // for any deleted or inserted rows, we go into the w:trPr properties, and add the appropriate w:ins or w:del element, and therefore
  880. // when generating the document, the appropriate row will be marked as deleted or inserted.
  881. MarkRowsAsDeletedOrInserted(settings, fnCorrelatedSequence);
  882. // the following gets a flattened list of ComparisonUnitAtoms, with status indicated in each ComparisonUnitAtom: Deleted, Inserted, or Equal
  883. List<ComparisonUnitAtom> fnListOfComparisonUnitAtoms =
  884. FlattenToComparisonUnitAtomList(fnCorrelatedSequence, settings);
  885. if (False)
  886. {
  887. var sb = new StringBuilder();
  888. foreach (ComparisonUnitAtom item in fnListOfComparisonUnitAtoms)
  889. sb.Append(item + Environment.NewLine);
  890. string sbs = sb.ToString();
  891. TestUtil.NotePad(sbs);
  892. }
  893. // hack = set the guid ID of the table, row, or cell from the 'before' document to be equal to the 'after' document.
  894. // note - we don't want to do the hack until after flattening all of the groups. At the end of the flattening, we should simply
  895. // have a list of ComparisonUnitAtoms, appropriately marked as equal, inserted, or deleted.
  896. // the table id will be hacked in the normal course of events.
  897. // in the case where a row is deleted, not necessary to hack - the deleted row ID will do.
  898. // in the case where a row is inserted, not necessary to hack - the inserted row ID will do as well.
  899. AssembleAncestorUnidsInOrderToRebuildXmlTreeProperly(fnListOfComparisonUnitAtoms);
  900. object newFootnoteEndnoteChildren =
  901. ProduceNewWmlMarkupFromCorrelatedSequence(partToUseAfter, fnListOfComparisonUnitAtoms, settings);
  902. var tempElement = new XElement(W.body, newFootnoteEndnoteChildren);
  903. bool hasFootnoteReference = tempElement.Descendants(W.r).Any(r =>
  904. {
  905. var b = false;
  906. if ((string) r.Elements(W.rPr).Elements(W.rStyle).Attributes(W.val).FirstOrDefault() ==
  907. "FootnoteReference")
  908. b = true;
  909. if (r.Descendants(W.footnoteRef).Any())
  910. b = true;
  911. return b;
  912. });
  913. if (!hasFootnoteReference)
  914. {
  915. XElement firstPara = tempElement.Descendants(W.p).FirstOrDefault();
  916. if (firstPara != null)
  917. {
  918. XElement firstRun = firstPara.Element(W.r);
  919. if (firstRun != null)
  920. {
  921. if (fn.ContentElement.Name == W.footnoteReference)
  922. firstRun.AddBeforeSelf(
  923. new XElement(W.r,
  924. new XElement(W.rPr,
  925. new XElement(W.rStyle,
  926. new XAttribute(W.val, "FootnoteReference"))),
  927. new XElement(W.footnoteRef)));
  928. else
  929. firstRun.AddBeforeSelf(
  930. new XElement(W.r,
  931. new XElement(W.rPr,
  932. new XElement(W.rStyle,
  933. new XAttribute(W.val, "EndnoteReference"))),
  934. new XElement(W.endnoteRef)));
  935. }
  936. }
  937. }
  938. var newTempElement = (XElement) WordprocessingMLUtil.WmlOrderElementsPerStandard(tempElement);
  939. XElement newContentElement = newTempElement.Descendants()
  940. .FirstOrDefault(d => d.Name == W.footnote || d.Name == W.endnote);
  941. if (newContentElement == null)
  942. throw new OpenXmlPowerToolsException("Internal error");
  943. footnoteEndnoteAfter.ReplaceNodes(newContentElement.Nodes());
  944. }
  945. }
  946. else if (fn.CorrelationStatus == CorrelationStatus.Inserted)
  947. {
  948. if (fn.ContentElement.Name == W.footnoteReference)
  949. {
  950. footnoteEndnoteAfter = footnotesPartAfterXDoc
  951. .Root
  952. .Elements()
  953. .FirstOrDefault(fnn => (string) fnn.Attribute(W.id) == afterId);
  954. partToUseAfter = footnotesPartAfter;
  955. partToUseAfterXDoc = footnotesPartAfterXDoc;
  956. }
  957. else
  958. {
  959. footnoteEndnoteAfter = endnotesPartAfterXDoc
  960. .Root
  961. .Elements()
  962. .FirstOrDefault(fnn => (string) fnn.Attribute(W.id) == afterId);
  963. partToUseAfter = endnotesPartAfter;
  964. partToUseAfterXDoc = endnotesPartAfterXDoc;
  965. }
  966. AddSha1HashToBlockLevelContent(partToUseAfter, footnoteEndnoteAfter, settings);
  967. ComparisonUnitAtom[] fncal2 = CreateComparisonUnitAtomList(partToUseAfter, footnoteEndnoteAfter, settings);
  968. ComparisonUnit[] fncus2 = GetComparisonUnitList(fncal2, settings);
  969. var insertedCorrSequ = new List<CorrelatedSequence>
  970. {
  971. new CorrelatedSequence
  972. {
  973. ComparisonUnitArray1 = null,
  974. ComparisonUnitArray2 = fncus2,
  975. CorrelationStatus = CorrelationStatus.Inserted
  976. }
  977. };
  978. if (False)
  979. {
  980. var sb = new StringBuilder();
  981. foreach (CorrelatedSequence item in insertedCorrSequ)
  982. sb.Append(item).Append(Environment.NewLine);
  983. string sbs = sb.ToString();
  984. TestUtil.NotePad(sbs);
  985. }
  986. MarkRowsAsDeletedOrInserted(settings, insertedCorrSequ);
  987. List<ComparisonUnitAtom> fnListOfComparisonUnitAtoms =
  988. FlattenToComparisonUnitAtomList(insertedCorrSequ, settings);
  989. AssembleAncestorUnidsInOrderToRebuildXmlTreeProperly(fnListOfComparisonUnitAtoms);
  990. object newFootnoteEndnoteChildren = ProduceNewWmlMarkupFromCorrelatedSequence(partToUseAfter,
  991. fnListOfComparisonUnitAtoms, settings);
  992. var tempElement = new XElement(W.body, newFootnoteEndnoteChildren);
  993. bool hasFootnoteReference = tempElement.Descendants(W.r).Any(r =>
  994. {
  995. var b = false;
  996. if ((string) r.Elements(W.rPr).Elements(W.rStyle).Attributes(W.val).FirstOrDefault() ==
  997. "FootnoteReference")
  998. b = true;
  999. if (r.Descendants(W.footnoteRef).Any())
  1000. b = true;
  1001. return b;
  1002. });
  1003. if (!hasFootnoteReference)
  1004. {
  1005. XElement firstPara = tempElement.Descendants(W.p).FirstOrDefault();
  1006. if (firstPara != null)
  1007. {
  1008. XElement firstRun = firstPara.Descendants(W.r).FirstOrDefault();
  1009. if (firstRun != null)
  1010. {
  1011. if (fn.ContentElement.Name == W.footnoteReference)
  1012. firstRun.AddBeforeSelf(
  1013. new XElement(W.r,
  1014. new XElement(W.rPr,
  1015. new XElement(W.rStyle,
  1016. new XAttribute(W.val, "FootnoteReference"))),
  1017. new XElement(W.footnoteRef)));
  1018. else
  1019. firstRun.AddBeforeSelf(
  1020. new XElement(W.r,
  1021. new XElement(W.rPr,
  1022. new XElement(W.rStyle,
  1023. new XAttribute(W.val, "EndnoteReference"))),
  1024. new XElement(W.endnoteRef)));
  1025. }
  1026. }
  1027. }
  1028. var newTempElement = (XElement) WordprocessingMLUtil.WmlOrderElementsPerStandard(tempElement);
  1029. XElement newContentElement = newTempElement
  1030. .Descendants()
  1031. .FirstOrDefault(d => d.Name == W.footnote || d.Name == W.endnote);
  1032. if (newContentElement == null)
  1033. throw new OpenXmlPowerToolsException("Internal error");
  1034. footnoteEndnoteAfter.ReplaceNodes(newContentElement.Nodes());
  1035. }
  1036. else if (fn.CorrelationStatus == CorrelationStatus.Deleted)
  1037. {
  1038. if (fn.ContentElement.Name == W.footnoteReference)
  1039. {
  1040. footnoteEndnoteBefore = footnotesPartBeforeXDoc
  1041. .Root
  1042. .Elements()
  1043. .FirstOrDefault(fnn => (string) fnn.Attribute(W.id) == afterId);
  1044. partToUseAfter = footnotesPartAfter;
  1045. partToUseAfterXDoc = footnotesPartAfterXDoc;
  1046. }
  1047. else
  1048. {
  1049. footnoteEndnoteBefore = endnotesPartBeforeXDoc
  1050. .Root
  1051. .Elements()
  1052. .FirstOrDefault(fnn => (string) fnn.Attribute(W.id) == afterId);
  1053. partToUseBefore = endnotesPartBefore;
  1054. partToUseBeforeXDoc = endnotesPartBeforeXDoc;
  1055. }
  1056. AddSha1HashToBlockLevelContent(partToUseBefore, footnoteEndnoteBefore, settings);
  1057. ComparisonUnitAtom[] fncal2 = CreateComparisonUnitAtomList(partToUseBefore, footnoteEndnoteBefore, settings);
  1058. ComparisonUnit[] fncus2 = GetComparisonUnitList(fncal2, settings);
  1059. var deletedCorrSequ = new List<CorrelatedSequence>
  1060. {
  1061. new CorrelatedSequence
  1062. {
  1063. ComparisonUnitArray1 = fncus2,
  1064. ComparisonUnitArray2 = null,
  1065. CorrelationStatus = CorrelationStatus.Deleted
  1066. }
  1067. };
  1068. if (False)
  1069. {
  1070. var sb = new StringBuilder();
  1071. foreach (CorrelatedSequence item in deletedCorrSequ)
  1072. sb.Append(item).Append(Environment.NewLine);
  1073. string sbs = sb.ToString();
  1074. TestUtil.NotePad(sbs);
  1075. }
  1076. MarkRowsAsDeletedOrInserted(settings, deletedCorrSequ);
  1077. List<ComparisonUnitAtom> fnListOfComparisonUnitAtoms =
  1078. FlattenToComparisonUnitAtomList(deletedCorrSequ, settings);
  1079. if (fnListOfComparisonUnitAtoms.Any())
  1080. {
  1081. AssembleAncestorUnidsInOrderToRebuildXmlTreeProperly(fnListOfComparisonUnitAtoms);
  1082. object newFootnoteEndnoteChildren = ProduceNewWmlMarkupFromCorrelatedSequence(partToUseBefore,
  1083. fnListOfComparisonUnitAtoms, settings);
  1084. var tempElement = new XElement(W.body, newFootnoteEndnoteChildren);
  1085. bool hasFootnoteReference = tempElement.Descendants(W.r).Any(r =>
  1086. {
  1087. var b = false;
  1088. if ((string) r.Elements(W.rPr).Elements(W.rStyle).Attributes(W.val).FirstOrDefault() ==
  1089. "FootnoteReference")
  1090. b = true;
  1091. if (r.Descendants(W.footnoteRef).Any())
  1092. b = true;
  1093. return b;
  1094. });
  1095. if (!hasFootnoteReference)
  1096. {
  1097. XElement firstPara = tempElement.Descendants(W.p).FirstOrDefault();
  1098. if (firstPara != null)
  1099. {
  1100. XElement firstRun = firstPara.Descendants(W.r).FirstOrDefault();
  1101. if (firstRun != null)
  1102. {
  1103. if (fn.ContentElement.Name == W.footnoteReference)
  1104. firstRun.AddBeforeSelf(
  1105. new XElement(W.r,
  1106. new XElement(W.rPr,
  1107. new XElement(W.rStyle,
  1108. new XAttribute(W.val, "FootnoteReference"))),
  1109. new XElement(W.footnoteRef)));
  1110. else
  1111. firstRun.AddBeforeSelf(
  1112. new XElement(W.r,
  1113. new XElement(W.rPr,
  1114. new XElement(W.rStyle,
  1115. new XAttribute(W.val, "EndnoteReference"))),
  1116. new XElement(W.endnoteRef)));
  1117. }
  1118. }
  1119. }
  1120. var newTempElement = (XElement) WordprocessingMLUtil.WmlOrderElementsPerStandard(tempElement);
  1121. XElement newContentElement = newTempElement.Descendants()
  1122. .FirstOrDefault(d => d.Name == W.footnote || d.Name == W.endnote);
  1123. if (newContentElement == null)
  1124. throw new OpenXmlPowerToolsException("Internal error");
  1125. footnoteEndnoteBefore.ReplaceNodes(newContentElement.Nodes());
  1126. }
  1127. }
  1128. else
  1129. {
  1130. throw new OpenXmlPowerToolsException("Internal error");
  1131. }
  1132. }
  1133. }
  1134. private static void RectifyFootnoteEndnoteIds(
  1135. MainDocumentPart mainDocumentPartBefore,
  1136. MainDocumentPart mainDocumentPartAfter,
  1137. MainDocumentPart mainDocumentPartWithRevisions,
  1138. XDocument mainDocumentXDoc,
  1139. WmlComparerSettings settings)
  1140. {
  1141. FootnotesPart footnotesPartBefore = mainDocumentPartBefore.FootnotesPart;
  1142. EndnotesPart endnotesPartBefore = mainDocumentPartBefore.EndnotesPart;
  1143. FootnotesPart footnotesPartAfter = mainDocumentPartAfter.FootnotesPart;
  1144. EndnotesPart endnotesPartAfter = mainDocumentPartAfter.EndnotesPart;
  1145. FootnotesPart footnotesPartWithRevisions = mainDocumentPartWithRevisions.FootnotesPart;
  1146. EndnotesPart endnotesPartWithRevisions = mainDocumentPartWithRevisions.EndnotesPart;
  1147. XDocument footnotesPartBeforeXDoc = null;
  1148. if (footnotesPartBefore != null)
  1149. footnotesPartBeforeXDoc = footnotesPartBefore.GetXDocument();
  1150. XDocument footnotesPartAfterXDoc = null;
  1151. if (footnotesPartAfter != null)
  1152. footnotesPartAfterXDoc = footnotesPartAfter.GetXDocument();
  1153. XDocument footnotesPartWithRevisionsXDoc = null;
  1154. if (footnotesPartWithRevisions != null)
  1155. {
  1156. footnotesPartWithRevisionsXDoc = footnotesPartWithRevisions.GetXDocument();
  1157. footnotesPartWithRevisionsXDoc
  1158. .Root
  1159. .Elements(W.footnote)
  1160. .Where(e => (string) e.Attribute(W.id) != "-1" && (string) e.Attribute(W.id) != "0")
  1161. .Remove();
  1162. }
  1163. XDocument endnotesPartBeforeXDoc = null;
  1164. if (endnotesPartBefore != null)
  1165. endnotesPartBeforeXDoc = endnotesPartBefore.GetXDocument();
  1166. XDocument endnotesPartAfterXDoc = null;
  1167. if (endnotesPartAfter != null)
  1168. endnotesPartAfterXDoc = endnotesPartAfter.GetXDocument();
  1169. XDocument endnotesPartWithRevisionsXDoc = null;
  1170. if (endnotesPartWithRevisions != null)
  1171. {
  1172. endnotesPartWithRevisionsXDoc = endnotesPartWithRevisions.GetXDocument();
  1173. endnotesPartWithRevisionsXDoc
  1174. .Root
  1175. .Elements(W.endnote)
  1176. .Where(e => (string) e.Attribute(W.id) != "-1" && (string) e.Attribute(W.id) != "0")
  1177. .Remove();
  1178. }
  1179. var footnotesRefs = mainDocumentXDoc
  1180. .Descendants(W.footnoteReference)
  1181. .Select((fn, idx) =>
  1182. {
  1183. return new
  1184. {
  1185. FootNote = fn,
  1186. Idx = idx
  1187. };
  1188. });
  1189. foreach (var fn in footnotesRefs)
  1190. {
  1191. var oldId = (string) fn.FootNote.Attribute(W.id);
  1192. string newId = (fn.Idx + 1).ToString();
  1193. fn.FootNote.Attribute(W.id).Value = newId;
  1194. XElement footnote = footnotesPartAfterXDoc
  1195. .Root
  1196. .Elements()
  1197. .FirstOrDefault(e => (string) e.Attribute(W.id) == oldId);
  1198. if (footnote == null)
  1199. {
  1200. footnote = footnotesPartBeforeXDoc
  1201. .Root
  1202. .Elements()
  1203. .FirstOrDefault(e => (string) e.Attribute(W.id) == oldId);
  1204. }
  1205. if (footnote == null)
  1206. throw new OpenXmlPowerToolsException("Internal error");
  1207. var cloned = new XElement(footnote);
  1208. cloned.Attribute(W.id).Value = newId;
  1209. footnotesPartWithRevisionsXDoc
  1210. .Root
  1211. .Add(cloned);
  1212. }
  1213. var endnotesRefs = mainDocumentXDoc
  1214. .Descendants(W.endnoteReference)
  1215. .Select((fn, idx) =>
  1216. {
  1217. return new
  1218. {
  1219. Endnote = fn,
  1220. Idx = idx
  1221. };
  1222. });
  1223. foreach (var fn in endnotesRefs)
  1224. {
  1225. var oldId = (string) fn.Endnote.Attribute(W.id);
  1226. string newId = (fn.Idx + 1).ToString();
  1227. fn.Endnote.Attribute(W.id).Value = newId;
  1228. XElement endnote = endnotesPartAfterXDoc
  1229. .Root
  1230. .Elements()
  1231. .FirstOrDefault(e => (string) e.Attribute(W.id) == oldId);
  1232. if (endnote == null)
  1233. {
  1234. endnote = endnotesPartBeforeXDoc
  1235. .Root
  1236. .Elements()
  1237. .FirstOrDefault(e => (string) e.Attribute(W.id) == oldId);
  1238. }
  1239. if (endnote == null)
  1240. throw new OpenXmlPowerToolsException("Internal error");
  1241. var cloned = new XElement(endnote);
  1242. cloned.Attribute(W.id).Value = newId;
  1243. endnotesPartWithRevisionsXDoc
  1244. .Root
  1245. .Add(cloned);
  1246. }
  1247. if (footnotesPartWithRevisionsXDoc != null)
  1248. {
  1249. MarkContentAsDeletedOrInserted(footnotesPartWithRevisionsXDoc, settings);
  1250. CoalesceAdjacentRunsWithIdenticalFormatting(footnotesPartWithRevisionsXDoc);
  1251. var newXDocRoot =
  1252. (XElement) WordprocessingMLUtil.WmlOrderElementsPerStandard(footnotesPartWithRevisionsXDoc.Root);
  1253. footnotesPartWithRevisionsXDoc.Root.ReplaceWith(newXDocRoot);
  1254. IgnorePt14Namespace(footnotesPartWithRevisionsXDoc.Root);
  1255. footnotesPartWithRevisions.PutXDocument();
  1256. }
  1257. if (endnotesPartWithRevisionsXDoc != null)
  1258. {
  1259. MarkContentAsDeletedOrInserted(endnotesPartWithRevisionsXDoc, settings);
  1260. CoalesceAdjacentRunsWithIdenticalFormatting(endnotesPartWithRevisionsXDoc);
  1261. var newXDocRoot = (XElement) WordprocessingMLUtil.WmlOrderElementsPerStandard(endnotesPartWithRevisionsXDoc.Root);
  1262. endnotesPartWithRevisionsXDoc.Root.ReplaceWith(newXDocRoot);
  1263. IgnorePt14Namespace(endnotesPartWithRevisionsXDoc.Root);
  1264. endnotesPartWithRevisions.PutXDocument();
  1265. }
  1266. }
  1267. private static void ConjoinDeletedInsertedParagraphMarks(MainDocumentPart mainDocumentPart, XDocument newXDoc)
  1268. {
  1269. ConjoinMultipleParagraphMarks(newXDoc);
  1270. if (mainDocumentPart.FootnotesPart != null)
  1271. {
  1272. XDocument fnXDoc = mainDocumentPart.FootnotesPart.GetXDocument();
  1273. ConjoinMultipleParagraphMarks(fnXDoc);
  1274. mainDocumentPart.FootnotesPart.PutXDocument();
  1275. }
  1276. if (mainDocumentPart.EndnotesPart != null)
  1277. {
  1278. XDocument fnXDoc = mainDocumentPart.EndnotesPart.GetXDocument();
  1279. ConjoinMultipleParagraphMarks(fnXDoc);
  1280. mainDocumentPart.EndnotesPart.PutXDocument();
  1281. }
  1282. }
  1283. // it is possible, per the algorithm, for the algorithm to find that the paragraph mark for a single paragraph has been
  1284. // inserted and deleted. If the algorithm sets them to equal, then sometimes it will equate paragraph marks that should
  1285. // not be equated.
  1286. private static void ConjoinMultipleParagraphMarks(XDocument xDoc)
  1287. {
  1288. object newRoot = ConjoinTransform(xDoc.Root);
  1289. xDoc.Root?.ReplaceWith(newRoot);
  1290. }
  1291. private static object ConjoinTransform(XNode node)
  1292. {
  1293. if (node is XElement element)
  1294. {
  1295. if (element.Name == W.p && element.Elements(W.pPr).Count() >= 2)
  1296. {
  1297. var pPr = new XElement(element.Elements(W.pPr).First());
  1298. pPr.Elements(W.rPr).Elements().Where(r => r.Name == W.ins || r.Name == W.del).Remove();
  1299. pPr.Attributes(PtOpenXml.Status).Remove();
  1300. var newPara = new XElement(W.p,
  1301. element.Attributes(),
  1302. pPr,
  1303. element.Elements().Where(c => c.Name != W.pPr));
  1304. return newPara;
  1305. }
  1306. return new XElement(element.Name,
  1307. element.Attributes(),
  1308. element.Nodes().Select(ConjoinTransform));
  1309. }
  1310. return node;
  1311. }
  1312. private static void FixUpRevisionIds(WordprocessingDocument wDocWithRevisions, XDocument newXDoc)
  1313. {
  1314. IEnumerable<XElement> footnoteRevisions = Enumerable.Empty<XElement>();
  1315. if (wDocWithRevisions.MainDocumentPart.FootnotesPart != null)
  1316. {
  1317. XDocument fnxd = wDocWithRevisions.MainDocumentPart.FootnotesPart.GetXDocument();
  1318. footnoteRevisions = fnxd
  1319. .Descendants()
  1320. .Where(d => d.Name == W.ins || d.Name == W.del);
  1321. }
  1322. IEnumerable<XElement> endnoteRevisions = Enumerable.Empty<XElement>();
  1323. if (wDocWithRevisions.MainDocumentPart.EndnotesPart != null)
  1324. {
  1325. XDocument fnxd = wDocWithRevisions.MainDocumentPart.EndnotesPart.GetXDocument();
  1326. endnoteRevisions = fnxd
  1327. .Descendants()
  1328. .Where(d => d.Name == W.ins || d.Name == W.del);
  1329. }
  1330. IEnumerable<XElement> mainRevisions = newXDoc
  1331. .Descendants()
  1332. .Where(d => d.Name == W.ins || d.Name == W.del);
  1333. var allRevisions = mainRevisions
  1334. .Concat(footnoteRevisions)
  1335. .Concat(endnoteRevisions)
  1336. .Select((r, i) =>
  1337. {
  1338. return new
  1339. {
  1340. Rev = r,
  1341. Idx = i + 1
  1342. };
  1343. });
  1344. foreach (var item in allRevisions)
  1345. item.Rev.Attribute(W.id).Value = item.Idx.ToString();
  1346. if (wDocWithRevisions.MainDocumentPart.FootnotesPart != null)
  1347. wDocWithRevisions.MainDocumentPart.FootnotesPart.PutXDocument();
  1348. if (wDocWithRevisions.MainDocumentPart.EndnotesPart != null)
  1349. wDocWithRevisions.MainDocumentPart.EndnotesPart.PutXDocument();
  1350. }
  1351. private static void MoveLastSectPrToChildOfBody(XDocument newXDoc)
  1352. {
  1353. XElement lastParaWithSectPr = newXDoc
  1354. .Root
  1355. .Elements(W.body)
  1356. .Elements(W.p)
  1357. .Where(p => p.Elements(W.pPr).Elements(W.sectPr).Any())
  1358. .LastOrDefault();
  1359. if (lastParaWithSectPr != null)
  1360. {
  1361. newXDoc.Root.Element(W.body).Add(lastParaWithSectPr.Elements(W.pPr).Elements(W.sectPr));
  1362. lastParaWithSectPr.Elements(W.pPr).Elements(W.sectPr).Remove();
  1363. }
  1364. }
  1365. private static void FixUpFootnotesEndnotesWithCustomMarkers(WordprocessingDocument wDocWithRevisions)
  1366. {
  1367. #if FALSE
  1368. // this needs to change
  1369. <w:del w:author = "Open-Xml-PowerTools"
  1370. w:id = "7"
  1371. w:date = "2017-06-07T12:23:22.8601285-07:00">
  1372. <w:r>
  1373. <w:rPr pt14:Unid = "ec75a71361c84562a757eee8b28fc229">
  1374. <w:rFonts w:cs = "Times New Roman Bold"
  1375. pt14:Unid = "16bb355df5964ba09854f9152c97242b" />
  1376. <w:b w:val = "0"
  1377. pt14:Unid = "9abcec54ad414791a5627cbb198e8aa9" />
  1378. <w:bCs pt14:Unid = "71ecd2eba85e4bfaa92b3d618e2f8829" />
  1379. <w:position w:val = "6"
  1380. pt14:Unid = "61793f6a5f494700b7f2a3a753ce9055" />
  1381. <w:sz w:val = "16"
  1382. pt14:Unid = "60b3cd020c214d0ea07e5a68ae0e4efe" />
  1383. <w:szCs w:val = "16"
  1384. pt14:Unid = "9ae61a724de44a75868180aac44ea380" />
  1385. </w:rPr>
  1386. <w:footnoteReference w:customMarkFollows = "1"
  1387. w:id = "1"
  1388. pt14:Status = "Deleted" />
  1389. </w:r>
  1390. </w:del>
  1391. <w:del w:author = "Open-Xml-PowerTools"
  1392. w:id = "8"
  1393. w:date = "2017-06-07T12:23:22.8601285-07:00">
  1394. <w:r>
  1395. <w:rPr pt14:Unid = "445caef74a624e588e7adaa6d7775639">
  1396. <w:rFonts w:cs = "Times New Roman Bold"
  1397. pt14:Unid = "5920885f8ec44c53bcaece2de7eafda2" />
  1398. <w:b w:val = "0"
  1399. pt14:Unid = "023a29e2e6d44c3b8c5df47317ace4c6" />
  1400. <w:bCs pt14:Unid = "e96e37daf9174b268ef4731df831df7d" />
  1401. <w:position w:val = "6"
  1402. pt14:Unid = "be3f8ff7ed0745ae9340bb2706b28b1f" />
  1403. <w:sz w:val = "16"
  1404. pt14:Unid = "6fbbde024e7c46b9b72435ae50065459" />
  1405. <w:szCs w:val = "16"
  1406. pt14:Unid = "cc82e7bd75f441f2b609eae0672fb285" />
  1407. </w:rPr>
  1408. <w:delText>1</w:delText>
  1409. </w:r>
  1410. </w:del>
  1411. // to this
  1412. <w:del w:author = "Open-Xml-PowerTools"
  1413. w:id = "7"
  1414. w:date = "2017-06-07T12:23:22.8601285-07:00">
  1415. <w:r>
  1416. <w:rPr pt14:Unid = "ec75a71361c84562a757eee8b28fc229">
  1417. <w:rFonts w:cs = "Times New Roman Bold"
  1418. pt14:Unid = "16bb355df5964ba09854f9152c97242b" />
  1419. <w:b w:val = "0"
  1420. pt14:Unid = "9abcec54ad414791a5627cbb198e8aa9" />
  1421. <w:bCs pt14:Unid = "71ecd2eba85e4bfaa92b3d618e2f8829" />
  1422. <w:position w:val = "6"
  1423. pt14:Unid = "61793f6a5f494700b7f2a3a753ce9055" />
  1424. <w:sz w:val = "16"
  1425. pt14:Unid = "60b3cd020c214d0ea07e5a68ae0e4efe" />
  1426. <w:szCs w:val = "16"
  1427. pt14:Unid = "9ae61a724de44a75868180aac44ea380" />
  1428. </w:rPr>
  1429. <w:footnoteReference w:customMarkFollows = "1"
  1430. w:id = "1"
  1431. pt14:Status = "Deleted" />
  1432. <w:delText>1</w:delText>
  1433. </w:r>
  1434. </w:del>
  1435. #endif
  1436. // this is pretty random - a bug in Word prevents display of a document if the delText element does not immediately follow the footnoteReference element, in the same run.
  1437. XDocument mainXDoc = wDocWithRevisions.MainDocumentPart.GetXDocument();
  1438. var newRoot = (XElement) FootnoteEndnoteReferenceCleanupTransform(mainXDoc.Root);
  1439. mainXDoc.Root?.ReplaceWith(newRoot);
  1440. wDocWithRevisions.MainDocumentPart.PutXDocument();
  1441. }
  1442. private static object FootnoteEndnoteReferenceCleanupTransform(XNode node)
  1443. {
  1444. var element = node as XElement;
  1445. if (element != null)
  1446. {
  1447. // small optimization to eliminate the work for most elements
  1448. if (element.Element(W.del) != null || element.Element(W.ins) != null)
  1449. {
  1450. bool hasFootnoteEndnoteReferencesThatNeedCleanedUp = element
  1451. .Elements()
  1452. .Where(e => e.Name == W.del || e.Name == W.ins)
  1453. .Elements(W.r)
  1454. .Elements()
  1455. .Where(e => e.Name == W.footnoteReference || e.Name == W.endnoteReference)
  1456. .Attributes(W.customMarkFollows)
  1457. .Any();
  1458. if (hasFootnoteEndnoteReferencesThatNeedCleanedUp)
  1459. {
  1460. var clone = new XElement(element.Name,
  1461. element.Attributes(),
  1462. element.Nodes().Select(n => FootnoteEndnoteReferenceCleanupTransform(n)));
  1463. IEnumerable<XElement> footnoteEndnoteReferencesToAdjust = clone
  1464. .Descendants()
  1465. .Where(d => d.Name == W.footnoteReference || d.Name == W.endnoteReference)
  1466. .Where(d => d.Attribute(W.customMarkFollows) != null);
  1467. foreach (XElement fnenr in footnoteEndnoteReferencesToAdjust)
  1468. {
  1469. XElement par = fnenr.Parent;
  1470. XElement gp = fnenr.Parent.Parent;
  1471. if (par.Name == W.r &&
  1472. gp.Name == W.del)
  1473. {
  1474. if (par.Element(W.delText) != null)
  1475. continue;
  1476. XElement afterGp = gp.ElementsAfterSelf().FirstOrDefault();
  1477. if (afterGp == null)
  1478. continue;
  1479. IEnumerable<XElement> afterGpDelText = afterGp.Elements(W.r).Elements(W.delText);
  1480. if (afterGpDelText.Any())
  1481. {
  1482. par.Add(afterGpDelText); // this will clone and add to run that contains the reference
  1483. afterGpDelText.Remove(); // this leaves an empty run, does not matter.
  1484. }
  1485. }
  1486. if (par.Name == W.r &&
  1487. gp.Name == W.ins)
  1488. {
  1489. if (par.Element(W.t) != null)
  1490. continue;
  1491. XElement afterGp = gp.ElementsAfterSelf().FirstOrDefault();
  1492. if (afterGp == null)
  1493. continue;
  1494. IEnumerable<XElement> afterGpText = afterGp.Elements(W.r).Elements(W.t);
  1495. if (afterGpText.Any())
  1496. {
  1497. par.Add(afterGpText); // this will clone and add to run that contains the reference
  1498. afterGpText.Remove(); // this leaves an empty run, does not matter.
  1499. }
  1500. }
  1501. }
  1502. return clone;
  1503. }
  1504. }
  1505. else
  1506. {
  1507. return new XElement(element.Name,
  1508. element.Attributes(),
  1509. element.Nodes().Select(n => FootnoteEndnoteReferenceCleanupTransform(n)));
  1510. }
  1511. }
  1512. return node;
  1513. }
  1514. private static void FixUpRevMarkIds(WordprocessingDocument wDoc)
  1515. {
  1516. IEnumerable<XElement> revMarksToChange = wDoc
  1517. .ContentParts()
  1518. .Select(cp => cp.GetXDocument())
  1519. .Select(xd => xd.Descendants().Where(d => d.Name == W.ins || d.Name == W.del))
  1520. .SelectMany(m => m);
  1521. var nextId = 0;
  1522. foreach (XElement item in revMarksToChange)
  1523. {
  1524. XAttribute idAtt = item.Attribute(W.id);
  1525. if (idAtt != null)
  1526. idAtt.Value = nextId++.ToString();
  1527. }
  1528. foreach (OpenXmlPart cp in wDoc.ContentParts())
  1529. cp.PutXDocument();
  1530. }
  1531. private static void FixUpDocPrIds(WordprocessingDocument wDoc)
  1532. {
  1533. XName elementToFind = WP.docPr;
  1534. IEnumerable<XElement> docPrToChange = wDoc
  1535. .ContentParts()
  1536. .Select(cp => cp.GetXDocument())
  1537. .Select(xd => xd.Descendants().Where(d => d.Name == elementToFind))
  1538. .SelectMany(m => m);
  1539. var nextId = 1;
  1540. foreach (XElement item in docPrToChange)
  1541. {
  1542. XAttribute idAtt = item.Attribute("id");
  1543. if (idAtt != null)
  1544. idAtt.Value = nextId++.ToString();
  1545. }
  1546. foreach (OpenXmlPart cp in wDoc.ContentParts())
  1547. cp.PutXDocument();
  1548. }
  1549. private static void FixUpShapeIds(WordprocessingDocument wDoc)
  1550. {
  1551. XName elementToFind = VML.shape;
  1552. IEnumerable<XElement> shapeIdsToChange = wDoc
  1553. .ContentParts()
  1554. .Select(cp => cp.GetXDocument())
  1555. .Select(xd => xd.Descendants().Where(d => d.Name == elementToFind))
  1556. .SelectMany(m => m);
  1557. var nextId = 1;
  1558. foreach (XElement item in shapeIdsToChange)
  1559. {
  1560. int thisId = nextId++;
  1561. XAttribute idAtt = item.Attribute("id");
  1562. if (idAtt != null)
  1563. idAtt.Value = thisId.ToString();
  1564. XElement oleObject = item.Parent.Element(O.OLEObject);
  1565. if (oleObject != null)
  1566. {
  1567. XAttribute shapeIdAtt = oleObject.Attribute("ShapeID");
  1568. if (shapeIdAtt != null)
  1569. shapeIdAtt.Value = thisId.ToString();
  1570. }
  1571. }
  1572. foreach (OpenXmlPart cp in wDoc.ContentParts())
  1573. cp.PutXDocument();
  1574. }
  1575. private static void FixUpShapeTypeIds(WordprocessingDocument wDoc)
  1576. {
  1577. XName elementToFind = VML.shapetype;
  1578. IEnumerable<XElement> shapeTypeIdsToChange = wDoc
  1579. .ContentParts()
  1580. .Select(cp => cp.GetXDocument())
  1581. .Select(xd => xd.Descendants().Where(d => d.Name == elementToFind))
  1582. .SelectMany(m => m);
  1583. var nextId = 1;
  1584. foreach (XElement item in shapeTypeIdsToChange)
  1585. {
  1586. int thisId = nextId++;
  1587. XAttribute idAtt = item.Attribute("id");
  1588. if (idAtt != null)
  1589. idAtt.Value = thisId.ToString();
  1590. XElement shape = item.Parent.Element(VML.shape);
  1591. if (shape != null)
  1592. {
  1593. XAttribute typeAtt = shape.Attribute("type");
  1594. if (typeAtt != null)
  1595. typeAtt.Value = thisId.ToString();
  1596. }
  1597. }
  1598. foreach (OpenXmlPart cp in wDoc.ContentParts())
  1599. cp.PutXDocument();
  1600. }
  1601. private static void AddFootnotesEndnotesStyles(WordprocessingDocument wDocWithRevisions)
  1602. {
  1603. XDocument mainXDoc = wDocWithRevisions.MainDocumentPart.GetXDocument();
  1604. bool hasFootnotes = mainXDoc.Descendants(W.footnoteReference).Any();
  1605. bool hasEndnotes = mainXDoc.Descendants(W.endnoteReference).Any();
  1606. StyleDefinitionsPart styleDefinitionsPart = wDocWithRevisions.MainDocumentPart.StyleDefinitionsPart;
  1607. XDocument sXDoc = styleDefinitionsPart.GetXDocument();
  1608. if (hasFootnotes)
  1609. {
  1610. XElement footnoteTextStyle = sXDoc
  1611. .Root
  1612. .Elements(W.style)
  1613. .FirstOrDefault(s => (string) s.Attribute(W.styleId) == "FootnoteText");
  1614. if (footnoteTextStyle == null)
  1615. {
  1616. var footnoteTextStyleMarkup =
  1617. @"<w:style w:type=""paragraph""
  1618. w:styleId=""FootnoteText""
  1619. xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1620. <w:name w:val=""footnote text""/>
  1621. <w:basedOn w:val=""Normal""/>
  1622. <w:link w:val=""FootnoteTextChar""/>
  1623. <w:uiPriority w:val=""99""/>
  1624. <w:semiHidden/>
  1625. <w:unhideWhenUsed/>
  1626. <w:pPr>
  1627. <w:spacing w:after=""0""
  1628. w:line=""240""
  1629. w:lineRule=""auto""/>
  1630. </w:pPr>
  1631. <w:rPr>
  1632. <w:sz w:val=""20""/>
  1633. <w:szCs w:val=""20""/>
  1634. </w:rPr>
  1635. </w:style>";
  1636. XElement ftsElement = XElement.Parse(footnoteTextStyleMarkup);
  1637. sXDoc.Root.Add(ftsElement);
  1638. }
  1639. XElement footnoteTextCharStyle = sXDoc
  1640. .Root
  1641. .Elements(W.style)
  1642. .FirstOrDefault(s => (string) s.Attribute(W.styleId) == "FootnoteTextChar");
  1643. if (footnoteTextCharStyle == null)
  1644. {
  1645. var footnoteTextCharStyleMarkup =
  1646. @"<w:style w:type=""character""
  1647. w:customStyle=""1""
  1648. w:styleId=""FootnoteTextChar""
  1649. xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1650. <w:name w:val=""Footnote Text Char""/>
  1651. <w:basedOn w:val=""DefaultParagraphFont""/>
  1652. <w:link w:val=""FootnoteText""/>
  1653. <w:uiPriority w:val=""99""/>
  1654. <w:semiHidden/>
  1655. <w:rPr>
  1656. <w:sz w:val=""20""/>
  1657. <w:szCs w:val=""20""/>
  1658. </w:rPr>
  1659. </w:style>";
  1660. XElement fntcsElement = XElement.Parse(footnoteTextCharStyleMarkup);
  1661. sXDoc.Root.Add(fntcsElement);
  1662. }
  1663. XElement footnoteReferenceStyle = sXDoc
  1664. .Root
  1665. .Elements(W.style)
  1666. .FirstOrDefault(s => (string) s.Attribute(W.styleId) == "FootnoteReference");
  1667. if (footnoteReferenceStyle == null)
  1668. {
  1669. var footnoteReferenceStyleMarkup =
  1670. @"<w:style w:type=""character""
  1671. w:styleId=""FootnoteReference""
  1672. xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1673. <w:name w:val=""footnote reference""/>
  1674. <w:basedOn w:val=""DefaultParagraphFont""/>
  1675. <w:uiPriority w:val=""99""/>
  1676. <w:semiHidden/>
  1677. <w:unhideWhenUsed/>
  1678. <w:rPr>
  1679. <w:vertAlign w:val=""superscript""/>
  1680. </w:rPr>
  1681. </w:style>";
  1682. XElement fnrsElement = XElement.Parse(footnoteReferenceStyleMarkup);
  1683. sXDoc.Root.Add(fnrsElement);
  1684. }
  1685. }
  1686. if (hasEndnotes)
  1687. {
  1688. XElement endnoteTextStyle = sXDoc
  1689. .Root
  1690. .Elements(W.style)
  1691. .FirstOrDefault(s => (string) s.Attribute(W.styleId) == "EndnoteText");
  1692. if (endnoteTextStyle == null)
  1693. {
  1694. var endnoteTextStyleMarkup =
  1695. @"<w:style w:type=""paragraph""
  1696. w:styleId=""EndnoteText""
  1697. xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1698. <w:name w:val=""endnote text""/>
  1699. <w:basedOn w:val=""Normal""/>
  1700. <w:link w:val=""EndnoteTextChar""/>
  1701. <w:uiPriority w:val=""99""/>
  1702. <w:semiHidden/>
  1703. <w:unhideWhenUsed/>
  1704. <w:pPr>
  1705. <w:spacing w:after=""0""
  1706. w:line=""240""
  1707. w:lineRule=""auto""/>
  1708. </w:pPr>
  1709. <w:rPr>
  1710. <w:sz w:val=""20""/>
  1711. <w:szCs w:val=""20""/>
  1712. </w:rPr>
  1713. </w:style>";
  1714. XElement etsElement = XElement.Parse(endnoteTextStyleMarkup);
  1715. sXDoc.Root.Add(etsElement);
  1716. }
  1717. XElement endnoteTextCharStyle = sXDoc
  1718. .Root
  1719. .Elements(W.style)
  1720. .FirstOrDefault(s => (string) s.Attribute(W.styleId) == "EndnoteTextChar");
  1721. if (endnoteTextCharStyle == null)
  1722. {
  1723. var endnoteTextCharStyleMarkup =
  1724. @"<w:style w:type=""character""
  1725. w:customStyle=""1""
  1726. w:styleId=""EndnoteTextChar""
  1727. xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1728. <w:name w:val=""Endnote Text Char""/>
  1729. <w:basedOn w:val=""DefaultParagraphFont""/>
  1730. <w:link w:val=""EndnoteText""/>
  1731. <w:uiPriority w:val=""99""/>
  1732. <w:semiHidden/>
  1733. <w:rPr>
  1734. <w:sz w:val=""20""/>
  1735. <w:szCs w:val=""20""/>
  1736. </w:rPr>
  1737. </w:style>";
  1738. XElement entcsElement = XElement.Parse(endnoteTextCharStyleMarkup);
  1739. sXDoc.Root.Add(entcsElement);
  1740. }
  1741. XElement endnoteReferenceStyle = sXDoc
  1742. .Root
  1743. .Elements(W.style)
  1744. .FirstOrDefault(s => (string) s.Attribute(W.styleId) == "EndnoteReference");
  1745. if (endnoteReferenceStyle == null)
  1746. {
  1747. var endnoteReferenceStyleMarkup =
  1748. @"<w:style w:type=""character""
  1749. w:styleId=""EndnoteReference""
  1750. xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
  1751. <w:name w:val=""endnote reference""/>
  1752. <w:basedOn w:val=""DefaultParagraphFont""/>
  1753. <w:uiPriority w:val=""99""/>
  1754. <w:semiHidden/>
  1755. <w:unhideWhenUsed/>
  1756. <w:rPr>
  1757. <w:vertAlign w:val=""superscript""/>
  1758. </w:rPr>
  1759. </w:style>";
  1760. XElement enrsElement = XElement.Parse(endnoteReferenceStyleMarkup);
  1761. sXDoc.Root.Add(enrsElement);
  1762. }
  1763. }
  1764. if (hasFootnotes || hasEndnotes)
  1765. {
  1766. styleDefinitionsPart.PutXDocument();
  1767. }
  1768. }
  1769. private static void CopyMissingStylesFromOneDocToAnother(WordprocessingDocument wDocFrom, WordprocessingDocument wDocTo)
  1770. {
  1771. XDocument revisionsStylesXDoc = wDocTo.MainDocumentPart.StyleDefinitionsPart.GetXDocument();
  1772. XDocument afterStylesXDoc = wDocFrom.MainDocumentPart.StyleDefinitionsPart.GetXDocument();
  1773. foreach (XElement style in afterStylesXDoc.Root.Elements(W.style))
  1774. {
  1775. var type = (string) style.Attribute(W.type);
  1776. var styleId = (string) style.Attribute(W.styleId);
  1777. XElement styleInRevDoc = revisionsStylesXDoc
  1778. .Root
  1779. .Elements(W.style)
  1780. .FirstOrDefault(st => (string) st.Attribute(W.type) == type &&
  1781. (string) st.Attribute(W.styleId) == styleId);
  1782. if (styleInRevDoc != null)
  1783. continue;
  1784. var cloned = new XElement(style);
  1785. if (cloned.Attribute(W._default) != null)
  1786. cloned.Attribute(W._default).Remove();
  1787. revisionsStylesXDoc.Root.Add(cloned);
  1788. }
  1789. wDocTo.MainDocumentPart.StyleDefinitionsPart.PutXDocument();
  1790. }
  1791. private static void DeleteFootnotePropertiesInSettings(WordprocessingDocument wDocWithRevisions)
  1792. {
  1793. DocumentSettingsPart settingsPart = wDocWithRevisions.MainDocumentPart.DocumentSettingsPart;
  1794. if (settingsPart != null)
  1795. {
  1796. XDocument sxDoc = settingsPart.GetXDocument();
  1797. sxDoc.Root?.Elements().Where(e => e.Name == W.footnotePr || e.Name == W.endnotePr).Remove();
  1798. settingsPart.PutXDocument();
  1799. }
  1800. }
  1801. private static object CloneForStructureHash(XNode node)
  1802. {
  1803. if (node is XElement element)
  1804. {
  1805. return new XElement(element.Name,
  1806. element.Attributes(),
  1807. element.Elements().Select(CloneForStructureHash));
  1808. }
  1809. return null;
  1810. }
  1811. private static List<CorrelatedSequence> FindCommonAtBeginningAndEnd(
  1812. CorrelatedSequence unknown,
  1813. WmlComparerSettings settings)
  1814. {
  1815. int lengthToCompare = Math.Min(unknown.ComparisonUnitArray1.Length, unknown.ComparisonUnitArray2.Length);
  1816. int countCommonAtBeginning = unknown
  1817. .ComparisonUnitArray1
  1818. .Take(lengthToCompare)
  1819. .Zip(unknown.ComparisonUnitArray2,
  1820. (pu1, pu2) => new
  1821. {
  1822. Pu1 = pu1,
  1823. Pu2 = pu2
  1824. })
  1825. .TakeWhile(pair => pair.Pu1.SHA1Hash == pair.Pu2.SHA1Hash)
  1826. .Count();
  1827. if (countCommonAtBeginning != 0 && countCommonAtBeginning / (double) lengthToCompare < settings.DetailThreshold)
  1828. countCommonAtBeginning = 0;
  1829. if (countCommonAtBeginning != 0)
  1830. {
  1831. var newSequence = new List<CorrelatedSequence>();
  1832. var csEqual = new CorrelatedSequence
  1833. {
  1834. CorrelationStatus = CorrelationStatus.Equal,
  1835. ComparisonUnitArray1 = unknown
  1836. .ComparisonUnitArray1
  1837. .Take(countCommonAtBeginning)
  1838. .ToArray(),
  1839. ComparisonUnitArray2 = unknown
  1840. .ComparisonUnitArray2
  1841. .Take(countCommonAtBeginning)
  1842. .ToArray()
  1843. };
  1844. newSequence.Add(csEqual);
  1845. int remainingLeft = unknown.ComparisonUnitArray1.Length - countCommonAtBeginning;
  1846. int remainingRight = unknown.ComparisonUnitArray2.Length - countCommonAtBeginning;
  1847. if (remainingLeft != 0 && remainingRight == 0)
  1848. {
  1849. var csDeleted = new CorrelatedSequence
  1850. {
  1851. CorrelationStatus = CorrelationStatus.Deleted,
  1852. ComparisonUnitArray1 = unknown.ComparisonUnitArray1.Skip(countCommonAtBeginning).ToArray(),
  1853. ComparisonUnitArray2 = null
  1854. };
  1855. newSequence.Add(csDeleted);
  1856. }
  1857. else if (remainingLeft == 0 && remainingRight != 0)
  1858. {
  1859. var csInserted = new CorrelatedSequence
  1860. {
  1861. CorrelationStatus = CorrelationStatus.Inserted,
  1862. ComparisonUnitArray1 = null,
  1863. ComparisonUnitArray2 = unknown.ComparisonUnitArray2.Skip(countCommonAtBeginning).ToArray()
  1864. };
  1865. newSequence.Add(csInserted);
  1866. }
  1867. else if (remainingLeft != 0 && remainingRight != 0)
  1868. {
  1869. if (unknown.ComparisonUnitArray1[0] is ComparisonUnitWord first1 &&
  1870. unknown.ComparisonUnitArray2[0] is ComparisonUnitWord first2)
  1871. {
  1872. // if operating at the word level and
  1873. // if the last word on the left != pPr && last word on right != pPr
  1874. // then create an unknown for the rest of the paragraph, and create an unknown for the rest of the unknown
  1875. // if the last word on the left != pPr and last word on right == pPr
  1876. // then create deleted for the left, and create an unknown for the rest of the unknown
  1877. // if the last word on the left == pPr and last word on right != pPr
  1878. // then create inserted for the right, and create an unknown for the rest of the unknown
  1879. // if the last word on the left == pPr and last word on right == pPr
  1880. // then create an unknown for the rest of the unknown
  1881. ComparisonUnit[] remainingInLeft = unknown
  1882. .ComparisonUnitArray1
  1883. .Skip(countCommonAtBeginning)
  1884. .ToArray();
  1885. ComparisonUnit[] remainingInRight = unknown
  1886. .ComparisonUnitArray2
  1887. .Skip(countCommonAtBeginning)
  1888. .ToArray();
  1889. ComparisonUnitAtom lastContentAtomLeft = unknown.ComparisonUnitArray1[countCommonAtBeginning - 1]
  1890. .DescendantContentAtoms()
  1891. .FirstOrDefault();
  1892. ComparisonUnitAtom lastContentAtomRight = unknown.ComparisonUnitArray2[countCommonAtBeginning - 1]
  1893. .DescendantContentAtoms()
  1894. .FirstOrDefault();
  1895. if (lastContentAtomLeft?.ContentElement.Name != W.pPr && lastContentAtomRight?.ContentElement.Name != W.pPr)
  1896. {
  1897. List<ComparisonUnit[]> split1 = SplitAtParagraphMark(remainingInLeft);
  1898. List<ComparisonUnit[]> split2 = SplitAtParagraphMark(remainingInRight);
  1899. if (split1.Count() == 1 && split2.Count() == 1)
  1900. {
  1901. var csUnknown2 = new CorrelatedSequence
  1902. {
  1903. CorrelationStatus = CorrelationStatus.Unknown,
  1904. ComparisonUnitArray1 = split1.First(),
  1905. ComparisonUnitArray2 = split2.First()
  1906. };
  1907. newSequence.Add(csUnknown2);
  1908. return newSequence;
  1909. }
  1910. if (split1.Count == 2 && split2.Count == 2)
  1911. {
  1912. var csUnknown2 = new CorrelatedSequence
  1913. {
  1914. CorrelationStatus = CorrelationStatus.Unknown,
  1915. ComparisonUnitArray1 = split1.First(),
  1916. ComparisonUnitArray2 = split2.First()
  1917. };
  1918. newSequence.Add(csUnknown2);
  1919. var csUnknown3 = new CorrelatedSequence
  1920. {
  1921. CorrelationStatus = CorrelationStatus.Unknown,
  1922. ComparisonUnitArray1 = split1.Skip(1).First(),
  1923. ComparisonUnitArray2 = split2.Skip(1).First()
  1924. };
  1925. newSequence.Add(csUnknown3);
  1926. return newSequence;
  1927. }
  1928. }
  1929. }
  1930. var csUnknown = new CorrelatedSequence
  1931. {
  1932. CorrelationStatus = CorrelationStatus.Unknown,
  1933. ComparisonUnitArray1 = unknown.ComparisonUnitArray1.Skip(countCommonAtBeginning).ToArray(),
  1934. ComparisonUnitArray2 = unknown.ComparisonUnitArray2.Skip(countCommonAtBeginning).ToArray()
  1935. };
  1936. newSequence.Add(csUnknown);
  1937. }
  1938. else if (remainingLeft == 0 && remainingRight == 0)
  1939. {
  1940. // nothing to do
  1941. }
  1942. return newSequence;
  1943. }
  1944. // if we get to here, then countCommonAtBeginning == 0
  1945. int countCommonAtEnd = unknown
  1946. .ComparisonUnitArray1
  1947. .Reverse()
  1948. .Take(lengthToCompare)
  1949. .Zip(unknown
  1950. .ComparisonUnitArray2
  1951. .Reverse()
  1952. .Take(lengthToCompare),
  1953. (pu1, pu2) => new
  1954. {
  1955. Pu1 = pu1,
  1956. Pu2 = pu2
  1957. })
  1958. .TakeWhile(pair => pair.Pu1.SHA1Hash == pair.Pu2.SHA1Hash)
  1959. .Count();
  1960. // never start a common section with a paragraph mark. However, it is OK to set two paragraph marks as equal.
  1961. while (true)
  1962. {
  1963. if (countCommonAtEnd <= 1)
  1964. break;
  1965. ComparisonUnit firstCommon = unknown
  1966. .ComparisonUnitArray1
  1967. .Reverse()
  1968. .Take(countCommonAtEnd)
  1969. .LastOrDefault();
  1970. if (!(firstCommon is ComparisonUnitWord firstCommonWord))
  1971. break;
  1972. // if the word contains more than one atom, then not a paragraph mark
  1973. if (firstCommonWord.Contents.Count() != 1)
  1974. break;
  1975. if (!(firstCommonWord.Contents.First() is ComparisonUnitAtom firstCommonAtom))
  1976. break;
  1977. if (firstCommonAtom.ContentElement.Name != W.pPr)
  1978. break;
  1979. countCommonAtEnd--;
  1980. }
  1981. var isOnlyParagraphMark = false;
  1982. if (countCommonAtEnd == 1)
  1983. {
  1984. ComparisonUnit firstCommon = unknown
  1985. .ComparisonUnitArray1
  1986. .Reverse()
  1987. .Take(countCommonAtEnd)
  1988. .LastOrDefault();
  1989. if (firstCommon is ComparisonUnitWord firstCommonWord)
  1990. {
  1991. // if the word contains more than one atom, then not a paragraph mark
  1992. if (firstCommonWord.Contents.Count == 1)
  1993. {
  1994. if (firstCommonWord.Contents.First() is ComparisonUnitAtom firstCommonAtom)
  1995. {
  1996. if (firstCommonAtom.ContentElement.Name == W.pPr)
  1997. isOnlyParagraphMark = true;
  1998. }
  1999. }
  2000. }
  2001. }
  2002. if (countCommonAtEnd == 2)
  2003. {
  2004. ComparisonUnit firstCommon = unknown
  2005. .ComparisonUnitArray1
  2006. .Reverse()
  2007. .Take(countCommonAtEnd)
  2008. .LastOrDefault();
  2009. ComparisonUnit secondCommon = unknown
  2010. .ComparisonUnitArray1
  2011. .Reverse()
  2012. .Take(countCommonAtEnd)
  2013. .FirstOrDefault();
  2014. if (firstCommon is ComparisonUnitWord firstCommonWord && secondCommon is ComparisonUnitWord secondCommonWord)
  2015. {
  2016. // if the word contains more than one atom, then not a paragraph mark
  2017. if (firstCommonWord.Contents.Count == 1 && secondCommonWord.Contents.Count == 1)
  2018. {
  2019. if (firstCommonWord.Contents.First() is ComparisonUnitAtom firstCommonAtom &&
  2020. secondCommonWord.Contents.First() is ComparisonUnitAtom secondCommonAtom)
  2021. {
  2022. if (secondCommonAtom.ContentElement.Name == W.pPr)
  2023. isOnlyParagraphMark = true;
  2024. }
  2025. }
  2026. }
  2027. }
  2028. if (!isOnlyParagraphMark && countCommonAtEnd != 0 &&
  2029. countCommonAtEnd / (double) lengthToCompare < settings.DetailThreshold)
  2030. {
  2031. countCommonAtEnd = 0;
  2032. }
  2033. // If the following test is not there, the test below sets the end paragraph mark of the entire document equal to the end paragraph
  2034. // mark of the first paragraph in the other document, causing lines to be out of order.
  2035. // [InlineData("WC010-Para-Before-Table-Unmodified.docx", "WC010-Para-Before-Table-Mod.docx", 3)]
  2036. if (isOnlyParagraphMark)
  2037. {
  2038. countCommonAtEnd = 0;
  2039. }
  2040. if (countCommonAtEnd == 0)
  2041. {
  2042. return null;
  2043. }
  2044. // if countCommonAtEnd != 0, and if it contains a paragraph mark, then if there are comparison units in the same paragraph before the common at end (in either version)
  2045. // then we want to put all of those comparison units into a single unknown, where they must be resolved against each other. We don't want those comparison units to go into the middle unknown comparison unit.
  2046. if (countCommonAtEnd != 0)
  2047. {
  2048. var remainingInLeftParagraph = 0;
  2049. var remainingInRightParagraph = 0;
  2050. List<ComparisonUnit> commonEndSeq = unknown
  2051. .ComparisonUnitArray1
  2052. .Reverse()
  2053. .Take(countCommonAtEnd)
  2054. .Reverse()
  2055. .ToList();
  2056. ComparisonUnit firstOfCommonEndSeq = commonEndSeq.First();
  2057. if (firstOfCommonEndSeq is ComparisonUnitWord)
  2058. {
  2059. // are there any paragraph marks in the common seq at end?
  2060. //if (commonEndSeq.Any(cu => cu.Contents.OfType<ComparisonUnitAtom>().First().ContentElement.Name == W.pPr))
  2061. if (commonEndSeq.Any(cu =>
  2062. {
  2063. ComparisonUnitAtom firstComparisonUnitAtom = cu.Contents.OfType<ComparisonUnitAtom>().FirstOrDefault();
  2064. if (firstComparisonUnitAtom == null)
  2065. return false;
  2066. return firstComparisonUnitAtom.ContentElement.Name == W.pPr;
  2067. }))
  2068. {
  2069. remainingInLeftParagraph = unknown
  2070. .ComparisonUnitArray1
  2071. .Reverse()
  2072. .Skip(countCommonAtEnd)
  2073. .TakeWhile(cu =>
  2074. {
  2075. if (!(cu is ComparisonUnitWord))
  2076. return false;
  2077. ComparisonUnitAtom firstComparisonUnitAtom =
  2078. cu.Contents.OfType<ComparisonUnitAtom>().FirstOrDefault();
  2079. if (firstComparisonUnitAtom == null)
  2080. return true;
  2081. return firstComparisonUnitAtom.ContentElement.Name != W.pPr;
  2082. })
  2083. .Count();
  2084. remainingInRightParagraph = unknown
  2085. .ComparisonUnitArray2
  2086. .Reverse()
  2087. .Skip(countCommonAtEnd)
  2088. .TakeWhile(cu =>
  2089. {
  2090. if (!(cu is ComparisonUnitWord))
  2091. return false;
  2092. ComparisonUnitAtom firstComparisonUnitAtom =
  2093. cu.Contents.OfType<ComparisonUnitAtom>().FirstOrDefault();
  2094. if (firstComparisonUnitAtom == null)
  2095. return true;
  2096. return firstComparisonUnitAtom.ContentElement.Name != W.pPr;
  2097. })
  2098. .Count();
  2099. }
  2100. }
  2101. var newSequence = new List<CorrelatedSequence>();
  2102. int beforeCommonParagraphLeft = unknown.ComparisonUnitArray1.Length - remainingInLeftParagraph - countCommonAtEnd;
  2103. int beforeCommonParagraphRight =
  2104. unknown.ComparisonUnitArray2.Length - remainingInRightParagraph - countCommonAtEnd;
  2105. if (beforeCommonParagraphLeft != 0 && beforeCommonParagraphRight == 0)
  2106. {
  2107. var csDeleted = new CorrelatedSequence();
  2108. csDeleted.CorrelationStatus = CorrelationStatus.Deleted;
  2109. csDeleted.ComparisonUnitArray1 = unknown.ComparisonUnitArray1.Take(beforeCommonParagraphLeft).ToArray();
  2110. csDeleted.ComparisonUnitArray2 = null;
  2111. newSequence.Add(csDeleted);
  2112. }
  2113. else if (beforeCommonParagraphLeft == 0 && beforeCommonParagraphRight != 0)
  2114. {
  2115. var csInserted = new CorrelatedSequence();
  2116. csInserted.CorrelationStatus = CorrelationStatus.Inserted;
  2117. csInserted.ComparisonUnitArray1 = null;
  2118. csInserted.ComparisonUnitArray2 = unknown.ComparisonUnitArray2.Take(beforeCommonParagraphRight).ToArray();
  2119. newSequence.Add(csInserted);
  2120. }
  2121. else if (beforeCommonParagraphLeft != 0 && beforeCommonParagraphRight != 0)
  2122. {
  2123. var csUnknown = new CorrelatedSequence();
  2124. csUnknown.CorrelationStatus = CorrelationStatus.Unknown;
  2125. csUnknown.ComparisonUnitArray1 = unknown.ComparisonUnitArray1.Take(beforeCommonParagraphLeft).ToArray();
  2126. csUnknown.ComparisonUnitArray2 = unknown.ComparisonUnitArray2.Take(beforeCommonParagraphRight).ToArray();
  2127. newSequence.Add(csUnknown);
  2128. }
  2129. else if (beforeCommonParagraphLeft == 0 && beforeCommonParagraphRight == 0)
  2130. {
  2131. // nothing to do
  2132. }
  2133. if (remainingInLeftParagraph != 0 && remainingInRightParagraph == 0)
  2134. {
  2135. var csDeleted = new CorrelatedSequence();
  2136. csDeleted.CorrelationStatus = CorrelationStatus.Deleted;
  2137. csDeleted.ComparisonUnitArray1 = unknown.ComparisonUnitArray1.Skip(beforeCommonParagraphLeft)
  2138. .Take(remainingInLeftParagraph).ToArray();
  2139. csDeleted.ComparisonUnitArray2 = null;
  2140. newSequence.Add(csDeleted);
  2141. }
  2142. else if (remainingInLeftParagraph == 0 && remainingInRightParagraph != 0)
  2143. {
  2144. var csInserted = new CorrelatedSequence();
  2145. csInserted.CorrelationStatus = CorrelationStatus.Inserted;
  2146. csInserted.ComparisonUnitArray1 = null;
  2147. csInserted.ComparisonUnitArray2 = unknown.ComparisonUnitArray2.Skip(beforeCommonParagraphRight)
  2148. .Take(remainingInRightParagraph).ToArray();
  2149. newSequence.Add(csInserted);
  2150. }
  2151. else if (remainingInLeftParagraph != 0 && remainingInRightParagraph != 0)
  2152. {
  2153. var csUnknown = new CorrelatedSequence();
  2154. csUnknown.CorrelationStatus = CorrelationStatus.Unknown;
  2155. csUnknown.ComparisonUnitArray1 = unknown.ComparisonUnitArray1.Skip(beforeCommonParagraphLeft)
  2156. .Take(remainingInLeftParagraph).ToArray();
  2157. csUnknown.ComparisonUnitArray2 = unknown.ComparisonUnitArray2.Skip(beforeCommonParagraphRight)
  2158. .Take(remainingInRightParagraph).ToArray();
  2159. newSequence.Add(csUnknown);
  2160. }
  2161. else if (remainingInLeftParagraph == 0 && remainingInRightParagraph == 0)
  2162. {
  2163. // nothing to do
  2164. }
  2165. var csEqual = new CorrelatedSequence();
  2166. csEqual.CorrelationStatus = CorrelationStatus.Equal;
  2167. csEqual.ComparisonUnitArray1 = unknown.ComparisonUnitArray1
  2168. .Skip(unknown.ComparisonUnitArray1.Length - countCommonAtEnd).ToArray();
  2169. csEqual.ComparisonUnitArray2 = unknown.ComparisonUnitArray2
  2170. .Skip(unknown.ComparisonUnitArray2.Length - countCommonAtEnd).ToArray();
  2171. newSequence.Add(csEqual);
  2172. return newSequence;
  2173. }
  2174. return null;
  2175. #if false
  2176. var middleLeft = unknown
  2177. .ComparisonUnitArray1
  2178. .Skip(countCommonAtBeginning)
  2179. .SkipLast(remainingInLeftParagraph)
  2180. .SkipLast(countCommonAtEnd)
  2181. .ToArray();
  2182. var middleRight = unknown
  2183. .ComparisonUnitArray2
  2184. .Skip(countCommonAtBeginning)
  2185. .SkipLast(remainingInRightParagraph)
  2186. .SkipLast(countCommonAtEnd)
  2187. .ToArray();
  2188. if (middleLeft.Length > 0 && middleRight.Length == 0)
  2189. {
  2190. CorrelatedSequence cs = new CorrelatedSequence();
  2191. cs.CorrelationStatus = CorrelationStatus.Deleted;
  2192. cs.ComparisonUnitArray1 = middleLeft;
  2193. cs.ComparisonUnitArray2 = null;
  2194. newSequence.Add(cs);
  2195. }
  2196. else if (middleLeft.Length == 0 && middleRight.Length > 0)
  2197. {
  2198. CorrelatedSequence cs = new CorrelatedSequence();
  2199. cs.CorrelationStatus = CorrelationStatus.Inserted;
  2200. cs.ComparisonUnitArray1 = null;
  2201. cs.ComparisonUnitArray2 = middleRight;
  2202. newSequence.Add(cs);
  2203. }
  2204. else if (middleLeft.Length > 0 && middleRight.Length > 0)
  2205. {
  2206. CorrelatedSequence cs = new CorrelatedSequence();
  2207. cs.CorrelationStatus = CorrelationStatus.Unknown;
  2208. cs.ComparisonUnitArray1 = middleLeft;
  2209. cs.ComparisonUnitArray2 = middleRight;
  2210. newSequence.Add(cs);
  2211. }
  2212. var remainingInParaLeft = unknown
  2213. .ComparisonUnitArray1
  2214. .Skip(countCommonAtBeginning)
  2215. .Skip(middleLeft.Length)
  2216. .Take(remainingInLeftParagraph)
  2217. .ToArray();
  2218. var remainingInParaRight = unknown
  2219. .ComparisonUnitArray2
  2220. .Skip(countCommonAtBeginning)
  2221. .Skip(middleRight.Length)
  2222. .Take(remainingInRightParagraph)
  2223. .ToArray();
  2224. if (remainingInParaLeft.Length > 0 && remainingInParaRight.Length == 0)
  2225. {
  2226. CorrelatedSequence cs = new CorrelatedSequence();
  2227. cs.CorrelationStatus = CorrelationStatus.Deleted;
  2228. cs.ComparisonUnitArray1 = remainingInParaLeft;
  2229. cs.ComparisonUnitArray2 = null;
  2230. newSequence.Add(cs);
  2231. }
  2232. else if (remainingInParaLeft.Length == 0 && remainingInParaRight.Length > 0)
  2233. {
  2234. CorrelatedSequence cs = new CorrelatedSequence();
  2235. cs.CorrelationStatus = CorrelationStatus.Inserted;
  2236. cs.ComparisonUnitArray1 = null;
  2237. cs.ComparisonUnitArray2 = remainingInParaRight;
  2238. newSequence.Add(cs);
  2239. }
  2240. else if (remainingInParaLeft.Length > 0 && remainingInParaRight.Length > 0)
  2241. {
  2242. CorrelatedSequence cs = new CorrelatedSequence();
  2243. cs.CorrelationStatus = CorrelationStatus.Unknown;
  2244. cs.ComparisonUnitArray1 = remainingInParaLeft;
  2245. cs.ComparisonUnitArray2 = remainingInParaRight;
  2246. newSequence.Add(cs);
  2247. }
  2248. if (countCommonAtEnd != 0)
  2249. {
  2250. CorrelatedSequence cs = new CorrelatedSequence();
  2251. cs.CorrelationStatus = CorrelationStatus.Equal;
  2252. cs.ComparisonUnitArray1 = unknown
  2253. .ComparisonUnitArray1
  2254. .Skip(countCommonAtBeginning + middleLeft.Length + remainingInParaLeft.Length)
  2255. .ToArray();
  2256. cs.ComparisonUnitArray2 = unknown
  2257. .ComparisonUnitArray2
  2258. .Skip(countCommonAtBeginning + middleRight.Length + remainingInParaRight.Length)
  2259. .ToArray();
  2260. if (cs.ComparisonUnitArray1.Length != cs.ComparisonUnitArray2.Length)
  2261. throw new OpenXmlPowerToolsException("Internal error");
  2262. newSequence.Add(cs);
  2263. }
  2264. return newSequence;
  2265. #endif
  2266. }
  2267. private static List<ComparisonUnit[]> SplitAtParagraphMark(ComparisonUnit[] cua)
  2268. {
  2269. int i;
  2270. for (i = 0; i < cua.Length; i++)
  2271. {
  2272. ComparisonUnitAtom atom = cua[i].DescendantContentAtoms().FirstOrDefault();
  2273. if (atom != null && atom.ContentElement.Name == W.pPr)
  2274. break;
  2275. }
  2276. if (i == cua.Length)
  2277. {
  2278. return new List<ComparisonUnit[]>
  2279. {
  2280. cua
  2281. };
  2282. }
  2283. return new List<ComparisonUnit[]>
  2284. {
  2285. cua.Take(i).ToArray(),
  2286. cua.Skip(i).ToArray()
  2287. };
  2288. }
  2289. private static object CoalesceRecurse(
  2290. OpenXmlPart part,
  2291. IEnumerable<ComparisonUnitAtom> list,
  2292. int level,
  2293. WmlComparerSettings settings)
  2294. {
  2295. IEnumerable<IGrouping<string, ComparisonUnitAtom>> grouped = list.GroupBy(ca =>
  2296. {
  2297. if (level >= ca.AncestorElements.Length)
  2298. return "";
  2299. return ca.AncestorUnids[level];
  2300. })
  2301. .Where(g => g.Key != "");
  2302. // if there are no deeper children, then we're done.
  2303. if (!grouped.Any())
  2304. return null;
  2305. if (False)
  2306. {
  2307. var sb = new StringBuilder();
  2308. foreach (IGrouping<string, ComparisonUnitAtom> group in grouped)
  2309. {
  2310. sb.AppendFormat("Group Key: {0}", @group.Key);
  2311. sb.Append(Environment.NewLine);
  2312. foreach (ComparisonUnitAtom groupChildItem in @group)
  2313. {
  2314. sb.Append(" ");
  2315. sb.Append(groupChildItem.ToString(0));
  2316. sb.Append(Environment.NewLine);
  2317. }
  2318. sb.Append(Environment.NewLine);
  2319. }
  2320. string sbs = sb.ToString();
  2321. TestUtil.NotePad(sbs);
  2322. }
  2323. List<object> elementList = grouped
  2324. .Select(g =>
  2325. {
  2326. XElement ancestorBeingConstructed =
  2327. g.First().AncestorElements[level]; // these will all be the same, by definition
  2328. // need to group by corr stat
  2329. List<IGrouping<string, ComparisonUnitAtom>> groupedChildren = g
  2330. .GroupAdjacent(gc =>
  2331. {
  2332. var key = "";
  2333. if (level < gc.AncestorElements.Length - 1)
  2334. {
  2335. key = gc.AncestorUnids[level + 1];
  2336. }
  2337. if (gc.AncestorElements.Skip(level).Any(ae => ae.Name == W.txbxContent))
  2338. key += "|" + CorrelationStatus.Equal.ToString();
  2339. else
  2340. key += "|" + gc.CorrelationStatus.ToString();
  2341. return key;
  2342. })
  2343. .ToList();
  2344. if (ancestorBeingConstructed.Name == W.p)
  2345. {
  2346. List<object> newChildElements = groupedChildren
  2347. .Select(gc =>
  2348. {
  2349. string[] spl = gc.Key.Split('|');
  2350. if (spl[0] == "")
  2351. {
  2352. return (object) gc.Select(gcc =>
  2353. {
  2354. var dup = new XElement(gcc.ContentElement);
  2355. if (spl[1] == "Deleted")
  2356. dup.Add(new XAttribute(PtOpenXml.Status, "Deleted"));
  2357. else if (spl[1] == "Inserted")
  2358. dup.Add(new XAttribute(PtOpenXml.Status, "Inserted"));
  2359. return dup;
  2360. });
  2361. }
  2362. return CoalesceRecurse(part, gc, level + 1, settings);
  2363. })
  2364. .ToList();
  2365. var newPara = new XElement(W.p,
  2366. ancestorBeingConstructed.Attributes().Where(a => a.Name.Namespace != PtOpenXml.pt),
  2367. new XAttribute(PtOpenXml.Unid, g.Key),
  2368. newChildElements);
  2369. return newPara;
  2370. }
  2371. if (ancestorBeingConstructed.Name == W.r)
  2372. {
  2373. List<object> newChildElements = groupedChildren
  2374. .Select(gc =>
  2375. {
  2376. string[] spl = gc.Key.Split('|');
  2377. if (spl[0] == "")
  2378. {
  2379. return (object) gc.Select(gcc =>
  2380. {
  2381. var dup = new XElement(gcc.ContentElement);
  2382. if (spl[1] == "Deleted")
  2383. dup.Add(new XAttribute(PtOpenXml.Status, "Deleted"));
  2384. else if (spl[1] == "Inserted")
  2385. dup.Add(new XAttribute(PtOpenXml.Status, "Inserted"));
  2386. return dup;
  2387. });
  2388. }
  2389. return CoalesceRecurse(part, gc, level + 1, settings);
  2390. })
  2391. .ToList();
  2392. XElement rPr = ancestorBeingConstructed.Element(W.rPr);
  2393. var newRun = new XElement(W.r,
  2394. ancestorBeingConstructed.Attributes().Where(a => a.Name.Namespace != PtOpenXml.pt),
  2395. rPr,
  2396. newChildElements);
  2397. return newRun;
  2398. }
  2399. if (ancestorBeingConstructed.Name == W.t)
  2400. {
  2401. List<object> newChildElements = groupedChildren
  2402. .Select(gc =>
  2403. {
  2404. string textOfTextElement = gc.Select(gce => gce.ContentElement.Value).StringConcatenate();
  2405. bool del = gc.First().CorrelationStatus == CorrelationStatus.Deleted;
  2406. bool ins = gc.First().CorrelationStatus == CorrelationStatus.Inserted;
  2407. if (del)
  2408. return (object) new XElement(W.delText,
  2409. new XAttribute(PtOpenXml.Status, "Deleted"),
  2410. GetXmlSpaceAttribute(textOfTextElement),
  2411. textOfTextElement);
  2412. if (ins)
  2413. return (object) new XElement(W.t,
  2414. new XAttribute(PtOpenXml.Status, "Inserted"),
  2415. GetXmlSpaceAttribute(textOfTextElement),
  2416. textOfTextElement);
  2417. return (object) new XElement(W.t,
  2418. GetXmlSpaceAttribute(textOfTextElement),
  2419. textOfTextElement);
  2420. })
  2421. .ToList();
  2422. return newChildElements;
  2423. }
  2424. if (ancestorBeingConstructed.Name == W.drawing)
  2425. {
  2426. List<object> newChildElements = groupedChildren
  2427. .Select(gc =>
  2428. {
  2429. bool del = gc.First().CorrelationStatus == CorrelationStatus.Deleted;
  2430. if (del)
  2431. {
  2432. return (object) gc.Select(gcc =>
  2433. {
  2434. var newDrawing = new XElement(gcc.ContentElement);
  2435. newDrawing.Add(new XAttribute(PtOpenXml.Status, "Deleted"));
  2436. OpenXmlPart openXmlPartOfDeletedContent = gc.First().Part;
  2437. OpenXmlPart openXmlPartInNewDocument = part;
  2438. return gc.Select(gce =>
  2439. {
  2440. Package packageOfDeletedContent = openXmlPartOfDeletedContent.OpenXmlPackage.Package;
  2441. Package packageOfNewContent = openXmlPartInNewDocument.OpenXmlPackage.Package;
  2442. PackagePart partInDeletedDocument = packageOfDeletedContent.GetPart(part.Uri);
  2443. PackagePart partInNewDocument = packageOfNewContent.GetPart(part.Uri);
  2444. return MoveRelatedPartsToDestination(
  2445. partInDeletedDocument,
  2446. partInNewDocument,
  2447. newDrawing);
  2448. });
  2449. });
  2450. }
  2451. bool ins = gc.First().CorrelationStatus == CorrelationStatus.Inserted;
  2452. if (ins)
  2453. {
  2454. return gc.Select(gcc =>
  2455. {
  2456. var newDrawing = new XElement(gcc.ContentElement);
  2457. newDrawing.Add(new XAttribute(PtOpenXml.Status, "Inserted"));
  2458. OpenXmlPart openXmlPartOfInsertedContent = gc.First().Part;
  2459. OpenXmlPart openXmlPartInNewDocument = part;
  2460. return gc.Select(gce =>
  2461. {
  2462. Package packageOfSourceContent = openXmlPartOfInsertedContent.OpenXmlPackage.Package;
  2463. Package packageOfNewContent = openXmlPartInNewDocument.OpenXmlPackage.Package;
  2464. PackagePart partInDeletedDocument = packageOfSourceContent.GetPart(part.Uri);
  2465. PackagePart partInNewDocument = packageOfNewContent.GetPart(part.Uri);
  2466. return MoveRelatedPartsToDestination(
  2467. partInDeletedDocument,
  2468. partInNewDocument,
  2469. newDrawing);
  2470. });
  2471. });
  2472. }
  2473. return gc.Select(gcc => gcc.ContentElement);
  2474. })
  2475. .ToList();
  2476. return newChildElements;
  2477. }
  2478. if (ancestorBeingConstructed.Name == M.oMath || ancestorBeingConstructed.Name == M.oMathPara)
  2479. {
  2480. List<IEnumerable<XElement>> newChildElements = groupedChildren
  2481. .Select(gc =>
  2482. {
  2483. bool del = gc.First().CorrelationStatus == CorrelationStatus.Deleted;
  2484. if (del)
  2485. {
  2486. return gc.Select(gcc =>
  2487. new XElement(W.del,
  2488. new XAttribute(W.author, settings.AuthorForRevisions),
  2489. new XAttribute(W.id, _maxId++),
  2490. new XAttribute(W.date, settings.DateTimeForRevisions),
  2491. gcc.ContentElement));
  2492. }
  2493. bool ins = gc.First().CorrelationStatus == CorrelationStatus.Inserted;
  2494. if (ins)
  2495. {
  2496. return gc.Select(gcc =>
  2497. new XElement(W.ins,
  2498. new XAttribute(W.author, settings.AuthorForRevisions),
  2499. new XAttribute(W.id, _maxId++),
  2500. new XAttribute(W.date, settings.DateTimeForRevisions),
  2501. gcc.ContentElement));
  2502. }
  2503. return gc.Select(gcc => gcc.ContentElement);
  2504. })
  2505. .ToList();
  2506. return newChildElements;
  2507. }
  2508. if (AllowableRunChildren.Contains(ancestorBeingConstructed.Name))
  2509. {
  2510. List<IEnumerable<XElement>> newChildElements = groupedChildren
  2511. .Select(gc =>
  2512. {
  2513. bool del = gc.First().CorrelationStatus == CorrelationStatus.Deleted;
  2514. bool ins = gc.First().CorrelationStatus == CorrelationStatus.Inserted;
  2515. if (del)
  2516. {
  2517. return gc.Select(gcc =>
  2518. {
  2519. var dup = new XElement(ancestorBeingConstructed.Name,
  2520. ancestorBeingConstructed.Attributes().Where(a => a.Name.Namespace != PtOpenXml.pt),
  2521. new XAttribute(PtOpenXml.Status, "Deleted"));
  2522. return dup;
  2523. });
  2524. }
  2525. if (ins)
  2526. {
  2527. return gc.Select(gcc =>
  2528. {
  2529. var dup = new XElement(ancestorBeingConstructed.Name,
  2530. ancestorBeingConstructed.Attributes().Where(a => a.Name.Namespace != PtOpenXml.pt),
  2531. new XAttribute(PtOpenXml.Status, "Inserted"));
  2532. return dup;
  2533. });
  2534. }
  2535. return gc.Select(gcc => gcc.ContentElement);
  2536. })
  2537. .ToList();
  2538. return newChildElements;
  2539. }
  2540. if (ancestorBeingConstructed.Name == W.tbl)
  2541. return ReconstructElement(part, g, ancestorBeingConstructed, W.tblPr, W.tblGrid, null, level, settings);
  2542. if (ancestorBeingConstructed.Name == W.tr)
  2543. return ReconstructElement(part, g, ancestorBeingConstructed, W.trPr, null, null, level, settings);
  2544. if (ancestorBeingConstructed.Name == W.tc)
  2545. return ReconstructElement(part, g, ancestorBeingConstructed, W.tcPr, null, null, level, settings);
  2546. if (ancestorBeingConstructed.Name == W.sdt)
  2547. return ReconstructElement(part, g, ancestorBeingConstructed, W.sdtPr, W.sdtEndPr, null, level, settings);
  2548. if (ancestorBeingConstructed.Name == W.pict)
  2549. return ReconstructElement(part, g, ancestorBeingConstructed, VML.shapetype, null, null, level, settings);
  2550. if (ancestorBeingConstructed.Name == VML.shape)
  2551. return ReconstructElement(part, g, ancestorBeingConstructed, W10.wrap, null, null, level, settings);
  2552. if (ancestorBeingConstructed.Name == W._object)
  2553. return ReconstructElement(part, g, ancestorBeingConstructed, VML.shapetype, VML.shape, O.OLEObject, level,
  2554. settings);
  2555. if (ancestorBeingConstructed.Name == W.ruby)
  2556. return ReconstructElement(part, g, ancestorBeingConstructed, W.rubyPr, null, null, level, settings);
  2557. return (object) ReconstructElement(part, g, ancestorBeingConstructed, null, null, null, level, settings);
  2558. })
  2559. .ToList();
  2560. return elementList;
  2561. }
  2562. private static XElement ReconstructElement(
  2563. OpenXmlPart part,
  2564. IGrouping<string, ComparisonUnitAtom> g,
  2565. XElement ancestorBeingConstructed,
  2566. XName props1XName,
  2567. XName props2XName,
  2568. XName props3XName,
  2569. int level,
  2570. WmlComparerSettings settings)
  2571. {
  2572. object newChildElements = CoalesceRecurse(part, g, level + 1, settings);
  2573. object props1 = null;
  2574. if (props1XName != null)
  2575. props1 = ancestorBeingConstructed.Elements(props1XName);
  2576. object props2 = null;
  2577. if (props2XName != null)
  2578. props2 = ancestorBeingConstructed.Elements(props2XName);
  2579. object props3 = null;
  2580. if (props3XName != null)
  2581. props3 = ancestorBeingConstructed.Elements(props3XName);
  2582. var reconstructedElement = new XElement(ancestorBeingConstructed.Name,
  2583. ancestorBeingConstructed.Attributes(),
  2584. props1, props2, props3, newChildElements);
  2585. return reconstructedElement;
  2586. }
  2587. private static void SetAfterUnids(CorrelatedSequence unknown)
  2588. {
  2589. if (unknown.ComparisonUnitArray1.Length == 1 && unknown.ComparisonUnitArray2.Length == 1)
  2590. {
  2591. if (unknown.ComparisonUnitArray1[0] is ComparisonUnitGroup cua1 &&
  2592. unknown.ComparisonUnitArray2[0] is ComparisonUnitGroup cua2 &&
  2593. cua1.ComparisonUnitGroupType == cua2.ComparisonUnitGroupType)
  2594. {
  2595. ComparisonUnitGroupType groupType = cua1.ComparisonUnitGroupType;
  2596. IEnumerable<ComparisonUnitAtom> da1 = cua1.DescendantContentAtoms();
  2597. IEnumerable<ComparisonUnitAtom> da2 = cua2.DescendantContentAtoms();
  2598. XName takeThruName = null;
  2599. switch (groupType)
  2600. {
  2601. case ComparisonUnitGroupType.Paragraph:
  2602. takeThruName = W.p;
  2603. break;
  2604. case ComparisonUnitGroupType.Table:
  2605. takeThruName = W.tbl;
  2606. break;
  2607. case ComparisonUnitGroupType.Row:
  2608. takeThruName = W.tr;
  2609. break;
  2610. case ComparisonUnitGroupType.Cell:
  2611. takeThruName = W.tc;
  2612. break;
  2613. case ComparisonUnitGroupType.Textbox:
  2614. takeThruName = W.txbxContent;
  2615. break;
  2616. }
  2617. if (takeThruName == null)
  2618. throw new OpenXmlPowerToolsException("Internal error");
  2619. var relevantAncestors = new List<XElement>();
  2620. foreach (XElement ae in da1.First().AncestorElements)
  2621. {
  2622. if (ae.Name != takeThruName)
  2623. {
  2624. relevantAncestors.Add(ae);
  2625. continue;
  2626. }
  2627. relevantAncestors.Add(ae);
  2628. break;
  2629. }
  2630. string[] unidList = relevantAncestors
  2631. .Select(a =>
  2632. {
  2633. var unid = (string) a.Attribute(PtOpenXml.Unid);
  2634. if (unid == null)
  2635. throw new OpenXmlPowerToolsException("Internal error");
  2636. return unid;
  2637. })
  2638. .ToArray();
  2639. foreach (ComparisonUnitAtom da in da2)
  2640. {
  2641. IEnumerable<XElement> ancestorsToSet = da.AncestorElements.Take(unidList.Length);
  2642. var zipped = ancestorsToSet.Zip(unidList, (a, u) =>
  2643. new
  2644. {
  2645. Ancestor = a,
  2646. Unid = u
  2647. });
  2648. foreach (var z in zipped)
  2649. {
  2650. XAttribute unid = z.Ancestor.Attribute(PtOpenXml.Unid);
  2651. if (z.Ancestor.Name == W.footnotes || z.Ancestor.Name == W.endnotes)
  2652. continue;
  2653. if (unid == null)
  2654. throw new OpenXmlPowerToolsException("Internal error");
  2655. unid.Value = z.Unid;
  2656. }
  2657. }
  2658. }
  2659. }
  2660. }
  2661. private static List<CorrelatedSequence> ProcessCorrelatedHashes(CorrelatedSequence unknown, WmlComparerSettings settings)
  2662. {
  2663. // never attempt this optimization if there are less than 3 groups
  2664. int maxd = Math.Min(unknown.ComparisonUnitArray1.Length, unknown.ComparisonUnitArray2.Length);
  2665. if (maxd < 3)
  2666. return null;
  2667. if (unknown.ComparisonUnitArray1.FirstOrDefault() is ComparisonUnitGroup firstInCu1 &&
  2668. unknown.ComparisonUnitArray2.FirstOrDefault() is ComparisonUnitGroup firstInCu2)
  2669. {
  2670. if ((firstInCu1.ComparisonUnitGroupType == ComparisonUnitGroupType.Paragraph ||
  2671. firstInCu1.ComparisonUnitGroupType == ComparisonUnitGroupType.Table ||
  2672. firstInCu1.ComparisonUnitGroupType == ComparisonUnitGroupType.Row) &&
  2673. (firstInCu2.ComparisonUnitGroupType == ComparisonUnitGroupType.Paragraph ||
  2674. firstInCu2.ComparisonUnitGroupType == ComparisonUnitGroupType.Table ||
  2675. firstInCu2.ComparisonUnitGroupType == ComparisonUnitGroupType.Row))
  2676. {
  2677. ComparisonUnitGroupType groupType = firstInCu1.ComparisonUnitGroupType;
  2678. // Next want to do the lcs algorithm on this.
  2679. // potentially, we will find all paragraphs are correlated, but they may not be for two reasons-
  2680. // - if there were changes that were not tracked
  2681. // - if the anomalies in the change tracking cause there to be a mismatch in the number of paragraphs
  2682. // therefore we are going to do the whole LCS algorithm thing and at the end of the process, we set
  2683. // up the correlated sequence list where correlated paragraphs are together in their own unknown
  2684. // correlated sequence.
  2685. ComparisonUnit[] cul1 = unknown.ComparisonUnitArray1;
  2686. ComparisonUnit[] cul2 = unknown.ComparisonUnitArray2;
  2687. var currentLongestCommonSequenceLength = 0;
  2688. var currentLongestCommonSequenceAtomCount = 0;
  2689. int currentI1 = -1;
  2690. int currentI2 = -1;
  2691. for (var i1 = 0; i1 < cul1.Length; i1++)
  2692. {
  2693. for (var i2 = 0; i2 < cul2.Length; i2++)
  2694. {
  2695. var thisSequenceLength = 0;
  2696. var thisSequenceAtomCount = 0;
  2697. int thisI1 = i1;
  2698. int thisI2 = i2;
  2699. while (true)
  2700. {
  2701. bool match = cul1[thisI1] is ComparisonUnitGroup group1 &&
  2702. cul2[thisI2] is ComparisonUnitGroup group2 &&
  2703. group1.ComparisonUnitGroupType == group2.ComparisonUnitGroupType &&
  2704. group1.CorrelatedSHA1Hash != null &&
  2705. group2.CorrelatedSHA1Hash != null &&
  2706. group1.CorrelatedSHA1Hash == group2.CorrelatedSHA1Hash;
  2707. if (match)
  2708. {
  2709. thisSequenceAtomCount += cul1[thisI1].DescendantContentAtomsCount;
  2710. thisI1++;
  2711. thisI2++;
  2712. thisSequenceLength++;
  2713. if (thisI1 == cul1.Length || thisI2 == cul2.Length)
  2714. {
  2715. if (thisSequenceAtomCount > currentLongestCommonSequenceAtomCount)
  2716. {
  2717. currentLongestCommonSequenceLength = thisSequenceLength;
  2718. currentLongestCommonSequenceAtomCount = thisSequenceAtomCount;
  2719. currentI1 = i1;
  2720. currentI2 = i2;
  2721. }
  2722. break;
  2723. }
  2724. }
  2725. else
  2726. {
  2727. if (thisSequenceAtomCount > currentLongestCommonSequenceAtomCount)
  2728. {
  2729. currentLongestCommonSequenceLength = thisSequenceLength;
  2730. currentLongestCommonSequenceAtomCount = thisSequenceAtomCount;
  2731. currentI1 = i1;
  2732. currentI2 = i2;
  2733. }
  2734. break;
  2735. }
  2736. }
  2737. }
  2738. }
  2739. // here we want to have some sort of threshold, and if the currentLongestCommonSequenceLength is not
  2740. // longer than the threshold, then don't do anything
  2741. var doCorrelation = false;
  2742. if (currentLongestCommonSequenceLength == 1)
  2743. {
  2744. int numberOfAtoms1 = unknown.ComparisonUnitArray1[currentI1].DescendantContentAtoms().Count();
  2745. int numberOfAtoms2 = unknown.ComparisonUnitArray2[currentI2].DescendantContentAtoms().Count();
  2746. if (numberOfAtoms1 > 16 && numberOfAtoms2 > 16)
  2747. {
  2748. doCorrelation = true;
  2749. }
  2750. }
  2751. else if (currentLongestCommonSequenceLength > 1 && currentLongestCommonSequenceLength <= 3)
  2752. {
  2753. int numberOfAtoms1 = unknown
  2754. .ComparisonUnitArray1
  2755. .Skip(currentI1)
  2756. .Take(currentLongestCommonSequenceLength)
  2757. .Select(z => z.DescendantContentAtoms().Count())
  2758. .Sum();
  2759. int numberOfAtoms2 = unknown
  2760. .ComparisonUnitArray2
  2761. .Skip(currentI2)
  2762. .Take(currentLongestCommonSequenceLength)
  2763. .Select(z => z.DescendantContentAtoms().Count())
  2764. .Sum();
  2765. if (numberOfAtoms1 > 32 && numberOfAtoms2 > 32)
  2766. {
  2767. doCorrelation = true;
  2768. }
  2769. }
  2770. else if (currentLongestCommonSequenceLength > 3)
  2771. {
  2772. doCorrelation = true;
  2773. }
  2774. if (doCorrelation)
  2775. {
  2776. var newListOfCorrelatedSequence = new List<CorrelatedSequence>();
  2777. if (currentI1 > 0 && currentI2 == 0)
  2778. {
  2779. var deletedCorrelatedSequence = new CorrelatedSequence
  2780. {
  2781. CorrelationStatus = CorrelationStatus.Deleted,
  2782. ComparisonUnitArray1 = cul1.Take(currentI1).ToArray(),
  2783. ComparisonUnitArray2 = null
  2784. };
  2785. newListOfCorrelatedSequence.Add(deletedCorrelatedSequence);
  2786. }
  2787. else if (currentI1 == 0 && currentI2 > 0)
  2788. {
  2789. var insertedCorrelatedSequence = new CorrelatedSequence
  2790. {
  2791. CorrelationStatus = CorrelationStatus.Inserted,
  2792. ComparisonUnitArray1 = null,
  2793. ComparisonUnitArray2 = cul2.Take(currentI2).ToArray()
  2794. };
  2795. newListOfCorrelatedSequence.Add(insertedCorrelatedSequence);
  2796. }
  2797. else if (currentI1 > 0 && currentI2 > 0)
  2798. {
  2799. var unknownCorrelatedSequence = new CorrelatedSequence
  2800. {
  2801. CorrelationStatus = CorrelationStatus.Unknown,
  2802. ComparisonUnitArray1 = cul1.Take(currentI1).ToArray(),
  2803. ComparisonUnitArray2 = cul2.Take(currentI2).ToArray()
  2804. };
  2805. newListOfCorrelatedSequence.Add(unknownCorrelatedSequence);
  2806. }
  2807. else if (currentI1 == 0 && currentI2 == 0)
  2808. {
  2809. // nothing to do
  2810. }
  2811. for (var i = 0; i < currentLongestCommonSequenceLength; i++)
  2812. {
  2813. var unknownCorrelatedSequence = new CorrelatedSequence
  2814. {
  2815. CorrelationStatus = CorrelationStatus.Unknown,
  2816. ComparisonUnitArray1 = cul1
  2817. .Skip(currentI1)
  2818. .Skip(i)
  2819. .Take(1)
  2820. .ToArray(),
  2821. ComparisonUnitArray2 = cul2
  2822. .Skip(currentI2)
  2823. .Skip(i)
  2824. .Take(1)
  2825. .ToArray()
  2826. };
  2827. newListOfCorrelatedSequence.Add(unknownCorrelatedSequence);
  2828. }
  2829. int endI1 = currentI1 + currentLongestCommonSequenceLength;
  2830. int endI2 = currentI2 + currentLongestCommonSequenceLength;
  2831. if (endI1 < cul1.Length && endI2 == cul2.Length)
  2832. {
  2833. var deletedCorrelatedSequence = new CorrelatedSequence
  2834. {
  2835. CorrelationStatus = CorrelationStatus.Deleted,
  2836. ComparisonUnitArray1 = cul1.Skip(endI1).ToArray(),
  2837. ComparisonUnitArray2 = null
  2838. };
  2839. newListOfCorrelatedSequence.Add(deletedCorrelatedSequence);
  2840. }
  2841. else if (endI1 == cul1.Length && endI2 < cul2.Length)
  2842. {
  2843. var insertedCorrelatedSequence = new CorrelatedSequence
  2844. {
  2845. CorrelationStatus = CorrelationStatus.Inserted,
  2846. ComparisonUnitArray1 = null,
  2847. ComparisonUnitArray2 = cul2.Skip(endI2).ToArray()
  2848. };
  2849. newListOfCorrelatedSequence.Add(insertedCorrelatedSequence);
  2850. }
  2851. else if (endI1 < cul1.Length && endI2 < cul2.Length)
  2852. {
  2853. var unknownCorrelatedSequence = new CorrelatedSequence
  2854. {
  2855. CorrelationStatus = CorrelationStatus.Unknown,
  2856. ComparisonUnitArray1 = cul1.Skip(endI1).ToArray(),
  2857. ComparisonUnitArray2 = cul2.Skip(endI2).ToArray()
  2858. };
  2859. newListOfCorrelatedSequence.Add(unknownCorrelatedSequence);
  2860. }
  2861. else if (endI1 == cul1.Length && endI2 == cul2.Length)
  2862. {
  2863. // nothing to do
  2864. }
  2865. return newListOfCorrelatedSequence;
  2866. }
  2867. return null;
  2868. }
  2869. }
  2870. return null;
  2871. }
  2872. }
  2873. }