set method

void set(
  1. int x,
  2. Cell? cell
)

Sets the cell at x, applying wide-cell overwrite rules.

Implementation

void set(int x, Cell? cell) {
  // Upstream: maxCellWidth = 5.
  const maxCellWidth = 5;

  final lineWidth = _cells.length;
  if (x < 0 || x >= lineWidth) return;

  // Wide-cell overwrite clearing (port of `buffer.go:Line.Set`).
  final prev = at(x);
  if (prev != null) {
    final pw = prev.width;
    if (pw > 1) {
      for (var j = 0; j < pw && x + j < lineWidth; j++) {
        final c = prev.clone()..empty();
        replace(x + j, c);
      }
    } else if (pw == 0) {
      // Placeholder overwrite: scan left for the wide cell origin.
      for (var j = 1; j < maxCellWidth && x - j >= 0; j++) {
        final wide = at(x - j);
        if (wide == null) continue;
        final ww = wide.width;
        if (ww > 1 && j < ww) {
          for (var k = 0; k < ww && x - j + k < lineWidth; k++) {
            final c = wide.clone()..empty();
            replace(x - j + k, c);
          }
          break;
        }
      }
    }
  }

  if (cell == null) {
    replace(x, Cell.emptyCell());
    return;
  }

  replaceWithClone(x, cell);
  final cw = cell.width;

  if (x + cw > lineWidth) {
    for (var i = 0; i < cw && x + i < lineWidth; i++) {
      final c = cell.clone()..empty();
      replace(x + i, c);
    }
    return;
  }

  if (cw > 1) {
    // Mark placeholder cells with zero-width zero cells.
    for (var j = 1; j < cw && x + j < lineWidth; j++) {
      replace(x + j, Cell());
    }
  }
}