buildSyntaxHighlightedText static method

TextSpan buildSyntaxHighlightedText(
  1. String code
)

Builds syntax highlighted text with vibrant colors

Implementation

static TextSpan buildSyntaxHighlightedText(String code) {
  final lines = code.split('\n');
  final List<TextSpan> spans = [];

  // Track bracket nesting levels globally across all lines
  int parenthesesLevel = 0;
  int braceLevel = 0;
  int bracketLevel = 0;

  for (int i = 0; i < lines.length; i++) {
    // Add line number
    spans.add(
      TextSpan(
        text: '${(i + 1).toString().padLeft(2)}  ',
        style: const TextStyle(
          color: Color(0xFFFFFFFF),
          fontSize: 12,
          fontWeight: FontWeight.bold,
        ),
      ),
    );

    // Add separator
    spans.add(
      TextSpan(
        text: '    ',
        style: TextStyle(
          color: Colors.cyan.shade400,
          fontWeight: FontWeight.bold,
        ),
      ),
    );

    // Add syntax highlighted line
    final lineSpan = _highlightLine(
      lines[i],
      parenthesesLevel,
      braceLevel,
      bracketLevel,
    );
    spans.add(lineSpan.span);

    // Update global nesting levels
    parenthesesLevel = lineSpan.parenthesesLevel;
    braceLevel = lineSpan.braceLevel;
    bracketLevel = lineSpan.bracketLevel;

    // Add newline except for last line
    if (i < lines.length - 1) {
      spans.add(const TextSpan(text: '\n'));
    }
  }

  return TextSpan(children: spans);
}