insertCells method

void insertCells(
  1. int start,
  2. int count, [
  3. CursorStyle? style,
  4. int? end,
])

Inserts count cells at start. New cells are initialized with style.

Implementation

void insertCells(int start, int count, [CursorStyle? style, int? end]) {
  end ??= _length;
  assert(start >= 0 && start < _length);
  assert(end >= start && end <= _length);
  assert(count >= 0 && start + count <= end);

  style ??= CursorStyle.empty;
  final combiningCharacters = Map<int, String>.of(_combiningCharacters);
  final underlineColors = Map<int, int>.of(_underlineColors);

  if (start > 0 && getWidth(start - 1) == 2) {
    eraseCell(start - 1, style);
  }

  if (start + count < end) {
    final moveStart = start * _cellSize;
    final moveEnd = (end - count) * _cellSize;
    final moveOffset = count * _cellSize;
    for (var i = moveEnd - 1; i >= moveStart; i--) {
      _data[i + moveOffset] = _data[i];
    }
  }

  final eraseEnd = min(start + count, end);
  for (var i = start; i < eraseEnd; i++) {
    eraseCell(i, style);
  }

  if (end > 0 && getWidth(end - 1) == 2) {
    eraseCell(end - 1, style);
  }

  _combiningCharacters.clear();
  _underlineColors.clear();
  for (final entry in combiningCharacters.entries) {
    if (entry.key < start) {
      if (getCodePoint(entry.key) != 0) {
        _combiningCharacters[entry.key] = entry.value;
      }
      continue;
    }

    final newIndex = entry.key + count;
    if (entry.key < end && newIndex < end && getCodePoint(newIndex) != 0) {
      _combiningCharacters[newIndex] = entry.value;
      continue;
    }

    if (entry.key >= end && getCodePoint(entry.key) != 0) {
      _combiningCharacters[entry.key] = entry.value;
    }
  }
  for (final entry in underlineColors.entries) {
    if (entry.key < start) {
      if (getCodePoint(entry.key) != 0) {
        _underlineColors[entry.key] = entry.value;
      }
      continue;
    }

    final newIndex = entry.key + count;
    if (entry.key < end && newIndex < end && getCodePoint(newIndex) != 0) {
      _underlineColors[newIndex] = entry.value;
      continue;
    }

    if (entry.key >= end && getCodePoint(entry.key) != 0) {
      _underlineColors[entry.key] = entry.value;
    }
  }

  // Update anchors, move anchors that are after the inserted range.
  for (final anchor in _anchors.toList()) {
    if (anchor.x >= end - count && anchor.x < end) {
      anchor.dispose();
      continue;
    }

    if (anchor.x >= start && anchor.x < end - count) {
      anchor.reposition(anchor.x + count);
    }
  }
}