diff_match_patch.js 75 KB

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