highlight method

String highlight ({dynamic color })
override

Prints the text associated with this span in a user-friendly way.

This is identical to message, except that it doesn't print the file name, line number, column number, or message. If length is 0 and this isn't a SourceSpanWithContext, returns an empty string.

color may either be a String, a bool, or null. If it's a string, it indicates an ANSII terminal color escape that should be used to highlight the span's text. If it's true, it indicates that the text should be highlighted using the default color. If it's false or null, it indicates that the text shouldn't be highlighted.

Implementation

String highlight({color}) {
  if (color == true) color = colors.RED;
  if (color == false) color = null;

  var column = start.column;
  var buffer = new StringBuffer();
  String textLine;
  if (this is SourceSpanWithContext) {
    var context = (this as SourceSpanWithContext).context;
    var lineStart = findLineStart(context, text, column);
    if (lineStart != null && lineStart > 0) {
      buffer.write(context.substring(0, lineStart));
      context = context.substring(lineStart);
    }
    var endIndex = context.indexOf('\n');
    textLine = endIndex == -1 ? context : context.substring(0, endIndex + 1);
    column = math.min(column, textLine.length);
  } else if (length == 0) {
    return "";
  } else {
    textLine = text.split("\n").first;
    column = 0;
  }

  var toColumn =
      math.min(column + end.offset - start.offset, textLine.length);
  if (color != null) {
    buffer.write(textLine.substring(0, column));
    buffer.write(color);
    buffer.write(textLine.substring(column, toColumn));
    buffer.write(colors.NONE);
    buffer.write(textLine.substring(toColumn));
  } else {
    buffer.write(textLine);
  }
  if (!textLine.endsWith('\n')) buffer.write('\n');

  for (var i = 0; i < column; i++) {
    if (textLine.codeUnitAt(i) == $tab) {
      buffer.writeCharCode($tab);
    } else {
      buffer.writeCharCode($space);
    }
  }

  if (color != null) buffer.write(color);
  buffer.write('^' * math.max(toColumn - column, 1));
  if (color != null) buffer.write(colors.NONE);
  return buffer.toString();
}