diff.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. // Copyright (c) 2012-2016 The go-diff authors. All rights reserved.
  2. // https://github.com/sergi/go-diff
  3. // See the included LICENSE file for license details.
  4. //
  5. // go-diff is a Go implementation of Google's Diff, Match, and Patch library
  6. // Original library is Copyright (c) 2006 Google Inc.
  7. // http://code.google.com/p/google-diff-match-patch/
  8. package diffmatchpatch
  9. import (
  10. "bytes"
  11. "errors"
  12. "fmt"
  13. "html"
  14. "math"
  15. "net/url"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "unicode/utf8"
  21. )
  22. // Operation defines the operation of a diff item.
  23. type Operation int8
  24. //go:generate stringer -type=Operation -trimprefix=Diff
  25. const (
  26. // DiffDelete item represents a delete diff.
  27. DiffDelete Operation = -1
  28. // DiffInsert item represents an insert diff.
  29. DiffInsert Operation = 1
  30. // DiffEqual item represents an equal diff.
  31. DiffEqual Operation = 0
  32. )
  33. // Diff represents one diff operation
  34. type Diff struct {
  35. Type Operation
  36. Text string
  37. }
  38. // splice removes amount elements from slice at index index, replacing them with elements.
  39. func splice(slice []Diff, index int, amount int, elements ...Diff) []Diff {
  40. if len(elements) == amount {
  41. // Easy case: overwrite the relevant items.
  42. copy(slice[index:], elements)
  43. return slice
  44. }
  45. if len(elements) < amount {
  46. // Fewer new items than old.
  47. // Copy in the new items.
  48. copy(slice[index:], elements)
  49. // Shift the remaining items left.
  50. copy(slice[index+len(elements):], slice[index+amount:])
  51. // Calculate the new end of the slice.
  52. end := len(slice) - amount + len(elements)
  53. // Zero stranded elements at end so that they can be garbage collected.
  54. tail := slice[end:]
  55. for i := range tail {
  56. tail[i] = Diff{}
  57. }
  58. return slice[:end]
  59. }
  60. // More new items than old.
  61. // Make room in slice for new elements.
  62. // There's probably an even more efficient way to do this,
  63. // but this is simple and clear.
  64. need := len(slice) - amount + len(elements)
  65. for len(slice) < need {
  66. slice = append(slice, Diff{})
  67. }
  68. // Shift slice elements right to make room for new elements.
  69. copy(slice[index+len(elements):], slice[index+amount:])
  70. // Copy in new elements.
  71. copy(slice[index:], elements)
  72. return slice
  73. }
  74. // DiffMain finds the differences between two texts.
  75. // If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.
  76. func (dmp *DiffMatchPatch) DiffMain(text1, text2 string, checklines bool) []Diff {
  77. return dmp.DiffMainRunes([]rune(text1), []rune(text2), checklines)
  78. }
  79. // DiffMainRunes finds the differences between two rune sequences.
  80. // If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.
  81. func (dmp *DiffMatchPatch) DiffMainRunes(text1, text2 []rune, checklines bool) []Diff {
  82. var deadline time.Time
  83. if dmp.DiffTimeout > 0 {
  84. deadline = time.Now().Add(dmp.DiffTimeout)
  85. }
  86. return dmp.diffMainRunes(text1, text2, checklines, deadline)
  87. }
  88. func (dmp *DiffMatchPatch) diffMainRunes(text1, text2 []rune, checklines bool, deadline time.Time) []Diff {
  89. if runesEqual(text1, text2) {
  90. var diffs []Diff
  91. if len(text1) > 0 {
  92. diffs = append(diffs, Diff{DiffEqual, string(text1)})
  93. }
  94. return diffs
  95. }
  96. // Trim off common prefix (speedup).
  97. commonlength := commonPrefixLength(text1, text2)
  98. commonprefix := text1[:commonlength]
  99. text1 = text1[commonlength:]
  100. text2 = text2[commonlength:]
  101. // Trim off common suffix (speedup).
  102. commonlength = commonSuffixLength(text1, text2)
  103. commonsuffix := text1[len(text1)-commonlength:]
  104. text1 = text1[:len(text1)-commonlength]
  105. text2 = text2[:len(text2)-commonlength]
  106. // Compute the diff on the middle block.
  107. diffs := dmp.diffCompute(text1, text2, checklines, deadline)
  108. // Restore the prefix and suffix.
  109. if len(commonprefix) != 0 {
  110. diffs = append([]Diff{Diff{DiffEqual, string(commonprefix)}}, diffs...)
  111. }
  112. if len(commonsuffix) != 0 {
  113. diffs = append(diffs, Diff{DiffEqual, string(commonsuffix)})
  114. }
  115. return dmp.DiffCleanupMerge(diffs)
  116. }
  117. // diffCompute finds the differences between two rune slices. Assumes that the texts do not have any common prefix or suffix.
  118. func (dmp *DiffMatchPatch) diffCompute(text1, text2 []rune, checklines bool, deadline time.Time) []Diff {
  119. diffs := []Diff{}
  120. if len(text1) == 0 {
  121. // Just add some text (speedup).
  122. return append(diffs, Diff{DiffInsert, string(text2)})
  123. } else if len(text2) == 0 {
  124. // Just delete some text (speedup).
  125. return append(diffs, Diff{DiffDelete, string(text1)})
  126. }
  127. var longtext, shorttext []rune
  128. if len(text1) > len(text2) {
  129. longtext = text1
  130. shorttext = text2
  131. } else {
  132. longtext = text2
  133. shorttext = text1
  134. }
  135. if i := runesIndex(longtext, shorttext); i != -1 {
  136. op := DiffInsert
  137. // Swap insertions for deletions if diff is reversed.
  138. if len(text1) > len(text2) {
  139. op = DiffDelete
  140. }
  141. // Shorter text is inside the longer text (speedup).
  142. return []Diff{
  143. Diff{op, string(longtext[:i])},
  144. Diff{DiffEqual, string(shorttext)},
  145. Diff{op, string(longtext[i+len(shorttext):])},
  146. }
  147. } else if len(shorttext) == 1 {
  148. // Single character string.
  149. // After the previous speedup, the character can't be an equality.
  150. return []Diff{
  151. Diff{DiffDelete, string(text1)},
  152. Diff{DiffInsert, string(text2)},
  153. }
  154. // Check to see if the problem can be split in two.
  155. } else if hm := dmp.diffHalfMatch(text1, text2); hm != nil {
  156. // A half-match was found, sort out the return data.
  157. text1A := hm[0]
  158. text1B := hm[1]
  159. text2A := hm[2]
  160. text2B := hm[3]
  161. midCommon := hm[4]
  162. // Send both pairs off for separate processing.
  163. diffsA := dmp.diffMainRunes(text1A, text2A, checklines, deadline)
  164. diffsB := dmp.diffMainRunes(text1B, text2B, checklines, deadline)
  165. // Merge the results.
  166. diffs := diffsA
  167. diffs = append(diffs, Diff{DiffEqual, string(midCommon)})
  168. diffs = append(diffs, diffsB...)
  169. return diffs
  170. } else if checklines && len(text1) > 100 && len(text2) > 100 {
  171. return dmp.diffLineMode(text1, text2, deadline)
  172. }
  173. return dmp.diffBisect(text1, text2, deadline)
  174. }
  175. // diffLineMode does a quick line-level diff on both []runes, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs.
  176. func (dmp *DiffMatchPatch) diffLineMode(text1, text2 []rune, deadline time.Time) []Diff {
  177. // Scan the text on a line-by-line basis first.
  178. text1, text2, linearray := dmp.diffLinesToRunes(text1, text2)
  179. diffs := dmp.diffMainRunes(text1, text2, false, deadline)
  180. // Convert the diff back to original text.
  181. diffs = dmp.DiffCharsToLines(diffs, linearray)
  182. // Eliminate freak matches (e.g. blank lines)
  183. diffs = dmp.DiffCleanupSemantic(diffs)
  184. // Rediff any replacement blocks, this time character-by-character.
  185. // Add a dummy entry at the end.
  186. diffs = append(diffs, Diff{DiffEqual, ""})
  187. pointer := 0
  188. countDelete := 0
  189. countInsert := 0
  190. // NOTE: Rune slices are slower than using strings in this case.
  191. textDelete := ""
  192. textInsert := ""
  193. for pointer < len(diffs) {
  194. switch diffs[pointer].Type {
  195. case DiffInsert:
  196. countInsert++
  197. textInsert += diffs[pointer].Text
  198. case DiffDelete:
  199. countDelete++
  200. textDelete += diffs[pointer].Text
  201. case DiffEqual:
  202. // Upon reaching an equality, check for prior redundancies.
  203. if countDelete >= 1 && countInsert >= 1 {
  204. // Delete the offending records and add the merged ones.
  205. diffs = splice(diffs, pointer-countDelete-countInsert,
  206. countDelete+countInsert)
  207. pointer = pointer - countDelete - countInsert
  208. a := dmp.diffMainRunes([]rune(textDelete), []rune(textInsert), false, deadline)
  209. for j := len(a) - 1; j >= 0; j-- {
  210. diffs = splice(diffs, pointer, 0, a[j])
  211. }
  212. pointer = pointer + len(a)
  213. }
  214. countInsert = 0
  215. countDelete = 0
  216. textDelete = ""
  217. textInsert = ""
  218. }
  219. pointer++
  220. }
  221. return diffs[:len(diffs)-1] // Remove the dummy entry at the end.
  222. }
  223. // DiffBisect finds the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff.
  224. // If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.
  225. // See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  226. func (dmp *DiffMatchPatch) DiffBisect(text1, text2 string, deadline time.Time) []Diff {
  227. // Unused in this code, but retained for interface compatibility.
  228. return dmp.diffBisect([]rune(text1), []rune(text2), deadline)
  229. }
  230. // diffBisect finds the 'middle snake' of a diff, splits the problem in two and returns the recursively constructed diff.
  231. // See Myers's 1986 paper: An O(ND) Difference Algorithm and Its Variations.
  232. func (dmp *DiffMatchPatch) diffBisect(runes1, runes2 []rune, deadline time.Time) []Diff {
  233. // Cache the text lengths to prevent multiple calls.
  234. runes1Len, runes2Len := len(runes1), len(runes2)
  235. maxD := (runes1Len + runes2Len + 1) / 2
  236. vOffset := maxD
  237. vLength := 2 * maxD
  238. v1 := make([]int, vLength)
  239. v2 := make([]int, vLength)
  240. for i := range v1 {
  241. v1[i] = -1
  242. v2[i] = -1
  243. }
  244. v1[vOffset+1] = 0
  245. v2[vOffset+1] = 0
  246. delta := runes1Len - runes2Len
  247. // If the total number of characters is odd, then the front path will collide with the reverse path.
  248. front := (delta%2 != 0)
  249. // Offsets for start and end of k loop. Prevents mapping of space beyond the grid.
  250. k1start := 0
  251. k1end := 0
  252. k2start := 0
  253. k2end := 0
  254. for d := 0; d < maxD; d++ {
  255. // Bail out if deadline is reached.
  256. if !deadline.IsZero() && d%16 == 0 && time.Now().After(deadline) {
  257. break
  258. }
  259. // Walk the front path one step.
  260. for k1 := -d + k1start; k1 <= d-k1end; k1 += 2 {
  261. k1Offset := vOffset + k1
  262. var x1 int
  263. if k1 == -d || (k1 != d && v1[k1Offset-1] < v1[k1Offset+1]) {
  264. x1 = v1[k1Offset+1]
  265. } else {
  266. x1 = v1[k1Offset-1] + 1
  267. }
  268. y1 := x1 - k1
  269. for x1 < runes1Len && y1 < runes2Len {
  270. if runes1[x1] != runes2[y1] {
  271. break
  272. }
  273. x1++
  274. y1++
  275. }
  276. v1[k1Offset] = x1
  277. if x1 > runes1Len {
  278. // Ran off the right of the graph.
  279. k1end += 2
  280. } else if y1 > runes2Len {
  281. // Ran off the bottom of the graph.
  282. k1start += 2
  283. } else if front {
  284. k2Offset := vOffset + delta - k1
  285. if k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] != -1 {
  286. // Mirror x2 onto top-left coordinate system.
  287. x2 := runes1Len - v2[k2Offset]
  288. if x1 >= x2 {
  289. // Overlap detected.
  290. return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline)
  291. }
  292. }
  293. }
  294. }
  295. // Walk the reverse path one step.
  296. for k2 := -d + k2start; k2 <= d-k2end; k2 += 2 {
  297. k2Offset := vOffset + k2
  298. var x2 int
  299. if k2 == -d || (k2 != d && v2[k2Offset-1] < v2[k2Offset+1]) {
  300. x2 = v2[k2Offset+1]
  301. } else {
  302. x2 = v2[k2Offset-1] + 1
  303. }
  304. var y2 = x2 - k2
  305. for x2 < runes1Len && y2 < runes2Len {
  306. if runes1[runes1Len-x2-1] != runes2[runes2Len-y2-1] {
  307. break
  308. }
  309. x2++
  310. y2++
  311. }
  312. v2[k2Offset] = x2
  313. if x2 > runes1Len {
  314. // Ran off the left of the graph.
  315. k2end += 2
  316. } else if y2 > runes2Len {
  317. // Ran off the top of the graph.
  318. k2start += 2
  319. } else if !front {
  320. k1Offset := vOffset + delta - k2
  321. if k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] != -1 {
  322. x1 := v1[k1Offset]
  323. y1 := vOffset + x1 - k1Offset
  324. // Mirror x2 onto top-left coordinate system.
  325. x2 = runes1Len - x2
  326. if x1 >= x2 {
  327. // Overlap detected.
  328. return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline)
  329. }
  330. }
  331. }
  332. }
  333. }
  334. // Diff took too long and hit the deadline or number of diffs equals number of characters, no commonality at all.
  335. return []Diff{
  336. Diff{DiffDelete, string(runes1)},
  337. Diff{DiffInsert, string(runes2)},
  338. }
  339. }
  340. func (dmp *DiffMatchPatch) diffBisectSplit(runes1, runes2 []rune, x, y int,
  341. deadline time.Time) []Diff {
  342. runes1a := runes1[:x]
  343. runes2a := runes2[:y]
  344. runes1b := runes1[x:]
  345. runes2b := runes2[y:]
  346. // Compute both diffs serially.
  347. diffs := dmp.diffMainRunes(runes1a, runes2a, false, deadline)
  348. diffsb := dmp.diffMainRunes(runes1b, runes2b, false, deadline)
  349. return append(diffs, diffsb...)
  350. }
  351. // DiffLinesToChars splits two texts into a list of strings, and educes the texts to a string of hashes where each Unicode character represents one line.
  352. // It's slightly faster to call DiffLinesToRunes first, followed by DiffMainRunes.
  353. func (dmp *DiffMatchPatch) DiffLinesToChars(text1, text2 string) (string, string, []string) {
  354. chars1, chars2, lineArray := dmp.DiffLinesToRunes(text1, text2)
  355. return string(chars1), string(chars2), lineArray
  356. }
  357. // DiffLinesToRunes splits two texts into a list of runes. Each rune represents one line.
  358. func (dmp *DiffMatchPatch) DiffLinesToRunes(text1, text2 string) ([]rune, []rune, []string) {
  359. // '\x00' is a valid character, but various debuggers don't like it. So we'll insert a junk entry to avoid generating a null character.
  360. lineArray := []string{""} // e.g. lineArray[4] == 'Hello\n'
  361. lineHash := map[string]int{} // e.g. lineHash['Hello\n'] == 4
  362. chars1 := dmp.diffLinesToRunesMunge(text1, &lineArray, lineHash)
  363. chars2 := dmp.diffLinesToRunesMunge(text2, &lineArray, lineHash)
  364. return chars1, chars2, lineArray
  365. }
  366. func (dmp *DiffMatchPatch) diffLinesToRunes(text1, text2 []rune) ([]rune, []rune, []string) {
  367. return dmp.DiffLinesToRunes(string(text1), string(text2))
  368. }
  369. // diffLinesToRunesMunge splits a text into an array of strings, and reduces the texts to a []rune where each Unicode character represents one line.
  370. // We use strings instead of []runes as input mainly because you can't use []rune as a map key.
  371. func (dmp *DiffMatchPatch) diffLinesToRunesMunge(text string, lineArray *[]string, lineHash map[string]int) []rune {
  372. // Walk the text, pulling out a substring for each line. text.split('\n') would would temporarily double our memory footprint. Modifying text would create many large strings to garbage collect.
  373. lineStart := 0
  374. lineEnd := -1
  375. runes := []rune{}
  376. for lineEnd < len(text)-1 {
  377. lineEnd = indexOf(text, "\n", lineStart)
  378. if lineEnd == -1 {
  379. lineEnd = len(text) - 1
  380. }
  381. line := text[lineStart : lineEnd+1]
  382. lineStart = lineEnd + 1
  383. lineValue, ok := lineHash[line]
  384. if ok {
  385. runes = append(runes, rune(lineValue))
  386. } else {
  387. *lineArray = append(*lineArray, line)
  388. lineHash[line] = len(*lineArray) - 1
  389. runes = append(runes, rune(len(*lineArray)-1))
  390. }
  391. }
  392. return runes
  393. }
  394. // DiffCharsToLines rehydrates the text in a diff from a string of line hashes to real lines of text.
  395. func (dmp *DiffMatchPatch) DiffCharsToLines(diffs []Diff, lineArray []string) []Diff {
  396. hydrated := make([]Diff, 0, len(diffs))
  397. for _, aDiff := range diffs {
  398. chars := aDiff.Text
  399. text := make([]string, len(chars))
  400. for i, r := range chars {
  401. text[i] = lineArray[r]
  402. }
  403. aDiff.Text = strings.Join(text, "")
  404. hydrated = append(hydrated, aDiff)
  405. }
  406. return hydrated
  407. }
  408. // DiffCommonPrefix determines the common prefix length of two strings.
  409. func (dmp *DiffMatchPatch) DiffCommonPrefix(text1, text2 string) int {
  410. // Unused in this code, but retained for interface compatibility.
  411. return commonPrefixLength([]rune(text1), []rune(text2))
  412. }
  413. // DiffCommonSuffix determines the common suffix length of two strings.
  414. func (dmp *DiffMatchPatch) DiffCommonSuffix(text1, text2 string) int {
  415. // Unused in this code, but retained for interface compatibility.
  416. return commonSuffixLength([]rune(text1), []rune(text2))
  417. }
  418. // commonPrefixLength returns the length of the common prefix of two rune slices.
  419. func commonPrefixLength(text1, text2 []rune) int {
  420. // Linear search. See comment in commonSuffixLength.
  421. n := 0
  422. for ; n < len(text1) && n < len(text2); n++ {
  423. if text1[n] != text2[n] {
  424. return n
  425. }
  426. }
  427. return n
  428. }
  429. // commonSuffixLength returns the length of the common suffix of two rune slices.
  430. func commonSuffixLength(text1, text2 []rune) int {
  431. // Use linear search rather than the binary search discussed at https://neil.fraser.name/news/2007/10/09/.
  432. // See discussion at https://github.com/sergi/go-diff/issues/54.
  433. i1 := len(text1)
  434. i2 := len(text2)
  435. for n := 0; ; n++ {
  436. i1--
  437. i2--
  438. if i1 < 0 || i2 < 0 || text1[i1] != text2[i2] {
  439. return n
  440. }
  441. }
  442. }
  443. // DiffCommonOverlap determines if the suffix of one string is the prefix of another.
  444. func (dmp *DiffMatchPatch) DiffCommonOverlap(text1 string, text2 string) int {
  445. // Cache the text lengths to prevent multiple calls.
  446. text1Length := len(text1)
  447. text2Length := len(text2)
  448. // Eliminate the null case.
  449. if text1Length == 0 || text2Length == 0 {
  450. return 0
  451. }
  452. // Truncate the longer string.
  453. if text1Length > text2Length {
  454. text1 = text1[text1Length-text2Length:]
  455. } else if text1Length < text2Length {
  456. text2 = text2[0:text1Length]
  457. }
  458. textLength := int(math.Min(float64(text1Length), float64(text2Length)))
  459. // Quick check for the worst case.
  460. if text1 == text2 {
  461. return textLength
  462. }
  463. // Start by looking for a single character match and increase length until no match is found. Performance analysis: http://neil.fraser.name/news/2010/11/04/
  464. best := 0
  465. length := 1
  466. for {
  467. pattern := text1[textLength-length:]
  468. found := strings.Index(text2, pattern)
  469. if found == -1 {
  470. break
  471. }
  472. length += found
  473. if found == 0 || text1[textLength-length:] == text2[0:length] {
  474. best = length
  475. length++
  476. }
  477. }
  478. return best
  479. }
  480. // DiffHalfMatch checks whether the two texts share a substring which is at least half the length of the longer text. This speedup can produce non-minimal diffs.
  481. func (dmp *DiffMatchPatch) DiffHalfMatch(text1, text2 string) []string {
  482. // Unused in this code, but retained for interface compatibility.
  483. runeSlices := dmp.diffHalfMatch([]rune(text1), []rune(text2))
  484. if runeSlices == nil {
  485. return nil
  486. }
  487. result := make([]string, len(runeSlices))
  488. for i, r := range runeSlices {
  489. result[i] = string(r)
  490. }
  491. return result
  492. }
  493. func (dmp *DiffMatchPatch) diffHalfMatch(text1, text2 []rune) [][]rune {
  494. if dmp.DiffTimeout <= 0 {
  495. // Don't risk returning a non-optimal diff if we have unlimited time.
  496. return nil
  497. }
  498. var longtext, shorttext []rune
  499. if len(text1) > len(text2) {
  500. longtext = text1
  501. shorttext = text2
  502. } else {
  503. longtext = text2
  504. shorttext = text1
  505. }
  506. if len(longtext) < 4 || len(shorttext)*2 < len(longtext) {
  507. return nil // Pointless.
  508. }
  509. // First check if the second quarter is the seed for a half-match.
  510. hm1 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+3)/4))
  511. // Check again based on the third quarter.
  512. hm2 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+1)/2))
  513. hm := [][]rune{}
  514. if hm1 == nil && hm2 == nil {
  515. return nil
  516. } else if hm2 == nil {
  517. hm = hm1
  518. } else if hm1 == nil {
  519. hm = hm2
  520. } else {
  521. // Both matched. Select the longest.
  522. if len(hm1[4]) > len(hm2[4]) {
  523. hm = hm1
  524. } else {
  525. hm = hm2
  526. }
  527. }
  528. // A half-match was found, sort out the return data.
  529. if len(text1) > len(text2) {
  530. return hm
  531. }
  532. return [][]rune{hm[2], hm[3], hm[0], hm[1], hm[4]}
  533. }
  534. // diffHalfMatchI checks if a substring of shorttext exist within longtext such that the substring is at least half the length of longtext?
  535. // Returns a slice containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle, or null if there was no match.
  536. func (dmp *DiffMatchPatch) diffHalfMatchI(l, s []rune, i int) [][]rune {
  537. var bestCommonA []rune
  538. var bestCommonB []rune
  539. var bestCommonLen int
  540. var bestLongtextA []rune
  541. var bestLongtextB []rune
  542. var bestShorttextA []rune
  543. var bestShorttextB []rune
  544. // Start with a 1/4 length substring at position i as a seed.
  545. seed := l[i : i+len(l)/4]
  546. for j := runesIndexOf(s, seed, 0); j != -1; j = runesIndexOf(s, seed, j+1) {
  547. prefixLength := commonPrefixLength(l[i:], s[j:])
  548. suffixLength := commonSuffixLength(l[:i], s[:j])
  549. if bestCommonLen < suffixLength+prefixLength {
  550. bestCommonA = s[j-suffixLength : j]
  551. bestCommonB = s[j : j+prefixLength]
  552. bestCommonLen = len(bestCommonA) + len(bestCommonB)
  553. bestLongtextA = l[:i-suffixLength]
  554. bestLongtextB = l[i+prefixLength:]
  555. bestShorttextA = s[:j-suffixLength]
  556. bestShorttextB = s[j+prefixLength:]
  557. }
  558. }
  559. if bestCommonLen*2 < len(l) {
  560. return nil
  561. }
  562. return [][]rune{
  563. bestLongtextA,
  564. bestLongtextB,
  565. bestShorttextA,
  566. bestShorttextB,
  567. append(bestCommonA, bestCommonB...),
  568. }
  569. }
  570. // DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities.
  571. func (dmp *DiffMatchPatch) DiffCleanupSemantic(diffs []Diff) []Diff {
  572. changes := false
  573. // Stack of indices where equalities are found.
  574. equalities := make([]int, 0, len(diffs))
  575. var lastequality string
  576. // Always equal to diffs[equalities[equalitiesLength - 1]][1]
  577. var pointer int // Index of current position.
  578. // Number of characters that changed prior to the equality.
  579. var lengthInsertions1, lengthDeletions1 int
  580. // Number of characters that changed after the equality.
  581. var lengthInsertions2, lengthDeletions2 int
  582. for pointer < len(diffs) {
  583. if diffs[pointer].Type == DiffEqual {
  584. // Equality found.
  585. equalities = append(equalities, pointer)
  586. lengthInsertions1 = lengthInsertions2
  587. lengthDeletions1 = lengthDeletions2
  588. lengthInsertions2 = 0
  589. lengthDeletions2 = 0
  590. lastequality = diffs[pointer].Text
  591. } else {
  592. // An insertion or deletion.
  593. if diffs[pointer].Type == DiffInsert {
  594. lengthInsertions2 += len(diffs[pointer].Text)
  595. } else {
  596. lengthDeletions2 += len(diffs[pointer].Text)
  597. }
  598. // Eliminate an equality that is smaller or equal to the edits on both sides of it.
  599. difference1 := int(math.Max(float64(lengthInsertions1), float64(lengthDeletions1)))
  600. difference2 := int(math.Max(float64(lengthInsertions2), float64(lengthDeletions2)))
  601. if len(lastequality) > 0 &&
  602. (len(lastequality) <= difference1) &&
  603. (len(lastequality) <= difference2) {
  604. // Duplicate record.
  605. insPoint := equalities[len(equalities)-1]
  606. diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality})
  607. // Change second copy to insert.
  608. diffs[insPoint+1].Type = DiffInsert
  609. // Throw away the equality we just deleted.
  610. equalities = equalities[:len(equalities)-1]
  611. if len(equalities) > 0 {
  612. equalities = equalities[:len(equalities)-1]
  613. }
  614. pointer = -1
  615. if len(equalities) > 0 {
  616. pointer = equalities[len(equalities)-1]
  617. }
  618. lengthInsertions1 = 0 // Reset the counters.
  619. lengthDeletions1 = 0
  620. lengthInsertions2 = 0
  621. lengthDeletions2 = 0
  622. lastequality = ""
  623. changes = true
  624. }
  625. }
  626. pointer++
  627. }
  628. // Normalize the diff.
  629. if changes {
  630. diffs = dmp.DiffCleanupMerge(diffs)
  631. }
  632. diffs = dmp.DiffCleanupSemanticLossless(diffs)
  633. // Find any overlaps between deletions and insertions.
  634. // e.g: <del>abcxxx</del><ins>xxxdef</ins>
  635. // -> <del>abc</del>xxx<ins>def</ins>
  636. // e.g: <del>xxxabc</del><ins>defxxx</ins>
  637. // -> <ins>def</ins>xxx<del>abc</del>
  638. // Only extract an overlap if it is as big as the edit ahead or behind it.
  639. pointer = 1
  640. for pointer < len(diffs) {
  641. if diffs[pointer-1].Type == DiffDelete &&
  642. diffs[pointer].Type == DiffInsert {
  643. deletion := diffs[pointer-1].Text
  644. insertion := diffs[pointer].Text
  645. overlapLength1 := dmp.DiffCommonOverlap(deletion, insertion)
  646. overlapLength2 := dmp.DiffCommonOverlap(insertion, deletion)
  647. if overlapLength1 >= overlapLength2 {
  648. if float64(overlapLength1) >= float64(len(deletion))/2 ||
  649. float64(overlapLength1) >= float64(len(insertion))/2 {
  650. // Overlap found. Insert an equality and trim the surrounding edits.
  651. diffs = splice(diffs, pointer, 0, Diff{DiffEqual, insertion[:overlapLength1]})
  652. diffs[pointer-1].Text =
  653. deletion[0 : len(deletion)-overlapLength1]
  654. diffs[pointer+1].Text = insertion[overlapLength1:]
  655. pointer++
  656. }
  657. } else {
  658. if float64(overlapLength2) >= float64(len(deletion))/2 ||
  659. float64(overlapLength2) >= float64(len(insertion))/2 {
  660. // Reverse overlap found. Insert an equality and swap and trim the surrounding edits.
  661. overlap := Diff{DiffEqual, deletion[:overlapLength2]}
  662. diffs = splice(diffs, pointer, 0, overlap)
  663. diffs[pointer-1].Type = DiffInsert
  664. diffs[pointer-1].Text = insertion[0 : len(insertion)-overlapLength2]
  665. diffs[pointer+1].Type = DiffDelete
  666. diffs[pointer+1].Text = deletion[overlapLength2:]
  667. pointer++
  668. }
  669. }
  670. pointer++
  671. }
  672. pointer++
  673. }
  674. return diffs
  675. }
  676. // Define some regex patterns for matching boundaries.
  677. var (
  678. nonAlphaNumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]`)
  679. whitespaceRegex = regexp.MustCompile(`\s`)
  680. linebreakRegex = regexp.MustCompile(`[\r\n]`)
  681. blanklineEndRegex = regexp.MustCompile(`\n\r?\n$`)
  682. blanklineStartRegex = regexp.MustCompile(`^\r?\n\r?\n`)
  683. )
  684. // diffCleanupSemanticScore computes a score representing whether the internal boundary falls on logical boundaries.
  685. // Scores range from 6 (best) to 0 (worst). Closure, but does not reference any external variables.
  686. func diffCleanupSemanticScore(one, two string) int {
  687. if len(one) == 0 || len(two) == 0 {
  688. // Edges are the best.
  689. return 6
  690. }
  691. // Each port of this function behaves slightly differently due to subtle differences in each language's definition of things like 'whitespace'. Since this function's purpose is largely cosmetic, the choice has been made to use each language's native features rather than force total conformity.
  692. rune1, _ := utf8.DecodeLastRuneInString(one)
  693. rune2, _ := utf8.DecodeRuneInString(two)
  694. char1 := string(rune1)
  695. char2 := string(rune2)
  696. nonAlphaNumeric1 := nonAlphaNumericRegex.MatchString(char1)
  697. nonAlphaNumeric2 := nonAlphaNumericRegex.MatchString(char2)
  698. whitespace1 := nonAlphaNumeric1 && whitespaceRegex.MatchString(char1)
  699. whitespace2 := nonAlphaNumeric2 && whitespaceRegex.MatchString(char2)
  700. lineBreak1 := whitespace1 && linebreakRegex.MatchString(char1)
  701. lineBreak2 := whitespace2 && linebreakRegex.MatchString(char2)
  702. blankLine1 := lineBreak1 && blanklineEndRegex.MatchString(one)
  703. blankLine2 := lineBreak2 && blanklineEndRegex.MatchString(two)
  704. if blankLine1 || blankLine2 {
  705. // Five points for blank lines.
  706. return 5
  707. } else if lineBreak1 || lineBreak2 {
  708. // Four points for line breaks.
  709. return 4
  710. } else if nonAlphaNumeric1 && !whitespace1 && whitespace2 {
  711. // Three points for end of sentences.
  712. return 3
  713. } else if whitespace1 || whitespace2 {
  714. // Two points for whitespace.
  715. return 2
  716. } else if nonAlphaNumeric1 || nonAlphaNumeric2 {
  717. // One point for non-alphanumeric.
  718. return 1
  719. }
  720. return 0
  721. }
  722. // DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary.
  723. // E.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
  724. func (dmp *DiffMatchPatch) DiffCleanupSemanticLossless(diffs []Diff) []Diff {
  725. pointer := 1
  726. // Intentionally ignore the first and last element (don't need checking).
  727. for pointer < len(diffs)-1 {
  728. if diffs[pointer-1].Type == DiffEqual &&
  729. diffs[pointer+1].Type == DiffEqual {
  730. // This is a single edit surrounded by equalities.
  731. equality1 := diffs[pointer-1].Text
  732. edit := diffs[pointer].Text
  733. equality2 := diffs[pointer+1].Text
  734. // First, shift the edit as far left as possible.
  735. commonOffset := dmp.DiffCommonSuffix(equality1, edit)
  736. if commonOffset > 0 {
  737. commonString := edit[len(edit)-commonOffset:]
  738. equality1 = equality1[0 : len(equality1)-commonOffset]
  739. edit = commonString + edit[:len(edit)-commonOffset]
  740. equality2 = commonString + equality2
  741. }
  742. // Second, step character by character right, looking for the best fit.
  743. bestEquality1 := equality1
  744. bestEdit := edit
  745. bestEquality2 := equality2
  746. bestScore := diffCleanupSemanticScore(equality1, edit) +
  747. diffCleanupSemanticScore(edit, equality2)
  748. for len(edit) != 0 && len(equality2) != 0 {
  749. _, sz := utf8.DecodeRuneInString(edit)
  750. if len(equality2) < sz || edit[:sz] != equality2[:sz] {
  751. break
  752. }
  753. equality1 += edit[:sz]
  754. edit = edit[sz:] + equality2[:sz]
  755. equality2 = equality2[sz:]
  756. score := diffCleanupSemanticScore(equality1, edit) +
  757. diffCleanupSemanticScore(edit, equality2)
  758. // The >= encourages trailing rather than leading whitespace on edits.
  759. if score >= bestScore {
  760. bestScore = score
  761. bestEquality1 = equality1
  762. bestEdit = edit
  763. bestEquality2 = equality2
  764. }
  765. }
  766. if diffs[pointer-1].Text != bestEquality1 {
  767. // We have an improvement, save it back to the diff.
  768. if len(bestEquality1) != 0 {
  769. diffs[pointer-1].Text = bestEquality1
  770. } else {
  771. diffs = splice(diffs, pointer-1, 1)
  772. pointer--
  773. }
  774. diffs[pointer].Text = bestEdit
  775. if len(bestEquality2) != 0 {
  776. diffs[pointer+1].Text = bestEquality2
  777. } else {
  778. diffs = append(diffs[:pointer+1], diffs[pointer+2:]...)
  779. pointer--
  780. }
  781. }
  782. }
  783. pointer++
  784. }
  785. return diffs
  786. }
  787. // DiffCleanupEfficiency reduces the number of edits by eliminating operationally trivial equalities.
  788. func (dmp *DiffMatchPatch) DiffCleanupEfficiency(diffs []Diff) []Diff {
  789. changes := false
  790. // Stack of indices where equalities are found.
  791. type equality struct {
  792. data int
  793. next *equality
  794. }
  795. var equalities *equality
  796. // Always equal to equalities[equalitiesLength-1][1]
  797. lastequality := ""
  798. pointer := 0 // Index of current position.
  799. // Is there an insertion operation before the last equality.
  800. preIns := false
  801. // Is there a deletion operation before the last equality.
  802. preDel := false
  803. // Is there an insertion operation after the last equality.
  804. postIns := false
  805. // Is there a deletion operation after the last equality.
  806. postDel := false
  807. for pointer < len(diffs) {
  808. if diffs[pointer].Type == DiffEqual { // Equality found.
  809. if len(diffs[pointer].Text) < dmp.DiffEditCost &&
  810. (postIns || postDel) {
  811. // Candidate found.
  812. equalities = &equality{
  813. data: pointer,
  814. next: equalities,
  815. }
  816. preIns = postIns
  817. preDel = postDel
  818. lastequality = diffs[pointer].Text
  819. } else {
  820. // Not a candidate, and can never become one.
  821. equalities = nil
  822. lastequality = ""
  823. }
  824. postIns = false
  825. postDel = false
  826. } else { // An insertion or deletion.
  827. if diffs[pointer].Type == DiffDelete {
  828. postDel = true
  829. } else {
  830. postIns = true
  831. }
  832. // Five types to be split:
  833. // <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
  834. // <ins>A</ins>X<ins>C</ins><del>D</del>
  835. // <ins>A</ins><del>B</del>X<ins>C</ins>
  836. // <ins>A</del>X<ins>C</ins><del>D</del>
  837. // <ins>A</ins><del>B</del>X<del>C</del>
  838. var sumPres int
  839. if preIns {
  840. sumPres++
  841. }
  842. if preDel {
  843. sumPres++
  844. }
  845. if postIns {
  846. sumPres++
  847. }
  848. if postDel {
  849. sumPres++
  850. }
  851. if len(lastequality) > 0 &&
  852. ((preIns && preDel && postIns && postDel) ||
  853. ((len(lastequality) < dmp.DiffEditCost/2) && sumPres == 3)) {
  854. insPoint := equalities.data
  855. // Duplicate record.
  856. diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality})
  857. // Change second copy to insert.
  858. diffs[insPoint+1].Type = DiffInsert
  859. // Throw away the equality we just deleted.
  860. equalities = equalities.next
  861. lastequality = ""
  862. if preIns && preDel {
  863. // No changes made which could affect previous entry, keep going.
  864. postIns = true
  865. postDel = true
  866. equalities = nil
  867. } else {
  868. if equalities != nil {
  869. equalities = equalities.next
  870. }
  871. if equalities != nil {
  872. pointer = equalities.data
  873. } else {
  874. pointer = -1
  875. }
  876. postIns = false
  877. postDel = false
  878. }
  879. changes = true
  880. }
  881. }
  882. pointer++
  883. }
  884. if changes {
  885. diffs = dmp.DiffCleanupMerge(diffs)
  886. }
  887. return diffs
  888. }
  889. // DiffCleanupMerge reorders and merges like edit sections. Merge equalities.
  890. // Any edit section can move as long as it doesn't cross an equality.
  891. func (dmp *DiffMatchPatch) DiffCleanupMerge(diffs []Diff) []Diff {
  892. // Add a dummy entry at the end.
  893. diffs = append(diffs, Diff{DiffEqual, ""})
  894. pointer := 0
  895. countDelete := 0
  896. countInsert := 0
  897. commonlength := 0
  898. textDelete := []rune(nil)
  899. textInsert := []rune(nil)
  900. for pointer < len(diffs) {
  901. switch diffs[pointer].Type {
  902. case DiffInsert:
  903. countInsert++
  904. textInsert = append(textInsert, []rune(diffs[pointer].Text)...)
  905. pointer++
  906. break
  907. case DiffDelete:
  908. countDelete++
  909. textDelete = append(textDelete, []rune(diffs[pointer].Text)...)
  910. pointer++
  911. break
  912. case DiffEqual:
  913. // Upon reaching an equality, check for prior redundancies.
  914. if countDelete+countInsert > 1 {
  915. if countDelete != 0 && countInsert != 0 {
  916. // Factor out any common prefixies.
  917. commonlength = commonPrefixLength(textInsert, textDelete)
  918. if commonlength != 0 {
  919. x := pointer - countDelete - countInsert
  920. if x > 0 && diffs[x-1].Type == DiffEqual {
  921. diffs[x-1].Text += string(textInsert[:commonlength])
  922. } else {
  923. diffs = append([]Diff{Diff{DiffEqual, string(textInsert[:commonlength])}}, diffs...)
  924. pointer++
  925. }
  926. textInsert = textInsert[commonlength:]
  927. textDelete = textDelete[commonlength:]
  928. }
  929. // Factor out any common suffixies.
  930. commonlength = commonSuffixLength(textInsert, textDelete)
  931. if commonlength != 0 {
  932. insertIndex := len(textInsert) - commonlength
  933. deleteIndex := len(textDelete) - commonlength
  934. diffs[pointer].Text = string(textInsert[insertIndex:]) + diffs[pointer].Text
  935. textInsert = textInsert[:insertIndex]
  936. textDelete = textDelete[:deleteIndex]
  937. }
  938. }
  939. // Delete the offending records and add the merged ones.
  940. if countDelete == 0 {
  941. diffs = splice(diffs, pointer-countInsert,
  942. countDelete+countInsert,
  943. Diff{DiffInsert, string(textInsert)})
  944. } else if countInsert == 0 {
  945. diffs = splice(diffs, pointer-countDelete,
  946. countDelete+countInsert,
  947. Diff{DiffDelete, string(textDelete)})
  948. } else {
  949. diffs = splice(diffs, pointer-countDelete-countInsert,
  950. countDelete+countInsert,
  951. Diff{DiffDelete, string(textDelete)},
  952. Diff{DiffInsert, string(textInsert)})
  953. }
  954. pointer = pointer - countDelete - countInsert + 1
  955. if countDelete != 0 {
  956. pointer++
  957. }
  958. if countInsert != 0 {
  959. pointer++
  960. }
  961. } else if pointer != 0 && diffs[pointer-1].Type == DiffEqual {
  962. // Merge this equality with the previous one.
  963. diffs[pointer-1].Text += diffs[pointer].Text
  964. diffs = append(diffs[:pointer], diffs[pointer+1:]...)
  965. } else {
  966. pointer++
  967. }
  968. countInsert = 0
  969. countDelete = 0
  970. textDelete = nil
  971. textInsert = nil
  972. break
  973. }
  974. }
  975. if len(diffs[len(diffs)-1].Text) == 0 {
  976. diffs = diffs[0 : len(diffs)-1] // Remove the dummy entry at the end.
  977. }
  978. // Second pass: look for single edits surrounded on both sides by equalities which can be shifted sideways to eliminate an equality. E.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
  979. changes := false
  980. pointer = 1
  981. // Intentionally ignore the first and last element (don't need checking).
  982. for pointer < (len(diffs) - 1) {
  983. if diffs[pointer-1].Type == DiffEqual &&
  984. diffs[pointer+1].Type == DiffEqual {
  985. // This is a single edit surrounded by equalities.
  986. if strings.HasSuffix(diffs[pointer].Text, diffs[pointer-1].Text) {
  987. // Shift the edit over the previous equality.
  988. diffs[pointer].Text = diffs[pointer-1].Text +
  989. diffs[pointer].Text[:len(diffs[pointer].Text)-len(diffs[pointer-1].Text)]
  990. diffs[pointer+1].Text = diffs[pointer-1].Text + diffs[pointer+1].Text
  991. diffs = splice(diffs, pointer-1, 1)
  992. changes = true
  993. } else if strings.HasPrefix(diffs[pointer].Text, diffs[pointer+1].Text) {
  994. // Shift the edit over the next equality.
  995. diffs[pointer-1].Text += diffs[pointer+1].Text
  996. diffs[pointer].Text =
  997. diffs[pointer].Text[len(diffs[pointer+1].Text):] + diffs[pointer+1].Text
  998. diffs = splice(diffs, pointer+1, 1)
  999. changes = true
  1000. }
  1001. }
  1002. pointer++
  1003. }
  1004. // If shifts were made, the diff needs reordering and another shift sweep.
  1005. if changes {
  1006. diffs = dmp.DiffCleanupMerge(diffs)
  1007. }
  1008. return diffs
  1009. }
  1010. // DiffXIndex returns the equivalent location in s2.
  1011. func (dmp *DiffMatchPatch) DiffXIndex(diffs []Diff, loc int) int {
  1012. chars1 := 0
  1013. chars2 := 0
  1014. lastChars1 := 0
  1015. lastChars2 := 0
  1016. lastDiff := Diff{}
  1017. for i := 0; i < len(diffs); i++ {
  1018. aDiff := diffs[i]
  1019. if aDiff.Type != DiffInsert {
  1020. // Equality or deletion.
  1021. chars1 += len(aDiff.Text)
  1022. }
  1023. if aDiff.Type != DiffDelete {
  1024. // Equality or insertion.
  1025. chars2 += len(aDiff.Text)
  1026. }
  1027. if chars1 > loc {
  1028. // Overshot the location.
  1029. lastDiff = aDiff
  1030. break
  1031. }
  1032. lastChars1 = chars1
  1033. lastChars2 = chars2
  1034. }
  1035. if lastDiff.Type == DiffDelete {
  1036. // The location was deleted.
  1037. return lastChars2
  1038. }
  1039. // Add the remaining character length.
  1040. return lastChars2 + (loc - lastChars1)
  1041. }
  1042. // DiffPrettyHtml converts a []Diff into a pretty HTML report.
  1043. // It is intended as an example from which to write one's own display functions.
  1044. func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string {
  1045. var buff bytes.Buffer
  1046. for _, diff := range diffs {
  1047. text := strings.Replace(html.EscapeString(diff.Text), "\n", "&para;<br>", -1)
  1048. switch diff.Type {
  1049. case DiffInsert:
  1050. _, _ = buff.WriteString("<ins style=\"background:#e6ffe6;\">")
  1051. _, _ = buff.WriteString(text)
  1052. _, _ = buff.WriteString("</ins>")
  1053. case DiffDelete:
  1054. _, _ = buff.WriteString("<del style=\"background:#ffe6e6;\">")
  1055. _, _ = buff.WriteString(text)
  1056. _, _ = buff.WriteString("</del>")
  1057. case DiffEqual:
  1058. _, _ = buff.WriteString("<span>")
  1059. _, _ = buff.WriteString(text)
  1060. _, _ = buff.WriteString("</span>")
  1061. }
  1062. }
  1063. return buff.String()
  1064. }
  1065. // DiffPrettyText converts a []Diff into a colored text report.
  1066. func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string {
  1067. var buff bytes.Buffer
  1068. for _, diff := range diffs {
  1069. text := diff.Text
  1070. switch diff.Type {
  1071. case DiffInsert:
  1072. _, _ = buff.WriteString("\x1b[32m")
  1073. _, _ = buff.WriteString(text)
  1074. _, _ = buff.WriteString("\x1b[0m")
  1075. case DiffDelete:
  1076. _, _ = buff.WriteString("\x1b[31m")
  1077. _, _ = buff.WriteString(text)
  1078. _, _ = buff.WriteString("\x1b[0m")
  1079. case DiffEqual:
  1080. _, _ = buff.WriteString(text)
  1081. }
  1082. }
  1083. return buff.String()
  1084. }
  1085. // DiffText1 computes and returns the source text (all equalities and deletions).
  1086. func (dmp *DiffMatchPatch) DiffText1(diffs []Diff) string {
  1087. //StringBuilder text = new StringBuilder()
  1088. var text bytes.Buffer
  1089. for _, aDiff := range diffs {
  1090. if aDiff.Type != DiffInsert {
  1091. _, _ = text.WriteString(aDiff.Text)
  1092. }
  1093. }
  1094. return text.String()
  1095. }
  1096. // DiffText2 computes and returns the destination text (all equalities and insertions).
  1097. func (dmp *DiffMatchPatch) DiffText2(diffs []Diff) string {
  1098. var text bytes.Buffer
  1099. for _, aDiff := range diffs {
  1100. if aDiff.Type != DiffDelete {
  1101. _, _ = text.WriteString(aDiff.Text)
  1102. }
  1103. }
  1104. return text.String()
  1105. }
  1106. // DiffLevenshtein computes the Levenshtein distance that is the number of inserted, deleted or substituted characters.
  1107. func (dmp *DiffMatchPatch) DiffLevenshtein(diffs []Diff) int {
  1108. levenshtein := 0
  1109. insertions := 0
  1110. deletions := 0
  1111. for _, aDiff := range diffs {
  1112. switch aDiff.Type {
  1113. case DiffInsert:
  1114. insertions += utf8.RuneCountInString(aDiff.Text)
  1115. case DiffDelete:
  1116. deletions += utf8.RuneCountInString(aDiff.Text)
  1117. case DiffEqual:
  1118. // A deletion and an insertion is one substitution.
  1119. levenshtein += max(insertions, deletions)
  1120. insertions = 0
  1121. deletions = 0
  1122. }
  1123. }
  1124. levenshtein += max(insertions, deletions)
  1125. return levenshtein
  1126. }
  1127. // DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2.
  1128. // E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation.
  1129. func (dmp *DiffMatchPatch) DiffToDelta(diffs []Diff) string {
  1130. var text bytes.Buffer
  1131. for _, aDiff := range diffs {
  1132. switch aDiff.Type {
  1133. case DiffInsert:
  1134. _, _ = text.WriteString("+")
  1135. _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1))
  1136. _, _ = text.WriteString("\t")
  1137. break
  1138. case DiffDelete:
  1139. _, _ = text.WriteString("-")
  1140. _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text)))
  1141. _, _ = text.WriteString("\t")
  1142. break
  1143. case DiffEqual:
  1144. _, _ = text.WriteString("=")
  1145. _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text)))
  1146. _, _ = text.WriteString("\t")
  1147. break
  1148. }
  1149. }
  1150. delta := text.String()
  1151. if len(delta) != 0 {
  1152. // Strip off trailing tab character.
  1153. delta = delta[0 : utf8.RuneCountInString(delta)-1]
  1154. delta = unescaper.Replace(delta)
  1155. }
  1156. return delta
  1157. }
  1158. // DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff.
  1159. func (dmp *DiffMatchPatch) DiffFromDelta(text1 string, delta string) (diffs []Diff, err error) {
  1160. i := 0
  1161. runes := []rune(text1)
  1162. for _, token := range strings.Split(delta, "\t") {
  1163. if len(token) == 0 {
  1164. // Blank tokens are ok (from a trailing \t).
  1165. continue
  1166. }
  1167. // Each token begins with a one character parameter which specifies the operation of this token (delete, insert, equality).
  1168. param := token[1:]
  1169. switch op := token[0]; op {
  1170. case '+':
  1171. // Decode would Diff all "+" to " "
  1172. param = strings.Replace(param, "+", "%2b", -1)
  1173. param, err = url.QueryUnescape(param)
  1174. if err != nil {
  1175. return nil, err
  1176. }
  1177. if !utf8.ValidString(param) {
  1178. return nil, fmt.Errorf("invalid UTF-8 token: %q", param)
  1179. }
  1180. diffs = append(diffs, Diff{DiffInsert, param})
  1181. case '=', '-':
  1182. n, err := strconv.ParseInt(param, 10, 0)
  1183. if err != nil {
  1184. return nil, err
  1185. } else if n < 0 {
  1186. return nil, errors.New("Negative number in DiffFromDelta: " + param)
  1187. }
  1188. i += int(n)
  1189. // Break out if we are out of bounds, go1.6 can't handle this very well
  1190. if i > len(runes) {
  1191. break
  1192. }
  1193. // Remember that string slicing is by byte - we want by rune here.
  1194. text := string(runes[i-int(n) : i])
  1195. if op == '=' {
  1196. diffs = append(diffs, Diff{DiffEqual, text})
  1197. } else {
  1198. diffs = append(diffs, Diff{DiffDelete, text})
  1199. }
  1200. default:
  1201. // Anything else is an error.
  1202. return nil, errors.New("Invalid diff operation in DiffFromDelta: " + string(token[0]))
  1203. }
  1204. }
  1205. if i != len(runes) {
  1206. return nil, fmt.Errorf("Delta length (%v) is different from source text length (%v)", i, len(text1))
  1207. }
  1208. return diffs, nil
  1209. }