diff_match_patch.js 75 KB

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