diff.go 42 KB

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