HighlightedDiff.of constructor

HighlightedDiff.of(
  1. FileDiff diff, {
  2. required Highlighter highlighter,
  3. required SyntaxTheme theme,
  4. String? language,
  5. Duration? budget,
})

Highlights diff. The language comes from language if given, otherwise from the file extension. Unknown languages stay plain.

With a budget, the new file and then the old one are tokenized for at most that long, whether from full texts or a patch's hunks, after at least one line of each. tokenize continues. Lines not tokenized yet are plain.

Implementation

factory HighlightedDiff.of(
  FileDiff diff, {
  required Highlighter highlighter,
  required SyntaxTheme theme,
  String? language,
  Duration? budget,
}) {
  final grammar = _grammarFor(diff, highlighter, language);
  if (grammar == null) {
    // Plain: each line is one token, made when it's asked for.
    return HighlightedDiff._(
      theme,
      const {},
      const {},
      oldPlain: _textOf(diff, old: true),
      newPlain: _textOf(diff, old: false),
    );
  }
  final oldLines = diff.oldLines;
  final newLines = diff.newLines;
  if (oldLines != null && newLines != null) {
    final oldDocument = TokenizedDocument(grammar);
    final newDocument = TokenizedDocument(grammar);
    final highlighted = HighlightedDiff._(
      theme,
      const {},
      const {},
      oldDocument: oldDocument,
      newDocument: newDocument,
      sides: [_DocumentSide(newDocument), _DocumentSide(oldDocument)],
    );
    final clock = Stopwatch()..start();
    newDocument.update(newLines.join('\n'), budget: budget);
    oldDocument.update(oldLines.join('\n'), budget: _left(budget, clock));
    return highlighted;
  }

  final old = <int, List<ThemedToken>>{};
  final newer = <int, List<ThemedToken>>{};
  final newSide = _HunkSide(grammar, theme, diff.hunks, newer, old: false);
  final oldSide = _HunkSide(grammar, theme, diff.hunks, old, old: true);
  final clock = Stopwatch()..start();
  newSide.tokenize(budget: budget);
  oldSide.tokenize(budget: _left(budget, clock));
  return HighlightedDiff._(theme, old, newer, sides: [newSide, oldSide]);
}