highlightCode method

String highlightCode(
  1. String code, {
  2. String? language,
})

Highlights code and returns ANSI-styled output.

If language is not specified or not recognized, attempts auto-detection. Falls back to plain text styling if highlighting fails.

Implementation

String highlightCode(String code, {String? language}) {
  // Normalize the language name
  final lang = _normalizeLanguage(language);

  // Try to highlight with the specified language
  if (lang != null && lang.isNotEmpty) {
    try {
      final result = highlight.parse(code, language: lang);
      if (result.nodes != null && result.nodes!.isNotEmpty) {
        return _nodesToAnsi(result.nodes!);
      }
    } catch (e) {
      // Language not recognized, fall through to auto-detection
    }
  }

  // Try auto-detection
  try {
    final result = highlight.parse(code, autoDetection: true);
    if (result.nodes != null &&
        result.nodes!.isNotEmpty &&
        result.language != null &&
        result.language != 'plaintext') {
      return _nodesToAnsi(result.nodes!);
    }
  } catch (e) {
    // Auto-detection failed
  }

  // Default: return with text style
  final textStyle = theme.text;
  if (textStyle != null) {
    return textStyle.inline(true).render(code);
  }
  return code;
}