diff function
Find the differences between two texts. Simplifies the problem by stripping any common prefix or suffix off the texts before diffing.
text1
is the old string to be diffed.text2
is the new string to be diffed.timeout
is an optional number of seconds to map a diff before giving up (0 for infinity).checklines
is an optional speedup flag. If 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.deadline
is an optional time when the diff should be complete by. Used internally for recursive calls. Users should setdiffTimeout
instead.
Returns a List of Diff objects.
Implementation
List<Diff> diff(String text1, String text2,
{double timeout: 1.0, bool checklines: true,
DateTime? deadline}) {
// Set a deadline by which time the diff must be complete.
if (deadline == null) {
deadline = new DateTime.now();
if (timeout <= 0) {
// One year should be sufficient for 'infinity'.
deadline = deadline.add(new Duration(days: 365));
} else {
deadline = deadline.add(new Duration(
milliseconds: (timeout * 1000).toInt()));
}
}
// Check for equality (speedup).
List<Diff> diffs;
if (text1 == text2) {
diffs = [];
if (!text1.isEmpty) {
diffs.add(new Diff(DIFF_EQUAL, text1));
}
return diffs;
}
// Trim off common prefix (speedup).
int commonlength = commonPrefix(text1, text2);
String commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = commonSuffix(text1, text2);
String 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.
diffs = _diffCompute(text1, text2, timeout, checklines, deadline);
// Restore the prefix and suffix.
if (!commonprefix.isEmpty) {
diffs.insert(0, new Diff(DIFF_EQUAL, commonprefix));
}
if (!commonsuffix.isEmpty) {
diffs.add(new Diff(DIFF_EQUAL, commonsuffix));
}
cleanupMerge(diffs);
return diffs;
}