diff_match_patch.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339
  1. /**
  2. * Diff Match and Patch
  3. *
  4. * Copyright 2006 Google Inc.
  5. * http://code.google.com/p/google-diff-match-patch/
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. /**
  20. * @fileoverview Computes the difference between two texts to create a patch.
  21. * Applies the patch onto another text, allowing for errors.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. /**
  25. * Class containing the diff, match and patch methods.
  26. * @constructor
  27. */
  28. function diff_match_patch() {
  29. // Defaults.
  30. // Redefine these in your program to override the defaults.
  31. // Number of seconds to map a diff before giving up (0 for infinity).
  32. this.Diff_Timeout = 1.0
  33. // Cost of an empty edit operation in terms of edit characters.
  34. this.Diff_EditCost = 4
  35. // At what point is no match declared (0.0 = perfection, 1.0 = very loose).
  36. this.Match_Threshold = 0.5
  37. // How far to search for a match (0 = exact location, 1000+ = broad match).
  38. // A match this many characters away from the expected location will add
  39. // 1.0 to the score (0.0 is a perfect match).
  40. this.Match_Distance = 1000
  41. // When deleting a large block of text (over ~64 characters), how close do
  42. // the contents have to be to match the expected contents. (0.0 = perfection,
  43. // 1.0 = very loose). Note that Match_Threshold controls how closely the
  44. // end points of a delete need to match.
  45. this.Patch_DeleteThreshold = 0.5
  46. // Chunk size for context length.
  47. this.Patch_Margin = 4
  48. // The number of bits in an int.
  49. this.Match_MaxBits = 32
  50. }
  51. // DIFF FUNCTIONS
  52. /**
  53. * The data structure representing a diff is an array of tuples:
  54. * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
  55. * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
  56. */
  57. var DIFF_DELETE = -1
  58. var DIFF_INSERT = 1
  59. var DIFF_EQUAL = 0
  60. /** @typedef {{0: number, 1: string}} */
  61. diff_match_patch.Diff
  62. /**
  63. * Find the differences between two texts. Simplifies the problem by stripping
  64. * any common prefix or suffix off the texts before diffing.
  65. * @param {string} text1 Old string to be diffed.
  66. * @param {string} text2 New string to be diffed.
  67. * @param {boolean=} opt_checklines Optional speedup flag. If present and false,
  68. * then don't run a line-level diff first to identify the changed areas.
  69. * Defaults to true, which does a faster, slightly less optimal diff.
  70. * @param {number} opt_deadline Optional time when the diff should be complete
  71. * by. Used internally for recursive calls. Users should set DiffTimeout
  72. * instead.
  73. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  74. */
  75. diff_match_patch.prototype.diff_main = function (
  76. text1,
  77. text2,
  78. opt_checklines,
  79. opt_deadline
  80. ) {
  81. // Set a deadline by which time the diff must be complete.
  82. if (typeof opt_deadline === 'undefined') {
  83. if (this.Diff_Timeout <= 0) {
  84. opt_deadline = Number.MAX_VALUE
  85. } else {
  86. opt_deadline = new Date().getTime() + this.Diff_Timeout * 1000
  87. }
  88. }
  89. var deadline = opt_deadline
  90. // Check for null inputs.
  91. if (text1 == null || text2 == null) {
  92. throw new Error('Null input. (diff_main)')
  93. }
  94. // Check for equality (speedup).
  95. if (text1 == text2) {
  96. if (text1) {
  97. return [[DIFF_EQUAL, text1]]
  98. }
  99. return []
  100. }
  101. if (typeof opt_checklines === 'undefined') {
  102. opt_checklines = true
  103. }
  104. var checklines = opt_checklines
  105. // Trim off common prefix (speedup).
  106. var commonlength = this.diff_commonPrefix(text1, text2)
  107. var commonprefix = text1.substring(0, commonlength)
  108. text1 = text1.substring(commonlength)
  109. text2 = text2.substring(commonlength)
  110. // Trim off common suffix (speedup).
  111. commonlength = this.diff_commonSuffix(text1, text2)
  112. var commonsuffix = text1.substring(text1.length - commonlength)
  113. text1 = text1.substring(0, text1.length - commonlength)
  114. text2 = text2.substring(0, text2.length - commonlength)
  115. // Compute the diff on the middle block.
  116. var diffs = this.diff_compute_(text1, text2, checklines, deadline)
  117. // Restore the prefix and suffix.
  118. if (commonprefix) {
  119. diffs.unshift([DIFF_EQUAL, commonprefix])
  120. }
  121. if (commonsuffix) {
  122. diffs.push([DIFF_EQUAL, commonsuffix])
  123. }
  124. this.diff_cleanupMerge(diffs)
  125. return diffs
  126. }
  127. /**
  128. * Find the differences between two texts. Assumes that the texts do not
  129. * have any common prefix or suffix.
  130. * @param {string} text1 Old string to be diffed.
  131. * @param {string} text2 New string to be diffed.
  132. * @param {boolean} checklines Speedup flag. If false, then don't run a
  133. * line-level diff first to identify the changed areas.
  134. * If true, then run a faster, slightly less optimal diff.
  135. * @param {number} deadline Time when the diff should be complete by.
  136. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  137. * @private
  138. */
  139. diff_match_patch.prototype.diff_compute_ = function (
  140. text1,
  141. text2,
  142. checklines,
  143. deadline
  144. ) {
  145. var diffs
  146. if (!text1) {
  147. // Just add some text (speedup).
  148. return [[DIFF_INSERT, text2]]
  149. }
  150. if (!text2) {
  151. // Just delete some text (speedup).
  152. return [[DIFF_DELETE, text1]]
  153. }
  154. var longtext = text1.length > text2.length ? text1 : text2
  155. var shorttext = text1.length > text2.length ? text2 : text1
  156. var i = longtext.indexOf(shorttext)
  157. if (i != -1) {
  158. // Shorter text is inside the longer text (speedup).
  159. diffs = [
  160. [DIFF_INSERT, longtext.substring(0, i)],
  161. [DIFF_EQUAL, shorttext],
  162. [DIFF_INSERT, longtext.substring(i + shorttext.length)],
  163. ]
  164. // Swap insertions for deletions if diff is reversed.
  165. if (text1.length > text2.length) {
  166. diffs[0][0] = diffs[2][0] = DIFF_DELETE
  167. }
  168. return diffs
  169. }
  170. if (shorttext.length == 1) {
  171. // Single character string.
  172. // After the previous speedup, the character can't be an equality.
  173. return [
  174. [DIFF_DELETE, text1],
  175. [DIFF_INSERT, text2],
  176. ]
  177. }
  178. // Check to see if the problem can be split in two.
  179. var hm = this.diff_halfMatch_(text1, text2)
  180. if (hm) {
  181. // A half-match was found, sort out the return data.
  182. var text1_a = hm[0]
  183. var text1_b = hm[1]
  184. var text2_a = hm[2]
  185. var text2_b = hm[3]
  186. var mid_common = hm[4]
  187. // Send both pairs off for separate processing.
  188. var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline)
  189. var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline)
  190. // Merge the results.
  191. return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b)
  192. }
  193. if (checklines && text1.length > 100 && text2.length > 100) {
  194. return this.diff_lineMode_(text1, text2, deadline)
  195. }
  196. return this.diff_bisect_(text1, text2, deadline)
  197. }
  198. /**
  199. * Do a quick line-level diff on both strings, then rediff the parts for
  200. * greater accuracy.
  201. * This speedup can produce non-minimal diffs.
  202. * @param {string} text1 Old string to be diffed.
  203. * @param {string} text2 New string to be diffed.
  204. * @param {number} deadline Time when the diff should be complete by.
  205. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  206. * @private
  207. */
  208. diff_match_patch.prototype.diff_lineMode_ = function (text1, text2, deadline) {
  209. // Scan the text on a line-by-line basis first.
  210. var a = this.diff_linesToChars_(text1, text2)
  211. text1 = a.chars1
  212. text2 = a.chars2
  213. var linearray = a.lineArray
  214. var diffs = this.diff_main(text1, text2, false, deadline)
  215. // Convert the diff back to original text.
  216. this.diff_charsToLines_(diffs, linearray)
  217. // Eliminate freak matches (e.g. blank lines)
  218. this.diff_cleanupSemantic(diffs)
  219. // Rediff any replacement blocks, this time character-by-character.
  220. // Add a dummy entry at the end.
  221. diffs.push([DIFF_EQUAL, ''])
  222. var pointer = 0
  223. var count_delete = 0
  224. var count_insert = 0
  225. var text_delete = ''
  226. var text_insert = ''
  227. while (pointer < diffs.length) {
  228. switch (diffs[pointer][0]) {
  229. case DIFF_INSERT:
  230. count_insert++
  231. text_insert += diffs[pointer][1]
  232. break
  233. case DIFF_DELETE:
  234. count_delete++
  235. text_delete += diffs[pointer][1]
  236. break
  237. case DIFF_EQUAL:
  238. // Upon reaching an equality, check for prior redundancies.
  239. if (count_delete >= 1 && count_insert >= 1) {
  240. // Delete the offending records and add the merged ones.
  241. diffs.splice(
  242. pointer - count_delete - count_insert,
  243. count_delete + count_insert
  244. )
  245. pointer = pointer - count_delete - count_insert
  246. var a = this.diff_main(text_delete, text_insert, false, deadline)
  247. for (var j = a.length - 1; j >= 0; j--) {
  248. diffs.splice(pointer, 0, a[j])
  249. }
  250. pointer = pointer + a.length
  251. }
  252. count_insert = 0
  253. count_delete = 0
  254. text_delete = ''
  255. text_insert = ''
  256. break
  257. }
  258. pointer++
  259. }
  260. diffs.pop() // Remove the dummy entry at the end.
  261. return diffs
  262. }
  263. /**
  264. * Find the 'middle snake' of a diff, split the problem in two
  265. * and return the recursively constructed diff.
  266. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  267. * @param {string} text1 Old string to be diffed.
  268. * @param {string} text2 New string to be diffed.
  269. * @param {number} deadline Time at which to bail if not yet complete.
  270. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  271. * @private
  272. */
  273. diff_match_patch.prototype.diff_bisect_ = function (text1, text2, deadline) {
  274. // Cache the text lengths to prevent multiple calls.
  275. var text1_length = text1.length
  276. var text2_length = text2.length
  277. var max_d = Math.ceil((text1_length + text2_length) / 2)
  278. var v_offset = max_d
  279. var v_length = 2 * max_d
  280. var v1 = new Array(v_length)
  281. var v2 = new Array(v_length)
  282. // Setting all elements to -1 is faster in Chrome & Firefox than mixing
  283. // integers and undefined.
  284. for (var x = 0; x < v_length; x++) {
  285. v1[x] = -1
  286. v2[x] = -1
  287. }
  288. v1[v_offset + 1] = 0
  289. v2[v_offset + 1] = 0
  290. var delta = text1_length - text2_length
  291. // If the total number of characters is odd, then the front path will collide
  292. // with the reverse path.
  293. var front = delta % 2 != 0
  294. // Offsets for start and end of k loop.
  295. // Prevents mapping of space beyond the grid.
  296. var k1start = 0
  297. var k1end = 0
  298. var k2start = 0
  299. var k2end = 0
  300. for (var d = 0; d < max_d; d++) {
  301. // Bail out if deadline is reached.
  302. if (new Date().getTime() > deadline) {
  303. break
  304. }
  305. // Walk the front path one step.
  306. for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
  307. var k1_offset = v_offset + k1
  308. var x1
  309. if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
  310. x1 = v1[k1_offset + 1]
  311. } else {
  312. x1 = v1[k1_offset - 1] + 1
  313. }
  314. var y1 = x1 - k1
  315. while (
  316. x1 < text1_length &&
  317. y1 < text2_length &&
  318. text1.charAt(x1) == text2.charAt(y1)
  319. ) {
  320. x1++
  321. y1++
  322. }
  323. v1[k1_offset] = x1
  324. if (x1 > text1_length) {
  325. // Ran off the right of the graph.
  326. k1end += 2
  327. } else if (y1 > text2_length) {
  328. // Ran off the bottom of the graph.
  329. k1start += 2
  330. } else if (front) {
  331. var k2_offset = v_offset + delta - k1
  332. if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
  333. // Mirror x2 onto top-left coordinate system.
  334. var x2 = text1_length - v2[k2_offset]
  335. if (x1 >= x2) {
  336. // Overlap detected.
  337. return this.diff_bisectSplit_(text1, text2, x1, y1, deadline)
  338. }
  339. }
  340. }
  341. }
  342. // Walk the reverse path one step.
  343. for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
  344. var k2_offset = v_offset + k2
  345. var x2
  346. if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
  347. x2 = v2[k2_offset + 1]
  348. } else {
  349. x2 = v2[k2_offset - 1] + 1
  350. }
  351. var y2 = x2 - k2
  352. while (
  353. x2 < text1_length &&
  354. y2 < text2_length &&
  355. text1.charAt(text1_length - x2 - 1) ==
  356. text2.charAt(text2_length - y2 - 1)
  357. ) {
  358. x2++
  359. y2++
  360. }
  361. v2[k2_offset] = x2
  362. if (x2 > text1_length) {
  363. // Ran off the left of the graph.
  364. k2end += 2
  365. } else if (y2 > text2_length) {
  366. // Ran off the top of the graph.
  367. k2start += 2
  368. } else if (!front) {
  369. var k1_offset = v_offset + delta - k2
  370. if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
  371. var x1 = v1[k1_offset]
  372. var y1 = v_offset + x1 - k1_offset
  373. // Mirror x2 onto top-left coordinate system.
  374. x2 = text1_length - x2
  375. if (x1 >= x2) {
  376. // Overlap detected.
  377. return this.diff_bisectSplit_(text1, text2, x1, y1, deadline)
  378. }
  379. }
  380. }
  381. }
  382. }
  383. // Diff took too long and hit the deadline or
  384. // number of diffs equals number of characters, no commonality at all.
  385. return [
  386. [DIFF_DELETE, text1],
  387. [DIFF_INSERT, text2],
  388. ]
  389. }
  390. /**
  391. * Given the location of the 'middle snake', split the diff in two parts
  392. * and recurse.
  393. * @param {string} text1 Old string to be diffed.
  394. * @param {string} text2 New string to be diffed.
  395. * @param {number} x Index of split point in text1.
  396. * @param {number} y Index of split point in text2.
  397. * @param {number} deadline Time at which to bail if not yet complete.
  398. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  399. * @private
  400. */
  401. diff_match_patch.prototype.diff_bisectSplit_ = function (
  402. text1,
  403. text2,
  404. x,
  405. y,
  406. deadline
  407. ) {
  408. var text1a = text1.substring(0, x)
  409. var text2a = text2.substring(0, y)
  410. var text1b = text1.substring(x)
  411. var text2b = text2.substring(y)
  412. // Compute both diffs serially.
  413. var diffs = this.diff_main(text1a, text2a, false, deadline)
  414. var diffsb = this.diff_main(text1b, text2b, false, deadline)
  415. return diffs.concat(diffsb)
  416. }
  417. /**
  418. * Split two texts into an array of strings. Reduce the texts to a string of
  419. * hashes where each Unicode character represents one line.
  420. * @param {string} text1 First string.
  421. * @param {string} text2 Second string.
  422. * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
  423. * An object containing the encoded text1, the encoded text2 and
  424. * the array of unique strings.
  425. * The zeroth element of the array of unique strings is intentionally blank.
  426. * @private
  427. */
  428. diff_match_patch.prototype.diff_linesToChars_ = function (text1, text2) {
  429. var lineArray = [] // e.g. lineArray[4] == 'Hello\n'
  430. var lineHash = {} // e.g. lineHash['Hello\n'] == 4
  431. // '\x00' is a valid character, but various debuggers don't like it.
  432. // So we'll insert a junk entry to avoid generating a null character.
  433. lineArray[0] = ''
  434. /**
  435. * Split a text into an array of strings. Reduce the texts to a string of
  436. * hashes where each Unicode character represents one line.
  437. * Modifies linearray and linehash through being a closure.
  438. * @param {string} text String to encode.
  439. * @return {string} Encoded string.
  440. * @private
  441. */
  442. function diff_linesToCharsMunge_(text) {
  443. var chars = ''
  444. // Walk the text, pulling out a substring for each line.
  445. // text.split('\n') would would temporarily double our memory footprint.
  446. // Modifying text would create many large strings to garbage collect.
  447. var lineStart = 0
  448. var lineEnd = -1
  449. // Keeping our own length variable is faster than looking it up.
  450. var lineArrayLength = lineArray.length
  451. while (lineEnd < text.length - 1) {
  452. lineEnd = text.indexOf('\n', lineStart)
  453. if (lineEnd == -1) {
  454. lineEnd = text.length - 1
  455. }
  456. var line = text.substring(lineStart, lineEnd + 1)
  457. lineStart = lineEnd + 1
  458. if (
  459. lineHash.hasOwnProperty
  460. ? lineHash.hasOwnProperty(line)
  461. : lineHash[line] !== undefined
  462. ) {
  463. chars += String.fromCharCode(lineHash[line])
  464. } else {
  465. chars += String.fromCharCode(lineArrayLength)
  466. lineHash[line] = lineArrayLength
  467. lineArray[lineArrayLength++] = line
  468. }
  469. }
  470. return chars
  471. }
  472. var chars1 = diff_linesToCharsMunge_(text1)
  473. var chars2 = diff_linesToCharsMunge_(text2)
  474. return { chars1: chars1, chars2: chars2, lineArray: lineArray }
  475. }
  476. /**
  477. * Rehydrate the text in a diff from a string of line hashes to real lines of
  478. * text.
  479. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  480. * @param {!Array.<string>} lineArray Array of unique strings.
  481. * @private
  482. */
  483. diff_match_patch.prototype.diff_charsToLines_ = function (diffs, lineArray) {
  484. for (var x = 0; x < diffs.length; x++) {
  485. var chars = diffs[x][1]
  486. var text = []
  487. for (var y = 0; y < chars.length; y++) {
  488. text[y] = lineArray[chars.charCodeAt(y)]
  489. }
  490. diffs[x][1] = text.join('')
  491. }
  492. }
  493. /**
  494. * Determine the common prefix of two strings.
  495. * @param {string} text1 First string.
  496. * @param {string} text2 Second string.
  497. * @return {number} The number of characters common to the start of each
  498. * string.
  499. */
  500. diff_match_patch.prototype.diff_commonPrefix = function (text1, text2) {
  501. // Quick check for common null cases.
  502. if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
  503. return 0
  504. }
  505. // Binary search.
  506. // Performance analysis: http://neil.fraser.name/news/2007/10/09/
  507. var pointermin = 0
  508. var pointermax = Math.min(text1.length, text2.length)
  509. var pointermid = pointermax
  510. var pointerstart = 0
  511. while (pointermin < pointermid) {
  512. if (
  513. text1.substring(pointerstart, pointermid) ==
  514. text2.substring(pointerstart, pointermid)
  515. ) {
  516. pointermin = pointermid
  517. pointerstart = pointermin
  518. } else {
  519. pointermax = pointermid
  520. }
  521. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin)
  522. }
  523. return pointermid
  524. }
  525. /**
  526. * Determine the common suffix of two strings.
  527. * @param {string} text1 First string.
  528. * @param {string} text2 Second string.
  529. * @return {number} The number of characters common to the end of each string.
  530. */
  531. diff_match_patch.prototype.diff_commonSuffix = function (text1, text2) {
  532. // Quick check for common null cases.
  533. if (
  534. !text1 ||
  535. !text2 ||
  536. text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)
  537. ) {
  538. return 0
  539. }
  540. // Binary search.
  541. // Performance analysis: http://neil.fraser.name/news/2007/10/09/
  542. var pointermin = 0
  543. var pointermax = Math.min(text1.length, text2.length)
  544. var pointermid = pointermax
  545. var pointerend = 0
  546. while (pointermin < pointermid) {
  547. if (
  548. text1.substring(text1.length - pointermid, text1.length - pointerend) ==
  549. text2.substring(text2.length - pointermid, text2.length - pointerend)
  550. ) {
  551. pointermin = pointermid
  552. pointerend = pointermin
  553. } else {
  554. pointermax = pointermid
  555. }
  556. pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin)
  557. }
  558. return pointermid
  559. }
  560. /**
  561. * Determine if the suffix of one string is the prefix of another.
  562. * @param {string} text1 First string.
  563. * @param {string} text2 Second string.
  564. * @return {number} The number of characters common to the end of the first
  565. * string and the start of the second string.
  566. * @private
  567. */
  568. diff_match_patch.prototype.diff_commonOverlap_ = function (text1, text2) {
  569. // Cache the text lengths to prevent multiple calls.
  570. var text1_length = text1.length
  571. var text2_length = text2.length
  572. // Eliminate the null case.
  573. if (text1_length == 0 || text2_length == 0) {
  574. return 0
  575. }
  576. // Truncate the longer string.
  577. if (text1_length > text2_length) {
  578. text1 = text1.substring(text1_length - text2_length)
  579. } else if (text1_length < text2_length) {
  580. text2 = text2.substring(0, text1_length)
  581. }
  582. var text_length = Math.min(text1_length, text2_length)
  583. // Quick check for the worst case.
  584. if (text1 == text2) {
  585. return text_length
  586. }
  587. // Start by looking for a single character match
  588. // and increase length until no match is found.
  589. // Performance analysis: http://neil.fraser.name/news/2010/11/04/
  590. var best = 0
  591. var length = 1
  592. while (true) {
  593. var pattern = text1.substring(text_length - length)
  594. var found = text2.indexOf(pattern)
  595. if (found == -1) {
  596. return best
  597. }
  598. length += found
  599. if (
  600. found == 0 ||
  601. text1.substring(text_length - length) == text2.substring(0, length)
  602. ) {
  603. best = length
  604. length++
  605. }
  606. }
  607. }
  608. /**
  609. * Do the two texts share a substring which is at least half the length of the
  610. * longer text?
  611. * This speedup can produce non-minimal diffs.
  612. * @param {string} text1 First string.
  613. * @param {string} text2 Second string.
  614. * @return {Array.<string>} Five element Array, containing the prefix of
  615. * text1, the suffix of text1, the prefix of text2, the suffix of
  616. * text2 and the common middle. Or null if there was no match.
  617. * @private
  618. */
  619. diff_match_patch.prototype.diff_halfMatch_ = function (text1, text2) {
  620. if (this.Diff_Timeout <= 0) {
  621. // Don't risk returning a non-optimal diff if we have unlimited time.
  622. return null
  623. }
  624. var longtext = text1.length > text2.length ? text1 : text2
  625. var shorttext = text1.length > text2.length ? text2 : text1
  626. if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
  627. return null // Pointless.
  628. }
  629. var dmp = this // 'this' becomes 'window' in a closure.
  630. /**
  631. * Does a substring of shorttext exist within longtext such that the substring
  632. * is at least half the length of longtext?
  633. * Closure, but does not reference any external variables.
  634. * @param {string} longtext Longer string.
  635. * @param {string} shorttext Shorter string.
  636. * @param {number} i Start index of quarter length substring within longtext.
  637. * @return {Array.<string>} Five element Array, containing the prefix of
  638. * longtext, the suffix of longtext, the prefix of shorttext, the suffix
  639. * of shorttext and the common middle. Or null if there was no match.
  640. * @private
  641. */
  642. function diff_halfMatchI_(longtext, shorttext, i) {
  643. // Start with a 1/4 length substring at position i as a seed.
  644. var seed = longtext.substring(i, i + Math.floor(longtext.length / 4))
  645. var j = -1
  646. var best_common = ''
  647. var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b
  648. while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
  649. var prefixLength = dmp.diff_commonPrefix(
  650. longtext.substring(i),
  651. shorttext.substring(j)
  652. )
  653. var suffixLength = dmp.diff_commonSuffix(
  654. longtext.substring(0, i),
  655. shorttext.substring(0, j)
  656. )
  657. if (best_common.length < suffixLength + prefixLength) {
  658. best_common =
  659. shorttext.substring(j - suffixLength, j) +
  660. shorttext.substring(j, j + prefixLength)
  661. best_longtext_a = longtext.substring(0, i - suffixLength)
  662. best_longtext_b = longtext.substring(i + prefixLength)
  663. best_shorttext_a = shorttext.substring(0, j - suffixLength)
  664. best_shorttext_b = shorttext.substring(j + prefixLength)
  665. }
  666. }
  667. if (best_common.length * 2 >= longtext.length) {
  668. return [
  669. best_longtext_a,
  670. best_longtext_b,
  671. best_shorttext_a,
  672. best_shorttext_b,
  673. best_common,
  674. ]
  675. } else {
  676. return null
  677. }
  678. }
  679. // First check if the second quarter is the seed for a half-match.
  680. var hm1 = diff_halfMatchI_(
  681. longtext,
  682. shorttext,
  683. Math.ceil(longtext.length / 4)
  684. )
  685. // Check again based on the third quarter.
  686. var hm2 = diff_halfMatchI_(
  687. longtext,
  688. shorttext,
  689. Math.ceil(longtext.length / 2)
  690. )
  691. var hm
  692. if (!hm1 && !hm2) {
  693. return null
  694. } else if (!hm2) {
  695. hm = hm1
  696. } else if (!hm1) {
  697. hm = hm2
  698. } else {
  699. // Both matched. Select the longest.
  700. hm = hm1[4].length > hm2[4].length ? hm1 : hm2
  701. }
  702. // A half-match was found, sort out the return data.
  703. var text1_a, text1_b, text2_a, text2_b
  704. if (text1.length > text2.length) {
  705. text1_a = hm[0]
  706. text1_b = hm[1]
  707. text2_a = hm[2]
  708. text2_b = hm[3]
  709. } else {
  710. text2_a = hm[0]
  711. text2_b = hm[1]
  712. text1_a = hm[2]
  713. text1_b = hm[3]
  714. }
  715. var mid_common = hm[4]
  716. return [text1_a, text1_b, text2_a, text2_b, mid_common]
  717. }
  718. /**
  719. * Reduce the number of edits by eliminating semantically trivial equalities.
  720. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  721. */
  722. diff_match_patch.prototype.diff_cleanupSemantic = function (diffs) {
  723. var changes = false
  724. var equalities = [] // Stack of indices where equalities are found.
  725. var equalitiesLength = 0 // Keeping our own length var is faster in JS.
  726. /** @type {?string} */
  727. var lastequality = null
  728. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  729. var pointer = 0 // Index of current position.
  730. // Number of characters that changed prior to the equality.
  731. var length_insertions1 = 0
  732. var length_deletions1 = 0
  733. // Number of characters that changed after the equality.
  734. var length_insertions2 = 0
  735. var length_deletions2 = 0
  736. while (pointer < diffs.length) {
  737. if (diffs[pointer][0] == DIFF_EQUAL) {
  738. // Equality found.
  739. equalities[equalitiesLength++] = pointer
  740. length_insertions1 = length_insertions2
  741. length_deletions1 = length_deletions2
  742. length_insertions2 = 0
  743. length_deletions2 = 0
  744. lastequality = diffs[pointer][1]
  745. } else {
  746. // An insertion or deletion.
  747. if (diffs[pointer][0] == DIFF_INSERT) {
  748. length_insertions2 += diffs[pointer][1].length
  749. } else {
  750. length_deletions2 += diffs[pointer][1].length
  751. }
  752. // Eliminate an equality that is smaller or equal to the edits on both
  753. // sides of it.
  754. if (
  755. lastequality &&
  756. lastequality.length <=
  757. Math.max(length_insertions1, length_deletions1) &&
  758. lastequality.length <= Math.max(length_insertions2, length_deletions2)
  759. ) {
  760. // Duplicate record.
  761. diffs.splice(equalities[equalitiesLength - 1], 0, [
  762. DIFF_DELETE,
  763. lastequality,
  764. ])
  765. // Change second copy to insert.
  766. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT
  767. // Throw away the equality we just deleted.
  768. equalitiesLength--
  769. // Throw away the previous equality (it needs to be reevaluated).
  770. equalitiesLength--
  771. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1
  772. length_insertions1 = 0 // Reset the counters.
  773. length_deletions1 = 0
  774. length_insertions2 = 0
  775. length_deletions2 = 0
  776. lastequality = null
  777. changes = true
  778. }
  779. }
  780. pointer++
  781. }
  782. // Normalize the diff.
  783. if (changes) {
  784. this.diff_cleanupMerge(diffs)
  785. }
  786. this.diff_cleanupSemanticLossless(diffs)
  787. // Find any overlaps between deletions and insertions.
  788. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  789. // -> <del>abc</del>xxx<ins>def</ins>
  790. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  791. // -> <ins>def</ins>xxx<del>abc</del>
  792. // Only extract an overlap if it is as big as the edit ahead or behind it.
  793. pointer = 1
  794. while (pointer < diffs.length) {
  795. if (
  796. diffs[pointer - 1][0] == DIFF_DELETE &&
  797. diffs[pointer][0] == DIFF_INSERT
  798. ) {
  799. var deletion = diffs[pointer - 1][1]
  800. var insertion = diffs[pointer][1]
  801. var overlap_length1 = this.diff_commonOverlap_(deletion, insertion)
  802. var overlap_length2 = this.diff_commonOverlap_(insertion, deletion)
  803. if (overlap_length1 >= overlap_length2) {
  804. if (
  805. overlap_length1 >= deletion.length / 2 ||
  806. overlap_length1 >= insertion.length / 2
  807. ) {
  808. // Overlap found. Insert an equality and trim the surrounding edits.
  809. diffs.splice(pointer, 0, [
  810. DIFF_EQUAL,
  811. insertion.substring(0, overlap_length1),
  812. ])
  813. diffs[pointer - 1][1] = deletion.substring(
  814. 0,
  815. deletion.length - overlap_length1
  816. )
  817. diffs[pointer + 1][1] = insertion.substring(overlap_length1)
  818. pointer++
  819. }
  820. } else {
  821. if (
  822. overlap_length2 >= deletion.length / 2 ||
  823. overlap_length2 >= insertion.length / 2
  824. ) {
  825. // Reverse overlap found.
  826. // Insert an equality and swap and trim the surrounding edits.
  827. diffs.splice(pointer, 0, [
  828. DIFF_EQUAL,
  829. deletion.substring(0, overlap_length2),
  830. ])
  831. diffs[pointer - 1][0] = DIFF_INSERT
  832. diffs[pointer - 1][1] = insertion.substring(
  833. 0,
  834. insertion.length - overlap_length2
  835. )
  836. diffs[pointer + 1][0] = DIFF_DELETE
  837. diffs[pointer + 1][1] = deletion.substring(overlap_length2)
  838. pointer++
  839. }
  840. }
  841. pointer++
  842. }
  843. pointer++
  844. }
  845. }
  846. /**
  847. * Look for single edits surrounded on both sides by equalities
  848. * which can be shifted sideways to align the edit to a word boundary.
  849. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
  850. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  851. */
  852. diff_match_patch.prototype.diff_cleanupSemanticLossless = function (diffs) {
  853. /**
  854. * Given two strings, compute a score representing whether the internal
  855. * boundary falls on logical boundaries.
  856. * Scores range from 6 (best) to 0 (worst).
  857. * Closure, but does not reference any external variables.
  858. * @param {string} one First string.
  859. * @param {string} two Second string.
  860. * @return {number} The score.
  861. * @private
  862. */
  863. function diff_cleanupSemanticScore_(one, two) {
  864. if (!one || !two) {
  865. // Edges are the best.
  866. return 6
  867. }
  868. // Each port of this function behaves slightly differently due to
  869. // subtle differences in each language's definition of things like
  870. // 'whitespace'. Since this function's purpose is largely cosmetic,
  871. // the choice has been made to use each language's native features
  872. // rather than force total conformity.
  873. var char1 = one.charAt(one.length - 1)
  874. var char2 = two.charAt(0)
  875. var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_)
  876. var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_)
  877. var whitespace1 =
  878. nonAlphaNumeric1 && char1.match(diff_match_patch.whitespaceRegex_)
  879. var whitespace2 =
  880. nonAlphaNumeric2 && char2.match(diff_match_patch.whitespaceRegex_)
  881. var lineBreak1 =
  882. whitespace1 && char1.match(diff_match_patch.linebreakRegex_)
  883. var lineBreak2 =
  884. whitespace2 && char2.match(diff_match_patch.linebreakRegex_)
  885. var blankLine1 =
  886. lineBreak1 && one.match(diff_match_patch.blanklineEndRegex_)
  887. var blankLine2 =
  888. lineBreak2 && two.match(diff_match_patch.blanklineStartRegex_)
  889. if (blankLine1 || blankLine2) {
  890. // Five points for blank lines.
  891. return 5
  892. } else if (lineBreak1 || lineBreak2) {
  893. // Four points for line breaks.
  894. return 4
  895. } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
  896. // Three points for end of sentences.
  897. return 3
  898. } else if (whitespace1 || whitespace2) {
  899. // Two points for whitespace.
  900. return 2
  901. } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
  902. // One point for non-alphanumeric.
  903. return 1
  904. }
  905. return 0
  906. }
  907. var pointer = 1
  908. // Intentionally ignore the first and last element (don't need checking).
  909. while (pointer < diffs.length - 1) {
  910. if (
  911. diffs[pointer - 1][0] == DIFF_EQUAL &&
  912. diffs[pointer + 1][0] == DIFF_EQUAL
  913. ) {
  914. // This is a single edit surrounded by equalities.
  915. var equality1 = diffs[pointer - 1][1]
  916. var edit = diffs[pointer][1]
  917. var equality2 = diffs[pointer + 1][1]
  918. // First, shift the edit as far left as possible.
  919. var commonOffset = this.diff_commonSuffix(equality1, edit)
  920. if (commonOffset) {
  921. var commonString = edit.substring(edit.length - commonOffset)
  922. equality1 = equality1.substring(0, equality1.length - commonOffset)
  923. edit = commonString + edit.substring(0, edit.length - commonOffset)
  924. equality2 = commonString + equality2
  925. }
  926. // Second, step character by character right, looking for the best fit.
  927. var bestEquality1 = equality1
  928. var bestEdit = edit
  929. var bestEquality2 = equality2
  930. var bestScore =
  931. diff_cleanupSemanticScore_(equality1, edit) +
  932. diff_cleanupSemanticScore_(edit, equality2)
  933. while (edit.charAt(0) === equality2.charAt(0)) {
  934. equality1 += edit.charAt(0)
  935. edit = edit.substring(1) + equality2.charAt(0)
  936. equality2 = equality2.substring(1)
  937. var score =
  938. diff_cleanupSemanticScore_(equality1, edit) +
  939. diff_cleanupSemanticScore_(edit, equality2)
  940. // The >= encourages trailing rather than leading whitespace on edits.
  941. if (score >= bestScore) {
  942. bestScore = score
  943. bestEquality1 = equality1
  944. bestEdit = edit
  945. bestEquality2 = equality2
  946. }
  947. }
  948. if (diffs[pointer - 1][1] != bestEquality1) {
  949. // We have an improvement, save it back to the diff.
  950. if (bestEquality1) {
  951. diffs[pointer - 1][1] = bestEquality1
  952. } else {
  953. diffs.splice(pointer - 1, 1)
  954. pointer--
  955. }
  956. diffs[pointer][1] = bestEdit
  957. if (bestEquality2) {
  958. diffs[pointer + 1][1] = bestEquality2
  959. } else {
  960. diffs.splice(pointer + 1, 1)
  961. pointer--
  962. }
  963. }
  964. }
  965. pointer++
  966. }
  967. }
  968. // Define some regex patterns for matching boundaries.
  969. diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/
  970. diff_match_patch.whitespaceRegex_ = /\s/
  971. diff_match_patch.linebreakRegex_ = /[\r\n]/
  972. diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/
  973. diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/
  974. /**
  975. * Reduce the number of edits by eliminating operationally trivial equalities.
  976. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  977. */
  978. diff_match_patch.prototype.diff_cleanupEfficiency = function (diffs) {
  979. var changes = false
  980. var equalities = [] // Stack of indices where equalities are found.
  981. var equalitiesLength = 0 // Keeping our own length var is faster in JS.
  982. /** @type {?string} */
  983. var lastequality = null
  984. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  985. var pointer = 0 // Index of current position.
  986. // Is there an insertion operation before the last equality.
  987. var pre_ins = false
  988. // Is there a deletion operation before the last equality.
  989. var pre_del = false
  990. // Is there an insertion operation after the last equality.
  991. var post_ins = false
  992. // Is there a deletion operation after the last equality.
  993. var post_del = false
  994. while (pointer < diffs.length) {
  995. if (diffs[pointer][0] == DIFF_EQUAL) {
  996. // Equality found.
  997. if (
  998. diffs[pointer][1].length < this.Diff_EditCost &&
  999. (post_ins || post_del)
  1000. ) {
  1001. // Candidate found.
  1002. equalities[equalitiesLength++] = pointer
  1003. pre_ins = post_ins
  1004. pre_del = post_del
  1005. lastequality = diffs[pointer][1]
  1006. } else {
  1007. // Not a candidate, and can never become one.
  1008. equalitiesLength = 0
  1009. lastequality = null
  1010. }
  1011. post_ins = post_del = false
  1012. } else {
  1013. // An insertion or deletion.
  1014. if (diffs[pointer][0] == DIFF_DELETE) {
  1015. post_del = true
  1016. } else {
  1017. post_ins = true
  1018. }
  1019. /*
  1020. * Five types to be split:
  1021. * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  1022. * <ins>A</ins>X<ins>C</ins><del>D</del>
  1023. * <ins>A</ins><del>B</del>X<ins>C</ins>
  1024. * <ins>A</del>X<ins>C</ins><del>D</del>
  1025. * <ins>A</ins><del>B</del>X<del>C</del>
  1026. */
  1027. if (
  1028. lastequality &&
  1029. ((pre_ins && pre_del && post_ins && post_del) ||
  1030. (lastequality.length < this.Diff_EditCost / 2 &&
  1031. pre_ins + pre_del + post_ins + post_del == 3))
  1032. ) {
  1033. // Duplicate record.
  1034. diffs.splice(equalities[equalitiesLength - 1], 0, [
  1035. DIFF_DELETE,
  1036. lastequality,
  1037. ])
  1038. // Change second copy to insert.
  1039. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT
  1040. equalitiesLength-- // Throw away the equality we just deleted;
  1041. lastequality = null
  1042. if (pre_ins && pre_del) {
  1043. // No changes made which could affect previous entry, keep going.
  1044. post_ins = post_del = true
  1045. equalitiesLength = 0
  1046. } else {
  1047. equalitiesLength-- // Throw away the previous equality.
  1048. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1
  1049. post_ins = post_del = false
  1050. }
  1051. changes = true
  1052. }
  1053. }
  1054. pointer++
  1055. }
  1056. if (changes) {
  1057. this.diff_cleanupMerge(diffs)
  1058. }
  1059. }
  1060. /**
  1061. * Reorder and merge like edit sections. Merge equalities.
  1062. * Any edit section can move as long as it doesn't cross an equality.
  1063. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1064. */
  1065. diff_match_patch.prototype.diff_cleanupMerge = function (diffs) {
  1066. diffs.push([DIFF_EQUAL, '']) // Add a dummy entry at the end.
  1067. var pointer = 0
  1068. var count_delete = 0
  1069. var count_insert = 0
  1070. var text_delete = ''
  1071. var text_insert = ''
  1072. var commonlength
  1073. while (pointer < diffs.length) {
  1074. switch (diffs[pointer][0]) {
  1075. case DIFF_INSERT:
  1076. count_insert++
  1077. text_insert += diffs[pointer][1]
  1078. pointer++
  1079. break
  1080. case DIFF_DELETE:
  1081. count_delete++
  1082. text_delete += diffs[pointer][1]
  1083. pointer++
  1084. break
  1085. case DIFF_EQUAL:
  1086. // Upon reaching an equality, check for prior redundancies.
  1087. if (count_delete + count_insert > 1) {
  1088. if (count_delete !== 0 && count_insert !== 0) {
  1089. // Factor out any common prefixies.
  1090. commonlength = this.diff_commonPrefix(text_insert, text_delete)
  1091. if (commonlength !== 0) {
  1092. if (
  1093. pointer - count_delete - count_insert > 0 &&
  1094. diffs[pointer - count_delete - count_insert - 1][0] ==
  1095. DIFF_EQUAL
  1096. ) {
  1097. diffs[pointer - count_delete - count_insert - 1][1] +=
  1098. text_insert.substring(0, commonlength)
  1099. } else {
  1100. diffs.splice(0, 0, [
  1101. DIFF_EQUAL,
  1102. text_insert.substring(0, commonlength),
  1103. ])
  1104. pointer++
  1105. }
  1106. text_insert = text_insert.substring(commonlength)
  1107. text_delete = text_delete.substring(commonlength)
  1108. }
  1109. // Factor out any common suffixies.
  1110. commonlength = this.diff_commonSuffix(text_insert, text_delete)
  1111. if (commonlength !== 0) {
  1112. diffs[pointer][1] =
  1113. text_insert.substring(text_insert.length - commonlength) +
  1114. diffs[pointer][1]
  1115. text_insert = text_insert.substring(
  1116. 0,
  1117. text_insert.length - commonlength
  1118. )
  1119. text_delete = text_delete.substring(
  1120. 0,
  1121. text_delete.length - commonlength
  1122. )
  1123. }
  1124. }
  1125. // Delete the offending records and add the merged ones.
  1126. if (count_delete === 0) {
  1127. diffs.splice(pointer - count_insert, count_delete + count_insert, [
  1128. DIFF_INSERT,
  1129. text_insert,
  1130. ])
  1131. } else if (count_insert === 0) {
  1132. diffs.splice(pointer - count_delete, count_delete + count_insert, [
  1133. DIFF_DELETE,
  1134. text_delete,
  1135. ])
  1136. } else {
  1137. diffs.splice(
  1138. pointer - count_delete - count_insert,
  1139. count_delete + count_insert,
  1140. [DIFF_DELETE, text_delete],
  1141. [DIFF_INSERT, text_insert]
  1142. )
  1143. }
  1144. pointer =
  1145. pointer -
  1146. count_delete -
  1147. count_insert +
  1148. (count_delete ? 1 : 0) +
  1149. (count_insert ? 1 : 0) +
  1150. 1
  1151. } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {
  1152. // Merge this equality with the previous one.
  1153. diffs[pointer - 1][1] += diffs[pointer][1]
  1154. diffs.splice(pointer, 1)
  1155. } else {
  1156. pointer++
  1157. }
  1158. count_insert = 0
  1159. count_delete = 0
  1160. text_delete = ''
  1161. text_insert = ''
  1162. break
  1163. }
  1164. }
  1165. if (diffs[diffs.length - 1][1] === '') {
  1166. diffs.pop() // Remove the dummy entry at the end.
  1167. }
  1168. // Second pass: look for single edits surrounded on both sides by equalities
  1169. // which can be shifted sideways to eliminate an equality.
  1170. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  1171. var changes = false
  1172. pointer = 1
  1173. // Intentionally ignore the first and last element (don't need checking).
  1174. while (pointer < diffs.length - 1) {
  1175. if (
  1176. diffs[pointer - 1][0] == DIFF_EQUAL &&
  1177. diffs[pointer + 1][0] == DIFF_EQUAL
  1178. ) {
  1179. // This is a single edit surrounded by equalities.
  1180. if (
  1181. diffs[pointer][1].substring(
  1182. diffs[pointer][1].length - diffs[pointer - 1][1].length
  1183. ) == diffs[pointer - 1][1]
  1184. ) {
  1185. // Shift the edit over the previous equality.
  1186. diffs[pointer][1] =
  1187. diffs[pointer - 1][1] +
  1188. diffs[pointer][1].substring(
  1189. 0,
  1190. diffs[pointer][1].length - diffs[pointer - 1][1].length
  1191. )
  1192. diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]
  1193. diffs.splice(pointer - 1, 1)
  1194. changes = true
  1195. } else if (
  1196. diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
  1197. diffs[pointer + 1][1]
  1198. ) {
  1199. // Shift the edit over the next equality.
  1200. diffs[pointer - 1][1] += diffs[pointer + 1][1]
  1201. diffs[pointer][1] =
  1202. diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
  1203. diffs[pointer + 1][1]
  1204. diffs.splice(pointer + 1, 1)
  1205. changes = true
  1206. }
  1207. }
  1208. pointer++
  1209. }
  1210. // If shifts were made, the diff needs reordering and another shift sweep.
  1211. if (changes) {
  1212. this.diff_cleanupMerge(diffs)
  1213. }
  1214. }
  1215. /**
  1216. * loc is a location in text1, compute and return the equivalent location in
  1217. * text2.
  1218. * e.g. 'The cat' vs 'The big cat', 1->1, 5->8
  1219. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1220. * @param {number} loc Location within text1.
  1221. * @return {number} Location within text2.
  1222. */
  1223. diff_match_patch.prototype.diff_xIndex = function (diffs, loc) {
  1224. var chars1 = 0
  1225. var chars2 = 0
  1226. var last_chars1 = 0
  1227. var last_chars2 = 0
  1228. var x
  1229. for (x = 0; x < diffs.length; x++) {
  1230. if (diffs[x][0] !== DIFF_INSERT) {
  1231. // Equality or deletion.
  1232. chars1 += diffs[x][1].length
  1233. }
  1234. if (diffs[x][0] !== DIFF_DELETE) {
  1235. // Equality or insertion.
  1236. chars2 += diffs[x][1].length
  1237. }
  1238. if (chars1 > loc) {
  1239. // Overshot the location.
  1240. break
  1241. }
  1242. last_chars1 = chars1
  1243. last_chars2 = chars2
  1244. }
  1245. // Was the location was deleted?
  1246. if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {
  1247. return last_chars2
  1248. }
  1249. // Add the remaining character length.
  1250. return last_chars2 + (loc - last_chars1)
  1251. }
  1252. /**
  1253. * Convert a diff array into a pretty HTML report.
  1254. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1255. * @return {string} HTML representation.
  1256. */
  1257. diff_match_patch.prototype.diff_prettyHtml = function (diffs) {
  1258. var html = []
  1259. var pattern_amp = /&/g
  1260. var pattern_lt = /</g
  1261. var pattern_gt = />/g
  1262. var pattern_para = /\n/g
  1263. for (var x = 0; x < diffs.length; x++) {
  1264. var op = diffs[x][0] // Operation (insert, delete, equal)
  1265. var data = diffs[x][1] // Text of change.
  1266. var text = data
  1267. .replace(pattern_amp, '&amp;')
  1268. .replace(pattern_lt, '&lt;')
  1269. .replace(pattern_gt, '&gt;')
  1270. .replace(pattern_para, '&para;<br>')
  1271. switch (op) {
  1272. case DIFF_INSERT:
  1273. html[x] = '<ins style="background:#e6ffe6;">' + text + '</ins>'
  1274. break
  1275. case DIFF_DELETE:
  1276. html[x] = '<del style="background:#ffe6e6;">' + text + '</del>'
  1277. break
  1278. case DIFF_EQUAL:
  1279. html[x] = '<span>' + text + '</span>'
  1280. break
  1281. }
  1282. }
  1283. return html.join('')
  1284. }
  1285. /**
  1286. * Compute and return the source text (all equalities and deletions).
  1287. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1288. * @return {string} Source text.
  1289. */
  1290. diff_match_patch.prototype.diff_text1 = function (diffs) {
  1291. var text = []
  1292. for (var x = 0; x < diffs.length; x++) {
  1293. if (diffs[x][0] !== DIFF_INSERT) {
  1294. text[x] = diffs[x][1]
  1295. }
  1296. }
  1297. return text.join('')
  1298. }
  1299. /**
  1300. * Compute and return the destination text (all equalities and insertions).
  1301. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1302. * @return {string} Destination text.
  1303. */
  1304. diff_match_patch.prototype.diff_text2 = function (diffs) {
  1305. var text = []
  1306. for (var x = 0; x < diffs.length; x++) {
  1307. if (diffs[x][0] !== DIFF_DELETE) {
  1308. text[x] = diffs[x][1]
  1309. }
  1310. }
  1311. return text.join('')
  1312. }
  1313. /**
  1314. * Compute the Levenshtein distance; the number of inserted, deleted or
  1315. * substituted characters.
  1316. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1317. * @return {number} Number of changes.
  1318. */
  1319. diff_match_patch.prototype.diff_levenshtein = function (diffs) {
  1320. var levenshtein = 0
  1321. var insertions = 0
  1322. var deletions = 0
  1323. for (var x = 0; x < diffs.length; x++) {
  1324. var op = diffs[x][0]
  1325. var data = diffs[x][1]
  1326. switch (op) {
  1327. case DIFF_INSERT:
  1328. insertions += data.length
  1329. break
  1330. case DIFF_DELETE:
  1331. deletions += data.length
  1332. break
  1333. case DIFF_EQUAL:
  1334. // A deletion and an insertion is one substitution.
  1335. levenshtein += Math.max(insertions, deletions)
  1336. insertions = 0
  1337. deletions = 0
  1338. break
  1339. }
  1340. }
  1341. levenshtein += Math.max(insertions, deletions)
  1342. return levenshtein
  1343. }
  1344. /**
  1345. * Crush the diff into an encoded string which describes the operations
  1346. * required to transform text1 into text2.
  1347. * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
  1348. * Operations are tab-separated. Inserted text is escaped using %xx notation.
  1349. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
  1350. * @return {string} Delta text.
  1351. */
  1352. diff_match_patch.prototype.diff_toDelta = function (diffs) {
  1353. var text = []
  1354. for (var x = 0; x < diffs.length; x++) {
  1355. switch (diffs[x][0]) {
  1356. case DIFF_INSERT:
  1357. text[x] = '+' + encodeURI(diffs[x][1])
  1358. break
  1359. case DIFF_DELETE:
  1360. text[x] = '-' + diffs[x][1].length
  1361. break
  1362. case DIFF_EQUAL:
  1363. text[x] = '=' + diffs[x][1].length
  1364. break
  1365. }
  1366. }
  1367. return text.join('\t').replace(/%20/g, ' ')
  1368. }
  1369. /**
  1370. * Given the original text1, and an encoded string which describes the
  1371. * operations required to transform text1 into text2, compute the full diff.
  1372. * @param {string} text1 Source string for the diff.
  1373. * @param {string} delta Delta text.
  1374. * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
  1375. * @throws {!Error} If invalid input.
  1376. */
  1377. diff_match_patch.prototype.diff_fromDelta = function (text1, delta) {
  1378. var diffs = []
  1379. var diffsLength = 0 // Keeping our own length var is faster in JS.
  1380. var pointer = 0 // Cursor in text1
  1381. var tokens = delta.split(/\t/g)
  1382. for (var x = 0; x < tokens.length; x++) {
  1383. // Each token begins with a one character parameter which specifies the
  1384. // operation of this token (delete, insert, equality).
  1385. var param = tokens[x].substring(1)
  1386. switch (tokens[x].charAt(0)) {
  1387. case '+':
  1388. try {
  1389. diffs[diffsLength++] = [DIFF_INSERT, decodeURI(param)]
  1390. } catch (ex) {
  1391. // Malformed URI sequence.
  1392. throw new Error('Illegal escape in diff_fromDelta: ' + param)
  1393. }
  1394. break
  1395. case '-':
  1396. // Fall through.
  1397. case '=':
  1398. var n = parseInt(param, 10)
  1399. if (isNaN(n) || n < 0) {
  1400. throw new Error('Invalid number in diff_fromDelta: ' + param)
  1401. }
  1402. var text = text1.substring(pointer, (pointer += n))
  1403. if (tokens[x].charAt(0) == '=') {
  1404. diffs[diffsLength++] = [DIFF_EQUAL, text]
  1405. } else {
  1406. diffs[diffsLength++] = [DIFF_DELETE, text]
  1407. }
  1408. break
  1409. default:
  1410. // Blank tokens are ok (from a trailing \t).
  1411. // Anything else is an error.
  1412. if (tokens[x]) {
  1413. throw new Error(
  1414. 'Invalid diff operation in diff_fromDelta: ' + tokens[x]
  1415. )
  1416. }
  1417. }
  1418. }
  1419. if (pointer != text1.length) {
  1420. throw new Error(
  1421. 'Delta length (' +
  1422. pointer +
  1423. ') does not equal source text length (' +
  1424. text1.length +
  1425. ').'
  1426. )
  1427. }
  1428. return diffs
  1429. }
  1430. // MATCH FUNCTIONS
  1431. /**
  1432. * Locate the best instance of 'pattern' in 'text' near 'loc'.
  1433. * @param {string} text The text to search.
  1434. * @param {string} pattern The pattern to search for.
  1435. * @param {number} loc The location to search around.
  1436. * @return {number} Best match index or -1.
  1437. */
  1438. diff_match_patch.prototype.match_main = function (text, pattern, loc) {
  1439. // Check for null inputs.
  1440. if (text == null || pattern == null || loc == null) {
  1441. throw new Error('Null input. (match_main)')
  1442. }
  1443. loc = Math.max(0, Math.min(loc, text.length))
  1444. if (text == pattern) {
  1445. // Shortcut (potentially not guaranteed by the algorithm)
  1446. return 0
  1447. } else if (!text.length) {
  1448. // Nothing to match.
  1449. return -1
  1450. } else if (text.substring(loc, loc + pattern.length) == pattern) {
  1451. // Perfect match at the perfect spot! (Includes case of null pattern)
  1452. return loc
  1453. } else {
  1454. // Do a fuzzy compare.
  1455. return this.match_bitap_(text, pattern, loc)
  1456. }
  1457. }
  1458. /**
  1459. * Locate the best instance of 'pattern' in 'text' near 'loc' using the
  1460. * Bitap algorithm.
  1461. * @param {string} text The text to search.
  1462. * @param {string} pattern The pattern to search for.
  1463. * @param {number} loc The location to search around.
  1464. * @return {number} Best match index or -1.
  1465. * @private
  1466. */
  1467. diff_match_patch.prototype.match_bitap_ = function (text, pattern, loc) {
  1468. if (pattern.length > this.Match_MaxBits) {
  1469. throw new Error('Pattern too long for this browser.')
  1470. }
  1471. // Initialise the alphabet.
  1472. var s = this.match_alphabet_(pattern)
  1473. var dmp = this // 'this' becomes 'window' in a closure.
  1474. /**
  1475. * Compute and return the score for a match with e errors and x location.
  1476. * Accesses loc and pattern through being a closure.
  1477. * @param {number} e Number of errors in match.
  1478. * @param {number} x Location of match.
  1479. * @return {number} Overall score for match (0.0 = good, 1.0 = bad).
  1480. * @private
  1481. */
  1482. function match_bitapScore_(e, x) {
  1483. var accuracy = e / pattern.length
  1484. var proximity = Math.abs(loc - x)
  1485. if (!dmp.Match_Distance) {
  1486. // Dodge divide by zero error.
  1487. return proximity ? 1.0 : accuracy
  1488. }
  1489. return accuracy + proximity / dmp.Match_Distance
  1490. }
  1491. // Highest score beyond which we give up.
  1492. var score_threshold = this.Match_Threshold
  1493. // Is there a nearby exact match? (speedup)
  1494. var best_loc = text.indexOf(pattern, loc)
  1495. if (best_loc != -1) {
  1496. score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold)
  1497. // What about in the other direction? (speedup)
  1498. best_loc = text.lastIndexOf(pattern, loc + pattern.length)
  1499. if (best_loc != -1) {
  1500. score_threshold = Math.min(
  1501. match_bitapScore_(0, best_loc),
  1502. score_threshold
  1503. )
  1504. }
  1505. }
  1506. // Initialise the bit arrays.
  1507. var matchmask = 1 << (pattern.length - 1)
  1508. best_loc = -1
  1509. var bin_min, bin_mid
  1510. var bin_max = pattern.length + text.length
  1511. var last_rd
  1512. for (var d = 0; d < pattern.length; d++) {
  1513. // Scan for the best match; each iteration allows for one more error.
  1514. // Run a binary search to determine how far from 'loc' we can stray at this
  1515. // error level.
  1516. bin_min = 0
  1517. bin_mid = bin_max
  1518. while (bin_min < bin_mid) {
  1519. if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {
  1520. bin_min = bin_mid
  1521. } else {
  1522. bin_max = bin_mid
  1523. }
  1524. bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min)
  1525. }
  1526. // Use the result from this iteration as the maximum for the next.
  1527. bin_max = bin_mid
  1528. var start = Math.max(1, loc - bin_mid + 1)
  1529. var finish = Math.min(loc + bin_mid, text.length) + pattern.length
  1530. var rd = Array(finish + 2)
  1531. rd[finish + 1] = (1 << d) - 1
  1532. for (var j = finish; j >= start; j--) {
  1533. // The alphabet (s) is a sparse hash, so the following line generates
  1534. // warnings.
  1535. var charMatch = s[text.charAt(j - 1)]
  1536. if (d === 0) {
  1537. // First pass: exact match.
  1538. rd[j] = ((rd[j + 1] << 1) | 1) & charMatch
  1539. } else {
  1540. // Subsequent passes: fuzzy match.
  1541. rd[j] =
  1542. (((rd[j + 1] << 1) | 1) & charMatch) |
  1543. (((last_rd[j + 1] | last_rd[j]) << 1) | 1) |
  1544. last_rd[j + 1]
  1545. }
  1546. if (rd[j] & matchmask) {
  1547. var score = match_bitapScore_(d, j - 1)
  1548. // This match will almost certainly be better than any existing match.
  1549. // But check anyway.
  1550. if (score <= score_threshold) {
  1551. // Told you so.
  1552. score_threshold = score
  1553. best_loc = j - 1
  1554. if (best_loc > loc) {
  1555. // When passing loc, don't exceed our current distance from loc.
  1556. start = Math.max(1, 2 * loc - best_loc)
  1557. } else {
  1558. // Already passed loc, downhill from here on in.
  1559. break
  1560. }
  1561. }
  1562. }
  1563. }
  1564. // No hope for a (better) match at greater error levels.
  1565. if (match_bitapScore_(d + 1, loc) > score_threshold) {
  1566. break
  1567. }
  1568. last_rd = rd
  1569. }
  1570. return best_loc
  1571. }
  1572. /**
  1573. * Initialise the alphabet for the Bitap algorithm.
  1574. * @param {string} pattern The text to encode.
  1575. * @return {!Object} Hash of character locations.
  1576. * @private
  1577. */
  1578. diff_match_patch.prototype.match_alphabet_ = function (pattern) {
  1579. var s = {}
  1580. for (var i = 0; i < pattern.length; i++) {
  1581. s[pattern.charAt(i)] = 0
  1582. }
  1583. for (var i = 0; i < pattern.length; i++) {
  1584. s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1)
  1585. }
  1586. return s
  1587. }
  1588. // PATCH FUNCTIONS
  1589. /**
  1590. * Increase the context until it is unique,
  1591. * but don't let the pattern expand beyond Match_MaxBits.
  1592. * @param {!diff_match_patch.patch_obj} patch The patch to grow.
  1593. * @param {string} text Source text.
  1594. * @private
  1595. */
  1596. diff_match_patch.prototype.patch_addContext_ = function (patch, text) {
  1597. if (text.length == 0) {
  1598. return
  1599. }
  1600. var pattern = text.substring(patch.start2, patch.start2 + patch.length1)
  1601. var padding = 0
  1602. // Look for the first and last matches of pattern in text. If two different
  1603. // matches are found, increase the pattern length.
  1604. while (
  1605. text.indexOf(pattern) != text.lastIndexOf(pattern) &&
  1606. pattern.length < this.Match_MaxBits - this.Patch_Margin - this.Patch_Margin
  1607. ) {
  1608. padding += this.Patch_Margin
  1609. pattern = text.substring(
  1610. patch.start2 - padding,
  1611. patch.start2 + patch.length1 + padding
  1612. )
  1613. }
  1614. // Add one chunk for good luck.
  1615. padding += this.Patch_Margin
  1616. // Add the prefix.
  1617. var prefix = text.substring(patch.start2 - padding, patch.start2)
  1618. if (prefix) {
  1619. patch.diffs.unshift([DIFF_EQUAL, prefix])
  1620. }
  1621. // Add the suffix.
  1622. var suffix = text.substring(
  1623. patch.start2 + patch.length1,
  1624. patch.start2 + patch.length1 + padding
  1625. )
  1626. if (suffix) {
  1627. patch.diffs.push([DIFF_EQUAL, suffix])
  1628. }
  1629. // Roll back the start points.
  1630. patch.start1 -= prefix.length
  1631. patch.start2 -= prefix.length
  1632. // Extend the lengths.
  1633. patch.length1 += prefix.length + suffix.length
  1634. patch.length2 += prefix.length + suffix.length
  1635. }
  1636. /**
  1637. * Compute a list of patches to turn text1 into text2.
  1638. * Use diffs if provided, otherwise compute it ourselves.
  1639. * There are four ways to call this function, depending on what data is
  1640. * available to the caller:
  1641. * Method 1:
  1642. * a = text1, b = text2
  1643. * Method 2:
  1644. * a = diffs
  1645. * Method 3 (optimal):
  1646. * a = text1, b = diffs
  1647. * Method 4 (deprecated, use method 3):
  1648. * a = text1, b = text2, c = diffs
  1649. *
  1650. * @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or
  1651. * Array of diff tuples for text1 to text2 (method 2).
  1652. * @param {string|!Array.<!diff_match_patch.Diff>} opt_b text2 (methods 1,4) or
  1653. * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
  1654. * @param {string|!Array.<!diff_match_patch.Diff>} opt_c Array of diff tuples
  1655. * for text1 to text2 (method 4) or undefined (methods 1,2,3).
  1656. * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
  1657. */
  1658. diff_match_patch.prototype.patch_make = function (a, opt_b, opt_c) {
  1659. var text1, diffs
  1660. if (
  1661. typeof a === 'string' &&
  1662. typeof opt_b === 'string' &&
  1663. typeof opt_c === 'undefined'
  1664. ) {
  1665. // Method 1: text1, text2
  1666. // Compute diffs from text1 and text2.
  1667. text1 = /** @type {string} */ (a)
  1668. diffs = this.diff_main(text1, /** @type {string} */ (opt_b), true)
  1669. if (diffs.length > 2) {
  1670. this.diff_cleanupSemantic(diffs)
  1671. this.diff_cleanupEfficiency(diffs)
  1672. }
  1673. } else if (
  1674. a &&
  1675. typeof a === 'object' &&
  1676. typeof opt_b === 'undefined' &&
  1677. typeof opt_c === 'undefined'
  1678. ) {
  1679. // Method 2: diffs
  1680. // Compute text1 from diffs.
  1681. diffs = /** @type {!Array.<!diff_match_patch.Diff>} */ (a)
  1682. text1 = this.diff_text1(diffs)
  1683. } else if (
  1684. typeof a === 'string' &&
  1685. opt_b &&
  1686. typeof opt_b === 'object' &&
  1687. typeof opt_c === 'undefined'
  1688. ) {
  1689. // Method 3: text1, diffs
  1690. text1 = /** @type {string} */ (a)
  1691. diffs = /** @type {!Array.<!diff_match_patch.Diff>} */ (opt_b)
  1692. } else if (
  1693. typeof a === 'string' &&
  1694. typeof opt_b === 'string' &&
  1695. opt_c &&
  1696. typeof opt_c === 'object'
  1697. ) {
  1698. // Method 4: text1, text2, diffs
  1699. // text2 is not used.
  1700. text1 = /** @type {string} */ (a)
  1701. diffs = /** @type {!Array.<!diff_match_patch.Diff>} */ (opt_c)
  1702. } else {
  1703. throw new Error('Unknown call format to patch_make.')
  1704. }
  1705. if (diffs.length === 0) {
  1706. return [] // Get rid of the null case.
  1707. }
  1708. var patches = []
  1709. var patch = new diff_match_patch.patch_obj()
  1710. var patchDiffLength = 0 // Keeping our own length var is faster in JS.
  1711. var char_count1 = 0 // Number of characters into the text1 string.
  1712. var char_count2 = 0 // Number of characters into the text2 string.
  1713. // Start with text1 (prepatch_text) and apply the diffs until we arrive at
  1714. // text2 (postpatch_text). We recreate the patches one by one to determine
  1715. // context info.
  1716. var prepatch_text = text1
  1717. var postpatch_text = text1
  1718. for (var x = 0; x < diffs.length; x++) {
  1719. var diff_type = diffs[x][0]
  1720. var diff_text = diffs[x][1]
  1721. if (!patchDiffLength && diff_type !== DIFF_EQUAL) {
  1722. // A new patch starts here.
  1723. patch.start1 = char_count1
  1724. patch.start2 = char_count2
  1725. }
  1726. switch (diff_type) {
  1727. case DIFF_INSERT:
  1728. patch.diffs[patchDiffLength++] = diffs[x]
  1729. patch.length2 += diff_text.length
  1730. postpatch_text =
  1731. postpatch_text.substring(0, char_count2) +
  1732. diff_text +
  1733. postpatch_text.substring(char_count2)
  1734. break
  1735. case DIFF_DELETE:
  1736. patch.length1 += diff_text.length
  1737. patch.diffs[patchDiffLength++] = diffs[x]
  1738. postpatch_text =
  1739. postpatch_text.substring(0, char_count2) +
  1740. postpatch_text.substring(char_count2 + diff_text.length)
  1741. break
  1742. case DIFF_EQUAL:
  1743. if (
  1744. diff_text.length <= 2 * this.Patch_Margin &&
  1745. patchDiffLength &&
  1746. diffs.length != x + 1
  1747. ) {
  1748. // Small equality inside a patch.
  1749. patch.diffs[patchDiffLength++] = diffs[x]
  1750. patch.length1 += diff_text.length
  1751. patch.length2 += diff_text.length
  1752. } else if (diff_text.length >= 2 * this.Patch_Margin) {
  1753. // Time for a new patch.
  1754. if (patchDiffLength) {
  1755. this.patch_addContext_(patch, prepatch_text)
  1756. patches.push(patch)
  1757. patch = new diff_match_patch.patch_obj()
  1758. patchDiffLength = 0
  1759. // Unlike Unidiff, our patch lists have a rolling context.
  1760. // http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
  1761. // Update prepatch text & pos to reflect the application of the
  1762. // just completed patch.
  1763. prepatch_text = postpatch_text
  1764. char_count1 = char_count2
  1765. }
  1766. }
  1767. break
  1768. }
  1769. // Update the current character count.
  1770. if (diff_type !== DIFF_INSERT) {
  1771. char_count1 += diff_text.length
  1772. }
  1773. if (diff_type !== DIFF_DELETE) {
  1774. char_count2 += diff_text.length
  1775. }
  1776. }
  1777. // Pick up the leftover patch if not empty.
  1778. if (patchDiffLength) {
  1779. this.patch_addContext_(patch, prepatch_text)
  1780. patches.push(patch)
  1781. }
  1782. return patches
  1783. }
  1784. /**
  1785. * Given an array of patches, return another array that is identical.
  1786. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1787. * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
  1788. */
  1789. diff_match_patch.prototype.patch_deepCopy = function (patches) {
  1790. // Making deep copies is hard in JavaScript.
  1791. var patchesCopy = []
  1792. for (var x = 0; x < patches.length; x++) {
  1793. var patch = patches[x]
  1794. var patchCopy = new diff_match_patch.patch_obj()
  1795. patchCopy.diffs = []
  1796. for (var y = 0; y < patch.diffs.length; y++) {
  1797. patchCopy.diffs[y] = patch.diffs[y].slice()
  1798. }
  1799. patchCopy.start1 = patch.start1
  1800. patchCopy.start2 = patch.start2
  1801. patchCopy.length1 = patch.length1
  1802. patchCopy.length2 = patch.length2
  1803. patchesCopy[x] = patchCopy
  1804. }
  1805. return patchesCopy
  1806. }
  1807. /**
  1808. * Merge a set of patches onto the text. Return a patched text, as well
  1809. * as a list of true/false values indicating which patches were applied.
  1810. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1811. * @param {string} text Old text.
  1812. * @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the
  1813. * new text and an array of boolean values.
  1814. */
  1815. diff_match_patch.prototype.patch_apply = function (patches, text) {
  1816. if (patches.length == 0) {
  1817. return [text, []]
  1818. }
  1819. // Deep copy the patches so that no changes are made to originals.
  1820. patches = this.patch_deepCopy(patches)
  1821. var nullPadding = this.patch_addPadding(patches)
  1822. text = nullPadding + text + nullPadding
  1823. this.patch_splitMax(patches)
  1824. // delta keeps track of the offset between the expected and actual location
  1825. // of the previous patch. If there are patches expected at positions 10 and
  1826. // 20, but the first patch was found at 12, delta is 2 and the second patch
  1827. // has an effective expected position of 22.
  1828. var delta = 0
  1829. var results = []
  1830. for (var x = 0; x < patches.length; x++) {
  1831. var expected_loc = patches[x].start2 + delta
  1832. var text1 = this.diff_text1(patches[x].diffs)
  1833. var start_loc
  1834. var end_loc = -1
  1835. if (text1.length > this.Match_MaxBits) {
  1836. // patch_splitMax will only provide an oversized pattern in the case of
  1837. // a monster delete.
  1838. start_loc = this.match_main(
  1839. text,
  1840. text1.substring(0, this.Match_MaxBits),
  1841. expected_loc
  1842. )
  1843. if (start_loc != -1) {
  1844. end_loc = this.match_main(
  1845. text,
  1846. text1.substring(text1.length - this.Match_MaxBits),
  1847. expected_loc + text1.length - this.Match_MaxBits
  1848. )
  1849. if (end_loc == -1 || start_loc >= end_loc) {
  1850. // Can't find valid trailing context. Drop this patch.
  1851. start_loc = -1
  1852. }
  1853. }
  1854. } else {
  1855. start_loc = this.match_main(text, text1, expected_loc)
  1856. }
  1857. if (start_loc == -1) {
  1858. // No match found. :(
  1859. results[x] = false
  1860. // Subtract the delta for this failed patch from subsequent patches.
  1861. delta -= patches[x].length2 - patches[x].length1
  1862. } else {
  1863. // Found a match. :)
  1864. results[x] = true
  1865. delta = start_loc - expected_loc
  1866. var text2
  1867. if (end_loc == -1) {
  1868. text2 = text.substring(start_loc, start_loc + text1.length)
  1869. } else {
  1870. text2 = text.substring(start_loc, end_loc + this.Match_MaxBits)
  1871. }
  1872. if (text1 == text2) {
  1873. // Perfect match, just shove the replacement text in.
  1874. text =
  1875. text.substring(0, start_loc) +
  1876. this.diff_text2(patches[x].diffs) +
  1877. text.substring(start_loc + text1.length)
  1878. } else {
  1879. // Imperfect match. Run a diff to get a framework of equivalent
  1880. // indices.
  1881. var diffs = this.diff_main(text1, text2, false)
  1882. if (
  1883. text1.length > this.Match_MaxBits &&
  1884. this.diff_levenshtein(diffs) / text1.length >
  1885. this.Patch_DeleteThreshold
  1886. ) {
  1887. // The end points match, but the content is unacceptably bad.
  1888. results[x] = false
  1889. } else {
  1890. this.diff_cleanupSemanticLossless(diffs)
  1891. var index1 = 0
  1892. var index2
  1893. for (var y = 0; y < patches[x].diffs.length; y++) {
  1894. var mod = patches[x].diffs[y]
  1895. if (mod[0] !== DIFF_EQUAL) {
  1896. index2 = this.diff_xIndex(diffs, index1)
  1897. }
  1898. if (mod[0] === DIFF_INSERT) {
  1899. // Insertion
  1900. text =
  1901. text.substring(0, start_loc + index2) +
  1902. mod[1] +
  1903. text.substring(start_loc + index2)
  1904. } else if (mod[0] === DIFF_DELETE) {
  1905. // Deletion
  1906. text =
  1907. text.substring(0, start_loc + index2) +
  1908. text.substring(
  1909. start_loc + this.diff_xIndex(diffs, index1 + mod[1].length)
  1910. )
  1911. }
  1912. if (mod[0] !== DIFF_DELETE) {
  1913. index1 += mod[1].length
  1914. }
  1915. }
  1916. }
  1917. }
  1918. }
  1919. }
  1920. // Strip the padding off.
  1921. text = text.substring(nullPadding.length, text.length - nullPadding.length)
  1922. return [text, results]
  1923. }
  1924. /**
  1925. * Add some padding on text start and end so that edges can match something.
  1926. * Intended to be called only from within patch_apply.
  1927. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1928. * @return {string} The padding string added to each side.
  1929. */
  1930. diff_match_patch.prototype.patch_addPadding = function (patches) {
  1931. var paddingLength = this.Patch_Margin
  1932. var nullPadding = ''
  1933. for (var x = 1; x <= paddingLength; x++) {
  1934. nullPadding += String.fromCharCode(x)
  1935. }
  1936. // Bump all the patches forward.
  1937. for (var x = 0; x < patches.length; x++) {
  1938. patches[x].start1 += paddingLength
  1939. patches[x].start2 += paddingLength
  1940. }
  1941. // Add some padding on start of first diff.
  1942. var patch = patches[0]
  1943. var diffs = patch.diffs
  1944. if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {
  1945. // Add nullPadding equality.
  1946. diffs.unshift([DIFF_EQUAL, nullPadding])
  1947. patch.start1 -= paddingLength // Should be 0.
  1948. patch.start2 -= paddingLength // Should be 0.
  1949. patch.length1 += paddingLength
  1950. patch.length2 += paddingLength
  1951. } else if (paddingLength > diffs[0][1].length) {
  1952. // Grow first equality.
  1953. var extraLength = paddingLength - diffs[0][1].length
  1954. diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1]
  1955. patch.start1 -= extraLength
  1956. patch.start2 -= extraLength
  1957. patch.length1 += extraLength
  1958. patch.length2 += extraLength
  1959. }
  1960. // Add some padding on end of last diff.
  1961. patch = patches[patches.length - 1]
  1962. diffs = patch.diffs
  1963. if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {
  1964. // Add nullPadding equality.
  1965. diffs.push([DIFF_EQUAL, nullPadding])
  1966. patch.length1 += paddingLength
  1967. patch.length2 += paddingLength
  1968. } else if (paddingLength > diffs[diffs.length - 1][1].length) {
  1969. // Grow last equality.
  1970. var extraLength = paddingLength - diffs[diffs.length - 1][1].length
  1971. diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength)
  1972. patch.length1 += extraLength
  1973. patch.length2 += extraLength
  1974. }
  1975. return nullPadding
  1976. }
  1977. /**
  1978. * Look through the patches and break up any which are longer than the maximum
  1979. * limit of the match algorithm.
  1980. * Intended to be called only from within patch_apply.
  1981. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  1982. */
  1983. diff_match_patch.prototype.patch_splitMax = function (patches) {
  1984. var patch_size = this.Match_MaxBits
  1985. for (var x = 0; x < patches.length; x++) {
  1986. if (patches[x].length1 <= patch_size) {
  1987. continue
  1988. }
  1989. var bigpatch = patches[x]
  1990. // Remove the big old patch.
  1991. patches.splice(x--, 1)
  1992. var start1 = bigpatch.start1
  1993. var start2 = bigpatch.start2
  1994. var precontext = ''
  1995. while (bigpatch.diffs.length !== 0) {
  1996. // Create one of several smaller patches.
  1997. var patch = new diff_match_patch.patch_obj()
  1998. var empty = true
  1999. patch.start1 = start1 - precontext.length
  2000. patch.start2 = start2 - precontext.length
  2001. if (precontext !== '') {
  2002. patch.length1 = patch.length2 = precontext.length
  2003. patch.diffs.push([DIFF_EQUAL, precontext])
  2004. }
  2005. while (
  2006. bigpatch.diffs.length !== 0 &&
  2007. patch.length1 < patch_size - this.Patch_Margin
  2008. ) {
  2009. var diff_type = bigpatch.diffs[0][0]
  2010. var diff_text = bigpatch.diffs[0][1]
  2011. if (diff_type === DIFF_INSERT) {
  2012. // Insertions are harmless.
  2013. patch.length2 += diff_text.length
  2014. start2 += diff_text.length
  2015. patch.diffs.push(bigpatch.diffs.shift())
  2016. empty = false
  2017. } else if (
  2018. diff_type === DIFF_DELETE &&
  2019. patch.diffs.length == 1 &&
  2020. patch.diffs[0][0] == DIFF_EQUAL &&
  2021. diff_text.length > 2 * patch_size
  2022. ) {
  2023. // This is a large deletion. Let it pass in one chunk.
  2024. patch.length1 += diff_text.length
  2025. start1 += diff_text.length
  2026. empty = false
  2027. patch.diffs.push([diff_type, diff_text])
  2028. bigpatch.diffs.shift()
  2029. } else {
  2030. // Deletion or equality. Only take as much as we can stomach.
  2031. diff_text = diff_text.substring(
  2032. 0,
  2033. patch_size - patch.length1 - this.Patch_Margin
  2034. )
  2035. patch.length1 += diff_text.length
  2036. start1 += diff_text.length
  2037. if (diff_type === DIFF_EQUAL) {
  2038. patch.length2 += diff_text.length
  2039. start2 += diff_text.length
  2040. } else {
  2041. empty = false
  2042. }
  2043. patch.diffs.push([diff_type, diff_text])
  2044. if (diff_text == bigpatch.diffs[0][1]) {
  2045. bigpatch.diffs.shift()
  2046. } else {
  2047. bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(
  2048. diff_text.length
  2049. )
  2050. }
  2051. }
  2052. }
  2053. // Compute the head context for the next patch.
  2054. precontext = this.diff_text2(patch.diffs)
  2055. precontext = precontext.substring(precontext.length - this.Patch_Margin)
  2056. // Append the end context for this patch.
  2057. var postcontext = this.diff_text1(bigpatch.diffs).substring(
  2058. 0,
  2059. this.Patch_Margin
  2060. )
  2061. if (postcontext !== '') {
  2062. patch.length1 += postcontext.length
  2063. patch.length2 += postcontext.length
  2064. if (
  2065. patch.diffs.length !== 0 &&
  2066. patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL
  2067. ) {
  2068. patch.diffs[patch.diffs.length - 1][1] += postcontext
  2069. } else {
  2070. patch.diffs.push([DIFF_EQUAL, postcontext])
  2071. }
  2072. }
  2073. if (!empty) {
  2074. patches.splice(++x, 0, patch)
  2075. }
  2076. }
  2077. }
  2078. }
  2079. /**
  2080. * Take a list of patches and return a textual representation.
  2081. * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
  2082. * @return {string} Text representation of patches.
  2083. */
  2084. diff_match_patch.prototype.patch_toText = function (patches) {
  2085. var text = []
  2086. for (var x = 0; x < patches.length; x++) {
  2087. text[x] = patches[x]
  2088. }
  2089. return text.join('')
  2090. }
  2091. /**
  2092. * Parse a textual representation of patches and return a list of Patch objects.
  2093. * @param {string} textline Text representation of patches.
  2094. * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
  2095. * @throws {!Error} If invalid input.
  2096. */
  2097. diff_match_patch.prototype.patch_fromText = function (textline) {
  2098. var patches = []
  2099. if (!textline) {
  2100. return patches
  2101. }
  2102. var text = textline.split('\n')
  2103. var textPointer = 0
  2104. var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/
  2105. while (textPointer < text.length) {
  2106. var m = text[textPointer].match(patchHeader)
  2107. if (!m) {
  2108. throw new Error('Invalid patch string: ' + text[textPointer])
  2109. }
  2110. var patch = new diff_match_patch.patch_obj()
  2111. patches.push(patch)
  2112. patch.start1 = parseInt(m[1], 10)
  2113. if (m[2] === '') {
  2114. patch.start1--
  2115. patch.length1 = 1
  2116. } else if (m[2] == '0') {
  2117. patch.length1 = 0
  2118. } else {
  2119. patch.start1--
  2120. patch.length1 = parseInt(m[2], 10)
  2121. }
  2122. patch.start2 = parseInt(m[3], 10)
  2123. if (m[4] === '') {
  2124. patch.start2--
  2125. patch.length2 = 1
  2126. } else if (m[4] == '0') {
  2127. patch.length2 = 0
  2128. } else {
  2129. patch.start2--
  2130. patch.length2 = parseInt(m[4], 10)
  2131. }
  2132. textPointer++
  2133. while (textPointer < text.length) {
  2134. var sign = text[textPointer].charAt(0)
  2135. try {
  2136. var line = decodeURI(text[textPointer].substring(1))
  2137. } catch (ex) {
  2138. // Malformed URI sequence.
  2139. throw new Error('Illegal escape in patch_fromText: ' + line)
  2140. }
  2141. if (sign == '-') {
  2142. // Deletion.
  2143. patch.diffs.push([DIFF_DELETE, line])
  2144. } else if (sign == '+') {
  2145. // Insertion.
  2146. patch.diffs.push([DIFF_INSERT, line])
  2147. } else if (sign == ' ') {
  2148. // Minor equality.
  2149. patch.diffs.push([DIFF_EQUAL, line])
  2150. } else if (sign == '@') {
  2151. // Start of next patch.
  2152. break
  2153. } else if (sign === '') {
  2154. // Blank line? Whatever.
  2155. } else {
  2156. // WTF?
  2157. throw new Error('Invalid patch mode "' + sign + '" in: ' + line)
  2158. }
  2159. textPointer++
  2160. }
  2161. }
  2162. return patches
  2163. }
  2164. /**
  2165. * Class representing one patch operation.
  2166. * @constructor
  2167. */
  2168. diff_match_patch.patch_obj = function () {
  2169. /** @type {!Array.<!diff_match_patch.Diff>} */
  2170. this.diffs = []
  2171. /** @type {?number} */
  2172. this.start1 = null
  2173. /** @type {?number} */
  2174. this.start2 = null
  2175. /** @type {number} */
  2176. this.length1 = 0
  2177. /** @type {number} */
  2178. this.length2 = 0
  2179. }
  2180. /**
  2181. * Emmulate GNU diff's format.
  2182. * Header: @@ -382,8 +481,9 @@
  2183. * Indicies are printed as 1-based, not 0-based.
  2184. * @return {string} The GNU diff string.
  2185. */
  2186. diff_match_patch.patch_obj.prototype.toString = function () {
  2187. var coords1, coords2
  2188. if (this.length1 === 0) {
  2189. coords1 = this.start1 + ',0'
  2190. } else if (this.length1 == 1) {
  2191. coords1 = this.start1 + 1
  2192. } else {
  2193. coords1 = this.start1 + 1 + ',' + this.length1
  2194. }
  2195. if (this.length2 === 0) {
  2196. coords2 = this.start2 + ',0'
  2197. } else if (this.length2 == 1) {
  2198. coords2 = this.start2 + 1
  2199. } else {
  2200. coords2 = this.start2 + 1 + ',' + this.length2
  2201. }
  2202. var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n']
  2203. var op
  2204. // Escape the body of the patch with %xx notation.
  2205. for (var x = 0; x < this.diffs.length; x++) {
  2206. switch (this.diffs[x][0]) {
  2207. case DIFF_INSERT:
  2208. op = '+'
  2209. break
  2210. case DIFF_DELETE:
  2211. op = '-'
  2212. break
  2213. case DIFF_EQUAL:
  2214. op = ' '
  2215. break
  2216. }
  2217. text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n'
  2218. }
  2219. return text.join('').replace(/%20/g, ' ')
  2220. }
  2221. // Export these global variables so that they survive Google's JS compiler.
  2222. // In a browser, 'this' will be 'window'.
  2223. // Users of node.js should 'require' the uncompressed version since Google's
  2224. // JS compiler may break the following exports for non-browser environments.
  2225. this.diff_match_patch = diff_match_patch
  2226. this.DIFF_DELETE = DIFF_DELETE
  2227. this.DIFF_INSERT = DIFF_INSERT
  2228. this.DIFF_EQUAL = DIFF_EQUAL