parseClipboardText function

List<List<String>> parseClipboardText(
  1. String text, {
  2. String delimiter = '\t',
})

Splits clipboard text back into a grid of cells: the inverse of toClipboardText.

Accepts the three line endings a clipboard can carry, because the text may have come from any application on any platform. A trailing newline does not produce an empty last row - spreadsheets add one - but an empty line in the middle does, since that is a row of blanks the user copied.

Quoted fields are understood, RFC 4180 style: a field wrapped in double quotes may contain the delimiter, a newline, or a doubled "" quote. Excel, Sheets and LibreOffice all quote such a cell, and reading the text literally split one cell containing a line break into two rows.

Implementation

List<List<String>> parseClipboardText(String text, {String delimiter = '\t'}) {
  if (text.isEmpty) return const [];
  // A trailing line break is punctuation - spreadsheets add one - so it is
  // taken off before parsing rather than becoming a row of one empty cell.
  final body = text.endsWith('\r\n')
      ? text.substring(0, text.length - 2)
      : (text.endsWith('\n') || text.endsWith('\r')
          ? text.substring(0, text.length - 1)
          : text);
  if (body.isEmpty) return const [];
  final rows = <List<String>>[];
  var row = <String>[];
  final field = StringBuffer();
  var quoted = false;
  var i = 0;

  void endField() {
    row.add(field.toString());
    field.clear();
  }

  void endRow() {
    endField();
    rows.add(row);
    row = <String>[];
  }

  while (i < body.length) {
    final char = body[i];
    if (quoted) {
      if (char == '"') {
        if (i + 1 < body.length && body[i + 1] == '"') {
          field.write('"');
          i += 2;
          continue;
        }
        quoted = false;
        i++;
        continue;
      }
      field.write(char);
      i++;
      continue;
    }
    if (char == '"' && field.isEmpty) {
      quoted = true;
      i++;
      continue;
    }
    if (delimiter.isNotEmpty && body.startsWith(delimiter, i)) {
      endField();
      i += delimiter.length;
      continue;
    }
    if (char == '\r' || char == '\n') {
      endRow();
      i += char == '\r' && i + 1 < body.length && body[i + 1] == '\n' ? 2 : 1;
      continue;
    }
    field.write(char);
    i++;
  }
  endRow();
  return rows;
}