highlightAuto method

AutoHighlightResult highlightAuto(
  1. String code, [
  2. List<String>? languageSubset
])

Highlighting with language detection. Accepts a string with the code to highlight. Returns an object with the following properties:

  • language (detected language)
  • relevance (int)
  • value (an HTML string with highlighting markup)
  • secondBest (object with the same structure for second-best heuristically detected language, may be absent)

Implementation

AutoHighlightResult highlightAuto(String code, [List<String>? languageSubset]) {
  final List<String> languages = languageSubset ?? _languages.keys.toList();
  final HighlightResult plaintext = justTextHighlightResult(code);
  final List<HighlightResult> results = languages
    .where((e) => getLanguage(e) != null)
    .where((e) => autoDetection(e))
    .map((name) => _highlight(name, code, false))
    .toList();
  results.insert(0, plaintext); // plaintext is always an option
  // Dart's list.sort() is not stable, here we need a stable sort
  mergeSort<HighlightResult>(results, compare: (a, b) {
    // sort base on relevance
    if (a.relevance != b.relevance) {
      return b.relevance - a.relevance < 0 ? -1 : 1;
    }

    // always award the tie to the base language
    // ie if C++ and Arduino are tied, it's more likely to be C++
    if (a.language != null && b.language != null) {
      if (getLanguage(a.language!)?.supersetOf == b.language) {
        return 1;
      } else if (getLanguage(b.language!)?.supersetOf == a.language) {
        return -1;
      }
    }

    // otherwise say they are equal, which has the effect of sorting on
    // relevance while preserving the original ordering - which is how ties
    // have historically been settled, ie the language that comes first always
    // wins in the case of a tie
    return 0;
  });
  return AutoHighlightResult(
    best: results[0],
    secondBest: results.length > 1 ? results[1]: null,
  );
}