renderAnsi function
Renders highlighted lines with 24-bit ANSI escape codes, for terminals.
Set background to paint the theme's background across each full row.
Control characters in the code, other than tab, are replaced with U+FFFD, so the code cannot emit its own escape sequences.
Implementation
String renderAnsi(
List<List<ThemedToken>> lines,
SyntaxTheme theme, {
bool background = false,
}) {
final out = StringBuffer();
final bg = background ? _sgrColor(48, theme.background) : '';
for (var i = 0; i < lines.length; i++) {
if (i > 0) out.write('\n');
// Erase to the end of the row in the background color.
if (background) out.write('\x1B[0m$bg\x1B[K');
for (final token in lines[i]) {
final style = token.style;
out
..write('\x1B[0m')
..write(bg)
..write(_sgrColor(38, style.foreground));
if (style.background != null) out.write(_sgrColor(48, style.background!));
if (style.bold) out.write('\x1B[1m');
if (style.italic) out.write('\x1B[3m');
if (style.underline) out.write('\x1B[4m');
if (style.strikethrough) out.write('\x1B[9m');
out.write(token.text.replaceAll(_controlChars, '\uFFFD'));
}
out.write('\x1B[0m');
}
return out.toString();
}