getSelectedText method

String getSelectedText()

Returns the currently selected text.

Implementation

String getSelectedText() {
  if (_selectionStart == null || _selectionEnd == null) return '';

  final (x1, y1) = _selectionStart!;
  final (x2, y2) = _selectionEnd!;

  final startY = math.min(y1, y2);
  final endY = math.max(y1, y2);

  if (startY < 0 || endY >= _lines.length) return '';

  final sb = StringBuffer();
  for (var y = startY; y <= endY; y++) {
    final line = _lines[y];
    int startX, endX;

    if (startY == endY) {
      startX = math.min(x1, x2);
      endX = math.max(x1, x2);
    } else if (y == startY) {
      startX = y1 < y2 ? x1 : x2;
      endX = line.length;
    } else if (y == endY) {
      startX = 0;
      endX = y1 < y2 ? x2 : x1;
    } else {
      startX = 0;
      endX = line.length;
    }

    startX = startX.clamp(0, line.length);
    endX = endX.clamp(0, line.length);

    if (startX < endX) {
      sb.write(line.sublist(startX, endX).join());
    }
    if (y < endY) {
      sb.write('\n');
    }
  }

  return sb.toString();
}