本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1345 lines
41KB

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