diff_match_patch.js 75 KB

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