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 = DateTime.now();
if (timeout <= 0) {
// One year should be sufficient for 'infinity'.
deadline = deadline.add(Duration(days: 365));
} else {
deadline = deadline.add(Duration(milliseconds: (timeout * 1000).toInt()));
}
}
// Check for equality (speedup).
List<Diff> diffs;
if (text1 == text2) {
diffs = [];
if (text1.isNotEmpty) {
diffs.add(Diff(DIFF_EQUAL, text1));
}
return diffs;
}
// Trim off common prefix (speedup).
var commonlength = commonPrefix(text1, text2);
var commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = 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.
diffs = _diffCompute(text1, text2, timeout, checklines, deadline);
// Restore the prefix and suffix.
if (commonprefix.isNotEmpty) {
diffs.insert(0, Diff(DIFF_EQUAL, commonprefix));
}
if (commonsuffix.isNotEmpty) {
diffs.add(Diff(DIFF_EQUAL, commonsuffix));
}
cleanupMerge(diffs);
return diffs;
}