From 3d4fe2eb6f0cb983356746fc99d806c9db9ae18b Mon Sep 17 00:00:00 2001 From: Sam El-Husseini Date: Thu, 25 Jul 2019 16:16:11 -0700 Subject: [PATCH 1/2] Port diff_match_patch into Typescript --- .gitignore | 2 + AUTHORS | 1 + typescript/diff_match_patch.d.ts | 66 + typescript/diff_match_patch.js | 1569 ++++++++++++++ typescript/diff_match_patch.ts | 2256 +++++++++++++++++++++ typescript/tests/diff_match_patch_test.ts | 1065 ++++++++++ typescript/tests/speedtest.ts | 457 +++++ typescript/tests/tsconfig.json | 15 + typescript/tsconfig.json | 17 + 9 files changed, 5448 insertions(+) create mode 100644 typescript/diff_match_patch.d.ts create mode 100644 typescript/diff_match_patch.js create mode 100644 typescript/diff_match_patch.ts create mode 100644 typescript/tests/diff_match_patch_test.ts create mode 100644 typescript/tests/speedtest.ts create mode 100644 typescript/tests/tsconfig.json create mode 100644 typescript/tsconfig.json diff --git a/.gitignore b/.gitignore index 41779de..34fcf30 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,5 @@ xcuserdata dart/tests/Speedtest.dart.js.deps dart/tests/Speedtest.dart.js.map + +typescript/tests/built \ No newline at end of file diff --git a/AUTHORS b/AUTHORS index c82809e..5fa1b79 100644 --- a/AUTHORS +++ b/AUTHORS @@ -7,4 +7,5 @@ Duncan Cross (Lua port) Jan Weiß (Objective C port) Matthaeus G. Chajdas (C# port) Mike Slemmer (C++ port) +Sam El-Husseini (TypeScript port) diff --git a/typescript/diff_match_patch.d.ts b/typescript/diff_match_patch.d.ts new file mode 100644 index 0000000..610cf7e --- /dev/null +++ b/typescript/diff_match_patch.d.ts @@ -0,0 +1,66 @@ +export default class diff_match_patch { + Diff_Timeout: number; + Diff_EditCost: number; + Match_Threshold: number; + Match_Distance: number; + Patch_DeleteThreshold: number; + Patch_Margin: number; + Match_MaxBits: number; + constructor(); + diff_main(text1: string, text2: string, opt_checklines?: boolean, opt_deadline?: number): Diff[]; + private diff_compute_; + private diff_lineMode_; + private diff_bisect_; + private diff_bisectSplit_; + private diff_linesToChars_; + private diff_charsToLines_; + diff_commonPrefix(text1: string, text2: string): number; + diff_commonSuffix(text1: string, text2: string): number; + private diff_commonOverlap_; + private diff_halfMatch_; + diff_cleanupSemantic(diffs: Diff[]): void; + diff_cleanupSemanticLossless(diffs: Diff[]): void; + private static nonAlphaNumericRegex_; + private static whitespaceRegex_; + private static linebreakRegex_; + private static blanklineEndRegex_; + private static blanklineStartRegex_; + diff_cleanupEfficiency(diffs: Diff[]): void; + diff_cleanupMerge(diffs: Diff[]): void; + diff_xIndex(diffs: Diff[], loc: number): number; + diff_prettyHtml(diffs: Diff[]): string; + diff_text1(diffs: Diff[]): string; + diff_text2(diffs: Diff[]): string; + diff_levenshtein(diffs: Diff[]): number; + diff_toDelta(diffs: Diff[]): string; + diff_fromDelta(text1: string, delta: string): Diff[]; + match_main(text: string, pattern: string, loc: number): number; + private match_bitap_; + private match_alphabet_; + private patch_addContext_; + patch_make(a: string | Diff[], opt_b?: string | Diff[], opt_c?: string | Diff[]): patch_obj[]; + patch_deepCopy(patches: patch_obj[]): patch_obj[]; + patch_apply(patches: patch_obj[], text: string): (string | boolean[])[]; + patch_addPadding(patches: patch_obj[]): string; + patch_splitMax(patches: patch_obj[]): void; + patch_toText(patches: patch_obj[]): string; + patch_fromText(textline: string): patch_obj[]; +} +export declare const DIFF_DELETE = -1; +export declare const DIFF_INSERT = 1; +export declare const DIFF_EQUAL = 0; +export declare class Diff { + operation: number; + text: string; + constructor(op: number, text: string); + toString(): string; +} +export declare class patch_obj { + diffs: Diff[]; + start1: number | null; + start2: number | null; + length1: number; + length2: number; + constructor(); + toString(): string; +} diff --git a/typescript/diff_match_patch.js b/typescript/diff_match_patch.js new file mode 100644 index 0000000..3c08d2d --- /dev/null +++ b/typescript/diff_match_patch.js @@ -0,0 +1,1569 @@ +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } +})(function (require, exports) { + "use strict"; + exports.__esModule = true; + var diff_match_patch = (function () { + function diff_match_patch() { + this.Diff_Timeout = 1.0; + this.Diff_EditCost = 4; + this.Match_Threshold = 0.5; + this.Match_Distance = 1000; + this.Patch_DeleteThreshold = 0.5; + this.Patch_Margin = 4; + this.Match_MaxBits = 32; + } + diff_match_patch.prototype.diff_main = function (text1, text2, opt_checklines, opt_deadline) { + if (typeof opt_deadline == 'undefined') { + if (this.Diff_Timeout <= 0) { + opt_deadline = Number.MAX_VALUE; + } + else { + opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000; + } + } + var deadline = opt_deadline; + if (text1 == null || text2 == null) { + throw new Error('Null input. (diff_main)'); + } + if (text1 == text2) { + if (text1) { + return [new Diff(exports.DIFF_EQUAL, text1)]; + } + return []; + } + if (typeof opt_checklines == 'undefined') { + opt_checklines = true; + } + var checklines = opt_checklines; + var commonlength = this.diff_commonPrefix(text1, text2); + var commonprefix = text1.substring(0, commonlength); + text1 = text1.substring(commonlength); + text2 = text2.substring(commonlength); + commonlength = this.diff_commonSuffix(text1, text2); + var commonsuffix = text1.substring(text1.length - commonlength); + text1 = text1.substring(0, text1.length - commonlength); + text2 = text2.substring(0, text2.length - commonlength); + var diffs = this.diff_compute_(text1, text2, checklines, deadline); + if (commonprefix) { + diffs.unshift(new Diff(exports.DIFF_EQUAL, commonprefix)); + } + if (commonsuffix) { + diffs.push(new Diff(exports.DIFF_EQUAL, commonsuffix)); + } + this.diff_cleanupMerge(diffs); + return diffs; + }; + ; + diff_match_patch.prototype.diff_compute_ = function (text1, text2, checklines, deadline) { + var diffs; + if (!text1) { + return [new Diff(exports.DIFF_INSERT, text2)]; + } + if (!text2) { + return [new Diff(exports.DIFF_DELETE, text1)]; + } + var longtext = text1.length > text2.length ? text1 : text2; + var shorttext = text1.length > text2.length ? text2 : text1; + var i = longtext.indexOf(shorttext); + if (i != -1) { + diffs = [new Diff(exports.DIFF_INSERT, longtext.substring(0, i)), + new Diff(exports.DIFF_EQUAL, shorttext), + new Diff(exports.DIFF_INSERT, longtext.substring(i + shorttext.length))]; + if (text1.length > text2.length) { + diffs[0].operation = diffs[2].operation = exports.DIFF_DELETE; + } + return diffs; + } + if (shorttext.length == 1) { + return [new Diff(exports.DIFF_DELETE, text1), + new Diff(exports.DIFF_INSERT, text2)]; + } + var hm = this.diff_halfMatch_(text1, text2); + if (hm) { + var text1_a = hm[0]; + var text1_b = hm[1]; + var text2_a = hm[2]; + var text2_b = hm[3]; + var mid_common = hm[4]; + var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); + var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); + return diffs_a.concat([new Diff(exports.DIFF_EQUAL, mid_common)], diffs_b); + } + if (checklines && text1.length > 100 && text2.length > 100) { + return this.diff_lineMode_(text1, text2, deadline); + } + return this.diff_bisect_(text1, text2, deadline); + }; + ; + diff_match_patch.prototype.diff_lineMode_ = function (text1, text2, deadline) { + var a = this.diff_linesToChars_(text1, text2); + text1 = a.chars1; + text2 = a.chars2; + var linearray = a.lineArray; + var diffs = this.diff_main(text1, text2, false, deadline); + this.diff_charsToLines_(diffs, linearray); + this.diff_cleanupSemantic(diffs); + diffs.push(new Diff(exports.DIFF_EQUAL, '')); + var pointer = 0; + var count_delete = 0; + var count_insert = 0; + var text_delete = ''; + var text_insert = ''; + while (pointer < diffs.length) { + switch (diffs[pointer].operation) { + case exports.DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer].text; + break; + case exports.DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer].text; + break; + case exports.DIFF_EQUAL: + if (count_delete >= 1 && count_insert >= 1) { + diffs.splice(pointer - count_delete - count_insert, count_delete + count_insert); + pointer = pointer - count_delete - count_insert; + var subDiff = this.diff_main(text_delete, text_insert, false, deadline); + for (var j = subDiff.length - 1; j >= 0; j--) { + diffs.splice(pointer, 0, subDiff[j]); + } + pointer = pointer + subDiff.length; + } + count_insert = 0; + count_delete = 0; + text_delete = ''; + text_insert = ''; + break; + } + pointer++; + } + diffs.pop(); + return diffs; + }; + ; + diff_match_patch.prototype.diff_bisect_ = function (text1, text2, deadline) { + var text1_length = text1.length; + var text2_length = text2.length; + var max_d = Math.ceil((text1_length + text2_length) / 2); + var v_offset = max_d; + var v_length = 2 * max_d; + var v1 = new Array(v_length); + var v2 = new Array(v_length); + for (var x = 0; x < v_length; x++) { + v1[x] = -1; + v2[x] = -1; + } + v1[v_offset + 1] = 0; + v2[v_offset + 1] = 0; + var delta = text1_length - text2_length; + var front = (delta % 2 != 0); + var k1start = 0; + var k1end = 0; + var k2start = 0; + var k2end = 0; + for (var d = 0; d < max_d; d++) { + if ((new Date()).getTime() > deadline) { + break; + } + for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { + var k1_offset = v_offset + k1; + var x1; + if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) { + x1 = v1[k1_offset + 1]; + } + else { + x1 = v1[k1_offset - 1] + 1; + } + var y1 = x1 - k1; + while (x1 < text1_length && y1 < text2_length && + text1.charAt(x1) == text2.charAt(y1)) { + x1++; + y1++; + } + v1[k1_offset] = x1; + if (x1 > text1_length) { + k1end += 2; + } + else if (y1 > text2_length) { + k1start += 2; + } + else if (front) { + var k2_offset = v_offset + delta - k1; + if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { + var x2 = text1_length - v2[k2_offset]; + if (x1 >= x2) { + return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); + } + } + } + } + for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { + var k2_offset = v_offset + k2; + var x2; + if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) { + x2 = v2[k2_offset + 1]; + } + else { + x2 = v2[k2_offset - 1] + 1; + } + var y2 = x2 - k2; + while (x2 < text1_length && y2 < text2_length && + text1.charAt(text1_length - x2 - 1) == + text2.charAt(text2_length - y2 - 1)) { + x2++; + y2++; + } + v2[k2_offset] = x2; + if (x2 > text1_length) { + k2end += 2; + } + else if (y2 > text2_length) { + k2start += 2; + } + else if (!front) { + var k1_offset = v_offset + delta - k2; + if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { + var x1 = v1[k1_offset]; + var y1 = v_offset + x1 - k1_offset; + x2 = text1_length - x2; + if (x1 >= x2) { + return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); + } + } + } + } + } + return [new Diff(exports.DIFF_DELETE, text1), + new Diff(exports.DIFF_INSERT, text2)]; + }; + ; + diff_match_patch.prototype.diff_bisectSplit_ = function (text1, text2, x, y, deadline) { + var text1a = text1.substring(0, x); + var text2a = text2.substring(0, y); + var text1b = text1.substring(x); + var text2b = text2.substring(y); + var diffs = this.diff_main(text1a, text2a, false, deadline); + var diffsb = this.diff_main(text1b, text2b, false, deadline); + return diffs.concat(diffsb); + }; + ; + diff_match_patch.prototype.diff_linesToChars_ = function (text1, text2) { + var lineArray = []; + var lineHash = {}; + lineArray[0] = ''; + function diff_linesToCharsMunge_(text) { + var chars = ''; + var lineStart = 0; + var lineEnd = -1; + var lineArrayLength = lineArray.length; + while (lineEnd < text.length - 1) { + lineEnd = text.indexOf('\n', lineStart); + if (lineEnd == -1) { + lineEnd = text.length - 1; + } + var line = text.substring(lineStart, lineEnd + 1); + if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : + (lineHash[line] !== undefined)) { + chars += String.fromCharCode(lineHash[line]); + } + else { + if (lineArrayLength == maxLines) { + line = text.substring(lineStart); + lineEnd = text.length; + } + chars += String.fromCharCode(lineArrayLength); + lineHash[line] = lineArrayLength; + lineArray[lineArrayLength++] = line; + } + lineStart = lineEnd + 1; + } + return chars; + } + var maxLines = 40000; + var chars1 = diff_linesToCharsMunge_(text1); + maxLines = 65535; + var chars2 = diff_linesToCharsMunge_(text2); + return { chars1: chars1, chars2: chars2, lineArray: lineArray }; + }; + ; + diff_match_patch.prototype.diff_charsToLines_ = function (diffs, lineArray) { + for (var i = 0; i < diffs.length; i++) { + var chars = diffs[i].text; + var text = []; + for (var j = 0; j < chars.length; j++) { + text[j] = lineArray[chars.charCodeAt(j)]; + } + diffs[i].text = text.join(''); + } + }; + ; + diff_match_patch.prototype.diff_commonPrefix = function (text1, text2) { + if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { + return 0; + } + var pointermin = 0; + var pointermax = Math.min(text1.length, text2.length); + var pointermid = pointermax; + var pointerstart = 0; + while (pointermin < pointermid) { + if (text1.substring(pointerstart, pointermid) == + text2.substring(pointerstart, pointermid)) { + pointermin = pointermid; + pointerstart = pointermin; + } + else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; + }; + ; + diff_match_patch.prototype.diff_commonSuffix = function (text1, text2) { + if (!text1 || !text2 || + text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { + return 0; + } + var pointermin = 0; + var pointermax = Math.min(text1.length, text2.length); + var pointermid = pointermax; + var pointerend = 0; + while (pointermin < pointermid) { + if (text1.substring(text1.length - pointermid, text1.length - pointerend) == + text2.substring(text2.length - pointermid, text2.length - pointerend)) { + pointermin = pointermid; + pointerend = pointermin; + } + else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; + }; + ; + diff_match_patch.prototype.diff_commonOverlap_ = function (text1, text2) { + var text1_length = text1.length; + var text2_length = text2.length; + if (text1_length == 0 || text2_length == 0) { + return 0; + } + if (text1_length > text2_length) { + text1 = text1.substring(text1_length - text2_length); + } + else if (text1_length < text2_length) { + text2 = text2.substring(0, text1_length); + } + var text_length = Math.min(text1_length, text2_length); + if (text1 == text2) { + return text_length; + } + var best = 0; + var length = 1; + while (true) { + var pattern = text1.substring(text_length - length); + var found = text2.indexOf(pattern); + if (found == -1) { + return best; + } + length += found; + if (found == 0 || text1.substring(text_length - length) == + text2.substring(0, length)) { + best = length; + length++; + } + } + }; + ; + diff_match_patch.prototype.diff_halfMatch_ = function (text1, text2) { + if (this.Diff_Timeout <= 0) { + return null; + } + var longtext = text1.length > text2.length ? text1 : text2; + var shorttext = text1.length > text2.length ? text2 : text1; + if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { + return null; + } + var dmp = this; + function diff_halfMatchI_(longtext, shorttext, i) { + var seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); + var j = -1; + var best_common = ''; + var best_longtext_a = ''; + var best_longtext_b = ''; + var best_shorttext_a = ''; + var best_shorttext_b = ''; + while ((j = shorttext.indexOf(seed, j + 1)) != -1) { + var prefixLength = dmp.diff_commonPrefix(longtext.substring(i), shorttext.substring(j)); + var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); + if (best_common.length < suffixLength + prefixLength) { + best_common = shorttext.substring(j - suffixLength, j) + + shorttext.substring(j, j + prefixLength); + best_longtext_a = longtext.substring(0, i - suffixLength); + best_longtext_b = longtext.substring(i + prefixLength); + best_shorttext_a = shorttext.substring(0, j - suffixLength); + best_shorttext_b = shorttext.substring(j + prefixLength); + } + } + if (best_common.length * 2 >= longtext.length) { + return [best_longtext_a, best_longtext_b, + best_shorttext_a, best_shorttext_b, best_common]; + } + else { + return null; + } + } + var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); + var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); + var hm; + if (!hm1 && !hm2) { + return null; + } + else if (!hm2) { + hm = hm1; + } + else if (!hm1) { + hm = hm2; + } + else { + hm = hm1[4].length > hm2[4].length ? hm1 : hm2; + } + var text1_a, text1_b, text2_a, text2_b; + if (text1.length > text2.length) { + text1_a = hm[0]; + text1_b = hm[1]; + text2_a = hm[2]; + text2_b = hm[3]; + } + else { + text2_a = hm[0]; + text2_b = hm[1]; + text1_a = hm[2]; + text1_b = hm[3]; + } + var mid_common = hm[4]; + return [text1_a, text1_b, text2_a, text2_b, mid_common]; + }; + ; + diff_match_patch.prototype.diff_cleanupSemantic = function (diffs) { + var changes = false; + var equalities = []; + var equalitiesLength = 0; + var lastEquality = null; + var pointer = 0; + var length_insertions1 = 0; + var length_deletions1 = 0; + var length_insertions2 = 0; + var length_deletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer].operation == exports.DIFF_EQUAL) { + equalities[equalitiesLength++] = pointer; + length_insertions1 = length_insertions2; + length_deletions1 = length_deletions2; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = diffs[pointer].text; + } + else { + if (diffs[pointer].operation == exports.DIFF_INSERT) { + length_insertions2 += diffs[pointer].text.length; + } + else { + length_deletions2 += diffs[pointer].text.length; + } + if (lastEquality && (lastEquality.length <= + Math.max(length_insertions1, length_deletions1)) && + (lastEquality.length <= Math.max(length_insertions2, length_deletions2))) { + diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(exports.DIFF_DELETE, lastEquality)); + diffs[equalities[equalitiesLength - 1] + 1].operation = exports.DIFF_INSERT; + equalitiesLength--; + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + length_insertions1 = 0; + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes = true; + } + } + pointer++; + } + if (changes) { + this.diff_cleanupMerge(diffs); + } + this.diff_cleanupSemanticLossless(diffs); + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1].operation == exports.DIFF_DELETE && + diffs[pointer].operation == exports.DIFF_INSERT) { + var deletion = diffs[pointer - 1].text; + var insertion = diffs[pointer].text; + var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); + var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); + if (overlap_length1 >= overlap_length2) { + if (overlap_length1 >= deletion.length / 2 || + overlap_length1 >= insertion.length / 2) { + diffs.splice(pointer, 0, new Diff(exports.DIFF_EQUAL, insertion.substring(0, overlap_length1))); + diffs[pointer - 1].text = + deletion.substring(0, deletion.length - overlap_length1); + diffs[pointer + 1].text = insertion.substring(overlap_length1); + pointer++; + } + } + else { + if (overlap_length2 >= deletion.length / 2 || + overlap_length2 >= insertion.length / 2) { + diffs.splice(pointer, 0, new Diff(exports.DIFF_EQUAL, deletion.substring(0, overlap_length2))); + diffs[pointer - 1].operation = exports.DIFF_INSERT; + diffs[pointer - 1].text = + insertion.substring(0, insertion.length - overlap_length2); + diffs[pointer + 1].operation = exports.DIFF_DELETE; + diffs[pointer + 1].text = + deletion.substring(overlap_length2); + pointer++; + } + } + pointer++; + } + pointer++; + } + }; + ; + diff_match_patch.prototype.diff_cleanupSemanticLossless = function (diffs) { + function diff_cleanupSemanticScore_(one, two) { + if (!one || !two) { + return 6; + } + var char1 = one.charAt(one.length - 1); + var char2 = two.charAt(0); + var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_); + var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_); + var whitespace1 = nonAlphaNumeric1 && + char1.match(diff_match_patch.whitespaceRegex_); + var whitespace2 = nonAlphaNumeric2 && + char2.match(diff_match_patch.whitespaceRegex_); + var lineBreak1 = whitespace1 && + char1.match(diff_match_patch.linebreakRegex_); + var lineBreak2 = whitespace2 && + char2.match(diff_match_patch.linebreakRegex_); + var blankLine1 = lineBreak1 && + one.match(diff_match_patch.blanklineEndRegex_); + var blankLine2 = lineBreak2 && + two.match(diff_match_patch.blanklineStartRegex_); + if (blankLine1 || blankLine2) { + return 5; + } + else if (lineBreak1 || lineBreak2) { + return 4; + } + else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { + return 3; + } + else if (whitespace1 || whitespace2) { + return 2; + } + else if (nonAlphaNumeric1 || nonAlphaNumeric2) { + return 1; + } + return 0; + } + var pointer = 1; + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1].operation == exports.DIFF_EQUAL && + diffs[pointer + 1].operation == exports.DIFF_EQUAL) { + var equality1 = diffs[pointer - 1].text; + var edit = diffs[pointer].text; + var equality2 = diffs[pointer + 1].text; + var commonOffset = this.diff_commonSuffix(equality1, edit); + if (commonOffset) { + var commonString = edit.substring(edit.length - commonOffset); + equality1 = equality1.substring(0, equality1.length - commonOffset); + edit = commonString + edit.substring(0, edit.length - commonOffset); + equality2 = commonString + equality2; + } + var bestEquality1 = equality1; + var bestEdit = edit; + var bestEquality2 = equality2; + var bestScore = diff_cleanupSemanticScore_(equality1, edit) + + diff_cleanupSemanticScore_(edit, equality2); + while (edit.charAt(0) === equality2.charAt(0)) { + equality1 += edit.charAt(0); + edit = edit.substring(1) + equality2.charAt(0); + equality2 = equality2.substring(1); + var score = diff_cleanupSemanticScore_(equality1, edit) + + diff_cleanupSemanticScore_(edit, equality2); + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + if (diffs[pointer - 1].text != bestEquality1) { + if (bestEquality1) { + diffs[pointer - 1].text = bestEquality1; + } + else { + diffs.splice(pointer - 1, 1); + pointer--; + } + diffs[pointer].text = bestEdit; + if (bestEquality2) { + diffs[pointer + 1].text = bestEquality2; + } + else { + diffs.splice(pointer + 1, 1); + pointer--; + } + } + } + pointer++; + } + }; + ; + diff_match_patch.prototype.diff_cleanupEfficiency = function (diffs) { + var changes = false; + var equalities = []; + var equalitiesLength = 0; + var lastEquality = null; + var pointer = 0; + var pre_ins = 0; + var pre_del = 0; + var post_ins = 0; + var post_del = 0; + while (pointer < diffs.length) { + if (diffs[pointer].operation == exports.DIFF_EQUAL) { + if (diffs[pointer].text.length < this.Diff_EditCost && + (post_ins || post_del)) { + equalities[equalitiesLength++] = pointer; + pre_ins = post_ins; + pre_del = post_del; + lastEquality = diffs[pointer].text; + } + else { + equalitiesLength = 0; + lastEquality = null; + } + post_ins = post_del = 0; + } + else { + if (diffs[pointer].operation == exports.DIFF_DELETE) { + post_del = 1; + } + else { + post_ins = 1; + } + if (lastEquality && ((pre_ins && pre_del && post_ins && post_del) || + ((lastEquality.length < this.Diff_EditCost / 2) && + (pre_ins + pre_del + post_ins + post_del) == 3))) { + diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(exports.DIFF_DELETE, lastEquality)); + diffs[equalities[equalitiesLength - 1] + 1].operation = exports.DIFF_INSERT; + equalitiesLength--; + lastEquality = null; + if (pre_ins && pre_del) { + post_ins = post_del = 1; + equalitiesLength = 0; + } + else { + equalitiesLength--; + pointer = equalitiesLength > 0 ? + equalities[equalitiesLength - 1] : -1; + post_ins = post_del = 0; + } + changes = true; + } + } + pointer++; + } + if (changes) { + this.diff_cleanupMerge(diffs); + } + }; + ; + diff_match_patch.prototype.diff_cleanupMerge = function (diffs) { + diffs.push(new Diff(exports.DIFF_EQUAL, '')); + var pointer = 0; + var count_delete = 0; + var count_insert = 0; + var text_delete = ''; + var text_insert = ''; + var commonlength; + while (pointer < diffs.length) { + switch (diffs[pointer].operation) { + case exports.DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer].text; + pointer++; + break; + case exports.DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer].text; + pointer++; + break; + case exports.DIFF_EQUAL: + if (count_delete + count_insert > 1) { + if (count_delete !== 0 && count_insert !== 0) { + commonlength = this.diff_commonPrefix(text_insert, text_delete); + if (commonlength !== 0) { + if ((pointer - count_delete - count_insert) > 0 && + diffs[pointer - count_delete - count_insert - 1].operation == + exports.DIFF_EQUAL) { + diffs[pointer - count_delete - count_insert - 1].text += + text_insert.substring(0, commonlength); + } + else { + diffs.splice(0, 0, new Diff(exports.DIFF_EQUAL, text_insert.substring(0, commonlength))); + pointer++; + } + text_insert = text_insert.substring(commonlength); + text_delete = text_delete.substring(commonlength); + } + commonlength = this.diff_commonSuffix(text_insert, text_delete); + if (commonlength !== 0) { + diffs[pointer].text = text_insert.substring(text_insert.length - + commonlength) + diffs[pointer].text; + text_insert = text_insert.substring(0, text_insert.length - + commonlength); + text_delete = text_delete.substring(0, text_delete.length - + commonlength); + } + } + pointer -= count_delete + count_insert; + diffs.splice(pointer, count_delete + count_insert); + if (text_delete.length) { + diffs.splice(pointer, 0, new Diff(exports.DIFF_DELETE, text_delete)); + pointer++; + } + if (text_insert.length) { + diffs.splice(pointer, 0, new Diff(exports.DIFF_INSERT, text_insert)); + pointer++; + } + pointer++; + } + else if (pointer !== 0 && diffs[pointer - 1].operation == exports.DIFF_EQUAL) { + diffs[pointer - 1].text += diffs[pointer].text; + diffs.splice(pointer, 1); + } + else { + pointer++; + } + count_insert = 0; + count_delete = 0; + text_delete = ''; + text_insert = ''; + break; + } + } + if (diffs[diffs.length - 1].text === '') { + diffs.pop(); + } + var changes = false; + pointer = 1; + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1].operation == exports.DIFF_EQUAL && + diffs[pointer + 1].operation == exports.DIFF_EQUAL) { + if (diffs[pointer].text.substring(diffs[pointer].text.length - + diffs[pointer - 1].text.length) == diffs[pointer - 1].text) { + diffs[pointer].text = diffs[pointer - 1].text + + diffs[pointer].text.substring(0, diffs[pointer].text.length - + diffs[pointer - 1].text.length); + diffs[pointer + 1].text = diffs[pointer - 1].text + diffs[pointer + 1].text; + diffs.splice(pointer - 1, 1); + changes = true; + } + else if (diffs[pointer].text.substring(0, diffs[pointer + 1].text.length) == + diffs[pointer + 1].text) { + diffs[pointer - 1].text += diffs[pointer + 1].text; + diffs[pointer].text = + diffs[pointer].text.substring(diffs[pointer + 1].text.length) + + diffs[pointer + 1].text; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + pointer++; + } + if (changes) { + this.diff_cleanupMerge(diffs); + } + }; + ; + diff_match_patch.prototype.diff_xIndex = function (diffs, loc) { + var chars1 = 0; + var chars2 = 0; + var last_chars1 = 0; + var last_chars2 = 0; + var x; + for (x = 0; x < diffs.length; x++) { + if (diffs[x].operation !== exports.DIFF_INSERT) { + chars1 += diffs[x].text.length; + } + if (diffs[x].operation !== exports.DIFF_DELETE) { + chars2 += diffs[x].text.length; + } + if (chars1 > loc) { + break; + } + last_chars1 = chars1; + last_chars2 = chars2; + } + if (diffs.length != x && diffs[x].operation === exports.DIFF_DELETE) { + return last_chars2; + } + return last_chars2 + (loc - last_chars1); + }; + ; + diff_match_patch.prototype.diff_prettyHtml = function (diffs) { + var html = []; + var pattern_amp = /&/g; + var pattern_lt = //g; + var pattern_para = /\n/g; + for (var x = 0; x < diffs.length; x++) { + var op = diffs[x].operation; + var data = diffs[x].text; + var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<') + .replace(pattern_gt, '>').replace(pattern_para, '¶
'); + switch (op) { + case exports.DIFF_INSERT: + html[x] = '' + text + ''; + break; + case exports.DIFF_DELETE: + html[x] = '' + text + ''; + break; + case exports.DIFF_EQUAL: + html[x] = '' + text + ''; + break; + } + } + return html.join(''); + }; + ; + diff_match_patch.prototype.diff_text1 = function (diffs) { + var text = []; + for (var x = 0; x < diffs.length; x++) { + if (diffs[x].operation !== exports.DIFF_INSERT) { + text[x] = diffs[x].text; + } + } + return text.join(''); + }; + ; + diff_match_patch.prototype.diff_text2 = function (diffs) { + var text = []; + for (var x = 0; x < diffs.length; x++) { + if (diffs[x].operation !== exports.DIFF_DELETE) { + text[x] = diffs[x].text; + } + } + return text.join(''); + }; + ; + diff_match_patch.prototype.diff_levenshtein = function (diffs) { + var levenshtein = 0; + var insertions = 0; + var deletions = 0; + for (var x = 0; x < diffs.length; x++) { + var op = diffs[x].operation; + var data = diffs[x].text; + switch (op) { + case exports.DIFF_INSERT: + insertions += data.length; + break; + case exports.DIFF_DELETE: + deletions += data.length; + break; + case exports.DIFF_EQUAL: + levenshtein += Math.max(insertions, deletions); + insertions = 0; + deletions = 0; + break; + } + } + levenshtein += Math.max(insertions, deletions); + return levenshtein; + }; + ; + diff_match_patch.prototype.diff_toDelta = function (diffs) { + var text = []; + for (var x = 0; x < diffs.length; x++) { + switch (diffs[x].operation) { + case exports.DIFF_INSERT: + text[x] = '+' + encodeURI(diffs[x].text); + break; + case exports.DIFF_DELETE: + text[x] = '-' + diffs[x].text.length; + break; + case exports.DIFF_EQUAL: + text[x] = '=' + diffs[x].text.length; + break; + } + } + return text.join('\t').replace(/%20/g, ' '); + }; + ; + diff_match_patch.prototype.diff_fromDelta = function (text1, delta) { + var diffs = []; + var diffsLength = 0; + var pointer = 0; + var tokens = delta.split(/\t/g); + for (var x = 0; x < tokens.length; x++) { + var param = tokens[x].substring(1); + switch (tokens[x].charAt(0)) { + case '+': + try { + diffs[diffsLength++] = + new Diff(exports.DIFF_INSERT, decodeURI(param)); + } + catch (ex) { + throw new Error('Illegal escape in diff_fromDelta: ' + param); + } + break; + case '-': + case '=': + var n = parseInt(param, 10); + if (isNaN(n) || n < 0) { + throw new Error('Invalid number in diff_fromDelta: ' + param); + } + var text = text1.substring(pointer, pointer += n); + if (tokens[x].charAt(0) == '=') { + diffs[diffsLength++] = new Diff(exports.DIFF_EQUAL, text); + } + else { + diffs[diffsLength++] = new Diff(exports.DIFF_DELETE, text); + } + break; + default: + if (tokens[x]) { + throw new Error('Invalid diff operation in diff_fromDelta: ' + + tokens[x]); + } + } + } + if (pointer != text1.length) { + throw new Error('Delta length (' + pointer + + ') does not equal source text length (' + text1.length + ').'); + } + return diffs; + }; + ; + diff_match_patch.prototype.match_main = function (text, pattern, loc) { + if (text == null || pattern == null || loc == null) { + throw new Error('Null input. (match_main)'); + } + loc = Math.max(0, Math.min(loc, text.length)); + if (text == pattern) { + return 0; + } + else if (!text.length) { + return -1; + } + else if (text.substring(loc, loc + pattern.length) == pattern) { + return loc; + } + else { + return this.match_bitap_(text, pattern, loc); + } + }; + ; + diff_match_patch.prototype.match_bitap_ = function (text, pattern, loc) { + if (pattern.length > this.Match_MaxBits) { + throw new Error('Pattern too long for this browser.'); + } + var s = this.match_alphabet_(pattern); + var dmp = this; + function match_bitapScore_(e, x) { + var accuracy = e / pattern.length; + var proximity = Math.abs(loc - x); + if (!dmp.Match_Distance) { + return proximity ? 1.0 : accuracy; + } + return accuracy + (proximity / dmp.Match_Distance); + } + var score_threshold = this.Match_Threshold; + var best_loc = text.indexOf(pattern, loc); + if (best_loc != -1) { + score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); + best_loc = text.lastIndexOf(pattern, loc + pattern.length); + if (best_loc != -1) { + score_threshold = + Math.min(match_bitapScore_(0, best_loc), score_threshold); + } + } + var matchmask = 1 << (pattern.length - 1); + best_loc = -1; + var bin_min, bin_mid; + var bin_max = pattern.length + text.length; + var last_rd = []; + for (var d = 0; d < pattern.length; d++) { + bin_min = 0; + bin_mid = bin_max; + while (bin_min < bin_mid) { + if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { + bin_min = bin_mid; + } + else { + bin_max = bin_mid; + } + bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); + } + bin_max = bin_mid; + var start = Math.max(1, loc - bin_mid + 1); + var finish = Math.min(loc + bin_mid, text.length) + pattern.length; + var rd = Array(finish + 2); + rd[finish + 1] = (1 << d) - 1; + for (var j = finish; j >= start; j--) { + var charMatch = s[text.charAt(j - 1)]; + if (d === 0) { + rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; + } + else { + rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | + (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | + last_rd[j + 1]; + } + if (rd[j] & matchmask) { + var score = match_bitapScore_(d, j - 1); + if (score <= score_threshold) { + score_threshold = score; + best_loc = j - 1; + if (best_loc > loc) { + start = Math.max(1, 2 * loc - best_loc); + } + else { + break; + } + } + } + } + if (match_bitapScore_(d + 1, loc) > score_threshold) { + break; + } + last_rd = rd; + } + return best_loc; + }; + ; + diff_match_patch.prototype.match_alphabet_ = function (pattern) { + var s = {}; + for (var i = 0; i < pattern.length; i++) { + s[pattern.charAt(i)] = 0; + } + for (var i = 0; i < pattern.length; i++) { + s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1); + } + return s; + }; + ; + diff_match_patch.prototype.patch_addContext_ = function (patch, text) { + if (text.length == 0) { + return; + } + if (patch.start2 === null) { + throw Error('patch not initialized'); + } + var pattern = text.substring(patch.start2, patch.start2 + patch.length1); + var padding = 0; + while (text.indexOf(pattern) != text.lastIndexOf(pattern) && + pattern.length < this.Match_MaxBits - this.Patch_Margin - + this.Patch_Margin) { + padding += this.Patch_Margin; + pattern = text.substring(patch.start2 - padding, patch.start2 + patch.length1 + padding); + } + padding += this.Patch_Margin; + var prefix = text.substring(patch.start2 - padding, patch.start2); + if (prefix) { + patch.diffs.unshift(new Diff(exports.DIFF_EQUAL, prefix)); + } + var suffix = text.substring(patch.start2 + patch.length1, patch.start2 + patch.length1 + padding); + if (suffix) { + patch.diffs.push(new Diff(exports.DIFF_EQUAL, suffix)); + } + patch.start1 -= prefix.length; + patch.start2 -= prefix.length; + patch.length1 += prefix.length + suffix.length; + patch.length2 += prefix.length + suffix.length; + }; + ; + diff_match_patch.prototype.patch_make = function (a, opt_b, opt_c) { + var text1, diffs; + if (typeof a == 'string' && typeof opt_b == 'string' && + typeof opt_c == 'undefined') { + text1 = (a); + diffs = this.diff_main(text1, (opt_b), true); + if (diffs.length > 2) { + this.diff_cleanupSemantic(diffs); + this.diff_cleanupEfficiency(diffs); + } + } + else if (a && typeof a == 'object' && typeof opt_b == 'undefined' && + typeof opt_c == 'undefined') { + diffs = (a); + text1 = this.diff_text1(diffs); + } + else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' && + typeof opt_c == 'undefined') { + text1 = (a); + diffs = (opt_b); + } + else if (typeof a == 'string' && typeof opt_b == 'string' && + opt_c && typeof opt_c == 'object') { + text1 = (a); + diffs = (opt_c); + } + else { + throw new Error('Unknown call format to patch_make.'); + } + if (diffs.length === 0) { + return []; + } + var patches = []; + var patch = new patch_obj(); + var patchDiffLength = 0; + var char_count1 = 0; + var char_count2 = 0; + var prepatch_text = text1; + var postpatch_text = text1; + for (var x = 0; x < diffs.length; x++) { + var diff_type = diffs[x].operation; + var diff_text = diffs[x].text; + if (!patchDiffLength && diff_type !== exports.DIFF_EQUAL) { + patch.start1 = char_count1; + patch.start2 = char_count2; + } + switch (diff_type) { + case exports.DIFF_INSERT: + patch.diffs[patchDiffLength++] = diffs[x]; + patch.length2 += diff_text.length; + postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + + postpatch_text.substring(char_count2); + break; + case exports.DIFF_DELETE: + patch.length1 += diff_text.length; + patch.diffs[patchDiffLength++] = diffs[x]; + postpatch_text = postpatch_text.substring(0, char_count2) + + postpatch_text.substring(char_count2 + + diff_text.length); + break; + case exports.DIFF_EQUAL: + if (diff_text.length <= 2 * this.Patch_Margin && + patchDiffLength && diffs.length != x + 1) { + patch.diffs[patchDiffLength++] = diffs[x]; + patch.length1 += diff_text.length; + patch.length2 += diff_text.length; + } + else if (diff_text.length >= 2 * this.Patch_Margin) { + if (patchDiffLength) { + this.patch_addContext_(patch, prepatch_text); + patches.push(patch); + patch = new patch_obj(); + patchDiffLength = 0; + prepatch_text = postpatch_text; + char_count1 = char_count2; + } + } + break; + } + if (diff_type !== exports.DIFF_INSERT) { + char_count1 += diff_text.length; + } + if (diff_type !== exports.DIFF_DELETE) { + char_count2 += diff_text.length; + } + } + if (patchDiffLength) { + this.patch_addContext_(patch, prepatch_text); + patches.push(patch); + } + return patches; + }; + ; + diff_match_patch.prototype.patch_deepCopy = function (patches) { + var patchesCopy = []; + for (var x = 0; x < patches.length; x++) { + var patch = patches[x]; + var patchCopy = new patch_obj(); + patchCopy.diffs = []; + for (var y = 0; y < patch.diffs.length; y++) { + patchCopy.diffs[y] = + new Diff(patch.diffs[y].operation, patch.diffs[y].text); + } + patchCopy.start1 = patch.start1; + patchCopy.start2 = patch.start2; + patchCopy.length1 = patch.length1; + patchCopy.length2 = patch.length2; + patchesCopy[x] = patchCopy; + } + return patchesCopy; + }; + ; + diff_match_patch.prototype.patch_apply = function (patches, text) { + if (patches.length == 0) { + return [text, []]; + } + patches = this.patch_deepCopy(patches); + var nullPadding = this.patch_addPadding(patches); + text = nullPadding + text + nullPadding; + this.patch_splitMax(patches); + var delta = 0; + var results = []; + for (var x = 0; x < patches.length; x++) { + var expected_loc = patches[x].start2 + delta; + var text1 = this.diff_text1(patches[x].diffs); + var start_loc; + var end_loc = -1; + if (text1.length > this.Match_MaxBits) { + start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits), expected_loc); + if (start_loc != -1) { + end_loc = this.match_main(text, text1.substring(text1.length - this.Match_MaxBits), expected_loc + text1.length - this.Match_MaxBits); + if (end_loc == -1 || start_loc >= end_loc) { + start_loc = -1; + } + } + } + else { + start_loc = this.match_main(text, text1, expected_loc); + } + if (start_loc == -1) { + results[x] = false; + delta -= patches[x].length2 - patches[x].length1; + } + else { + results[x] = true; + delta = start_loc - expected_loc; + var text2; + if (end_loc == -1) { + text2 = text.substring(start_loc, start_loc + text1.length); + } + else { + text2 = text.substring(start_loc, end_loc + this.Match_MaxBits); + } + if (text1 == text2) { + text = text.substring(0, start_loc) + + this.diff_text2(patches[x].diffs) + + text.substring(start_loc + text1.length); + } + else { + var diffs = this.diff_main(text1, text2, false); + if (text1.length > this.Match_MaxBits && + this.diff_levenshtein(diffs) / text1.length > + this.Patch_DeleteThreshold) { + results[x] = false; + } + else { + this.diff_cleanupSemanticLossless(diffs); + var index1 = 0; + var index2 = 0; + for (var y = 0; y < patches[x].diffs.length; y++) { + var mod = patches[x].diffs[y]; + if (mod.operation !== exports.DIFF_EQUAL) { + index2 = this.diff_xIndex(diffs, index1); + } + if (mod.operation === exports.DIFF_INSERT) { + text = text.substring(0, start_loc + index2) + mod.text + + text.substring(start_loc + index2); + } + else if (mod.operation === exports.DIFF_DELETE) { + text = text.substring(0, start_loc + index2) + + text.substring(start_loc + this.diff_xIndex(diffs, index1 + mod.text.length)); + } + if (mod.operation !== exports.DIFF_DELETE) { + index1 += mod.text.length; + } + } + } + } + } + } + text = text.substring(nullPadding.length, text.length - nullPadding.length); + return [text, results]; + }; + ; + diff_match_patch.prototype.patch_addPadding = function (patches) { + var paddingLength = this.Patch_Margin; + var nullPadding = ''; + for (var x = 1; x <= paddingLength; x++) { + nullPadding += String.fromCharCode(x); + } + for (var x = 0; x < patches.length; x++) { + patches[x].start1 += paddingLength; + patches[x].start2 += paddingLength; + } + var patch = patches[0]; + var diffs = patch.diffs; + if (diffs.length == 0 || diffs[0].operation != exports.DIFF_EQUAL) { + diffs.unshift(new Diff(exports.DIFF_EQUAL, nullPadding)); + patch.start1 -= paddingLength; + patch.start2 -= paddingLength; + patch.length1 += paddingLength; + patch.length2 += paddingLength; + } + else if (paddingLength > diffs[0].text.length) { + var extraLength = paddingLength - diffs[0].text.length; + diffs[0].text = nullPadding.substring(diffs[0].text.length) + diffs[0].text; + patch.start1 -= extraLength; + patch.start2 -= extraLength; + patch.length1 += extraLength; + patch.length2 += extraLength; + } + patch = patches[patches.length - 1]; + diffs = patch.diffs; + if (diffs.length == 0 || diffs[diffs.length - 1].operation != exports.DIFF_EQUAL) { + diffs.push(new Diff(exports.DIFF_EQUAL, nullPadding)); + patch.length1 += paddingLength; + patch.length2 += paddingLength; + } + else if (paddingLength > diffs[diffs.length - 1].text.length) { + var extraLength = paddingLength - diffs[diffs.length - 1].text.length; + diffs[diffs.length - 1].text += nullPadding.substring(0, extraLength); + patch.length1 += extraLength; + patch.length2 += extraLength; + } + return nullPadding; + }; + ; + diff_match_patch.prototype.patch_splitMax = function (patches) { + var patch_size = this.Match_MaxBits; + for (var x = 0; x < patches.length; x++) { + if (patches[x].length1 <= patch_size) { + continue; + } + var bigpatch = patches[x]; + patches.splice(x--, 1); + var start1 = bigpatch.start1; + var start2 = bigpatch.start2; + var precontext = ''; + while (bigpatch.diffs.length !== 0) { + var patch = new patch_obj(); + var empty = true; + patch.start1 = start1 - precontext.length; + patch.start2 = start2 - precontext.length; + if (precontext !== '') { + patch.length1 = patch.length2 = precontext.length; + patch.diffs.push(new Diff(exports.DIFF_EQUAL, precontext)); + } + while (bigpatch.diffs.length !== 0 && + patch.length1 < patch_size - this.Patch_Margin) { + var diff_type = bigpatch.diffs[0].operation; + var diff_text = bigpatch.diffs[0].text; + if (diff_type === exports.DIFF_INSERT) { + patch.length2 += diff_text.length; + start2 += diff_text.length; + patch.diffs.push(bigpatch.diffs.shift()); + empty = false; + } + else if (diff_type === exports.DIFF_DELETE && patch.diffs.length == 1 && + patch.diffs[0].operation == exports.DIFF_EQUAL && + diff_text.length > 2 * patch_size) { + patch.length1 += diff_text.length; + start1 += diff_text.length; + empty = false; + patch.diffs.push(new Diff(diff_type, diff_text)); + bigpatch.diffs.shift(); + } + else { + diff_text = diff_text.substring(0, patch_size - patch.length1 - this.Patch_Margin); + patch.length1 += diff_text.length; + start1 += diff_text.length; + if (diff_type === exports.DIFF_EQUAL) { + patch.length2 += diff_text.length; + start2 += diff_text.length; + } + else { + empty = false; + } + patch.diffs.push(new Diff(diff_type, diff_text)); + if (diff_text == bigpatch.diffs[0].text) { + bigpatch.diffs.shift(); + } + else { + bigpatch.diffs[0].text = + bigpatch.diffs[0].text.substring(diff_text.length); + } + } + } + precontext = this.diff_text2(patch.diffs); + precontext = + precontext.substring(precontext.length - this.Patch_Margin); + var postcontext = this.diff_text1(bigpatch.diffs) + .substring(0, this.Patch_Margin); + if (postcontext !== '') { + patch.length1 += postcontext.length; + patch.length2 += postcontext.length; + if (patch.diffs.length !== 0 && + patch.diffs[patch.diffs.length - 1].operation === exports.DIFF_EQUAL) { + patch.diffs[patch.diffs.length - 1].text += postcontext; + } + else { + patch.diffs.push(new Diff(exports.DIFF_EQUAL, postcontext)); + } + } + if (!empty) { + patches.splice(++x, 0, patch); + } + } + } + }; + ; + diff_match_patch.prototype.patch_toText = function (patches) { + var text = []; + for (var x = 0; x < patches.length; x++) { + text[x] = patches[x]; + } + return text.join(''); + }; + ; + diff_match_patch.prototype.patch_fromText = function (textline) { + var patches = []; + if (!textline) { + return patches; + } + var text = textline.split('\n'); + var textPointer = 0; + var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; + while (textPointer < text.length) { + var m = text[textPointer].match(patchHeader); + if (!m) { + throw new Error('Invalid patch string: ' + text[textPointer]); + } + var patch = new patch_obj(); + patches.push(patch); + patch.start1 = parseInt(m[1], 10); + if (m[2] === '') { + patch.start1--; + patch.length1 = 1; + } + else if (m[2] == '0') { + patch.length1 = 0; + } + else { + patch.start1--; + patch.length1 = parseInt(m[2], 10); + } + patch.start2 = parseInt(m[3], 10); + if (m[4] === '') { + patch.start2--; + patch.length2 = 1; + } + else if (m[4] == '0') { + patch.length2 = 0; + } + else { + patch.start2--; + patch.length2 = parseInt(m[4], 10); + } + textPointer++; + while (textPointer < text.length) { + var sign = text[textPointer].charAt(0); + try { + var line = decodeURI(text[textPointer].substring(1)); + } + catch (ex) { + throw new Error('Illegal escape in patch_fromText: ' + line); + } + if (sign == '-') { + patch.diffs.push(new Diff(exports.DIFF_DELETE, line)); + } + else if (sign == '+') { + patch.diffs.push(new Diff(exports.DIFF_INSERT, line)); + } + else if (sign == ' ') { + patch.diffs.push(new Diff(exports.DIFF_EQUAL, line)); + } + else if (sign == '@') { + break; + } + else if (sign === '') { + } + else { + throw new Error('Invalid patch mode "' + sign + '" in: ' + line); + } + textPointer++; + } + } + return patches; + }; + ; + diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; + diff_match_patch.whitespaceRegex_ = /\s/; + diff_match_patch.linebreakRegex_ = /[\r\n]/; + diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/; + diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/; + return diff_match_patch; + }()); + exports["default"] = diff_match_patch; + exports.DIFF_DELETE = -1; + exports.DIFF_INSERT = 1; + exports.DIFF_EQUAL = 0; + var Diff = (function () { + function Diff(op, text) { + this.operation = op; + this.text = text; + } + Diff.prototype.toString = function () { + return this.operation + ',' + this.text; + }; + ; + return Diff; + }()); + exports.Diff = Diff; + var patch_obj = (function () { + function patch_obj() { + this.diffs = []; + this.start1 = null; + this.start2 = null; + this.length1 = 0; + this.length2 = 0; + } + ; + patch_obj.prototype.toString = function () { + var coords1, coords2; + if (this.length1 === 0) { + coords1 = this.start1 + ',0'; + } + else if (this.length1 == 1) { + coords1 = this.start1 + 1; + } + else { + coords1 = (this.start1 + 1) + ',' + this.length1; + } + if (this.length2 === 0) { + coords2 = this.start2 + ',0'; + } + else if (this.length2 == 1) { + coords2 = this.start2 + 1; + } + else { + coords2 = (this.start2 + 1) + ',' + this.length2; + } + var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n']; + var op; + for (var x = 0; x < this.diffs.length; x++) { + switch (this.diffs[x].operation) { + case exports.DIFF_INSERT: + op = '+'; + break; + case exports.DIFF_DELETE: + op = '-'; + break; + case exports.DIFF_EQUAL: + op = ' '; + break; + } + text[x + 1] = op + encodeURI(this.diffs[x].text) + '\n'; + } + return text.join('').replace(/%20/g, ' '); + }; + ; + return patch_obj; + }()); + exports.patch_obj = patch_obj; +}); diff --git a/typescript/diff_match_patch.ts b/typescript/diff_match_patch.ts new file mode 100644 index 0000000..e040b54 --- /dev/null +++ b/typescript/diff_match_patch.ts @@ -0,0 +1,2256 @@ +/** + * Diff Match and Patch + * Copyright 2018 The diff-match-patch Authors. + * https://github.com/google/diff-match-patch + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @fileoverview Computes the difference between two texts to create a patch. + * Applies the patch onto another text, allowing for errors. + * @author fraser@google.com (Neil Fraser) + */ + +/** + * Class containing the diff, match and patch methods. + * @constructor + */ +export default class diff_match_patch { + + public Diff_Timeout: number; + public Diff_EditCost: number; + public Match_Threshold: number; + public Match_Distance: number; + public Patch_DeleteThreshold: number; + public Patch_Margin: number; + public Match_MaxBits: number; + + constructor() { + // Defaults. + // Redefine these in your program to override the defaults. + + // Number of seconds to map a diff before giving up (0 for infinity). + this.Diff_Timeout = 1.0; + // Cost of an empty edit operation in terms of edit characters. + this.Diff_EditCost = 4; + // At what point is no match declared (0.0 = perfection, 1.0 = very loose). + this.Match_Threshold = 0.5; + // How far to search for a match (0 = exact location, 1000+ = broad match). + // A match this many characters away from the expected location will add + // 1.0 to the score (0.0 is a perfect match). + this.Match_Distance = 1000; + // When deleting a large block of text (over ~64 characters), how close do + // the contents have to be to match the expected contents. (0.0 = perfection, + // 1.0 = very loose). Note that Match_Threshold controls how closely the + // end points of a delete need to match. + this.Patch_DeleteThreshold = 0.5; + // Chunk size for context length. + this.Patch_Margin = 4; + + // The number of bits in an int. + this.Match_MaxBits = 32; + } + + // DIFF FUNCTIONS + + /** + * Find the differences between two texts. Simplifies the problem by stripping + * any common prefix or suffix off the texts before diffing. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {boolean=} opt_checklines Optional speedup flag. If present and false, + * then don't run a line-level diff first to identify the changed areas. + * Defaults to true, which does a faster, slightly less optimal diff. + * @param {number=} opt_deadline Optional time when the diff should be complete + * by. Used internally for recursive calls. Users should set DiffTimeout + * instead. + * @return {!Array.} Array of diff tuples. + */ + diff_main(text1: string, text2: string, opt_checklines?: boolean, + opt_deadline?: number): Diff[] { + // Set a deadline by which time the diff must be complete. + if (typeof opt_deadline == 'undefined') { + if (this.Diff_Timeout <= 0) { + opt_deadline = Number.MAX_VALUE; + } else { + opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000; + } + } + var deadline = opt_deadline; + + // Check for null inputs. + if (text1 == null || text2 == null) { + throw new Error('Null input. (diff_main)'); + } + + // Check for equality (speedup). + if (text1 == text2) { + if (text1) { + return [new Diff(DIFF_EQUAL, text1)]; + } + return []; + } + + if (typeof opt_checklines == 'undefined') { + opt_checklines = true; + } + var checklines = opt_checklines; + + // Trim off common prefix (speedup). + var commonlength = this.diff_commonPrefix(text1, text2); + var commonprefix = text1.substring(0, commonlength); + text1 = text1.substring(commonlength); + text2 = text2.substring(commonlength); + + // Trim off common suffix (speedup). + commonlength = this.diff_commonSuffix(text1, text2); + var commonsuffix = text1.substring(text1.length - commonlength); + text1 = text1.substring(0, text1.length - commonlength); + text2 = text2.substring(0, text2.length - commonlength); + + // Compute the diff on the middle block. + var diffs = this.diff_compute_(text1, text2, checklines, deadline); + + // Restore the prefix and suffix. + if (commonprefix) { + diffs.unshift(new Diff(DIFF_EQUAL, commonprefix)); + } + if (commonsuffix) { + diffs.push(new Diff(DIFF_EQUAL, commonsuffix)); + } + this.diff_cleanupMerge(diffs); + return diffs; + }; + + + + /** + * Find the differences between two texts. Assumes that the texts do not + * have any common prefix or suffix. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {boolean} checklines Speedup flag. If false, then don't run a + * line-level diff first to identify the changed areas. + * If true, then run a faster, slightly less optimal diff. + * @param {number} deadline Time when the diff should be complete by. + * @return {!Array.} Array of diff tuples. + * @private + */ + private diff_compute_(text1: string, text2: string, checklines: boolean, + deadline: number): Diff[] { + var diffs; + + if (!text1) { + // Just add some text (speedup). + return [new Diff(DIFF_INSERT, text2)]; + } + + if (!text2) { + // Just delete some text (speedup). + return [new Diff(DIFF_DELETE, text1)]; + } + + var longtext = text1.length > text2.length ? text1 : text2; + var shorttext = text1.length > text2.length ? text2 : text1; + var i = longtext.indexOf(shorttext); + if (i != -1) { + // Shorter text is inside the longer text (speedup). + diffs = [new Diff(DIFF_INSERT, longtext.substring(0, i)), + new Diff(DIFF_EQUAL, shorttext), + new Diff(DIFF_INSERT, + longtext.substring(i + shorttext.length))]; + // Swap insertions for deletions if diff is reversed. + if (text1.length > text2.length) { + diffs[0].operation = diffs[2].operation = DIFF_DELETE; + } + return diffs; + } + + if (shorttext.length == 1) { + // Single character string. + // After the previous speedup, the character can't be an equality. + return [new Diff(DIFF_DELETE, text1), + new Diff(DIFF_INSERT, text2)]; + } + + // Check to see if the problem can be split in two. + var hm = this.diff_halfMatch_(text1, text2); + if (hm) { + // A half-match was found, sort out the return data. + var text1_a = hm[0]; + var text1_b = hm[1]; + var text2_a = hm[2]; + var text2_b = hm[3]; + var mid_common = hm[4]; + // Send both pairs off for separate processing. + var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); + var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); + // Merge the results. + return diffs_a.concat([new Diff(DIFF_EQUAL, mid_common)], + diffs_b); + } + + if (checklines && text1.length > 100 && text2.length > 100) { + return this.diff_lineMode_(text1, text2, deadline); + } + + return this.diff_bisect_(text1, text2, deadline); + }; + + + + /** + * Do a quick line-level diff on both strings, then rediff the parts for + * greater accuracy. + * This speedup can produce non-minimal diffs. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} deadline Time when the diff should be complete by. + * @return {!Array.} Array of diff tuples. + * @private + */ + private diff_lineMode_(text1: string, text2: string, deadline: number): Diff[] { + // Scan the text on a line-by-line basis first. + var a = this.diff_linesToChars_(text1, text2); + text1 = a.chars1; + text2 = a.chars2; + var linearray = a.lineArray; + + var diffs = this.diff_main(text1, text2, false, deadline); + + // Convert the diff back to original text. + this.diff_charsToLines_(diffs, linearray); + // Eliminate freak matches (e.g. blank lines) + this.diff_cleanupSemantic(diffs); + + // Rediff any replacement blocks, this time character-by-character. + // Add a dummy entry at the end. + diffs.push(new Diff(DIFF_EQUAL, '')); + var pointer = 0; + var count_delete = 0; + var count_insert = 0; + var text_delete = ''; + var text_insert = ''; + while (pointer < diffs.length) { + switch (diffs[pointer].operation) { + case DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer].text; + break; + case DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer].text; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (count_delete >= 1 && count_insert >= 1) { + // Delete the offending records and add the merged ones. + diffs.splice(pointer - count_delete - count_insert, + count_delete + count_insert); + pointer = pointer - count_delete - count_insert; + var subDiff = + this.diff_main(text_delete, text_insert, false, deadline); + for (var j = subDiff.length - 1; j >= 0; j--) { + diffs.splice(pointer, 0, subDiff[j]); + } + pointer = pointer + subDiff.length; + } + count_insert = 0; + count_delete = 0; + text_delete = ''; + text_insert = ''; + break; + } + pointer++; + } + diffs.pop(); // Remove the dummy entry at the end. + + return diffs; + }; + + + /** + * Find the 'middle snake' of a diff, split the problem in two + * and return the recursively constructed diff. + * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} deadline Time at which to bail if not yet complete. + * @return {!Array.} Array of diff tuples. + * @private + */ + private diff_bisect_(text1: string, text2: string, deadline: number): Diff[] { + // Cache the text lengths to prevent multiple calls. + var text1_length = text1.length; + var text2_length = text2.length; + var max_d = Math.ceil((text1_length + text2_length) / 2); + var v_offset = max_d; + var v_length = 2 * max_d; + var v1 = new Array(v_length); + var v2 = new Array(v_length); + // Setting all elements to -1 is faster in Chrome & Firefox than mixing + // integers and undefined. + for (var x = 0; x < v_length; x++) { + v1[x] = -1; + v2[x] = -1; + } + v1[v_offset + 1] = 0; + v2[v_offset + 1] = 0; + var delta = text1_length - text2_length; + // If the total number of characters is odd, then the front path will collide + // with the reverse path. + var front = (delta % 2 != 0); + // Offsets for start and end of k loop. + // Prevents mapping of space beyond the grid. + var k1start = 0; + var k1end = 0; + var k2start = 0; + var k2end = 0; + for (var d = 0; d < max_d; d++) { + // Bail out if deadline is reached. + if ((new Date()).getTime() > deadline) { + break; + } + + // Walk the front path one step. + for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { + var k1_offset = v_offset + k1; + var x1: number; + if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) { + x1 = v1[k1_offset + 1]; + } else { + x1 = v1[k1_offset - 1] + 1; + } + var y1 = x1 - k1; + while (x1 < text1_length && y1 < text2_length && + text1.charAt(x1) == text2.charAt(y1)) { + x1++; + y1++; + } + v1[k1_offset] = x1; + if (x1 > text1_length) { + // Ran off the right of the graph. + k1end += 2; + } else if (y1 > text2_length) { + // Ran off the bottom of the graph. + k1start += 2; + } else if (front) { + var k2_offset = v_offset + delta - k1; + if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { + // Mirror x2 onto top-left coordinate system. + var x2 = text1_length - v2[k2_offset]; + if (x1 >= x2) { + // Overlap detected. + return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); + } + } + } + } + + // Walk the reverse path one step. + for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { + var k2_offset = v_offset + k2; + var x2: number; + if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) { + x2 = v2[k2_offset + 1]; + } else { + x2 = v2[k2_offset - 1] + 1; + } + var y2 = x2 - k2; + while (x2 < text1_length && y2 < text2_length && + text1.charAt(text1_length - x2 - 1) == + text2.charAt(text2_length - y2 - 1)) { + x2++; + y2++; + } + v2[k2_offset] = x2; + if (x2 > text1_length) { + // Ran off the left of the graph. + k2end += 2; + } else if (y2 > text2_length) { + // Ran off the top of the graph. + k2start += 2; + } else if (!front) { + var k1_offset = v_offset + delta - k2; + if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { + var x1 = v1[k1_offset]; + var y1 = v_offset + x1 - k1_offset; + // Mirror x2 onto top-left coordinate system. + x2 = text1_length - x2; + if (x1 >= x2) { + // Overlap detected. + return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); + } + } + } + } + } + // Diff took too long and hit the deadline or + // number of diffs equals number of characters, no commonality at all. + return [new Diff(DIFF_DELETE, text1), + new Diff(DIFF_INSERT, text2)]; + }; + + + /** + * Given the location of the 'middle snake', split the diff in two parts + * and recurse. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} x Index of split point in text1. + * @param {number} y Index of split point in text2. + * @param {number} deadline Time at which to bail if not yet complete. + * @return {!Array.} Array of diff tuples. + * @private + */ + private diff_bisectSplit_(text1: string, text2: string, x: number, y: number, + deadline: number): Diff[] { + var text1a = text1.substring(0, x); + var text2a = text2.substring(0, y); + var text1b = text1.substring(x); + var text2b = text2.substring(y); + + // Compute both diffs serially. + var diffs = this.diff_main(text1a, text2a, false, deadline); + var diffsb = this.diff_main(text1b, text2b, false, deadline); + + return diffs.concat(diffsb); + }; + + + /** + * Split two texts into an array of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {{chars1: string, chars2: string, lineArray: !Array.}} + * An object containing the encoded text1, the encoded text2 and + * the array of unique strings. + * The zeroth element of the array of unique strings is intentionally blank. + * @private + */ + private diff_linesToChars_(text1: string, text2: string): { + chars1: string, chars2: string, lineArray: string[] + } { + var lineArray: string[] = []; // e.g. lineArray[4] == 'Hello\n' + var lineHash: {[key: string]: number} = {}; // e.g. lineHash['Hello\n'] == 4 + + // '\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. + lineArray[0] = ''; + + /** + * Split a text into an array of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * Modifies linearray and linehash through being a closure. + * @param {string} text String to encode. + * @return {string} Encoded string. + * @private + */ + function diff_linesToCharsMunge_(text: string): string { + var chars = ''; + // 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. + var lineStart = 0; + var lineEnd = -1; + // Keeping our own length variable is faster than looking it up. + var lineArrayLength = lineArray.length; + while (lineEnd < text.length - 1) { + lineEnd = text.indexOf('\n', lineStart); + if (lineEnd == -1) { + lineEnd = text.length - 1; + } + var line = text.substring(lineStart, lineEnd + 1); + + if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : + (lineHash[line] !== undefined)) { + chars += String.fromCharCode(lineHash[line]); + } else { + if (lineArrayLength == maxLines) { + // Bail out at 65535 because + // String.fromCharCode(65536) == String.fromCharCode(0) + line = text.substring(lineStart); + lineEnd = text.length; + } + chars += String.fromCharCode(lineArrayLength); + lineHash[line] = lineArrayLength; + lineArray[lineArrayLength++] = line; + } + lineStart = lineEnd + 1; + } + return chars; + } + // Allocate 2/3rds of the space for text1, the rest for text2. + var maxLines = 40000; + var chars1 = diff_linesToCharsMunge_(text1); + maxLines = 65535; + var chars2 = diff_linesToCharsMunge_(text2); + return { chars1: chars1, chars2: chars2, lineArray: lineArray }; + }; + + + /** + * Rehydrate the text in a diff from a string of line hashes to real lines of + * text. + * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} lineArray Array of unique strings. + * @private + */ + private diff_charsToLines_(diffs: Diff[], lineArray: string[]) { + for (var i = 0; i < diffs.length; i++) { + var chars = diffs[i].text; + var text: string[] = []; + for (var j = 0; j < chars.length; j++) { + text[j] = lineArray[chars.charCodeAt(j)]; + } + diffs[i].text = text.join(''); + } + }; + + + /** + * Determine the common prefix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the start of each + * string. + */ + diff_commonPrefix(text1: string, text2: string): number { + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { + return 0; + } + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + var pointermin = 0; + var pointermax = Math.min(text1.length, text2.length); + var pointermid = pointermax; + var pointerstart = 0; + while (pointermin < pointermid) { + if (text1.substring(pointerstart, pointermid) == + text2.substring(pointerstart, pointermid)) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; + }; + + + /** + * Determine the common suffix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of each string. + */ + diff_commonSuffix(text1: string, text2: string): number { + // Quick check for common null cases. + if (!text1 || !text2 || + text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { + return 0; + } + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + var pointermin = 0; + var pointermax = Math.min(text1.length, text2.length); + var pointermid = pointermax; + var pointerend = 0; + while (pointermin < pointermid) { + if (text1.substring(text1.length - pointermid, text1.length - pointerend) == + text2.substring(text2.length - pointermid, text2.length - pointerend)) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; + }; + + + /** + * Determine if the suffix of one string is the prefix of another. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of the first + * string and the start of the second string. + * @private + */ + private diff_commonOverlap_(text1: string, text2: string): number { + // Cache the text lengths to prevent multiple calls. + var text1_length = text1.length; + var text2_length = text2.length; + // Eliminate the null case. + if (text1_length == 0 || text2_length == 0) { + return 0; + } + // Truncate the longer string. + if (text1_length > text2_length) { + text1 = text1.substring(text1_length - text2_length); + } else if (text1_length < text2_length) { + text2 = text2.substring(0, text1_length); + } + var text_length = Math.min(text1_length, text2_length); + // Quick check for the worst case. + if (text1 == text2) { + return text_length; + } + + // Start by looking for a single character match + // and increase length until no match is found. + // Performance analysis: https://neil.fraser.name/news/2010/11/04/ + var best = 0; + var length = 1; + while (true) { + var pattern = text1.substring(text_length - length); + var found = text2.indexOf(pattern); + if (found == -1) { + return best; + } + length += found; + if (found == 0 || text1.substring(text_length - length) == + text2.substring(0, length)) { + best = length; + length++; + } + } + }; + + + /** + * Do the two texts share a substring which is at least half the length of the + * longer text? + * This speedup can produce non-minimal diffs. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {Array.} Five element Array, containing the prefix of + * text1, the suffix of text1, the prefix of text2, the suffix of + * text2 and the common middle. Or null if there was no match. + * @private + */ + private diff_halfMatch_(text1: string, text2: string): string[] | null { + if (this.Diff_Timeout <= 0) { + // Don't risk returning a non-optimal diff if we have unlimited time. + return null; + } + var longtext = text1.length > text2.length ? text1 : text2; + var shorttext = text1.length > text2.length ? text2 : text1; + if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { + return null; // Pointless. + } + var dmp = this; // 'this' becomes 'window' in a closure. + + /** + * Does a substring of shorttext exist within longtext such that the substring + * is at least half the length of longtext? + * Closure, but does not reference any external variables. + * @param {string} longtext Longer string. + * @param {string} shorttext Shorter string. + * @param {number} i Start index of quarter length substring within longtext. + * @return {Array.} Five element Array, 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. + * @private + */ + function diff_halfMatchI_(longtext: string, + shorttext: string, i: number): string[] | null { + // Start with a 1/4 length substring at position i as a seed. + var seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); + var j = -1; + var best_common = ''; + var best_longtext_a = ''; + var best_longtext_b = ''; + var best_shorttext_a = ''; + var best_shorttext_b = ''; + while ((j = shorttext.indexOf(seed, j + 1)) != -1) { + var prefixLength = dmp.diff_commonPrefix(longtext.substring(i), + shorttext.substring(j)); + var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i), + shorttext.substring(0, j)); + if (best_common.length < suffixLength + prefixLength) { + best_common = shorttext.substring(j - suffixLength, j) + + shorttext.substring(j, j + prefixLength); + best_longtext_a = longtext.substring(0, i - suffixLength); + best_longtext_b = longtext.substring(i + prefixLength); + best_shorttext_a = shorttext.substring(0, j - suffixLength); + best_shorttext_b = shorttext.substring(j + prefixLength); + } + } + if (best_common.length * 2 >= longtext.length) { + return [best_longtext_a, best_longtext_b, + best_shorttext_a, best_shorttext_b, best_common]; + } else { + return null; + } + } + + // First check if the second quarter is the seed for a half-match. + var hm1 = diff_halfMatchI_(longtext, shorttext, + Math.ceil(longtext.length / 4)); + // Check again based on the third quarter. + var hm2 = diff_halfMatchI_(longtext, shorttext, + Math.ceil(longtext.length / 2)); + var hm: string[] | null; + if (!hm1 && !hm2) { + return null; + } else if (!hm2) { + hm = hm1; + } else if (!hm1) { + hm = hm2; + } else { + // Both matched. Select the longest. + hm = hm1[4].length > hm2[4].length ? hm1 : hm2; + } + + // A half-match was found, sort out the return data. + var text1_a, text1_b, text2_a, text2_b; + if (text1.length > text2.length) { + text1_a = hm![0]; + text1_b = hm![1]; + text2_a = hm![2]; + text2_b = hm![3]; + } else { + text2_a = hm![0]; + text2_b = hm![1]; + text1_a = hm![2]; + text1_b = hm![3]; + } + var mid_common = hm![4]; + return [text1_a, text1_b, text2_a, text2_b, mid_common]; + }; + + + /** + * Reduce the number of edits by eliminating semantically trivial equalities. + * @param {!Array.} diffs Array of diff tuples. + */ + diff_cleanupSemantic(diffs: Diff[]) { + var changes = false; + var equalities: number[] = []; // Stack of indices where equalities are found. + var equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + var lastEquality = null; + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + var pointer = 0; // Index of current position. + // Number of characters that changed prior to the equality. + var length_insertions1 = 0; + var length_deletions1 = 0; + // Number of characters that changed after the equality. + var length_insertions2 = 0; + var length_deletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer].operation == DIFF_EQUAL) { // Equality found. + equalities[equalitiesLength++] = pointer; + length_insertions1 = length_insertions2; + length_deletions1 = length_deletions2; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = diffs[pointer].text; + } else { // An insertion or deletion. + if (diffs[pointer].operation == DIFF_INSERT) { + length_insertions2 += diffs[pointer].text.length; + } else { + length_deletions2 += diffs[pointer].text.length; + } + // Eliminate an equality that is smaller or equal to the edits on both + // sides of it. + if (lastEquality && (lastEquality.length <= + Math.max(length_insertions1, length_deletions1)) && + (lastEquality.length <= Math.max(length_insertions2, + length_deletions2))) { + // Duplicate record. + diffs.splice(equalities[equalitiesLength - 1], 0, + new Diff(DIFF_DELETE, lastEquality)); + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1].operation = DIFF_INSERT; + // Throw away the equality we just deleted. + equalitiesLength--; + // Throw away the previous equality (it needs to be reevaluated). + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + length_insertions1 = 0; // Reset the counters. + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes = true; + } + } + pointer++; + } + + // Normalize the diff. + if (changes) { + this.diff_cleanupMerge(diffs); + } + this.diff_cleanupSemanticLossless(diffs); + + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1].operation == DIFF_DELETE && + diffs[pointer].operation == DIFF_INSERT) { + var deletion = diffs[pointer - 1].text; + var insertion = diffs[pointer].text; + var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); + var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); + if (overlap_length1 >= overlap_length2) { + if (overlap_length1 >= deletion.length / 2 || + overlap_length1 >= insertion.length / 2) { + // Overlap found. Insert an equality and trim the surrounding edits. + diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, + insertion.substring(0, overlap_length1))); + diffs[pointer - 1].text = + deletion.substring(0, deletion.length - overlap_length1); + diffs[pointer + 1].text = insertion.substring(overlap_length1); + pointer++; + } + } else { + if (overlap_length2 >= deletion.length / 2 || + overlap_length2 >= insertion.length / 2) { + // Reverse overlap found. + // Insert an equality and swap and trim the surrounding edits. + diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, + deletion.substring(0, overlap_length2))); + diffs[pointer - 1].operation = DIFF_INSERT; + diffs[pointer - 1].text = + insertion.substring(0, insertion.length - overlap_length2); + diffs[pointer + 1].operation = DIFF_DELETE; + diffs[pointer + 1].text = + deletion.substring(overlap_length2); + pointer++; + } + } + pointer++; + } + pointer++; + } + }; + + + /** + * Look for single edits surrounded on both sides by equalities + * which can be shifted sideways to align the edit to a word boundary. + * e.g: The cat came. -> The cat came. + * @param {!Array.} diffs Array of diff tuples. + */ + diff_cleanupSemanticLossless(diffs: Diff[]) { + /** + * Given two strings, compute a score representing whether the internal + * boundary falls on logical boundaries. + * Scores range from 6 (best) to 0 (worst). + * Closure, but does not reference any external variables. + * @param {string} one First string. + * @param {string} two Second string. + * @return {number} The score. + * @private + */ + function diff_cleanupSemanticScore_(one: string, two: string): number { + if (!one || !two) { + // Edges are the best. + return 6; + } + + // 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. + var char1 = one.charAt(one.length - 1); + var char2 = two.charAt(0); + var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_); + var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_); + var whitespace1 = nonAlphaNumeric1 && + char1.match(diff_match_patch.whitespaceRegex_); + var whitespace2 = nonAlphaNumeric2 && + char2.match(diff_match_patch.whitespaceRegex_); + var lineBreak1 = whitespace1 && + char1.match(diff_match_patch.linebreakRegex_); + var lineBreak2 = whitespace2 && + char2.match(diff_match_patch.linebreakRegex_); + var blankLine1 = lineBreak1 && + one.match(diff_match_patch.blanklineEndRegex_); + var blankLine2 = lineBreak2 && + two.match(diff_match_patch.blanklineStartRegex_); + + if (blankLine1 || blankLine2) { + // Five points for blank lines. + return 5; + } else if (lineBreak1 || lineBreak2) { + // Four points for line breaks. + return 4; + } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { + // Three points for end of sentences. + return 3; + } else if (whitespace1 || whitespace2) { + // Two points for whitespace. + return 2; + } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { + // One point for non-alphanumeric. + return 1; + } + return 0; + } + + var pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1].operation == DIFF_EQUAL && + diffs[pointer + 1].operation == DIFF_EQUAL) { + // This is a single edit surrounded by equalities. + var equality1 = diffs[pointer - 1].text; + var edit = diffs[pointer].text; + var equality2 = diffs[pointer + 1].text; + + // First, shift the edit as far left as possible. + var commonOffset = this.diff_commonSuffix(equality1, edit); + if (commonOffset) { + var commonString = edit.substring(edit.length - commonOffset); + equality1 = equality1.substring(0, equality1.length - commonOffset); + edit = commonString + edit.substring(0, edit.length - commonOffset); + equality2 = commonString + equality2; + } + + // Second, step character by character right, looking for the best fit. + var bestEquality1 = equality1; + var bestEdit = edit; + var bestEquality2 = equality2; + var bestScore = diff_cleanupSemanticScore_(equality1, edit) + + diff_cleanupSemanticScore_(edit, equality2); + while (edit.charAt(0) === equality2.charAt(0)) { + equality1 += edit.charAt(0); + edit = edit.substring(1) + equality2.charAt(0); + equality2 = equality2.substring(1); + var score = diff_cleanupSemanticScore_(equality1, edit) + + diff_cleanupSemanticScore_(edit, equality2); + // The >= encourages trailing rather than leading whitespace on edits. + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + + if (diffs[pointer - 1].text != bestEquality1) { + // We have an improvement, save it back to the diff. + if (bestEquality1) { + diffs[pointer - 1].text = bestEquality1; + } else { + diffs.splice(pointer - 1, 1); + pointer--; + } + diffs[pointer].text = bestEdit; + if (bestEquality2) { + diffs[pointer + 1].text = bestEquality2; + } else { + diffs.splice(pointer + 1, 1); + pointer--; + } + } + } + pointer++; + } + }; + + + + // Define some regex patterns for matching boundaries. + private static nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; + private static whitespaceRegex_ = /\s/; + private static linebreakRegex_ = /[\r\n]/; + private static blanklineEndRegex_ = /\n\r?\n$/; + private static blanklineStartRegex_ = /^\r?\n\r?\n/; + + /** + * Reduce the number of edits by eliminating operationally trivial equalities. + * @param {!Array.} diffs Array of diff tuples. + */ + diff_cleanupEfficiency(diffs: Diff[]) { + var changes = false; + var equalities: number[] = []; // Stack of indices where equalities are found. + var equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + var lastEquality = null; + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + var pointer = 0; // Index of current position. + // Is there an insertion operation before the last equality. + var pre_ins = 0; + // Is there a deletion operation before the last equality. + var pre_del = 0; + // Is there an insertion operation after the last equality. + var post_ins = 0; + // Is there a deletion operation after the last equality. + var post_del = 0; + while (pointer < diffs.length) { + if (diffs[pointer].operation == DIFF_EQUAL) { // Equality found. + if (diffs[pointer].text.length < this.Diff_EditCost && + (post_ins || post_del)) { + // Candidate found. + equalities[equalitiesLength++] = pointer; + pre_ins = post_ins; + pre_del = post_del; + lastEquality = diffs[pointer].text; + } else { + // Not a candidate, and can never become one. + equalitiesLength = 0; + lastEquality = null; + } + post_ins = post_del = 0; + } else { // An insertion or deletion. + if (diffs[pointer].operation == DIFF_DELETE) { + post_del = 1; + } else { + post_ins = 1; + } + /* + * Five types to be split: + * ABXYCD + * AXCD + * ABXC + * AXCD + * ABXC + */ + if (lastEquality && ((pre_ins && pre_del && post_ins && post_del) || + ((lastEquality.length < this.Diff_EditCost / 2) && + (pre_ins + pre_del + post_ins + post_del) == 3))) { + // Duplicate record. + diffs.splice(equalities[equalitiesLength - 1], 0, + new Diff(DIFF_DELETE, lastEquality)); + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1].operation = DIFF_INSERT; + equalitiesLength--; // Throw away the equality we just deleted; + lastEquality = null; + if (pre_ins && pre_del) { + // No changes made which could affect previous entry, keep going. + post_ins = post_del = 1; + equalitiesLength = 0; + } else { + equalitiesLength--; // Throw away the previous equality. + pointer = equalitiesLength > 0 ? + equalities[equalitiesLength - 1] : -1; + post_ins = post_del = 0; + } + changes = true; + } + } + pointer++; + } + + if (changes) { + this.diff_cleanupMerge(diffs); + } + }; + + + /** + * Reorder and merge like edit sections. Merge equalities. + * Any edit section can move as long as it doesn't cross an equality. + * @param {!Array.} diffs Array of diff tuples. + */ + diff_cleanupMerge(diffs: Diff[]) { + // Add a dummy entry at the end. + diffs.push(new Diff(DIFF_EQUAL, '')); + var pointer = 0; + var count_delete = 0; + var count_insert = 0; + var text_delete = ''; + var text_insert = ''; + var commonlength; + while (pointer < diffs.length) { + switch (diffs[pointer].operation) { + case DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer].text; + pointer++; + break; + case DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer].text; + pointer++; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (count_delete + count_insert > 1) { + if (count_delete !== 0 && count_insert !== 0) { + // Factor out any common prefixies. + commonlength = this.diff_commonPrefix(text_insert, text_delete); + if (commonlength !== 0) { + if ((pointer - count_delete - count_insert) > 0 && + diffs[pointer - count_delete - count_insert - 1].operation == + DIFF_EQUAL) { + diffs[pointer - count_delete - count_insert - 1].text += + text_insert.substring(0, commonlength); + } else { + diffs.splice(0, 0, new Diff(DIFF_EQUAL, + text_insert.substring(0, commonlength))); + pointer++; + } + text_insert = text_insert.substring(commonlength); + text_delete = text_delete.substring(commonlength); + } + // Factor out any common suffixies. + commonlength = this.diff_commonSuffix(text_insert, text_delete); + if (commonlength !== 0) { + diffs[pointer].text = text_insert.substring(text_insert.length - + commonlength) + diffs[pointer].text; + text_insert = text_insert.substring(0, text_insert.length - + commonlength); + text_delete = text_delete.substring(0, text_delete.length - + commonlength); + } + } + // Delete the offending records and add the merged ones. + pointer -= count_delete + count_insert; + diffs.splice(pointer, count_delete + count_insert); + if (text_delete.length) { + diffs.splice(pointer, 0, + new Diff(DIFF_DELETE, text_delete)); + pointer++; + } + if (text_insert.length) { + diffs.splice(pointer, 0, + new Diff(DIFF_INSERT, text_insert)); + pointer++; + } + pointer++; + } else if (pointer !== 0 && diffs[pointer - 1].operation == DIFF_EQUAL) { + // Merge this equality with the previous one. + diffs[pointer - 1].text += diffs[pointer].text; + diffs.splice(pointer, 1); + } else { + pointer++; + } + count_insert = 0; + count_delete = 0; + text_delete = ''; + text_insert = ''; + break; + } + } + if (diffs[diffs.length - 1].text === '') { + diffs.pop(); // Remove the dummy entry at the end. + } + + // Second pass: look for single edits surrounded on both sides by equalities + // which can be shifted sideways to eliminate an equality. + // e.g: ABAC -> ABAC + var changes = false; + pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1].operation == DIFF_EQUAL && + diffs[pointer + 1].operation == DIFF_EQUAL) { + // This is a single edit surrounded by equalities. + if (diffs[pointer].text.substring(diffs[pointer].text.length - + diffs[pointer - 1].text.length) == diffs[pointer - 1].text) { + // Shift the edit over the previous equality. + diffs[pointer].text = diffs[pointer - 1].text + + diffs[pointer].text.substring(0, diffs[pointer].text.length - + diffs[pointer - 1].text.length); + diffs[pointer + 1].text = diffs[pointer - 1].text + diffs[pointer + 1].text; + diffs.splice(pointer - 1, 1); + changes = true; + } else if (diffs[pointer].text.substring(0, diffs[pointer + 1].text.length) == + diffs[pointer + 1].text) { + // Shift the edit over the next equality. + diffs[pointer - 1].text += diffs[pointer + 1].text; + diffs[pointer].text = + diffs[pointer].text.substring(diffs[pointer + 1].text.length) + + diffs[pointer + 1].text; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + pointer++; + } + // If shifts were made, the diff needs reordering and another shift sweep. + if (changes) { + this.diff_cleanupMerge(diffs); + } + }; + + + /** + * loc is a location in text1, compute and return the equivalent location in + * text2. + * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 + * @param {!Array.} diffs Array of diff tuples. + * @param {number} loc Location within text1. + * @return {number} Location within text2. + */ + diff_xIndex(diffs: Diff[], loc: number): number { + var chars1 = 0; + var chars2 = 0; + var last_chars1 = 0; + var last_chars2 = 0; + var x; + for (x = 0; x < diffs.length; x++) { + if (diffs[x].operation !== DIFF_INSERT) { // Equality or deletion. + chars1 += diffs[x].text.length; + } + if (diffs[x].operation !== DIFF_DELETE) { // Equality or insertion. + chars2 += diffs[x].text.length; + } + if (chars1 > loc) { // Overshot the location. + break; + } + last_chars1 = chars1; + last_chars2 = chars2; + } + // Was the location was deleted? + if (diffs.length != x && diffs[x].operation === DIFF_DELETE) { + return last_chars2; + } + // Add the remaining character length. + return last_chars2 + (loc - last_chars1); + }; + + + /** + * Convert a diff array into a pretty HTML report. + * @param {!Array.} diffs Array of diff tuples. + * @return {string} HTML representation. + */ + diff_prettyHtml(diffs: Diff[]): string { + var html: string[] = []; + var pattern_amp = /&/g; + var pattern_lt = //g; + var pattern_para = /\n/g; + for (var x = 0; x < diffs.length; x++) { + var op = diffs[x].operation; // Operation (insert, delete, equal) + var data = diffs[x].text; // Text of change. + var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<') + .replace(pattern_gt, '>').replace(pattern_para, '¶
'); + switch (op) { + case DIFF_INSERT: + html[x] = '' + text + ''; + break; + case DIFF_DELETE: + html[x] = '' + text + ''; + break; + case DIFF_EQUAL: + html[x] = '' + text + ''; + break; + } + } + return html.join(''); + }; + + + /** + * Compute and return the source text (all equalities and deletions). + * @param {!Array.} diffs Array of diff tuples. + * @return {string} Source text. + */ + diff_text1(diffs: Diff[]): string { + var text: string[] = []; + for (var x = 0; x < diffs.length; x++) { + if (diffs[x].operation !== DIFF_INSERT) { + text[x] = diffs[x].text; + } + } + return text.join(''); + }; + + + /** + * Compute and return the destination text (all equalities and insertions). + * @param {!Array.} diffs Array of diff tuples. + * @return {string} Destination text. + */ + diff_text2(diffs: Diff[]): string { + var text = []; + for (var x = 0; x < diffs.length; x++) { + if (diffs[x].operation !== DIFF_DELETE) { + text[x] = diffs[x].text; + } + } + return text.join(''); + }; + + + /** + * Compute the Levenshtein distance; the number of inserted, deleted or + * substituted characters. + * @param {!Array.} diffs Array of diff tuples. + * @return {number} Number of changes. + */ + diff_levenshtein(diffs: Diff[]): number { + var levenshtein = 0; + var insertions = 0; + var deletions = 0; + for (var x = 0; x < diffs.length; x++) { + var op = diffs[x].operation; + var data = diffs[x].text; + switch (op) { + case DIFF_INSERT: + insertions += data.length; + break; + case DIFF_DELETE: + deletions += data.length; + break; + case DIFF_EQUAL: + // A deletion and an insertion is one substitution. + levenshtein += Math.max(insertions, deletions); + insertions = 0; + deletions = 0; + break; + } + } + levenshtein += Math.max(insertions, deletions); + return levenshtein; + }; + + + /** + * Crush the diff into an encoded string which describes the operations + * required to transform text1 into text2. + * 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. + * @param {!Array.} diffs Array of diff tuples. + * @return {string} Delta text. + */ + diff_toDelta(diffs: Diff[]): string { + var text: string[] = []; + for (var x = 0; x < diffs.length; x++) { + switch (diffs[x].operation) { + case DIFF_INSERT: + text[x] = '+' + encodeURI(diffs[x].text); + break; + case DIFF_DELETE: + text[x] = '-' + diffs[x].text.length; + break; + case DIFF_EQUAL: + text[x] = '=' + diffs[x].text.length; + break; + } + } + return text.join('\t').replace(/%20/g, ' '); + }; + + + /** + * Given the original text1, and an encoded string which describes the + * operations required to transform text1 into text2, compute the full diff. + * @param {string} text1 Source string for the diff. + * @param {string} delta Delta text. + * @return {!Array.} Array of diff tuples. + * @throws {!Error} If invalid input. + */ + diff_fromDelta(text1: string, delta: string): Diff[] { + var diffs: Diff[] = []; + var diffsLength = 0; // Keeping our own length var is faster in JS. + var pointer = 0; // Cursor in text1 + var tokens = delta.split(/\t/g); + for (var x = 0; x < tokens.length; x++) { + // Each token begins with a one character parameter which specifies the + // operation of this token (delete, insert, equality). + var param = tokens[x].substring(1); + switch (tokens[x].charAt(0)) { + case '+': + try { + diffs[diffsLength++] = + new Diff(DIFF_INSERT, decodeURI(param)); + } catch (ex) { + // Malformed URI sequence. + throw new Error('Illegal escape in diff_fromDelta: ' + param); + } + break; + case '-': + // Fall through. + case '=': + var n = parseInt(param, 10); + if (isNaN(n) || n < 0) { + throw new Error('Invalid number in diff_fromDelta: ' + param); + } + var text = text1.substring(pointer, pointer += n); + if (tokens[x].charAt(0) == '=') { + diffs[diffsLength++] = new Diff(DIFF_EQUAL, text); + } else { + diffs[diffsLength++] = new Diff(DIFF_DELETE, text); + } + break; + default: + // Blank tokens are ok (from a trailing \t). + // Anything else is an error. + if (tokens[x]) { + throw new Error('Invalid diff operation in diff_fromDelta: ' + + tokens[x]); + } + } + } + if (pointer != text1.length) { + throw new Error('Delta length (' + pointer + + ') does not equal source text length (' + text1.length + ').'); + } + return diffs; + }; + + + + + // MATCH FUNCTIONS + + + /** + * Locate the best instance of 'pattern' in 'text' near 'loc'. + * @param {string} text The text to search. + * @param {string} pattern The pattern to search for. + * @param {number} loc The location to search around. + * @return {number} Best match index or -1. + */ + match_main(text: string, pattern: string, loc: number): number { + // Check for null inputs. + if (text == null || pattern == null || loc == null) { + throw new Error('Null input. (match_main)'); + } + + loc = Math.max(0, Math.min(loc, text.length)); + if (text == pattern) { + // Shortcut (potentially not guaranteed by the algorithm) + return 0; + } else if (!text.length) { + // Nothing to match. + return -1; + } else if (text.substring(loc, loc + pattern.length) == pattern) { + // Perfect match at the perfect spot! (Includes case of null pattern) + return loc; + } else { + // Do a fuzzy compare. + return this.match_bitap_(text, pattern, loc); + } + }; + + + /** + * Locate the best instance of 'pattern' in 'text' near 'loc' using the + * Bitap algorithm. + * @param {string} text The text to search. + * @param {string} pattern The pattern to search for. + * @param {number} loc The location to search around. + * @return {number} Best match index or -1. + * @private + */ + private match_bitap_(text: string, pattern: string, loc: number): number { + if (pattern.length > this.Match_MaxBits) { + throw new Error('Pattern too long for this browser.'); + } + + // Initialise the alphabet. + var s = this.match_alphabet_(pattern); + + var dmp = this; // 'this' becomes 'window' in a closure. + + /** + * Compute and return the score for a match with e errors and x location. + * Accesses loc and pattern through being a closure. + * @param {number} e Number of errors in match. + * @param {number} x Location of match. + * @return {number} Overall score for match (0.0 = good, 1.0 = bad). + * @private + */ + function match_bitapScore_(e: number, x: number): number { + var accuracy = e / pattern.length; + var proximity = Math.abs(loc - x); + if (!dmp.Match_Distance) { + // Dodge divide by zero error. + return proximity ? 1.0 : accuracy; + } + return accuracy + (proximity / dmp.Match_Distance); + } + + // Highest score beyond which we give up. + var score_threshold = this.Match_Threshold; + // Is there a nearby exact match? (speedup) + var best_loc = text.indexOf(pattern, loc); + if (best_loc != -1) { + score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); + // What about in the other direction? (speedup) + best_loc = text.lastIndexOf(pattern, loc + pattern.length); + if (best_loc != -1) { + score_threshold = + Math.min(match_bitapScore_(0, best_loc), score_threshold); + } + } + + // Initialise the bit arrays. + var matchmask = 1 << (pattern.length - 1); + best_loc = -1; + + var bin_min, bin_mid; + var bin_max = pattern.length + text.length; + var last_rd: number[] = []; + for (var d = 0; d < pattern.length; d++) { + // Scan for the best match; each iteration allows for one more error. + // Run a binary search to determine how far from 'loc' we can stray at this + // error level. + bin_min = 0; + bin_mid = bin_max; + while (bin_min < bin_mid) { + if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { + bin_min = bin_mid; + } else { + bin_max = bin_mid; + } + bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); + } + // Use the result from this iteration as the maximum for the next. + bin_max = bin_mid; + var start = Math.max(1, loc - bin_mid + 1); + var finish = Math.min(loc + bin_mid, text.length) + pattern.length; + + var rd = Array(finish + 2); + rd[finish + 1] = (1 << d) - 1; + for (var j = finish; j >= start; j--) { + // The alphabet (s) is a sparse hash, so the following line generates + // warnings. + var charMatch = s[text.charAt(j - 1)]; + if (d === 0) { // First pass: exact match. + rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; + } else { // Subsequent passes: fuzzy match. + rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | + (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | + last_rd[j + 1]; + } + if (rd[j] & matchmask) { + var score = match_bitapScore_(d, j - 1); + // This match will almost certainly be better than any existing match. + // But check anyway. + if (score <= score_threshold) { + // Told you so. + score_threshold = score; + best_loc = j - 1; + if (best_loc > loc) { + // When passing loc, don't exceed our current distance from loc. + start = Math.max(1, 2 * loc - best_loc); + } else { + // Already passed loc, downhill from here on in. + break; + } + } + } + } + // No hope for a (better) match at greater error levels. + if (match_bitapScore_(d + 1, loc) > score_threshold) { + break; + } + last_rd = rd; + } + return best_loc; + }; + + + /** + * Initialise the alphabet for the Bitap algorithm. + * @param {string} pattern The text to encode. + * @return {!Object} Hash of character locations. + * @private + */ + private match_alphabet_(pattern: string): {[key: string]: number} { + var s: {[key: string]: number} = {}; + for (var i = 0; i < pattern.length; i++) { + s[pattern.charAt(i)] = 0; + } + for (var i = 0; i < pattern.length; i++) { + s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1); + } + return s; + }; + + + // PATCH FUNCTIONS + + + /** + * Increase the context until it is unique, + * but don't let the pattern expand beyond Match_MaxBits. + * @param {!diff_match_patch.patch_obj} patch The patch to grow. + * @param {string} text Source text. + * @private + */ + private patch_addContext_(patch: patch_obj, text: string) { + if (text.length == 0) { + return; + } + if (patch.start2 === null) { + throw Error('patch not initialized'); + } + var pattern = text.substring(patch.start2, patch.start2 + patch.length1); + var padding = 0; + + // Look for the first and last matches of pattern in text. If two different + // matches are found, increase the pattern length. + while (text.indexOf(pattern) != text.lastIndexOf(pattern) && + pattern.length < this.Match_MaxBits - this.Patch_Margin - + this.Patch_Margin) { + padding += this.Patch_Margin; + pattern = text.substring(patch.start2 - padding, + patch.start2 + patch.length1 + padding); + } + // Add one chunk for good luck. + padding += this.Patch_Margin; + + // Add the prefix. + var prefix = text.substring(patch.start2 - padding, patch.start2); + if (prefix) { + patch.diffs.unshift(new Diff(DIFF_EQUAL, prefix)); + } + // Add the suffix. + var suffix = text.substring(patch.start2 + patch.length1, + patch.start2 + patch.length1 + padding); + if (suffix) { + patch.diffs.push(new Diff(DIFF_EQUAL, suffix)); + } + + // Roll back the start points. + patch.start1! -= prefix.length; + patch.start2! -= prefix.length; + // Extend the lengths. + patch.length1 += prefix.length + suffix.length; + patch.length2 += prefix.length + suffix.length; + }; + + + /** + * Compute a list of patches to turn text1 into text2. + * Use diffs if provided, otherwise compute it ourselves. + * There are four ways to call this function, depending on what data is + * available to the caller: + * Method 1: + * a = text1, b = text2 + * Method 2: + * a = diffs + * Method 3 (optimal): + * a = text1, b = diffs + * Method 4 (deprecated, use method 3): + * a = text1, b = text2, c = diffs + * + * @param {string|!Array.} a text1 (methods 1,3,4) or + * Array of diff tuples for text1 to text2 (method 2). + * @param {string|!Array.=} opt_b text2 (methods 1,4) or + * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). + * @param {string|!Array.=} opt_c Array of diff tuples + * for text1 to text2 (method 4) or undefined (methods 1,2,3). + * @return {!Array.} Array of Patch objects. + */ + patch_make(a: string | Diff[], opt_b?: string | Diff[], + opt_c?: string | Diff[]): patch_obj[] { + var text1, diffs; + if (typeof a == 'string' && typeof opt_b == 'string' && + typeof opt_c == 'undefined') { + // Method 1: text1, text2 + // Compute diffs from text1 and text2. + text1 = /** @type {string} */(a); + diffs = this.diff_main(text1, /** @type {string} */(opt_b), true); + if (diffs.length > 2) { + this.diff_cleanupSemantic(diffs); + this.diff_cleanupEfficiency(diffs); + } + } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' && + typeof opt_c == 'undefined') { + // Method 2: diffs + // Compute text1 from diffs. + diffs = /** @type {!Array.} */(a); + text1 = this.diff_text1(diffs); + } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' && + typeof opt_c == 'undefined') { + // Method 3: text1, diffs + text1 = /** @type {string} */(a); + diffs = /** @type {!Array.} */(opt_b); + } else if (typeof a == 'string' && typeof opt_b == 'string' && + opt_c && typeof opt_c == 'object') { + // Method 4: text1, text2, diffs + // text2 is not used. + text1 = /** @type {string} */(a); + diffs = /** @type {!Array.} */(opt_c); + } else { + throw new Error('Unknown call format to patch_make.'); + } + + if (diffs.length === 0) { + return []; // Get rid of the null case. + } + var patches: patch_obj[] = []; + var patch = new patch_obj(); + var patchDiffLength = 0; // Keeping our own length var is faster in JS. + var char_count1 = 0; // Number of characters into the text1 string. + var char_count2 = 0; // Number of characters into the text2 string. + // Start with text1 (prepatch_text) and apply the diffs until we arrive at + // text2 (postpatch_text). We recreate the patches one by one to determine + // context info. + var prepatch_text = text1; + var postpatch_text = text1; + for (var x = 0; x < diffs.length; x++) { + var diff_type = diffs[x].operation; + var diff_text = diffs[x].text; + + if (!patchDiffLength && diff_type !== DIFF_EQUAL) { + // A new patch starts here. + patch.start1 = char_count1; + patch.start2 = char_count2; + } + + switch (diff_type) { + case DIFF_INSERT: + patch.diffs[patchDiffLength++] = diffs[x]; + patch.length2 += diff_text.length; + postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + + postpatch_text.substring(char_count2); + break; + case DIFF_DELETE: + patch.length1 += diff_text.length; + patch.diffs[patchDiffLength++] = diffs[x]; + postpatch_text = postpatch_text.substring(0, char_count2) + + postpatch_text.substring(char_count2 + + diff_text.length); + break; + case DIFF_EQUAL: + if (diff_text.length <= 2 * this.Patch_Margin && + patchDiffLength && diffs.length != x + 1) { + // Small equality inside a patch. + patch.diffs[patchDiffLength++] = diffs[x]; + patch.length1 += diff_text.length; + patch.length2 += diff_text.length; + } else if (diff_text.length >= 2 * this.Patch_Margin) { + // Time for a new patch. + if (patchDiffLength) { + this.patch_addContext_(patch, prepatch_text); + patches.push(patch); + patch = new patch_obj(); + patchDiffLength = 0; + // Unlike Unidiff, our patch lists have a rolling context. + // https://github.com/google/diff-match-patch/wiki/Unidiff + // Update prepatch text & pos to reflect the application of the + // just completed patch. + prepatch_text = postpatch_text; + char_count1 = char_count2; + } + } + break; + } + + // Update the current character count. + if (diff_type !== DIFF_INSERT) { + char_count1 += diff_text.length; + } + if (diff_type !== DIFF_DELETE) { + char_count2 += diff_text.length; + } + } + // Pick up the leftover patch if not empty. + if (patchDiffLength) { + this.patch_addContext_(patch, prepatch_text); + patches.push(patch); + } + + return patches; + }; + + + /** + * Given an array of patches, return another array that is identical. + * @param {!Array.} patches Array of Patch objects. + * @return {!Array.} Array of Patch objects. + */ + patch_deepCopy(patches: patch_obj[]): patch_obj[] { + // Making deep copies is hard in JavaScript. + var patchesCopy: patch_obj[] = []; + for (var x = 0; x < patches.length; x++) { + var patch = patches[x]; + var patchCopy = new patch_obj(); + patchCopy.diffs = []; + for (var y = 0; y < patch.diffs.length; y++) { + patchCopy.diffs[y] = + new Diff(patch.diffs[y].operation, patch.diffs[y].text); + } + patchCopy.start1 = patch.start1; + patchCopy.start2 = patch.start2; + patchCopy.length1 = patch.length1; + patchCopy.length2 = patch.length2; + patchesCopy[x] = patchCopy; + } + return patchesCopy; + }; + + + /** + * Merge a set of patches onto the text. Return a patched text, as well + * as a list of true/false values indicating which patches were applied. + * @param {!Array.} patches Array of Patch objects. + * @param {string} text Old text. + * @return {!Array.>} Two element Array, containing the + * new text and an array of boolean values. + */ + patch_apply(patches: patch_obj[], text: string): (string | boolean[])[] { + if (patches.length == 0) { + return [text, []]; + } + + // Deep copy the patches so that no changes are made to originals. + patches = this.patch_deepCopy(patches); + + var nullPadding = this.patch_addPadding(patches); + text = nullPadding + text + nullPadding; + + this.patch_splitMax(patches); + // delta keeps track of the offset between the expected and actual location + // of the previous patch. If there are patches expected at positions 10 and + // 20, but the first patch was found at 12, delta is 2 and the second patch + // has an effective expected position of 22. + var delta = 0; + var results: boolean[] = []; + for (var x = 0; x < patches.length; x++) { + var expected_loc = patches[x].start2! + delta; + var text1 = this.diff_text1(patches[x].diffs); + var start_loc; + var end_loc = -1; + if (text1.length > this.Match_MaxBits) { + // patch_splitMax will only provide an oversized pattern in the case of + // a monster delete. + start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits), + expected_loc); + if (start_loc != -1) { + end_loc = this.match_main(text, + text1.substring(text1.length - this.Match_MaxBits), + expected_loc + text1.length - this.Match_MaxBits); + if (end_loc == -1 || start_loc >= end_loc) { + // Can't find valid trailing context. Drop this patch. + start_loc = -1; + } + } + } else { + start_loc = this.match_main(text, text1, expected_loc); + } + if (start_loc == -1) { + // No match found. :( + results[x] = false; + // Subtract the delta for this failed patch from subsequent patches. + delta -= patches[x].length2 - patches[x].length1; + } else { + // Found a match. :) + results[x] = true; + delta = start_loc - expected_loc; + var text2; + if (end_loc == -1) { + text2 = text.substring(start_loc, start_loc + text1.length); + } else { + text2 = text.substring(start_loc, end_loc + this.Match_MaxBits); + } + if (text1 == text2) { + // Perfect match, just shove the replacement text in. + text = text.substring(0, start_loc) + + this.diff_text2(patches[x].diffs) + + text.substring(start_loc + text1.length); + } else { + // Imperfect match. Run a diff to get a framework of equivalent + // indices. + var diffs = this.diff_main(text1, text2, false); + if (text1.length > this.Match_MaxBits && + this.diff_levenshtein(diffs) / text1.length > + this.Patch_DeleteThreshold) { + // The end points match, but the content is unacceptably bad. + results[x] = false; + } else { + this.diff_cleanupSemanticLossless(diffs); + var index1 = 0; + var index2 = 0; + for (var y = 0; y < patches[x].diffs.length; y++) { + var mod = patches[x].diffs[y]; + if (mod.operation !== DIFF_EQUAL) { + index2 = this.diff_xIndex(diffs, index1); + } + if (mod.operation === DIFF_INSERT) { // Insertion + text = text.substring(0, start_loc + index2) + mod.text + + text.substring(start_loc + index2); + } else if (mod.operation === DIFF_DELETE) { // Deletion + text = text.substring(0, start_loc + index2!) + + text.substring(start_loc + this.diff_xIndex(diffs, + index1 + mod.text.length)); + } + if (mod.operation !== DIFF_DELETE) { + index1 += mod.text.length; + } + } + } + } + } + } + // Strip the padding off. + text = text.substring(nullPadding.length, text.length - nullPadding.length); + return [text, results]; + }; + + + /** + * Add some padding on text start and end so that edges can match something. + * Intended to be called only from within patch_apply. + * @param {!Array.} patches Array of Patch objects. + * @return {string} The padding string added to each side. + */ + patch_addPadding(patches: patch_obj[]): string { + var paddingLength = this.Patch_Margin; + var nullPadding = ''; + for (var x = 1; x <= paddingLength; x++) { + nullPadding += String.fromCharCode(x); + } + + // Bump all the patches forward. + for (var x = 0; x < patches.length; x++) { + patches[x].start1! += paddingLength; + patches[x].start2! += paddingLength; + } + + // Add some padding on start of first diff. + var patch = patches[0]; + var diffs = patch.diffs; + if (diffs.length == 0 || diffs[0].operation != DIFF_EQUAL) { + // Add nullPadding equality. + diffs.unshift(new Diff(DIFF_EQUAL, nullPadding)); + patch.start1! -= paddingLength; // Should be 0. + patch.start2! -= paddingLength; // Should be 0. + patch.length1 += paddingLength; + patch.length2 += paddingLength; + } else if (paddingLength > diffs[0].text.length) { + // Grow first equality. + var extraLength = paddingLength - diffs[0].text.length; + diffs[0].text = nullPadding.substring(diffs[0].text.length) + diffs[0].text; + patch.start1! -= extraLength; + patch.start2! -= extraLength; + patch.length1 += extraLength; + patch.length2 += extraLength; + } + + // Add some padding on end of last diff. + patch = patches[patches.length - 1]; + diffs = patch.diffs; + if (diffs.length == 0 || diffs[diffs.length - 1].operation != DIFF_EQUAL) { + // Add nullPadding equality. + diffs.push(new Diff(DIFF_EQUAL, nullPadding)); + patch.length1 += paddingLength; + patch.length2 += paddingLength; + } else if (paddingLength > diffs[diffs.length - 1].text.length) { + // Grow last equality. + var extraLength = paddingLength - diffs[diffs.length - 1].text.length; + diffs[diffs.length - 1].text += nullPadding.substring(0, extraLength); + patch.length1 += extraLength; + patch.length2 += extraLength; + } + + return nullPadding; + }; + + + /** + * Look through the patches and break up any which are longer than the maximum + * limit of the match algorithm. + * Intended to be called only from within patch_apply. + * @param {!Array.} patches Array of Patch objects. + */ + patch_splitMax(patches: patch_obj[]) { + var patch_size = this.Match_MaxBits; + for (var x = 0; x < patches.length; x++) { + if (patches[x].length1 <= patch_size) { + continue; + } + var bigpatch = patches[x]; + // Remove the big old patch. + patches.splice(x--, 1); + var start1 = bigpatch.start1; + var start2 = bigpatch.start2; + var precontext = ''; + while (bigpatch.diffs.length !== 0) { + // Create one of several smaller patches. + var patch = new patch_obj(); + var empty = true; + patch.start1 = start1! - precontext.length; + patch.start2 = start2! - precontext.length; + if (precontext !== '') { + patch.length1 = patch.length2 = precontext.length; + patch.diffs.push(new Diff(DIFF_EQUAL, precontext)); + } + while (bigpatch.diffs.length !== 0 && + patch.length1 < patch_size - this.Patch_Margin) { + var diff_type = bigpatch.diffs[0].operation; + var diff_text = bigpatch.diffs[0].text; + if (diff_type === DIFF_INSERT) { + // Insertions are harmless. + patch.length2 += diff_text.length; + start2! += diff_text.length; + patch.diffs.push(bigpatch.diffs.shift()!); + empty = false; + } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 && + patch.diffs[0].operation == DIFF_EQUAL && + diff_text.length > 2 * patch_size) { + // This is a large deletion. Let it pass in one chunk. + patch.length1 += diff_text.length; + start1! += diff_text.length; + empty = false; + patch.diffs.push(new Diff(diff_type, diff_text)); + bigpatch.diffs.shift(); + } else { + // Deletion or equality. Only take as much as we can stomach. + diff_text = diff_text.substring(0, + patch_size - patch.length1 - this.Patch_Margin); + patch.length1 += diff_text.length; + start1! += diff_text.length; + if (diff_type === DIFF_EQUAL) { + patch.length2 += diff_text.length; + start2! += diff_text.length; + } else { + empty = false; + } + patch.diffs.push(new Diff(diff_type, diff_text)); + if (diff_text == bigpatch.diffs[0].text) { + bigpatch.diffs.shift(); + } else { + bigpatch.diffs[0].text = + bigpatch.diffs[0].text.substring(diff_text.length); + } + } + } + // Compute the head context for the next patch. + precontext = this.diff_text2(patch.diffs); + precontext = + precontext.substring(precontext.length - this.Patch_Margin); + // Append the end context for this patch. + var postcontext = this.diff_text1(bigpatch.diffs) + .substring(0, this.Patch_Margin); + if (postcontext !== '') { + patch.length1 += postcontext.length; + patch.length2 += postcontext.length; + if (patch.diffs.length !== 0 && + patch.diffs[patch.diffs.length - 1].operation === DIFF_EQUAL) { + patch.diffs[patch.diffs.length - 1].text += postcontext; + } else { + patch.diffs.push(new Diff(DIFF_EQUAL, postcontext)); + } + } + if (!empty) { + patches.splice(++x, 0, patch); + } + } + } + }; + + + /** + * Take a list of patches and return a textual representation. + * @param {!Array.} patches Array of Patch objects. + * @return {string} Text representation of patches. + */ + patch_toText(patches: patch_obj[]): string { + var text: patch_obj[] = []; + for (var x = 0; x < patches.length; x++) { + text[x] = patches[x]; + } + return text.join(''); + }; + + + /** + * Parse a textual representation of patches and return a list of Patch objects. + * @param {string} textline Text representation of patches. + * @return {!Array.} Array of Patch objects. + * @throws {!Error} If invalid input. + */ + patch_fromText(textline: string): patch_obj[] { + var patches: patch_obj[] = []; + if (!textline) { + return patches; + } + var text = textline.split('\n'); + var textPointer = 0; + var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; + while (textPointer < text.length) { + var m = text[textPointer].match(patchHeader); + if (!m) { + throw new Error('Invalid patch string: ' + text[textPointer]); + } + var patch = new patch_obj(); + patches.push(patch); + patch.start1 = parseInt(m[1], 10); + if (m[2] === '') { + patch.start1--; + patch.length1 = 1; + } else if (m[2] == '0') { + patch.length1 = 0; + } else { + patch.start1--; + patch.length1 = parseInt(m[2], 10); + } + + patch.start2 = parseInt(m[3], 10); + if (m[4] === '') { + patch.start2--; + patch.length2 = 1; + } else if (m[4] == '0') { + patch.length2 = 0; + } else { + patch.start2--; + patch.length2 = parseInt(m[4], 10); + } + textPointer++; + + while (textPointer < text.length) { + var sign = text[textPointer].charAt(0); + try { + var line = decodeURI(text[textPointer].substring(1)); + } catch (ex) { + // Malformed URI sequence. + throw new Error('Illegal escape in patch_fromText: ' + line!); + } + if (sign == '-') { + // Deletion. + patch.diffs.push(new Diff(DIFF_DELETE, line)); + } else if (sign == '+') { + // Insertion. + patch.diffs.push(new Diff(DIFF_INSERT, line)); + } else if (sign == ' ') { + // Minor equality. + patch.diffs.push(new Diff(DIFF_EQUAL, line)); + } else if (sign == '@') { + // Start of next patch. + break; + } else if (sign === '') { + // Blank line? Whatever. + } else { + // WTF? + throw new Error('Invalid patch mode "' + sign + '" in: ' + line); + } + textPointer++; + } + } + return patches; + }; + +} + +export const DIFF_DELETE = -1; +export const DIFF_INSERT = 1; +export const DIFF_EQUAL = 0; + + +/** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ + + +/** + * Class representing one diff tuple. + * Attempts to look like a two-element array (which is what this used to be). + * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. + * @param {string} text Text to be deleted, inserted, or retained. + * @constructor + */ +export class Diff { + + operation: number; + text: string; + + constructor(op: number, text: string) { + this.operation = op; + this.text = text; + } + + /** + * Emulate the output of a two-element array. + * @return {string} Diff operation as a string. + */ + toString() { + return this.operation + ',' + this.text; + }; +} + + +/** + * Class representing one patch operation. + * @constructor + */ +export class patch_obj { + + public diffs: Diff[]; + public start1: number | null; + public start2: number | null; + public length1: number; + public length2: number; + + constructor() { + /** @type {!Array.} */ + this.diffs = []; + /** @type {?number} */ + this.start1 = null; + /** @type {?number} */ + this.start2 = null; + /** @type {number} */ + this.length1 = 0; + /** @type {number} */ + this.length2 = 0; + }; + + /** + * Emulate GNU diff's format. + * Header: @@ -382,8 +481,9 @@ + * Indices are printed as 1-based, not 0-based. + * @return {string} The GNU diff string. + */ + toString() { + var coords1, coords2; + if (this.length1 === 0) { + coords1 = this.start1 + ',0'; + } else if (this.length1 == 1) { + coords1 = this.start1! + 1; + } else { + coords1 = (this.start1! + 1) + ',' + this.length1; + } + if (this.length2 === 0) { + coords2 = this.start2! + ',0'; + } else if (this.length2 == 1) { + coords2 = this.start2! + 1; + } else { + coords2 = (this.start2! + 1) + ',' + this.length2; + } + var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n']; + var op; + // Escape the body of the patch with %xx notation. + for (var x = 0; x < this.diffs.length; x++) { + switch (this.diffs[x].operation) { + case DIFF_INSERT: + op = '+'; + break; + case DIFF_DELETE: + op = '-'; + break; + case DIFF_EQUAL: + op = ' '; + break; + } + text[x + 1] = op + encodeURI(this.diffs[x].text) + '\n'; + } + return text.join('').replace(/%20/g, ' '); + }; +} diff --git a/typescript/tests/diff_match_patch_test.ts b/typescript/tests/diff_match_patch_test.ts new file mode 100644 index 0000000..55022fc --- /dev/null +++ b/typescript/tests/diff_match_patch_test.ts @@ -0,0 +1,1065 @@ +/** + * Diff Match and Patch -- Test Harness + * Copyright 2018 The diff-match-patch Authors. + * https://github.com/google/diff-match-patch + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +import diff_match_patch, { Diff, patch_obj, DIFF_EQUAL, DIFF_INSERT, DIFF_DELETE } from '../diff_match_patch'; + +// If expected and actual are the equivalent, pass the test. +function assertEquivalent(msg: any, expected: any, actual?: any) { + if (typeof actual == 'undefined') { + // msg is optional. + actual = expected; + expected = msg; + msg = 'Expected: \'' + expected + '\' Actual: \'' + actual + '\''; + } + if (_equivalent(expected, actual)) { + return assertEquals(msg, String(expected), String(actual)); + } else { + return assertEquals(msg, expected, actual); + } +} + + +// Are a and b the equivalent? -- Recursive. +function _equivalent(a: any, b: any) { + if (a == b) { + return true; + } + if (typeof a == 'object' && typeof b == 'object' && a !== null && b !== null) { + if (a.toString() != b.toString()) { + return false; + } + for (var p in a) { + if (a.hasOwnProperty(p) && !_equivalent(a[p], b[p])) { + return false; + } + } + for (var p in b) { + if (a.hasOwnProperty(p) && !_equivalent(a[p], b[p])) { + return false; + } + } + return true; + } + return false; +} + + +function diff_rebuildtexts(diffs: Diff[]) { + // Construct the two texts which made up the diff originally. + var text1 = ''; + var text2 = ''; + for (var x = 0; x < diffs.length; x++) { + if (diffs[x].operation != DIFF_INSERT) { + text1 += diffs[x].text; + } + if (diffs[x].operation != DIFF_DELETE) { + text2 += diffs[x].text; + } + } + return [text1, text2]; +} + +var dmp = new diff_match_patch(); + + +// DIFF TEST FUNCTIONS + + +export function testDiffCommonPrefix() { + // Detect any common prefix. + // Null case. + assertEquals(0, dmp.diff_commonPrefix('abc', 'xyz')); + + // Non-null case. + assertEquals(4, dmp.diff_commonPrefix('1234abcdef', '1234xyz')); + + // Whole case. + assertEquals(4, dmp.diff_commonPrefix('1234', '1234xyz')); +} + +export function testDiffCommonSuffix() { + // Detect any common suffix. + // Null case. + assertEquals(0, dmp.diff_commonSuffix('abc', 'xyz')); + + // Non-null case. + assertEquals(4, dmp.diff_commonSuffix('abcdef1234', 'xyz1234')); + + // Whole case. + assertEquals(4, dmp.diff_commonSuffix('1234', 'xyz1234')); +} + +export function testDiffCommonOverlap() { + // Detect any suffix/prefix overlap. + // Null case. + assertEquals(0, (dmp as any).diff_commonOverlap_('', 'abcd')); + + // Whole case. + assertEquals(3, (dmp as any).diff_commonOverlap_('abc', 'abcd')); + + // No overlap. + assertEquals(0, (dmp as any).diff_commonOverlap_('123456', 'abcd')); + + // Overlap. + assertEquals(3, (dmp as any).diff_commonOverlap_('123456xxx', 'xxxabcd')); + + // Unicode. + // Some overly clever languages (C#) may treat ligatures as equal to their + // component letters. E.g. U+FB01 == 'fi' + assertEquals(0, (dmp as any).diff_commonOverlap_('fi', '\ufb01i')); +} + +export function testDiffHalfMatch() { + // Detect a halfmatch. + dmp.Diff_Timeout = 1; + // No match. + assertEquals(null, (dmp as any).diff_halfMatch_('1234567890', 'abcdef')); + + assertEquals(null, (dmp as any).diff_halfMatch_('12345', '23')); + + // Single Match. + assertEquivalent(['12', '90', 'a', 'z', '345678'], (dmp as any).diff_halfMatch_('1234567890', 'a345678z')); + + assertEquivalent(['a', 'z', '12', '90', '345678'], (dmp as any).diff_halfMatch_('a345678z', '1234567890')); + + assertEquivalent(['abc', 'z', '1234', '0', '56789'], (dmp as any).diff_halfMatch_('abc56789z', '1234567890')); + + assertEquivalent(['a', 'xyz', '1', '7890', '23456'], (dmp as any).diff_halfMatch_('a23456xyz', '1234567890')); + + // Multiple Matches. + assertEquivalent(['12123', '123121', 'a', 'z', '1234123451234'], (dmp as any).diff_halfMatch_('121231234123451234123121', 'a1234123451234z')); + + assertEquivalent(['', '-=-=-=-=-=', 'x', '', 'x-=-=-=-=-=-=-='], (dmp as any).diff_halfMatch_('x-=-=-=-=-=-=-=-=-=-=-=-=', 'xx-=-=-=-=-=-=-=')); + + assertEquivalent(['-=-=-=-=-=', '', '', 'y', '-=-=-=-=-=-=-=y'], (dmp as any).diff_halfMatch_('-=-=-=-=-=-=-=-=-=-=-=-=y', '-=-=-=-=-=-=-=yy')); + + // Non-optimal halfmatch. + // Optimal diff would be -q+x=H-i+e=lloHe+Hu=llo-Hew+y not -qHillo+x=HelloHe-w+Hulloy + assertEquivalent(['qHillo', 'w', 'x', 'Hulloy', 'HelloHe'], (dmp as any).diff_halfMatch_('qHilloHelloHew', 'xHelloHeHulloy')); + + // Optimal no halfmatch. + dmp.Diff_Timeout = 0; + assertEquals(null, (dmp as any).diff_halfMatch_('qHilloHelloHew', 'xHelloHeHulloy')); +} + +export function testDiffLinesToChars() { + function assertLinesToCharsResultEquals(a: any, b: any) { + assertEquals(a.chars1, b.chars1); + assertEquals(a.chars2, b.chars2); + assertEquivalent(a.lineArray, b.lineArray); + } + + // Convert lines down to characters. + assertLinesToCharsResultEquals({ chars1: '\x01\x02\x01', chars2: '\x02\x01\x02', lineArray: ['', 'alpha\n', 'beta\n'] }, (dmp as any).diff_linesToChars_('alpha\nbeta\nalpha\n', 'beta\nalpha\nbeta\n')); + + assertLinesToCharsResultEquals({ chars1: '', chars2: '\x01\x02\x03\x03', lineArray: ['', 'alpha\r\n', 'beta\r\n', '\r\n'] }, (dmp as any).diff_linesToChars_('', 'alpha\r\nbeta\r\n\r\n\r\n')); + + assertLinesToCharsResultEquals({ chars1: '\x01', chars2: '\x02', lineArray: ['', 'a', 'b'] }, (dmp as any).diff_linesToChars_('a', 'b')); + + // More than 256 to reveal any 8-bit limitations. + var n = 300; + var lineList = []; + var charList = []; + for (var i = 1; i < n + 1; i++) { + lineList[i - 1] = i + '\n'; + charList[i - 1] = String.fromCharCode(i); + } + assertEquals(n, lineList.length); + var lines = lineList.join(''); + var chars = charList.join(''); + assertEquals(n, chars.length); + lineList.unshift(''); + assertLinesToCharsResultEquals({ chars1: chars, chars2: '', lineArray: lineList }, (dmp as any).diff_linesToChars_(lines, '')); +} + +export function testDiffCharsToLines() { + // Convert chars up to lines. + var diffs: Diff[] = [new Diff(DIFF_EQUAL, '\x01\x02\x01'), new Diff(DIFF_INSERT, '\x02\x01\x02')]; + (dmp as any).diff_charsToLines_(diffs, ['', 'alpha\n', 'beta\n']); + assertEquivalent([new Diff(DIFF_EQUAL, 'alpha\nbeta\nalpha\n'), new Diff(DIFF_INSERT, 'beta\nalpha\nbeta\n')], diffs); + + // More than 256 to reveal any 8-bit limitations. + var n = 300; + var lineList = []; + var charList = []; + for (var i = 1; i < n + 1; i++) { + lineList[i - 1] = i + '\n'; + charList[i - 1] = String.fromCharCode(i); + } + assertEquals(n, lineList.length); + var lines = lineList.join(''); + var chars = charList.join(''); + assertEquals(n, chars.length); + lineList.unshift(''); + var diffs: Diff[] = [new Diff(DIFF_DELETE, chars)]; + (dmp as any).diff_charsToLines_(diffs, lineList); + assertEquivalent([new Diff(DIFF_DELETE, lines)], diffs); + + // More than 65536 to verify any 16-bit limitation. + lineList = []; + for (var i = 0; i < 66000; i++) { + lineList[i] = i + '\n'; + } + chars = lineList.join(''); + var results = (dmp as any).diff_linesToChars_(chars, ''); + diffs = [new Diff(DIFF_INSERT, results.chars1)]; + (dmp as any).diff_charsToLines_(diffs, results.lineArray); + assertEquals(chars, diffs[0].text); +} + +export function testDiffCleanupMerge() { + // Cleanup a messy diff. + // Null case. + var diffs: Diff[] = []; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([], diffs); + + // No change case. + diffs = [new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, 'b'), new Diff(DIFF_INSERT, 'c')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, 'b'), new Diff(DIFF_INSERT, 'c')], diffs); + + // Merge equalities. + diffs = [new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_EQUAL, 'b'), new Diff(DIFF_EQUAL, 'c')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'abc')], diffs); + + // Merge deletions. + diffs = [new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_DELETE, 'b'), new Diff(DIFF_DELETE, 'c')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abc')], diffs); + + // Merge insertions. + diffs = [new Diff(DIFF_INSERT, 'a'), new Diff(DIFF_INSERT, 'b'), new Diff(DIFF_INSERT, 'c')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_INSERT, 'abc')], diffs); + + // Merge interweave. + diffs = [new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_INSERT, 'b'), new Diff(DIFF_DELETE, 'c'), new Diff(DIFF_INSERT, 'd'), new Diff(DIFF_EQUAL, 'e'), new Diff(DIFF_EQUAL, 'f')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'ac'), new Diff(DIFF_INSERT, 'bd'), new Diff(DIFF_EQUAL, 'ef')], diffs); + + // Prefix and suffix detection. + diffs = [new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_INSERT, 'abc'), new Diff(DIFF_DELETE, 'dc')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, 'd'), new Diff(DIFF_INSERT, 'b'), new Diff(DIFF_EQUAL, 'c')], diffs); + + // Prefix and suffix detection with equalities. + diffs = [new Diff(DIFF_EQUAL, 'x'), new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_INSERT, 'abc'), new Diff(DIFF_DELETE, 'dc'), new Diff(DIFF_EQUAL, 'y')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'xa'), new Diff(DIFF_DELETE, 'd'), new Diff(DIFF_INSERT, 'b'), new Diff(DIFF_EQUAL, 'cy')], diffs); + + // Slide edit left. + diffs = [new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_INSERT, 'ba'), new Diff(DIFF_EQUAL, 'c')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_INSERT, 'ab'), new Diff(DIFF_EQUAL, 'ac')], diffs); + + // Slide edit right. + diffs = [new Diff(DIFF_EQUAL, 'c'), new Diff(DIFF_INSERT, 'ab'), new Diff(DIFF_EQUAL, 'a')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'ca'), new Diff(DIFF_INSERT, 'ba')], diffs); + + // Slide edit left recursive. + diffs = [new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, 'b'), new Diff(DIFF_EQUAL, 'c'), new Diff(DIFF_DELETE, 'ac'), new Diff(DIFF_EQUAL, 'x')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abc'), new Diff(DIFF_EQUAL, 'acx')], diffs); + + // Slide edit right recursive. + diffs = [new Diff(DIFF_EQUAL, 'x'), new Diff(DIFF_DELETE, 'ca'), new Diff(DIFF_EQUAL, 'c'), new Diff(DIFF_DELETE, 'b'), new Diff(DIFF_EQUAL, 'a')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'xca'), new Diff(DIFF_DELETE, 'cba')], diffs); + + // Empty merge. + diffs = [new Diff(DIFF_DELETE, 'b'), new Diff(DIFF_INSERT, 'ab'), new Diff(DIFF_EQUAL, 'c')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_INSERT, 'a'), new Diff(DIFF_EQUAL, 'bc')], diffs); + + // Empty equality. + diffs = [new Diff(DIFF_EQUAL, ''), new Diff(DIFF_INSERT, 'a'), new Diff(DIFF_EQUAL, 'b')]; + dmp.diff_cleanupMerge(diffs); + assertEquivalent([new Diff(DIFF_INSERT, 'a'), new Diff(DIFF_EQUAL, 'b')], diffs); +} + +export function testDiffCleanupSemanticLossless() { + // Slide diffs to match logical boundaries. + // Null case. + var diffs: Diff[] = []; + dmp.diff_cleanupSemanticLossless(diffs); + assertEquivalent([], diffs); + + // Blank lines. + diffs = [new Diff(DIFF_EQUAL, 'AAA\r\n\r\nBBB'), new Diff(DIFF_INSERT, '\r\nDDD\r\n\r\nBBB'), new Diff(DIFF_EQUAL, '\r\nEEE')]; + dmp.diff_cleanupSemanticLossless(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'AAA\r\n\r\n'), new Diff(DIFF_INSERT, 'BBB\r\nDDD\r\n\r\n'), new Diff(DIFF_EQUAL, 'BBB\r\nEEE')], diffs); + + // Line boundaries. + diffs = [new Diff(DIFF_EQUAL, 'AAA\r\nBBB'), new Diff(DIFF_INSERT, ' DDD\r\nBBB'), new Diff(DIFF_EQUAL, ' EEE')]; + dmp.diff_cleanupSemanticLossless(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'AAA\r\n'), new Diff(DIFF_INSERT, 'BBB DDD\r\n'), new Diff(DIFF_EQUAL, 'BBB EEE')], diffs); + + // Word boundaries. + diffs = [new Diff(DIFF_EQUAL, 'The c'), new Diff(DIFF_INSERT, 'ow and the c'), new Diff(DIFF_EQUAL, 'at.')]; + dmp.diff_cleanupSemanticLossless(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'The '), new Diff(DIFF_INSERT, 'cow and the '), new Diff(DIFF_EQUAL, 'cat.')], diffs); + + // Alphanumeric boundaries. + diffs = [new Diff(DIFF_EQUAL, 'The-c'), new Diff(DIFF_INSERT, 'ow-and-the-c'), new Diff(DIFF_EQUAL, 'at.')]; + dmp.diff_cleanupSemanticLossless(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'The-'), new Diff(DIFF_INSERT, 'cow-and-the-'), new Diff(DIFF_EQUAL, 'cat.')], diffs); + + // Hitting the start. + diffs = [new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_EQUAL, 'ax')]; + dmp.diff_cleanupSemanticLossless(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_EQUAL, 'aax')], diffs); + + // Hitting the end. + diffs = [new Diff(DIFF_EQUAL, 'xa'), new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_EQUAL, 'a')]; + dmp.diff_cleanupSemanticLossless(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'xaa'), new Diff(DIFF_DELETE, 'a')], diffs); + + // Sentence boundaries. + diffs = [new Diff(DIFF_EQUAL, 'The xxx. The '), new Diff(DIFF_INSERT, 'zzz. The '), new Diff(DIFF_EQUAL, 'yyy.')]; + dmp.diff_cleanupSemanticLossless(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'The xxx.'), new Diff(DIFF_INSERT, ' The zzz.'), new Diff(DIFF_EQUAL, ' The yyy.')], diffs); +} + +export function testDiffCleanupSemantic() { + // Cleanup semantically trivial equalities. + // Null case. + var diffs: Diff[] = []; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([], diffs); + + // No elimination #1. + diffs = [new Diff(DIFF_DELETE, 'ab'), new Diff(DIFF_INSERT, 'cd'), new Diff(DIFF_EQUAL, '12'), new Diff(DIFF_DELETE, 'e')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'ab'), new Diff(DIFF_INSERT, 'cd'), new Diff(DIFF_EQUAL, '12'), new Diff(DIFF_DELETE, 'e')], diffs); + + // No elimination #2. + diffs = [new Diff(DIFF_DELETE, 'abc'), new Diff(DIFF_INSERT, 'ABC'), new Diff(DIFF_EQUAL, '1234'), new Diff(DIFF_DELETE, 'wxyz')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abc'), new Diff(DIFF_INSERT, 'ABC'), new Diff(DIFF_EQUAL, '1234'), new Diff(DIFF_DELETE, 'wxyz')], diffs); + + // Simple elimination. + diffs = [new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_EQUAL, 'b'), new Diff(DIFF_DELETE, 'c')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abc'), new Diff(DIFF_INSERT, 'b')], diffs); + + // Backpass elimination. + diffs = [new Diff(DIFF_DELETE, 'ab'), new Diff(DIFF_EQUAL, 'cd'), new Diff(DIFF_DELETE, 'e'), new Diff(DIFF_EQUAL, 'f'), new Diff(DIFF_INSERT, 'g')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abcdef'), new Diff(DIFF_INSERT, 'cdfg')], diffs); + + // Multiple eliminations. + diffs = [new Diff(DIFF_INSERT, '1'), new Diff(DIFF_EQUAL, 'A'), new Diff(DIFF_DELETE, 'B'), new Diff(DIFF_INSERT, '2'), new Diff(DIFF_EQUAL, '_'), new Diff(DIFF_INSERT, '1'), new Diff(DIFF_EQUAL, 'A'), new Diff(DIFF_DELETE, 'B'), new Diff(DIFF_INSERT, '2')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'AB_AB'), new Diff(DIFF_INSERT, '1A2_1A2')], diffs); + + // Word boundaries. + diffs = [new Diff(DIFF_EQUAL, 'The c'), new Diff(DIFF_DELETE, 'ow and the c'), new Diff(DIFF_EQUAL, 'at.')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_EQUAL, 'The '), new Diff(DIFF_DELETE, 'cow and the '), new Diff(DIFF_EQUAL, 'cat.')], diffs); + + // No overlap elimination. + diffs = [new Diff(DIFF_DELETE, 'abcxx'), new Diff(DIFF_INSERT, 'xxdef')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abcxx'), new Diff(DIFF_INSERT, 'xxdef')], diffs); + + // Overlap elimination. + diffs = [new Diff(DIFF_DELETE, 'abcxxx'), new Diff(DIFF_INSERT, 'xxxdef')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abc'), new Diff(DIFF_EQUAL, 'xxx'), new Diff(DIFF_INSERT, 'def')], diffs); + + // Reverse overlap elimination. + diffs = [new Diff(DIFF_DELETE, 'xxxabc'), new Diff(DIFF_INSERT, 'defxxx')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_INSERT, 'def'), new Diff(DIFF_EQUAL, 'xxx'), new Diff(DIFF_DELETE, 'abc')], diffs); + + // Two overlap eliminations. + diffs = [new Diff(DIFF_DELETE, 'abcd1212'), new Diff(DIFF_INSERT, '1212efghi'), new Diff(DIFF_EQUAL, '----'), new Diff(DIFF_DELETE, 'A3'), new Diff(DIFF_INSERT, '3BC')]; + dmp.diff_cleanupSemantic(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abcd'), new Diff(DIFF_EQUAL, '1212'), new Diff(DIFF_INSERT, 'efghi'), new Diff(DIFF_EQUAL, '----'), new Diff(DIFF_DELETE, 'A'), new Diff(DIFF_EQUAL, '3'), new Diff(DIFF_INSERT, 'BC')], diffs); +} + +export function testDiffCleanupEfficiency() { + // Cleanup operationally trivial equalities. + dmp.Diff_EditCost = 4; + // Null case. + var diffs: Diff[] = []; + dmp.diff_cleanupEfficiency(diffs); + assertEquivalent([], diffs); + + // No elimination. + diffs = [new Diff(DIFF_DELETE, 'ab'), new Diff(DIFF_INSERT, '12'), new Diff(DIFF_EQUAL, 'wxyz'), new Diff(DIFF_DELETE, 'cd'), new Diff(DIFF_INSERT, '34')]; + dmp.diff_cleanupEfficiency(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'ab'), new Diff(DIFF_INSERT, '12'), new Diff(DIFF_EQUAL, 'wxyz'), new Diff(DIFF_DELETE, 'cd'), new Diff(DIFF_INSERT, '34')], diffs); + + // Four-edit elimination. + diffs = [new Diff(DIFF_DELETE, 'ab'), new Diff(DIFF_INSERT, '12'), new Diff(DIFF_EQUAL, 'xyz'), new Diff(DIFF_DELETE, 'cd'), new Diff(DIFF_INSERT, '34')]; + dmp.diff_cleanupEfficiency(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abxyzcd'), new Diff(DIFF_INSERT, '12xyz34')], diffs); + + // Three-edit elimination. + diffs = [new Diff(DIFF_INSERT, '12'), new Diff(DIFF_EQUAL, 'x'), new Diff(DIFF_DELETE, 'cd'), new Diff(DIFF_INSERT, '34')]; + dmp.diff_cleanupEfficiency(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'xcd'), new Diff(DIFF_INSERT, '12x34')], diffs); + + // Backpass elimination. + diffs = [new Diff(DIFF_DELETE, 'ab'), new Diff(DIFF_INSERT, '12'), new Diff(DIFF_EQUAL, 'xy'), new Diff(DIFF_INSERT, '34'), new Diff(DIFF_EQUAL, 'z'), new Diff(DIFF_DELETE, 'cd'), new Diff(DIFF_INSERT, '56')]; + dmp.diff_cleanupEfficiency(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abxyzcd'), new Diff(DIFF_INSERT, '12xy34z56')], diffs); + + // High cost elimination. + dmp.Diff_EditCost = 5; + diffs = [new Diff(DIFF_DELETE, 'ab'), new Diff(DIFF_INSERT, '12'), new Diff(DIFF_EQUAL, 'wxyz'), new Diff(DIFF_DELETE, 'cd'), new Diff(DIFF_INSERT, '34')]; + dmp.diff_cleanupEfficiency(diffs); + assertEquivalent([new Diff(DIFF_DELETE, 'abwxyzcd'), new Diff(DIFF_INSERT, '12wxyz34')], diffs); + dmp.Diff_EditCost = 4; +} + +export function testDiffPrettyHtml() { + // Pretty print. + var diffs: Diff[] = [new Diff(DIFF_EQUAL, 'a\n'), new Diff(DIFF_DELETE, 'b'), new Diff(DIFF_INSERT, 'c&d')]; + assertEquals('
<B>b</B>c&d', dmp.diff_prettyHtml(diffs)); +} + +export function testDiffText() { + // Compute the source and destination texts. + var diffs: Diff[] = [new Diff(DIFF_EQUAL, 'jump'), new Diff(DIFF_DELETE, 's'), new Diff(DIFF_INSERT, 'ed'), new Diff(DIFF_EQUAL, ' over '), new Diff(DIFF_DELETE, 'the'), new Diff(DIFF_INSERT, 'a'), new Diff(DIFF_EQUAL, ' lazy')]; + assertEquals('jumps over the lazy', dmp.diff_text1(diffs)); + + assertEquals('jumped over a lazy', dmp.diff_text2(diffs)); +} + +export function testDiffDelta() { + // Convert a diff into delta string. + var diffs: Diff[] = [new Diff(DIFF_EQUAL, 'jump'), new Diff(DIFF_DELETE, 's'), new Diff(DIFF_INSERT, 'ed'), new Diff(DIFF_EQUAL, ' over '), new Diff(DIFF_DELETE, 'the'), new Diff(DIFF_INSERT, 'a'), new Diff(DIFF_EQUAL, ' lazy'), new Diff(DIFF_INSERT, 'old dog')]; + var text1 = dmp.diff_text1(diffs); + assertEquals('jumps over the lazy', text1); + + var delta = dmp.diff_toDelta(diffs); + assertEquals('=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog', delta); + + // Convert delta string into a diff. + assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta)); + + // Generates error (19 != 20). + try { + dmp.diff_fromDelta(text1 + 'x', delta); + assertEquals(Error, null); + } catch (e) { + // Exception expected. + } + + // Generates error (19 != 18). + try { + dmp.diff_fromDelta(text1.substring(1), delta); + assertEquals(Error, null); + } catch (e) { + // Exception expected. + } + + // Generates error (%c3%xy invalid Unicode). + try { + dmp.diff_fromDelta('', '+%c3%xy'); + assertEquals(Error, null); + } catch (e) { + // Exception expected. + } + + // Test deltas with special characters. + diffs = [new Diff(DIFF_EQUAL, '\u0680 \x00 \t %'), new Diff(DIFF_DELETE, '\u0681 \x01 \n ^'), new Diff(DIFF_INSERT, '\u0682 \x02 \\ |')]; + text1 = dmp.diff_text1(diffs); + assertEquals('\u0680 \x00 \t %\u0681 \x01 \n ^', text1); + + delta = dmp.diff_toDelta(diffs); + assertEquals('=7\t-7\t+%DA%82 %02 %5C %7C', delta); + + // Convert delta string into a diff. + assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta)); + + // Verify pool of unchanged characters. + diffs = [new Diff(DIFF_INSERT, 'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ')]; + var text2 = dmp.diff_text2(diffs); + assertEquals('A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ', text2); + + delta = dmp.diff_toDelta(diffs); + assertEquals('+A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ', delta); + + // Convert delta string into a diff. + assertEquivalent(diffs, dmp.diff_fromDelta('', delta)); + + // 160 kb string. + var a = 'abcdefghij'; + for (var i = 0; i < 14; i++) { + a += a; + } + diffs = [new Diff(DIFF_INSERT, a)]; + delta = dmp.diff_toDelta(diffs); + assertEquals('+' + a, delta); + + // Convert delta string into a diff. + assertEquivalent(diffs, dmp.diff_fromDelta('', delta)); +} + +export function testDiffXIndex() { + // Translate a location in text1 to text2. + // Translation on equality. + assertEquals(5, dmp.diff_xIndex([new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_INSERT, '1234'), new Diff(DIFF_EQUAL, 'xyz')], 2)); + + // Translation on deletion. + assertEquals(1, dmp.diff_xIndex([new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, '1234'), new Diff(DIFF_EQUAL, 'xyz')], 3)); +} + +export function testDiffLevenshtein() { + // Levenshtein with trailing equality. + assertEquals(4, dmp.diff_levenshtein([new Diff(DIFF_DELETE, 'abc'), new Diff(DIFF_INSERT, '1234'), new Diff(DIFF_EQUAL, 'xyz')])); + // Levenshtein with leading equality. + assertEquals(4, dmp.diff_levenshtein([new Diff(DIFF_EQUAL, 'xyz'), new Diff(DIFF_DELETE, 'abc'), new Diff(DIFF_INSERT, '1234')])); + // Levenshtein with middle equality. + assertEquals(7, dmp.diff_levenshtein([new Diff(DIFF_DELETE, 'abc'), new Diff(DIFF_EQUAL, 'xyz'), new Diff(DIFF_INSERT, '1234')])); +} + +export function testDiffBisect() { + // Normal. + var a = 'cat'; + var b = 'map'; + // Since the resulting diff hasn't been normalized, it would be ok if + // the insertion and deletion pairs are swapped. + // If the order changes, tweak this test as required. + assertEquivalent([new Diff(DIFF_DELETE, 'c'), new Diff(DIFF_INSERT, 'm'), new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, 't'), new Diff(DIFF_INSERT, 'p')], (dmp as any).diff_bisect_(a, b, Number.MAX_VALUE)); + + // Timeout. + assertEquivalent([new Diff(DIFF_DELETE, 'cat'), new Diff(DIFF_INSERT, 'map')], (dmp as any).diff_bisect_(a, b, 0)); +} + +export function testDiffMain() { + // Perform a trivial diff. + // Null case. + assertEquivalent([], dmp.diff_main('', '', false)); + + // Equality. + assertEquivalent([new Diff(DIFF_EQUAL, 'abc')], dmp.diff_main('abc', 'abc', false)); + + // Simple insertion. + assertEquivalent([new Diff(DIFF_EQUAL, 'ab'), new Diff(DIFF_INSERT, '123'), new Diff(DIFF_EQUAL, 'c')], dmp.diff_main('abc', 'ab123c', false)); + + // Simple deletion. + assertEquivalent([new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, '123'), new Diff(DIFF_EQUAL, 'bc')], dmp.diff_main('a123bc', 'abc', false)); + + // Two insertions. + assertEquivalent([new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_INSERT, '123'), new Diff(DIFF_EQUAL, 'b'), new Diff(DIFF_INSERT, '456'), new Diff(DIFF_EQUAL, 'c')], dmp.diff_main('abc', 'a123b456c', false)); + + // Two deletions. + assertEquivalent([new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, '123'), new Diff(DIFF_EQUAL, 'b'), new Diff(DIFF_DELETE, '456'), new Diff(DIFF_EQUAL, 'c')], dmp.diff_main('a123b456c', 'abc', false)); + + // Perform a real diff. + // Switch off the timeout. + dmp.Diff_Timeout = 0; + // Simple cases. + assertEquivalent([new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_INSERT, 'b')], dmp.diff_main('a', 'b', false)); + + assertEquivalent([new Diff(DIFF_DELETE, 'Apple'), new Diff(DIFF_INSERT, 'Banana'), new Diff(DIFF_EQUAL, 's are a'), new Diff(DIFF_INSERT, 'lso'), new Diff(DIFF_EQUAL, ' fruit.')], dmp.diff_main('Apples are a fruit.', 'Bananas are also fruit.', false)); + + assertEquivalent([new Diff(DIFF_DELETE, 'a'), new Diff(DIFF_INSERT, '\u0680'), new Diff(DIFF_EQUAL, 'x'), new Diff(DIFF_DELETE, '\t'), new Diff(DIFF_INSERT, '\0')], dmp.diff_main('ax\t', '\u0680x\0', false)); + + // Overlaps. + assertEquivalent([new Diff(DIFF_DELETE, '1'), new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, 'y'), new Diff(DIFF_EQUAL, 'b'), new Diff(DIFF_DELETE, '2'), new Diff(DIFF_INSERT, 'xab')], dmp.diff_main('1ayb2', 'abxab', false)); + + assertEquivalent([new Diff(DIFF_INSERT, 'xaxcx'), new Diff(DIFF_EQUAL, 'abc'), new Diff(DIFF_DELETE, 'y')], dmp.diff_main('abcy', 'xaxcxabc', false)); + + assertEquivalent([new Diff(DIFF_DELETE, 'ABCD'), new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_DELETE, '='), new Diff(DIFF_INSERT, '-'), new Diff(DIFF_EQUAL, 'bcd'), new Diff(DIFF_DELETE, '='), new Diff(DIFF_INSERT, '-'), new Diff(DIFF_EQUAL, 'efghijklmnopqrs'), new Diff(DIFF_DELETE, 'EFGHIJKLMNOefg')], dmp.diff_main('ABCDa=bcd=efghijklmnopqrsEFGHIJKLMNOefg', 'a-bcd-efghijklmnopqrs', false)); + + // Large equality. + assertEquivalent([new Diff(DIFF_INSERT, ' '), new Diff(DIFF_EQUAL, 'a'), new Diff(DIFF_INSERT, 'nd'), new Diff(DIFF_EQUAL, ' [[Pennsylvania]]'), new Diff(DIFF_DELETE, ' and [[New')], dmp.diff_main('a [[Pennsylvania]] and [[New', ' and [[Pennsylvania]]', false)); + + // Timeout. + dmp.Diff_Timeout = 0.1; // 100ms + var a = '`Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.\n'; + var b = 'I am the very model of a modern major general,\nI\'ve information vegetable, animal, and mineral,\nI know the kings of England, and I quote the fights historical,\nFrom Marathon to Waterloo, in order categorical.\n'; + // Increase the text lengths by 1024 times to ensure a timeout. + for (var i = 0; i < 10; i++) { + a += a; + b += b; + } + var startTime = (new Date()).getTime(); + dmp.diff_main(a, b); + var endTime = (new Date()).getTime(); + // Test that we took at least the timeout period. + assertTrue(dmp.Diff_Timeout * 1000 <= endTime - startTime); + // Test that we didn't take forever (be forgiving). + // Theoretically this test could fail very occasionally if the + // OS task swaps or locks up for a second at the wrong moment. + assertTrue(dmp.Diff_Timeout * 1000 * 2 > endTime - startTime); + dmp.Diff_Timeout = 0; + + // Test the linemode speedup. + // Must be long to pass the 100 char cutoff. + // Simple line-mode. + a = '1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n'; + b = 'abcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\n'; + assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true)); + + // Single line-mode. + a = '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'; + b = 'abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij'; + assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true)); + + // Overlap line-mode. + a = '1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n'; + b = 'abcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n'; + var texts_linemode = diff_rebuildtexts(dmp.diff_main(a, b, true)); + var texts_textmode = diff_rebuildtexts(dmp.diff_main(a, b, false)); + assertEquivalent(texts_textmode, texts_linemode); + + // Test null inputs. + try { + dmp.diff_main(null, null); + assertEquals(Error, null); + } catch (e) { + // Exception expected. + } +} + + +// MATCH TEST FUNCTIONS + + +export function testMatchAlphabet() { + // Initialise the bitmasks for Bitap. + // Unique. + assertEquivalent({ 'a': 4, 'b': 2, 'c': 1 }, (dmp as any).match_alphabet_('abc')); + + // Duplicates. + assertEquivalent({ 'a': 37, 'b': 18, 'c': 8 }, (dmp as any).match_alphabet_('abcaba')); +} + +export function testMatchBitap() { + // Bitap algorithm. + dmp.Match_Distance = 100; + dmp.Match_Threshold = 0.5; + // Exact matches. + assertEquals(5, (dmp as any).match_bitap_('abcdefghijk', 'fgh', 5)); + + assertEquals(5, (dmp as any).match_bitap_('abcdefghijk', 'fgh', 0)); + + // Fuzzy matches. + assertEquals(4, (dmp as any).match_bitap_('abcdefghijk', 'efxhi', 0)); + + assertEquals(2, (dmp as any).match_bitap_('abcdefghijk', 'cdefxyhijk', 5)); + + assertEquals(-1, (dmp as any).match_bitap_('abcdefghijk', 'bxy', 1)); + + // Overflow. + assertEquals(2, (dmp as any).match_bitap_('123456789xx0', '3456789x0', 2)); + + // Threshold test. + dmp.Match_Threshold = 0.4; + assertEquals(4, (dmp as any).match_bitap_('abcdefghijk', 'efxyhi', 1)); + + dmp.Match_Threshold = 0.3; + assertEquals(-1, (dmp as any).match_bitap_('abcdefghijk', 'efxyhi', 1)); + + dmp.Match_Threshold = 0.0; + assertEquals(1, (dmp as any).match_bitap_('abcdefghijk', 'bcdef', 1)); + dmp.Match_Threshold = 0.5; + + // Multiple select. + assertEquals(0, (dmp as any).match_bitap_('abcdexyzabcde', 'abccde', 3)); + + assertEquals(8, (dmp as any).match_bitap_('abcdexyzabcde', 'abccde', 5)); + + // Distance test. + dmp.Match_Distance = 10; // Strict location. + assertEquals(-1, (dmp as any).match_bitap_('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 24)); + + assertEquals(0, (dmp as any).match_bitap_('abcdefghijklmnopqrstuvwxyz', 'abcdxxefg', 1)); + + dmp.Match_Distance = 1000; // Loose location. + assertEquals(0, (dmp as any).match_bitap_('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 24)); +} + +export function testMatchMain() { + // Full match. + // Shortcut matches. + assertEquals(0, dmp.match_main('abcdef', 'abcdef', 1000)); + + assertEquals(-1, dmp.match_main('', 'abcdef', 1)); + + assertEquals(3, dmp.match_main('abcdef', '', 3)); + + assertEquals(3, dmp.match_main('abcdef', 'de', 3)); + + // Beyond end match. + assertEquals(3, dmp.match_main("abcdef", "defy", 4)); + + // Oversized pattern. + assertEquals(0, dmp.match_main("abcdef", "abcdefy", 0)); + + // Complex match. + assertEquals(4, dmp.match_main('I am the very model of a modern major general.', ' that berry ', 5)); + + // Test null inputs. + try { + dmp.match_main(null, null, 0); + assertEquals(Error, null); + } catch (e) { + // Exception expected. + } +} + + +// PATCH TEST FUNCTIONS + + +export function testPatchObj() { + // Patch Object. + var p = new patch_obj(); + p.start1 = 20; + p.start2 = 21; + p.length1 = 18; + p.length2 = 17; + p.diffs = [new Diff(DIFF_EQUAL, 'jump'), new Diff(DIFF_DELETE, 's'), new Diff(DIFF_INSERT, 'ed'), new Diff(DIFF_EQUAL, ' over '), new Diff(DIFF_DELETE, 'the'), new Diff(DIFF_INSERT, 'a'), new Diff(DIFF_EQUAL, '\nlaz')]; + var strp = p.toString(); + assertEquals('@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n', strp); +} + +export function testPatchFromText() { + assertEquivalent([], dmp.patch_fromText(strp)); + + var strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n'; + assertEquals(strp, dmp.patch_fromText(strp)[0].toString()); + + assertEquals('@@ -1 +1 @@\n-a\n+b\n', dmp.patch_fromText('@@ -1 +1 @@\n-a\n+b\n')[0].toString()); + + assertEquals('@@ -1,3 +0,0 @@\n-abc\n', dmp.patch_fromText('@@ -1,3 +0,0 @@\n-abc\n')[0].toString()); + + assertEquals('@@ -0,0 +1,3 @@\n+abc\n', dmp.patch_fromText('@@ -0,0 +1,3 @@\n+abc\n')[0].toString()); + + // Generates error. + try { + dmp.patch_fromText('Bad\nPatch\n'); + assertEquals(Error, null); + } catch (e) { + // Exception expected. + } +} + +export function testPatchToText() { + var strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'; + var p = dmp.patch_fromText(strp); + assertEquals(strp, dmp.patch_toText(p)); + + strp = '@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n'; + p = dmp.patch_fromText(strp); + assertEquals(strp, dmp.patch_toText(p)); +} + +export function testPatchAddContext() { + dmp.Patch_Margin = 4; + var p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[0]; + (dmp as any).patch_addContext_(p, 'The quick brown fox jumps over the lazy dog.'); + assertEquals('@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n', p.toString()); + + // Same, but not enough trailing context. + p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[0]; + (dmp as any).patch_addContext_(p, 'The quick brown fox jumps.'); + assertEquals('@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n', p.toString()); + + // Same, but not enough leading context. + p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[0]; + (dmp as any).patch_addContext_(p, 'The quick brown fox jumps.'); + assertEquals('@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n', p.toString()); + + // Same, but with ambiguity. + p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[0]; + (dmp as any).patch_addContext_(p, 'The quick brown fox jumps. The quick brown fox crashes.'); + assertEquals('@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n', p.toString()); +} + +export function testPatchMake() { + // Null case. + var patches = dmp.patch_make('', ''); + assertEquals('', dmp.patch_toText(patches)); + + var text1 = 'The quick brown fox jumps over the lazy dog.'; + var text2 = 'That quick brown fox jumped over a lazy dog.'; + // Text2+Text1 inputs. + var expectedPatch = '@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n'; + // The second patch must be "-21,17 +21,18", not "-22,17 +21,18" due to rolling context. + patches = dmp.patch_make(text2, text1); + assertEquals(expectedPatch, dmp.patch_toText(patches)); + + // Text1+Text2 inputs. + expectedPatch = '@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'; + patches = dmp.patch_make(text1, text2); + assertEquals(expectedPatch, dmp.patch_toText(patches)); + + // Diff input. + var diffs = dmp.diff_main(text1, text2, false); + patches = dmp.patch_make(diffs); + assertEquals(expectedPatch, dmp.patch_toText(patches)); + + // Text1+Diff inputs. + patches = dmp.patch_make(text1, diffs); + assertEquals(expectedPatch, dmp.patch_toText(patches)); + + // Text1+Text2+Diff inputs (deprecated). + patches = dmp.patch_make(text1, text2, diffs); + assertEquals(expectedPatch, dmp.patch_toText(patches)); + + // Character encoding. + patches = dmp.patch_make('`1234567890-=[]\\;\',./', '~!@#$%^&*()_+{}|:"<>?'); + assertEquals('@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;\',./\n+~!@#$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n', dmp.patch_toText(patches)); + + // Character decoding. + diffs = [new Diff(DIFF_DELETE, '`1234567890-=[]\\;\',./'), new Diff(DIFF_INSERT, '~!@#$%^&*()_+{}|:"<>?')]; + assertEquivalent(diffs, dmp.patch_fromText('@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;\',./\n+~!@#$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n')[0].diffs); + + // Long string with repeats. + text1 = ''; + for (var x = 0; x < 100; x++) { + text1 += 'abcdef'; + } + text2 = text1 + '123'; + expectedPatch = '@@ -573,28 +573,31 @@\n cdefabcdefabcdefabcdefabcdef\n+123\n'; + patches = dmp.patch_make(text1, text2); + assertEquals(expectedPatch, dmp.patch_toText(patches)); + + // Test null inputs. + try { + dmp.patch_make(null); + assertEquals(Error, null); + } catch (e) { + // Exception expected. + } +} + +export function testPatchSplitMax() { + // Assumes that dmp.Match_MaxBits is 32. + var patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz01234567890', 'XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0'); + dmp.patch_splitMax(patches); + assertEquals('@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n', dmp.patch_toText(patches)); + + patches = dmp.patch_make('abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz', 'abcdefuvwxyz'); + var oldToText = dmp.patch_toText(patches); + dmp.patch_splitMax(patches); + assertEquals(oldToText, dmp.patch_toText(patches)); + + patches = dmp.patch_make('1234567890123456789012345678901234567890123456789012345678901234567890', 'abc'); + dmp.patch_splitMax(patches); + assertEquals('@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n', dmp.patch_toText(patches)); + + patches = dmp.patch_make('abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1', 'abcdefghij , h : 1 , t : 1 abcdefghij , h : 1 , t : 1 abcdefghij , h : 0 , t : 1'); + dmp.patch_splitMax(patches); + assertEquals('@@ -2,32 +2,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n', dmp.patch_toText(patches)); +} + +export function testPatchAddPadding() { + // Both edges full. + var patches = dmp.patch_make('', 'test'); + assertEquals('@@ -0,0 +1,4 @@\n+test\n', dmp.patch_toText(patches)); + dmp.patch_addPadding(patches); + assertEquals('@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n', dmp.patch_toText(patches)); + + // Both edges partial. + patches = dmp.patch_make('XY', 'XtestY'); + assertEquals('@@ -1,2 +1,6 @@\n X\n+test\n Y\n', dmp.patch_toText(patches)); + dmp.patch_addPadding(patches); + assertEquals('@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n', dmp.patch_toText(patches)); + + // Both edges none. + patches = dmp.patch_make('XXXXYYYY', 'XXXXtestYYYY'); + assertEquals('@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches)); + dmp.patch_addPadding(patches); + assertEquals('@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches)); +} + +export function testPatchApply() { + dmp.Match_Distance = 1000; + dmp.Match_Threshold = 0.5; + dmp.Patch_DeleteThreshold = 0.5; + // Null case. + var patches = dmp.patch_make('', ''); + var results = dmp.patch_apply(patches, 'Hello world.'); + assertEquivalent(['Hello world.', []], results); + + // Exact match. + patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.', 'That quick brown fox jumped over a lazy dog.'); + results = dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.'); + assertEquivalent(['That quick brown fox jumped over a lazy dog.', [true, true]], results); + + // Partial match. + results = dmp.patch_apply(patches, 'The quick red rabbit jumps over the tired tiger.'); + assertEquivalent(['That quick red rabbit jumped over a tired tiger.', [true, true]], results); + + // Failed match. + results = dmp.patch_apply(patches, 'I am the very model of a modern major general.'); + assertEquivalent(['I am the very model of a modern major general.', [false, false]], results); + + // Big delete, small change. + patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789012345678901234567890y', 'xabcy'); + results = dmp.patch_apply(patches, 'x123456789012345678901234567890-----++++++++++-----123456789012345678901234567890y'); + assertEquivalent(['xabcy', [true, true]], results); + + // Big delete, big change 1. + patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789012345678901234567890y', 'xabcy'); + results = dmp.patch_apply(patches, 'x12345678901234567890---------------++++++++++---------------12345678901234567890y'); + assertEquivalent(['xabc12345678901234567890---------------++++++++++---------------12345678901234567890y', [false, true]], results); + + // Big delete, big change 2. + dmp.Patch_DeleteThreshold = 0.6; + patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789012345678901234567890y', 'xabcy'); + results = dmp.patch_apply(patches, 'x12345678901234567890---------------++++++++++---------------12345678901234567890y'); + assertEquivalent(['xabcy', [true, true]], results); + dmp.Patch_DeleteThreshold = 0.5; + + // Compensate for failed patch. + dmp.Match_Threshold = 0.0; + dmp.Match_Distance = 0; + patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz--------------------1234567890', 'abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------1234567YYYYYYYYYY890'); + results = dmp.patch_apply(patches, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890'); + assertEquivalent(['ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890', [false, true]], results); + dmp.Match_Threshold = 0.5; + dmp.Match_Distance = 1000; + + // No side effects. + patches = dmp.patch_make('', 'test'); + var patchstr = dmp.patch_toText(patches); + dmp.patch_apply(patches, ''); + assertEquals(patchstr, dmp.patch_toText(patches)); + + // No side effects with major delete. + patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.', 'Woof'); + patchstr = dmp.patch_toText(patches); + dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.'); + assertEquals(patchstr, dmp.patch_toText(patches)); + + // Edge exact match. + patches = dmp.patch_make('', 'test'); + results = dmp.patch_apply(patches, ''); + assertEquivalent(['test', [true]], results); + + // Near edge exact match. + patches = dmp.patch_make('XY', 'XtestY'); + results = dmp.patch_apply(patches, 'XY'); + assertEquivalent(['XtestY', [true]], results); + + // Edge partial match. + patches = dmp.patch_make('y', 'y123'); + results = dmp.patch_apply(patches, 'x'); + assertEquivalent(['x123', [true]], results); +} + + + +// Counters for unit test results. +var test_good = 0; +var test_bad = 0; + +// If expected and actual are the identical, print 'Ok', otherwise 'Fail!' +export function assertEquals(msg: any, expected: any, actual?: any) { + if (typeof actual == 'undefined') { + // msg is optional. + actual = expected; + expected = msg; + msg = 'Expected: \'' + expected + '\' Actual: \'' + actual + '\''; + } + if (expected === actual) { + console.log("Ok"); + test_good++; + return true; + } else { + console.error("Fail!"); + msg = msg.replace(/&/g, '&').replace(//g, '>'); + console.error(msg); + test_bad++; + return false; + } +} + +function assertTrue(msg: any, actual?: any) { + if (typeof actual == 'undefined') { + // msg is optional. + actual = msg; + return assertEquals(true, actual); + } else { + return assertEquals(msg, true, actual); + } +} + +function assertFalse(msg: any, actual?: any) { + if (typeof actual == 'undefined') { + // msg is optional. + actual = msg; + return assertEquals(false, actual); + } else { + return assertEquals(msg, false, actual); + } +} + +function runTests() { + + for (var x = 0; x < tests.length; x++) { + console.log(tests[x]); + eval(tests[x] + '()'); + } +} + +var tests = [ + 'testDiffCommonPrefix', + 'testDiffCommonSuffix', + 'testDiffCommonOverlap', + 'testDiffHalfMatch', + 'testDiffLinesToChars', + 'testDiffCharsToLines', + 'testDiffCleanupMerge', + 'testDiffCleanupSemanticLossless', + 'testDiffCleanupSemantic', + 'testDiffCleanupEfficiency', + 'testDiffPrettyHtml', + 'testDiffText', + 'testDiffDelta', + 'testDiffXIndex', + 'testDiffLevenshtein', + 'testDiffBisect', + 'testDiffMain', + + 'testMatchAlphabet', + 'testMatchBitap', + 'testMatchMain', + + 'testPatchObj', + 'testPatchFromText', + 'testPatchToText', + 'testPatchAddContext', + 'testPatchMake', + 'testPatchSplitMax', + 'testPatchAddPadding', + 'testPatchApply']; + + +var startTime = (new Date()).getTime(); +runTests(); +var endTime = (new Date()).getTime(); +console.log("Done"); +console.log('Tests passed: ' + test_good + '\nTests failed: ' + test_bad); +console.log('Total time: ' + (endTime - startTime) + ' ms'); + diff --git a/typescript/tests/speedtest.ts b/typescript/tests/speedtest.ts new file mode 100644 index 0000000..c6397b8 --- /dev/null +++ b/typescript/tests/speedtest.ts @@ -0,0 +1,457 @@ +/** + * Diff Match and Patch -- Test Harness + * Copyright 2018 The diff-match-patch Authors. + * https://github.com/google/diff-match-patch + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import diff_match_patch from '../diff_match_patch'; + +const text1 = `This is a '''list of newspapers published by [[Journal Register Company]]'''. + +The company owns daily and weekly newspapers, other print media properties and newspaper-affiliated local Websites in the [[U.S.]] states of [[Connecticut]], [[Michigan]], [[New York]], [[Ohio]] and [[Pennsylvania]], organized in six geographic "clusters":<ref>[http://www.journalregister.com/newspapers.html Journal Register Company: Our Newspapers], accessed February 10, 2008.</ref> + +== Capital-Saratoga == +Three dailies, associated weeklies and [[pennysaver]]s in greater [[Albany, New York]]; also [http://www.capitalcentral.com capitalcentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com]. + +* ''The Oneida Daily Dispatch'' {{WS|oneidadispatch.com}} of [[Oneida, New York]] +* ''[[The Record (Troy)|The Record]]'' {{WS|troyrecord.com}} of [[Troy, New York]] +* ''[[The Saratogian]]'' {{WS|saratogian.com}} of [[Saratoga Springs, New York]] +* Weeklies: +** ''Community News'' {{WS|cnweekly.com}} weekly of [[Clifton Park, New York]] +** ''Rome Observer'' of [[Rome, New York]] +** ''Life & Times of Utica'' of [[Utica, New York]] + +== Connecticut == +Five dailies, associated weeklies and [[pennysaver]]s in the state of [[Connecticut]]; also [http://www.ctcentral.com CTcentral.com], [http://www.ctcarsandtrucks.com CTCarsAndTrucks.com] and [http://www.jobsinct.com JobsInCT.com]. + +* ''The Middletown Press'' {{WS|middletownpress.com}} of [[Middletown, Connecticut|Middletown]] +* ''[[New Haven Register]]'' {{WS|newhavenregister.com}} of [[New Haven, Connecticut|New Haven]] +* ''The Register Citizen'' {{WS|registercitizen.com}} of [[Torrington, Connecticut|Torrington]] + +* [[New Haven Register#Competitors|Elm City Newspapers]] {{WS|ctcentral.com}} +** ''The Advertiser'' of [[East Haven, Connecticut|East Haven]] +** ''Hamden Chronicle'' of [[Hamden, Connecticut|Hamden]] +** ''Milford Weekly'' of [[Milford, Connecticut|Milford]] +** ''The Orange Bulletin'' of [[Orange, Connecticut|Orange]] +** ''The Post'' of [[North Haven, Connecticut|North Haven]] +** ''Shelton Weekly'' of [[Shelton, Connecticut|Shelton]] +** ''The Stratford Bard'' of [[Stratford, Connecticut|Stratford]] +** ''Wallingford Voice'' of [[Wallingford, Connecticut|Wallingford]] +** ''West Haven News'' of [[West Haven, Connecticut|West Haven]] +* Housatonic Publications +** ''The New Milford Times'' {{WS|newmilfordtimes.com}} of [[New Milford, Connecticut|New Milford]] +** ''The Brookfield Journal'' of [[Brookfield, Connecticut|Brookfield]] +** ''The Kent Good Times Dispatch'' of [[Kent, Connecticut|Kent]] +** ''The Bethel Beacon'' of [[Bethel, Connecticut|Bethel]] +** ''The Litchfield Enquirer'' of [[Litchfield, Connecticut|Litchfield]] +** ''Litchfield County Times'' of [[Litchfield, Connecticut|Litchfield]] +* Imprint Newspapers {{WS|imprintnewspapers.com}} +** ''West Hartford News'' of [[West Hartford, Connecticut|West Hartford]] +** ''Windsor Journal'' of [[Windsor, Connecticut|Windsor]] +** ''Windsor Locks Journal'' of [[Windsor Locks, Connecticut|Windsor Locks]] +** ''Avon Post'' of [[Avon, Connecticut|Avon]] +** ''Farmington Post'' of [[Farmington, Connecticut|Farmington]] +** ''Simsbury Post'' of [[Simsbury, Connecticut|Simsbury]] +** ''Tri-Town Post'' of [[Burlington, Connecticut|Burlington]], [[Canton, Connecticut|Canton]] and [[Harwinton, Connecticut|Harwinton]] +* Minuteman Publications +** ''[[Fairfield Minuteman]]'' of [[Fairfield, Connecticut|Fairfield]] +** ''The Westport Minuteman'' {{WS|westportminuteman.com}} of [[Westport, Connecticut|Westport]] +* Shoreline Newspapers weeklies: +** ''Branford Review'' of [[Branford, Connecticut|Branford]] +** ''Clinton Recorder'' of [[Clinton, Connecticut|Clinton]] +** ''The Dolphin'' of [[Naval Submarine Base New London]] in [[New London, Connecticut|New London]] +** ''Main Street News'' {{WS|ctmainstreetnews.com}} of [[Essex, Connecticut|Essex]] +** ''Pictorial Gazette'' of [[Old Saybrook, Connecticut|Old Saybrook]] +** ''Regional Express'' of [[Colchester, Connecticut|Colchester]] +** ''Regional Standard'' of [[Colchester, Connecticut|Colchester]] +** ''Shoreline Times'' {{WS|shorelinetimes.com}} of [[Guilford, Connecticut|Guilford]] +** ''Shore View East'' of [[Madison, Connecticut|Madison]] +** ''Shore View West'' of [[Guilford, Connecticut|Guilford]] +* Other weeklies: +** ''Registro'' {{WS|registroct.com}} of [[New Haven, Connecticut|New Haven]] +** ''Thomaston Express'' {{WS|thomastownexpress.com}} of [[Thomaston, Connecticut|Thomaston]] +** ''Foothills Traders'' {{WS|foothillstrader.com}} of Torrington, Bristol, Canton + +== Michigan == +Four dailies, associated weeklies and [[pennysaver]]s in the state of [[Michigan]]; also [http://www.micentralhomes.com MIcentralhomes.com] and [http://www.micentralautos.com MIcentralautos.com] +* ''[[Oakland Press]]'' {{WS|theoaklandpress.com}} of [[Oakland, Michigan|Oakland]] +* ''Daily Tribune'' {{WS|dailytribune.com}} of [[Royal Oak, Michigan|Royal Oak]] +* ''Macomb Daily'' {{WS|macombdaily.com}} of [[Mt. Clemens, Michigan|Mt. Clemens]] +* ''[[Morning Sun]]'' {{WS|themorningsun.com}} of [[Mount Pleasant, Michigan|Mount Pleasant]] +* Heritage Newspapers {{WS|heritage.com}} +** ''Belleville View'' +** ''Ile Camera'' +** ''Monroe Guardian'' +** ''Ypsilanti Courier'' +** ''News-Herald'' +** ''Press & Guide'' +** ''Chelsea Standard & Dexter Leader'' +** ''Manchester Enterprise'' +** ''Milan News-Leader'' +** ''Saline Reporter'' +* Independent Newspapers {{WS|sourcenewspapers.com}} +** ''Advisor'' +** ''Source'' +* Morning Star {{WS|morningstarpublishing.com}} +** ''Alma Reminder'' +** ''Alpena Star'' +** ''Antrim County News'' +** ''Carson City Reminder'' +** ''The Leader & Kalkaskian'' +** ''Ogemaw/Oscoda County Star'' +** ''Petoskey/Charlevoix Star'' +** ''Presque Isle Star'' +** ''Preview Community Weekly'' +** ''Roscommon County Star'' +** ''St. Johns Reminder'' +** ''Straits Area Star'' +** ''The (Edmore) Advertiser'' +* Voice Newspapers {{WS|voicenews.com}} +** ''Armada Times'' +** ''Bay Voice'' +** ''Blue Water Voice'' +** ''Downriver Voice'' +** ''Macomb Township Voice'' +** ''North Macomb Voice'' +** ''Weekend Voice'' +** ''Suburban Lifestyles'' {{WS|suburbanlifestyles.com}} + +== Mid-Hudson == +One daily, associated magazines in the [[Hudson River Valley]] of [[New York]]; also [http://www.midhudsoncentral.com MidHudsonCentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com]. + +* ''[[Daily Freeman]]'' {{WS|dailyfreeman.com}} of [[Kingston, New York]] + +== Ohio == +Two dailies, associated magazines and three shared Websites, all in the state of [[Ohio]]: [http://www.allaroundcleveland.com AllAroundCleveland.com], [http://www.allaroundclevelandcars.com AllAroundClevelandCars.com] and [http://www.allaroundclevelandjobs.com AllAroundClevelandJobs.com]. + +* ''[[The News-Herald (Ohio)|The News-Herald]]'' {{WS|news-herald.com}} of [[Willoughby, Ohio|Willoughby]] +* ''[[The Morning Journal]]'' {{WS|morningjournal.com}} of [[Lorain, Ohio|Lorain]] + +== Philadelphia area == +Seven dailies and associated weeklies and magazines in [[Pennsylvania]] and [[New Jersey]], and associated Websites: [http://www.allaroundphilly.com AllAroundPhilly.com], [http://www.jobsinnj.com JobsInNJ.com], [http://www.jobsinpa.com JobsInPA.com], and [http://www.phillycarsearch.com PhillyCarSearch.com]. + +* ''The Daily Local'' {{WS|dailylocal.com}} of [[West Chester, Pennsylvania|West Chester]] +* ''[[Delaware County Daily and Sunday Times]] {{WS|delcotimes.com}} of Primos +* ''[[The Mercury (Pennsylvania)|The Mercury]]'' {{WS|pottstownmercury.com}} of [[Pottstown, Pennsylvania|Pottstown]] +* ''The Phoenix'' {{WS|phoenixvillenews.com}} of [[Phoenixville, Pennsylvania|Phoenixville]] +* ''[[The Reporter (Lansdale)|The Reporter]]'' {{WS|thereporteronline.com}} of [[Lansdale, Pennsylvania|Lansdale]] +* ''The Times Herald'' {{WS|timesherald.com}} of [[Norristown, Pennsylvania|Norristown]] +* ''[[The Trentonian]]'' {{WS|trentonian.com}} of [[Trenton, New Jersey]] + +* Weeklies +** ''El Latino Expreso'' of [[Trenton, New Jersey]] +** ''La Voz'' of [[Norristown, Pennsylvania]] +** ''The Village News'' of [[Downingtown, Pennsylvania]] +** ''The Times Record'' of [[Kennett Square, Pennsylvania]] +** ''The Tri-County Record'' {{WS|tricountyrecord.com}} of [[Morgantown, Pennsylvania]] +** ''News of Delaware County'' {{WS|newsofdelawarecounty.com}}of [[Havertown, Pennsylvania]] +** ''Main Line Times'' {{WS|mainlinetimes.com}}of [[Ardmore, Pennsylvania]] +** ''Penny Pincher'' of [[Pottstown, Pennsylvania]] +** ''Town Talk'' {{WS|towntalknews.com}} of [[Ridley, Pennsylvania]] +* Chesapeake Publishing {{WS|pa8newsgroup.com}} +** ''Solanco Sun Ledger'' of [[Quarryville, Pennsylvania]] +** ''Columbia Ledger'' of [[Columbia, Pennsylvania]] +** ''Coatesville Ledger'' of [[Downingtown, Pennsylvania]] +** ''Parkesburg Post Ledger'' of [[Quarryville, Pennsylvania]] +** ''Downingtown Ledger'' of [[Downingtown, Pennsylvania]] +** ''The Kennett Paper'' of [[Kennett Square, Pennsylvania]] +** ''Avon Grove Sun'' of [[West Grove, Pennsylvania]] +** ''Oxford Tribune'' of [[Oxford, Pennsylvania]] +** ''Elizabethtown Chronicle'' of [[Elizabethtown, Pennsylvania]] +** ''Donegal Ledger'' of [[Donegal, Pennsylvania]] +** ''Chadds Ford Post'' of [[Chadds Ford, Pennsylvania]] +** ''The Central Record'' of [[Medford, New Jersey]] +** ''Maple Shade Progress'' of [[Maple Shade, New Jersey]] +* Intercounty Newspapers {{WS|buckslocalnews.com}} +** ''The Review'' of Roxborough, Pennsylvania +** ''The Recorder'' of [[Conshohocken, Pennsylvania]] +** ''The Leader'' of [[Mount Airy, Pennsylvania|Mount Airy]] and West Oak Lake, Pennsylvania +** ''The Pennington Post'' of [[Pennington, New Jersey]] +** ''The Bristol Pilot'' of [[Bristol, Pennsylvania]] +** ''Yardley News'' of [[Yardley, Pennsylvania]] +** ''New Hope Gazette'' of [[New Hope, Pennsylvania]] +** ''Doylestown Patriot'' of [[Doylestown, Pennsylvania]] +** ''Newtown Advance'' of [[Newtown, Pennsylvania]] +** ''The Plain Dealer'' of [[Williamstown, New Jersey]] +** ''News Report'' of [[Sewell, New Jersey]] +** ''Record Breeze'' of [[Berlin, New Jersey]] +** ''Newsweekly'' of [[Moorestown, New Jersey]] +** ''Haddon Herald'' of [[Haddonfield, New Jersey]] +** ''New Egypt Press'' of [[New Egypt, New Jersey]] +** ''Community News'' of [[Pemberton, New Jersey]] +** ''Plymouth Meeting Journal'' of [[Plymouth Meeting, Pennsylvania]] +** ''Lafayette Hill Journal'' of [[Lafayette Hill, Pennsylvania]] +* Montgomery Newspapers {{WS|montgomerynews.com}} +** ''Ambler Gazette'' of [[Ambler, Pennsylvania]] +** ''Central Bucks Life'' of [[Bucks County, Pennsylvania]] +** ''The Colonial'' of [[Plymouth Meeting, Pennsylvania]] +** ''Glenside News'' of [[Glenside, Pennsylvania]] +** ''The Globe'' of [[Lower Moreland Township, Pennsylvania]] +** ''Main Line Life'' of [[Ardmore, Pennsylvania]] +** ''Montgomery Life'' of [[Fort Washington, Pennsylvania]] +** ''North Penn Life'' of [[Lansdale, Pennsylvania]] +** ''Perkasie News Herald'' of [[Perkasie, Pennsylvania]] +** ''Public Spirit'' of [[Hatboro, Pennsylvania]] +** ''Souderton Independent'' of [[Souderton, Pennsylvania]] +** ''Springfield Sun'' of [[Springfield, Pennsylvania]] +** ''Spring-Ford Reporter'' of [[Royersford, Pennsylvania]] +** ''Times Chronicle'' of [[Jenkintown, Pennsylvania]] +** ''Valley Item'' of [[Perkiomenville, Pennsylvania]] +** ''Willow Grove Guide'' of [[Willow Grove, Pennsylvania]] +* News Gleaner Publications (closed December 2008) {{WS|newsgleaner.com}} +** ''Life Newspapers'' of [[Philadelphia, Pennsylvania]] +* Suburban Publications +** ''The Suburban & Wayne Times'' {{WS|waynesuburban.com}} of [[Wayne, Pennsylvania]] +** ''The Suburban Advertiser'' of [[Exton, Pennsylvania]] +** ''The King of Prussia Courier'' of [[King of Prussia, Pennsylvania]] +* Press Newspapers {{WS|countypressonline.com}} +** ''County Press'' of [[Newtown Square, Pennsylvania]] +** ''Garnet Valley Press'' of [[Glen Mills, Pennsylvania]] +** ''Haverford Press'' of [[Newtown Square, Pennsylvania]] (closed January 2009) +** ''Hometown Press'' of [[Glen Mills, Pennsylvania]] (closed January 2009) +** ''Media Press'' of [[Newtown Square, Pennsylvania]] (closed January 2009) +** ''Springfield Press'' of [[Springfield, Pennsylvania]] +* Berks-Mont Newspapers {{WS|berksmontnews.com}} +** ''The Boyertown Area Times'' of [[Boyertown, Pennsylvania]] +** ''The Kutztown Area Patriot'' of [[Kutztown, Pennsylvania]] +** ''The Hamburg Area Item'' of [[Hamburg, Pennsylvania]] +** ''The Southern Berks News'' of [[Exeter Township, Berks County, Pennsylvania]] +** ''The Free Press'' of [[Quakertown, Pennsylvania]] +** ''The Saucon News'' of [[Quakertown, Pennsylvania]] +** ''Westside Weekly'' of [[Reading, Pennsylvania]] + +* Magazines +** ''Bucks Co. Town & Country Living'' +** ''Chester Co. Town & Country Living'' +** ''Montomgery Co. Town & Country Living'' +** ''Garden State Town & Country Living'' +** ''Montgomery Homes'' +** ''Philadelphia Golfer'' +** ''Parents Express'' +** ''Art Matters'' + +{{JRC}} + +==References== +<references /> + +[[Category:Journal Register publications|*]] +`; + +const text2 = `This is a '''list of newspapers published by [[Journal Register Company]]'''. + +The company owns daily and weekly newspapers, other print media properties and newspaper-affiliated local Websites in the [[U.S.]] states of [[Connecticut]], [[Michigan]], [[New York]], [[Ohio]], [[Pennsylvania]] and [[New Jersey]], organized in six geographic "clusters":<ref>[http://www.journalregister.com/publications.html Journal Register Company: Our Publications], accessed April 21, 2010.</ref> + +== Capital-Saratoga == +Three dailies, associated weeklies and [[pennysaver]]s in greater [[Albany, New York]]; also [http://www.capitalcentral.com capitalcentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com]. + +* ''The Oneida Daily Dispatch'' {{WS|oneidadispatch.com}} of [[Oneida, New York]] +* ''[[The Record (Troy)|The Record]]'' {{WS|troyrecord.com}} of [[Troy, New York]] +* ''[[The Saratogian]]'' {{WS|saratogian.com}} of [[Saratoga Springs, New York]] +* Weeklies: +** ''Community News'' {{WS|cnweekly.com}} weekly of [[Clifton Park, New York]] +** ''Rome Observer'' {{WS|romeobserver.com}} of [[Rome, New York]] +** ''WG Life '' {{WS|saratogian.com/wglife/}} of [[Wilton, New York]] +** ''Ballston Spa Life '' {{WS|saratogian.com/bspalife}} of [[Ballston Spa, New York]] +** ''Greenbush Life'' {{WS|troyrecord.com/greenbush}} of [[Troy, New York]] +** ''Latham Life'' {{WS|troyrecord.com/latham}} of [[Latham, New York]] +** ''River Life'' {{WS|troyrecord.com/river}} of [[Troy, New York]] + +== Connecticut == +Three dailies, associated weeklies and [[pennysaver]]s in the state of [[Connecticut]]; also [http://www.ctcentral.com CTcentral.com], [http://www.ctcarsandtrucks.com CTCarsAndTrucks.com] and [http://www.jobsinct.com JobsInCT.com]. + +* ''The Middletown Press'' {{WS|middletownpress.com}} of [[Middletown, Connecticut|Middletown]] +* ''[[New Haven Register]]'' {{WS|newhavenregister.com}} of [[New Haven, Connecticut|New Haven]] +* ''The Register Citizen'' {{WS|registercitizen.com}} of [[Torrington, Connecticut|Torrington]] + +* Housatonic Publications +** ''The Housatonic Times'' {{WS|housatonictimes.com}} of [[New Milford, Connecticut|New Milford]] +** ''Litchfield County Times'' {{WS|countytimes.com}} of [[Litchfield, Connecticut|Litchfield]] + +* Minuteman Publications +** ''[[Fairfield Minuteman]]'' {{WS|fairfieldminuteman.com}}of [[Fairfield, Connecticut|Fairfield]] +** ''The Westport Minuteman'' {{WS|westportminuteman.com}} of [[Westport, Connecticut|Westport]] + +* Shoreline Newspapers +** ''The Dolphin'' {{WS|dolphin-news.com}} of [[Naval Submarine Base New London]] in [[New London, Connecticut|New London]] +** ''Shoreline Times'' {{WS|shorelinetimes.com}} of [[Guilford, Connecticut|Guilford]] + +* Foothills Media Group {{WS|foothillsmediagroup.com}} +** ''Thomaston Express'' {{WS|thomastonexpress.com}} of [[Thomaston, Connecticut|Thomaston]] +** ''Good News About Torrington'' {{WS|goodnewsabouttorrington.com}} of [[Torrington, Connecticut|Torrington]] +** ''Granby News'' {{WS|foothillsmediagroup.com/granby}} of [[Granby, Connecticut|Granby]] +** ''Canton News'' {{WS|foothillsmediagroup.com/canton}} of [[Canton, Connecticut|Canton]] +** ''Avon News'' {{WS|foothillsmediagroup.com/avon}} of [[Avon, Connecticut|Avon]] +** ''Simsbury News'' {{WS|foothillsmediagroup.com/simsbury}} of [[Simsbury, Connecticut|Simsbury]] +** ''Litchfield News'' {{WS|foothillsmediagroup.com/litchfield}} of [[Litchfield, Connecticut|Litchfield]] +** ''Foothills Trader'' {{WS|foothillstrader.com}} of Torrington, Bristol, Canton + +* Other weeklies +** ''The Milford-Orange Bulletin'' {{WS|ctbulletin.com}} of [[Orange, Connecticut|Orange]] +** ''The Post-Chronicle'' {{WS|ctpostchronicle.com}} of [[North Haven, Connecticut|North Haven]] +** ''West Hartford News'' {{WS|westhartfordnews.com}} of [[West Hartford, Connecticut|West Hartford]] + +* Magazines +** ''The Connecticut Bride'' {{WS|connecticutmag.com}} +** ''Connecticut Magazine'' {{WS|theconnecticutbride.com}} +** ''Passport Magazine'' {{WS|passport-mag.com}} + +== Michigan == +Four dailies, associated weeklies and [[pennysaver]]s in the state of [[Michigan]]; also [http://www.micentralhomes.com MIcentralhomes.com] and [http://www.micentralautos.com MIcentralautos.com] +* ''[[Oakland Press]]'' {{WS|theoaklandpress.com}} of [[Oakland, Michigan|Oakland]] +* ''Daily Tribune'' {{WS|dailytribune.com}} of [[Royal Oak, Michigan|Royal Oak]] +* ''Macomb Daily'' {{WS|macombdaily.com}} of [[Mt. Clemens, Michigan|Mt. Clemens]] +* ''[[Morning Sun]]'' {{WS|themorningsun.com}} of [[Mount Pleasant, Michigan|Mount Pleasant]] + +* Heritage Newspapers {{WS|heritage.com}} +** ''Belleville View'' {{WS|bellevilleview.com}} +** ''Ile Camera'' {{WS|thenewsherald.com/ile_camera}} +** ''Monroe Guardian'' {{WS|monreguardian.com}} +** ''Ypsilanti Courier'' {{WS|ypsilanticourier.com}} +** ''News-Herald'' {{WS|thenewsherald.com}} +** ''Press & Guide'' {{WS|pressandguide.com}} +** ''Chelsea Standard & Dexter Leader'' {{WS|chelseastandard.com}} +** ''Manchester Enterprise'' {{WS|manchesterguardian.com}} +** ''Milan News-Leader'' {{WS|milannews.com}} +** ''Saline Reporter'' {{WS|salinereporter.com}} +* Independent Newspapers +** ''Advisor'' {{WS|sourcenewspapers.com}} +** ''Source'' {{WS|sourcenewspapers.com}} +* Morning Star {{WS|morningstarpublishing.com}} +** ''The Leader & Kalkaskian'' {{WS|leaderandkalkaskian.com}} +** ''Grand Traverse Insider'' {{WS|grandtraverseinsider.com}} +** ''Alma Reminder'' +** ''Alpena Star'' +** ''Ogemaw/Oscoda County Star'' +** ''Presque Isle Star'' +** ''St. Johns Reminder'' + +* Voice Newspapers {{WS|voicenews.com}} +** ''Armada Times'' +** ''Bay Voice'' +** ''Blue Water Voice'' +** ''Downriver Voice'' +** ''Macomb Township Voice'' +** ''North Macomb Voice'' +** ''Weekend Voice'' + +== Mid-Hudson == +One daily, associated magazines in the [[Hudson River Valley]] of [[New York]]; also [http://www.midhudsoncentral.com MidHudsonCentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com]. + +* ''[[Daily Freeman]]'' {{WS|dailyfreeman.com}} of [[Kingston, New York]] +* ''Las Noticias'' {{WS|lasnoticiasny.com}} of [[Kingston, New York]] + +== Ohio == +Two dailies, associated magazines and three shared Websites, all in the state of [[Ohio]]: [http://www.allaroundcleveland.com AllAroundCleveland.com], [http://www.allaroundclevelandcars.com AllAroundClevelandCars.com] and [http://www.allaroundclevelandjobs.com AllAroundClevelandJobs.com]. + +* ''[[The News-Herald (Ohio)|The News-Herald]]'' {{WS|news-herald.com}} of [[Willoughby, Ohio|Willoughby]] +* ''[[The Morning Journal]]'' {{WS|morningjournal.com}} of [[Lorain, Ohio|Lorain]] +* ''El Latino Expreso'' {{WS|lorainlatino.com}} of [[Lorain, Ohio|Lorain]] + +== Philadelphia area == +Seven dailies and associated weeklies and magazines in [[Pennsylvania]] and [[New Jersey]], and associated Websites: [http://www.allaroundphilly.com AllAroundPhilly.com], [http://www.jobsinnj.com JobsInNJ.com], [http://www.jobsinpa.com JobsInPA.com], and [http://www.phillycarsearch.com PhillyCarSearch.com]. + +* ''[[The Daily Local News]]'' {{WS|dailylocal.com}} of [[West Chester, Pennsylvania|West Chester]] +* ''[[Delaware County Daily and Sunday Times]] {{WS|delcotimes.com}} of Primos [[Upper Darby Township, Pennsylvania]] +* ''[[The Mercury (Pennsylvania)|The Mercury]]'' {{WS|pottstownmercury.com}} of [[Pottstown, Pennsylvania|Pottstown]] +* ''[[The Reporter (Lansdale)|The Reporter]]'' {{WS|thereporteronline.com}} of [[Lansdale, Pennsylvania|Lansdale]] +* ''The Times Herald'' {{WS|timesherald.com}} of [[Norristown, Pennsylvania|Norristown]] +* ''[[The Trentonian]]'' {{WS|trentonian.com}} of [[Trenton, New Jersey]] + +* Weeklies +* ''The Phoenix'' {{WS|phoenixvillenews.com}} of [[Phoenixville, Pennsylvania]] +** ''El Latino Expreso'' {{WS|njexpreso.com}} of [[Trenton, New Jersey]] +** ''La Voz'' {{WS|lavozpa.com}} of [[Norristown, Pennsylvania]] +** ''The Tri County Record'' {{WS|tricountyrecord.com}} of [[Morgantown, Pennsylvania]] +** ''Penny Pincher'' {{WS|pennypincherpa.com}}of [[Pottstown, Pennsylvania]] + +* Chesapeake Publishing {{WS|southernchestercountyweeklies.com}} +** ''The Kennett Paper'' {{WS|kennettpaper.com}} of [[Kennett Square, Pennsylvania]] +** ''Avon Grove Sun'' {{WS|avongrovesun.com}} of [[West Grove, Pennsylvania]] +** ''The Central Record'' {{WS|medfordcentralrecord.com}} of [[Medford, New Jersey]] +** ''Maple Shade Progress'' {{WS|mapleshadeprogress.com}} of [[Maple Shade, New Jersey]] + +* Intercounty Newspapers {{WS|buckslocalnews.com}} {{WS|southjerseylocalnews.com}} +** ''The Pennington Post'' {{WS|penningtonpost.com}} of [[Pennington, New Jersey]] +** ''The Bristol Pilot'' {{WS|bristolpilot.com}} of [[Bristol, Pennsylvania]] +** ''Yardley News'' {{WS|yardleynews.com}} of [[Yardley, Pennsylvania]] +** ''Advance of Bucks County'' {{WS|advanceofbucks.com}} of [[Newtown, Pennsylvania]] +** ''Record Breeze'' {{WS|recordbreeze.com}} of [[Berlin, New Jersey]] +** ''Community News'' {{WS|sjcommunitynews.com}} of [[Pemberton, New Jersey]] + +* Montgomery Newspapers {{WS|montgomerynews.com}} +** ''Ambler Gazette'' {{WS|amblergazette.com}} of [[Ambler, Pennsylvania]] +** ''The Colonial'' {{WS|colonialnews.com}} of [[Plymouth Meeting, Pennsylvania]] +** ''Glenside News'' {{WS|glensidenews.com}} of [[Glenside, Pennsylvania]] +** ''The Globe'' {{WS|globenewspaper.com}} of [[Lower Moreland Township, Pennsylvania]] +** ''Montgomery Life'' {{WS|montgomerylife.com}} of [[Fort Washington, Pennsylvania]] +** ''North Penn Life'' {{WS|northpennlife.com}} of [[Lansdale, Pennsylvania]] +** ''Perkasie News Herald'' {{WS|perkasienewsherald.com}} of [[Perkasie, Pennsylvania]] +** ''Public Spirit'' {{WS|thepublicspirit.com}} of [[Hatboro, Pennsylvania]] +** ''Souderton Independent'' {{WS|soudertonindependent.com}} of [[Souderton, Pennsylvania]] +** ''Springfield Sun'' {{WS|springfieldsun.com}} of [[Springfield, Pennsylvania]] +** ''Spring-Ford Reporter'' {{WS|springfordreporter.com}} of [[Royersford, Pennsylvania]] +** ''Times Chronicle'' {{WS|thetimeschronicle.com}} of [[Jenkintown, Pennsylvania]] +** ''Valley Item'' {{WS|valleyitem.com}} of [[Perkiomenville, Pennsylvania]] +** ''Willow Grove Guide'' {{WS|willowgroveguide.com}} of [[Willow Grove, Pennsylvania]] +** ''The Review'' {{WS|roxreview.com}} of [[Roxborough, Philadelphia, Pennsylvania]] + +* Main Line Media News {{WS|mainlinemedianews.com}} +** ''Main Line Times'' {{WS|mainlinetimes.com}} of [[Ardmore, Pennsylvania]] +** ''Main Line Life'' {{WS|mainlinelife.com}} of [[Ardmore, Pennsylvania]] +** ''The King of Prussia Courier'' {{WS|kingofprussiacourier.com}} of [[King of Prussia, Pennsylvania]] + +* Delaware County News Network {{WS|delconewsnetwork.com}} +** ''News of Delaware County'' {{WS|newsofdelawarecounty.com}} of [[Havertown, Pennsylvania]] +** ''County Press'' {{WS|countypressonline.com}} of [[Newtown Square, Pennsylvania]] +** ''Garnet Valley Press'' {{WS|countypressonline.com}} of [[Glen Mills, Pennsylvania]] +** ''Springfield Press'' {{WS|countypressonline.com}} of [[Springfield, Pennsylvania]] +** ''Town Talk'' {{WS|towntalknews.com}} of [[Ridley, Pennsylvania]] + +* Berks-Mont Newspapers {{WS|berksmontnews.com}} +** ''The Boyertown Area Times'' {{WS|berksmontnews.com/boyertown_area_times}} of [[Boyertown, Pennsylvania]] +** ''The Kutztown Area Patriot'' {{WS|berksmontnews.com/kutztown_area_patriot}} of [[Kutztown, Pennsylvania]] +** ''The Hamburg Area Item'' {{WS|berksmontnews.com/hamburg_area_item}} of [[Hamburg, Pennsylvania]] +** ''The Southern Berks News'' {{WS|berksmontnews.com/southern_berks_news}} of [[Exeter Township, Berks County, Pennsylvania]] +** ''Community Connection'' {{WS|berksmontnews.com/community_connection}} of [[Boyertown, Pennsylvania]] + +* Magazines +** ''Bucks Co. Town & Country Living'' {{WS|buckscountymagazine.com}} +** ''Parents Express'' {{WS|parents-express.com}} +** ''Real Men, Rednecks'' {{WS|realmenredneck.com}} + +{{JRC}} + +==References== +<references /> + +[[Category:Journal Register publications|*]] +`; + +function launch() { + var dmp = new diff_match_patch(); + dmp.Diff_Timeout = 0; + + // No warmup loop since it risks triggering an 'unresponsive script' dialog + // in client-side JavaScript + var ms_start = (new Date()).getTime(); + var d = dmp.diff_main(text1, text2, false); + var ms_end = (new Date()).getTime(); + + var ds = dmp.diff_prettyHtml(d); + console.log(ds + '\nTime: ' + (ms_end - ms_start) / 1000 + 's'); +} + +launch(); \ No newline at end of file diff --git a/typescript/tests/tsconfig.json b/typescript/tests/tsconfig.json new file mode 100644 index 0000000..8c1d134 --- /dev/null +++ b/typescript/tests/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "module": "commonjs", + "allowSyntheticDefaultImports": true, + "target": "es6", + "noImplicitAny": true, + "moduleResolution": "node", + "sourceMap": true, + "outDir": "built" + }, + "files": [ + "diff_match_patch_test.ts", + "speedtest.ts" + ] +} \ No newline at end of file diff --git a/typescript/tsconfig.json b/typescript/tsconfig.json new file mode 100644 index 0000000..d45abd9 --- /dev/null +++ b/typescript/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "UMD", + "declaration": true, + "noImplicitReturns": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitAny": true, + "strictNullChecks": true, + "removeComments": true, + "preserveConstEnums": true, + "outDir": "./" + }, + "files": [ + "diff_match_patch.ts" + ] +} \ No newline at end of file From 645d7c60478e60ce67a8aae5067697bac031e08a Mon Sep 17 00:00:00 2001 From: Sam El-Husseini Date: Mon, 29 Jul 2019 23:09:26 -0700 Subject: [PATCH 2/2] Allow accessing diff fields by field name or by index, add helper factory method to create Diff from array --- typescript/diff_match_patch.d.ts | 5 +- typescript/diff_match_patch.js | 31 ++++++++-- typescript/diff_match_patch.ts | 98 ++++++++++++++++++++------------ typescript/tsconfig.json | 1 + 4 files changed, 93 insertions(+), 42 deletions(-) diff --git a/typescript/diff_match_patch.d.ts b/typescript/diff_match_patch.d.ts index 610cf7e..7c4dca4 100644 --- a/typescript/diff_match_patch.d.ts +++ b/typescript/diff_match_patch.d.ts @@ -50,9 +50,12 @@ export declare const DIFF_DELETE = -1; export declare const DIFF_INSERT = 1; export declare const DIFF_EQUAL = 0; export declare class Diff { + 0: number; + 1: string; + constructor(op: number, text: string); + static fromArray(diffArray: [number, string]): Diff; operation: number; text: string; - constructor(op: number, text: string); toString(): string; } export declare class patch_obj { diff --git a/typescript/diff_match_patch.js b/typescript/diff_match_patch.js index 3c08d2d..4ebde3d 100644 --- a/typescript/diff_match_patch.js +++ b/typescript/diff_match_patch.js @@ -8,7 +8,7 @@ } })(function (require, exports) { "use strict"; - exports.__esModule = true; + Object.defineProperty(exports, "__esModule", { value: true }); var diff_match_patch = (function () { function diff_match_patch() { this.Diff_Timeout = 1.0; @@ -1499,15 +1499,38 @@ diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/; return diff_match_patch; }()); - exports["default"] = diff_match_patch; + exports.default = diff_match_patch; exports.DIFF_DELETE = -1; exports.DIFF_INSERT = 1; exports.DIFF_EQUAL = 0; var Diff = (function () { function Diff(op, text) { - this.operation = op; - this.text = text; + this[0] = op; + this[1] = text; } + Diff.fromArray = function (diffArray) { + return new Diff(diffArray[0], diffArray[1]); + }; + Object.defineProperty(Diff.prototype, "operation", { + get: function () { + return this[0]; + }, + set: function (op) { + this[0] = op; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Diff.prototype, "text", { + get: function () { + return this[1]; + }, + set: function (text) { + this[1] = text; + }, + enumerable: true, + configurable: true + }); Diff.prototype.toString = function () { return this.operation + ',' + this.text; }; diff --git a/typescript/diff_match_patch.ts b/typescript/diff_match_patch.ts index e040b54..bbb8e88 100644 --- a/typescript/diff_match_patch.ts +++ b/typescript/diff_match_patch.ts @@ -75,7 +75,7 @@ export default class diff_match_patch { * @param {number=} opt_deadline Optional time when the diff should be complete * by. Used internally for recursive calls. Users should set DiffTimeout * instead. - * @return {!Array.} Array of diff tuples. + * @return {!Array.} Array of diff tuples. */ diff_main(text1: string, text2: string, opt_checklines?: boolean, opt_deadline?: number): Diff[] { @@ -144,7 +144,7 @@ export default class diff_match_patch { * line-level diff first to identify the changed areas. * If true, then run a faster, slightly less optimal diff. * @param {number} deadline Time when the diff should be complete by. - * @return {!Array.} Array of diff tuples. + * @return {!Array.} Array of diff tuples. * @private */ private diff_compute_(text1: string, text2: string, checklines: boolean, @@ -217,7 +217,7 @@ export default class diff_match_patch { * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time when the diff should be complete by. - * @return {!Array.} Array of diff tuples. + * @return {!Array.} Array of diff tuples. * @private */ private diff_lineMode_(text1: string, text2: string, deadline: number): Diff[] { @@ -287,7 +287,7 @@ export default class diff_match_patch { * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time at which to bail if not yet complete. - * @return {!Array.} Array of diff tuples. + * @return {!Array.} Array of diff tuples. * @private */ private diff_bisect_(text1: string, text2: string, deadline: number): Diff[] { @@ -411,7 +411,7 @@ export default class diff_match_patch { * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @param {number} deadline Time at which to bail if not yet complete. - * @return {!Array.} Array of diff tuples. + * @return {!Array.} Array of diff tuples. * @private */ private diff_bisectSplit_(text1: string, text2: string, x: number, y: number, @@ -504,7 +504,7 @@ export default class diff_match_patch { /** * Rehydrate the text in a diff from a string of line hashes to real lines of * text. - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. * @param {!Array.} lineArray Array of unique strings. * @private */ @@ -738,7 +738,7 @@ export default class diff_match_patch { /** * Reduce the number of edits by eliminating semantically trivial equalities. - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. */ diff_cleanupSemantic(diffs: Diff[]) { var changes = false; @@ -853,7 +853,7 @@ export default class diff_match_patch { * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The cat came. -> The cat came. - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. */ diff_cleanupSemanticLossless(diffs: Diff[]) { /** @@ -985,7 +985,7 @@ export default class diff_match_patch { /** * Reduce the number of edits by eliminating operationally trivial equalities. - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. */ diff_cleanupEfficiency(diffs: Diff[]) { var changes = false; @@ -1067,7 +1067,7 @@ export default class diff_match_patch { /** * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. */ diff_cleanupMerge(diffs: Diff[]) { // Add a dummy entry at the end. @@ -1196,7 +1196,7 @@ export default class diff_match_patch { * loc is a location in text1, compute and return the equivalent location in * text2. * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. * @param {number} loc Location within text1. * @return {number} Location within text2. */ @@ -1230,7 +1230,7 @@ export default class diff_match_patch { /** * Convert a diff array into a pretty HTML report. - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. * @return {string} HTML representation. */ diff_prettyHtml(diffs: Diff[]): string { @@ -1262,7 +1262,7 @@ export default class diff_match_patch { /** * Compute and return the source text (all equalities and deletions). - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. * @return {string} Source text. */ diff_text1(diffs: Diff[]): string { @@ -1278,7 +1278,7 @@ export default class diff_match_patch { /** * Compute and return the destination text (all equalities and insertions). - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. * @return {string} Destination text. */ diff_text2(diffs: Diff[]): string { @@ -1295,7 +1295,7 @@ export default class diff_match_patch { /** * Compute the Levenshtein distance; the number of inserted, deleted or * substituted characters. - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. * @return {number} Number of changes. */ diff_levenshtein(diffs: Diff[]): number { @@ -1330,7 +1330,7 @@ export default class diff_match_patch { * required to transform text1 into text2. * 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. - * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} diffs Array of diff tuples. * @return {string} Delta text. */ diff_toDelta(diffs: Diff[]): string { @@ -1357,7 +1357,7 @@ export default class diff_match_patch { * operations required to transform text1 into text2, compute the full diff. * @param {string} text1 Source string for the diff. * @param {string} delta Delta text. - * @return {!Array.} Array of diff tuples. + * @return {!Array.} Array of diff tuples. * @throws {!Error} If invalid input. */ diff_fromDelta(text1: string, delta: string): Diff[] { @@ -1587,7 +1587,7 @@ export default class diff_match_patch { /** * Increase the context until it is unique, * but don't let the pattern expand beyond Match_MaxBits. - * @param {!diff_match_patch.patch_obj} patch The patch to grow. + * @param {!patch_obj} patch The patch to grow. * @param {string} text Source text. * @private */ @@ -1648,13 +1648,13 @@ export default class diff_match_patch { * Method 4 (deprecated, use method 3): * a = text1, b = text2, c = diffs * - * @param {string|!Array.} a text1 (methods 1,3,4) or + * @param {string|!Array.} a text1 (methods 1,3,4) or * Array of diff tuples for text1 to text2 (method 2). - * @param {string|!Array.=} opt_b text2 (methods 1,4) or + * @param {string|!Array.=} opt_b text2 (methods 1,4) or * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). - * @param {string|!Array.=} opt_c Array of diff tuples + * @param {string|!Array.=} opt_c Array of diff tuples * for text1 to text2 (method 4) or undefined (methods 1,2,3). - * @return {!Array.} Array of Patch objects. + * @return {!Array.} Array of Patch objects. */ patch_make(a: string | Diff[], opt_b?: string | Diff[], opt_c?: string | Diff[]): patch_obj[] { @@ -1673,19 +1673,19 @@ export default class diff_match_patch { typeof opt_c == 'undefined') { // Method 2: diffs // Compute text1 from diffs. - diffs = /** @type {!Array.} */(a); + diffs = /** @type {!Array.} */(a); text1 = this.diff_text1(diffs); } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' && typeof opt_c == 'undefined') { // Method 3: text1, diffs text1 = /** @type {string} */(a); - diffs = /** @type {!Array.} */(opt_b); + diffs = /** @type {!Array.} */(opt_b); } else if (typeof a == 'string' && typeof opt_b == 'string' && opt_c && typeof opt_c == 'object') { // Method 4: text1, text2, diffs // text2 is not used. text1 = /** @type {string} */(a); - diffs = /** @type {!Array.} */(opt_c); + diffs = /** @type {!Array.} */(opt_c); } else { throw new Error('Unknown call format to patch_make.'); } @@ -1772,8 +1772,8 @@ export default class diff_match_patch { /** * Given an array of patches, return another array that is identical. - * @param {!Array.} patches Array of Patch objects. - * @return {!Array.} Array of Patch objects. + * @param {!Array.} patches Array of Patch objects. + * @return {!Array.} Array of Patch objects. */ patch_deepCopy(patches: patch_obj[]): patch_obj[] { // Making deep copies is hard in JavaScript. @@ -1799,7 +1799,7 @@ export default class diff_match_patch { /** * Merge a set of patches onto the text. Return a patched text, as well * as a list of true/false values indicating which patches were applied. - * @param {!Array.} patches Array of Patch objects. + * @param {!Array.} patches Array of Patch objects. * @param {string} text Old text. * @return {!Array.>} Two element Array, containing the * new text and an array of boolean values. @@ -1907,7 +1907,7 @@ export default class diff_match_patch { /** * Add some padding on text start and end so that edges can match something. * Intended to be called only from within patch_apply. - * @param {!Array.} patches Array of Patch objects. + * @param {!Array.} patches Array of Patch objects. * @return {string} The padding string added to each side. */ patch_addPadding(patches: patch_obj[]): string { @@ -1967,7 +1967,7 @@ export default class diff_match_patch { * Look through the patches and break up any which are longer than the maximum * limit of the match algorithm. * Intended to be called only from within patch_apply. - * @param {!Array.} patches Array of Patch objects. + * @param {!Array.} patches Array of Patch objects. */ patch_splitMax(patches: patch_obj[]) { var patch_size = this.Match_MaxBits; @@ -2058,7 +2058,7 @@ export default class diff_match_patch { /** * Take a list of patches and return a textual representation. - * @param {!Array.} patches Array of Patch objects. + * @param {!Array.} patches Array of Patch objects. * @return {string} Text representation of patches. */ patch_toText(patches: patch_obj[]): string { @@ -2073,7 +2073,7 @@ export default class diff_match_patch { /** * Parse a textual representation of patches and return a list of Patch objects. * @param {string} textline Text representation of patches. - * @return {!Array.} Array of Patch objects. + * @return {!Array.} Array of Patch objects. * @throws {!Error} If invalid input. */ patch_fromText(textline: string): patch_obj[] { @@ -2169,12 +2169,36 @@ export const DIFF_EQUAL = 0; */ export class Diff { - operation: number; - text: string; + 0: number; + 1: string; constructor(op: number, text: string) { - this.operation = op; - this.text = text; + this[0] = op; + this[1] = text; + } + + /** + * Create a Diff object from a two-element array. + * @return {Diff} new Diff object. + */ + static fromArray(diffArray: [number, string]): Diff { + return new Diff(diffArray[0], diffArray[1]); + } + + get operation(): number { + return this[0]; + } + + set operation(op: number) { + this[0] = op; + } + + get text(): string { + return this[1]; + } + + set text(text: string) { + this[1] = text; } /** @@ -2200,7 +2224,7 @@ export class patch_obj { public length2: number; constructor() { - /** @type {!Array.} */ + /** @type {!Array.} */ this.diffs = []; /** @type {?number} */ this.start1 = null; diff --git a/typescript/tsconfig.json b/typescript/tsconfig.json index d45abd9..8d270af 100644 --- a/typescript/tsconfig.json +++ b/typescript/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "UMD", + "target": "es5", "declaration": true, "noImplicitReturns": true, "noUnusedLocals": true,