All files / json-crdt-extensions/peritext/editor Editor.ts

79.27% Statements 352/444
69.69% Branches 115/165
81.03% Functions 47/58
81.25% Lines 286/352

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 81557x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x                               57x 6x                 57x                   3283x   3283x 3283x 3283x 3283x       666x           1892x             1892x                         13341x 11551x 6x 13341x       18013x 18013x 33584x 33584x                 2175x             552x             48x 60x 48x                             547x       566x                 987x 987x       14x                                           564x 564x 564x 564x 564x 564x 564x 564x 564x               552x 552x 564x 564x 564x                             153x       1643x 1643x 1643x 1643x   1643x                     765x 765x 763x 109x 109x   654x 654x 654x 372x 30x 30x 30x   654x 654x 654x 654x                             1193x 1193x 4483x 4395x 4395x 3580x 3580x 3580x                         956x                       237x                                           1002x 1264x 1264x 943x 321x 1046x   1002x 258x                       77x 342x 342x 270x   77x 68x                                       869x                                       133x 133x 133x 133x         36x         41x 41x 41x 41x               40x 40x 40x 40x 40x 32x 32x 23x 23x 23x 17x 17x 17x 6x               34x 34x 34x 34x 28x 28x 19x 19x 18x 18x 18x 1x                         3262x 3262x   176x 176x     2810x 2810x     822x 88x 170x     62x 32x 62x     40x 20x 40x     4x                         526x 528x   466x 466x 466x 88x 466x     58x 58x 58x 58x 58x     4x 4x 4x 4x                           7x 7x 7x 7x                   32x 32x 32x 32x 32x 32x 32x                       41x 20x 20x 20x       28x 28x 28x           4x 4x                     6x 6x 6x 6x 6x 6x 6x 6x 6x           6x           6x           6x                   6x 6x 6x             6x                                                                                                               90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 150x 150x 84x 84x         84x   84x     84x 84x 84x 84x       90x       43x 43x 43x 43x 43x 43x 43x 43x 37x 37x 37x 37x 7x 7x 7x 7x 30x   43x 43x 43x 43x 7x 7x 7x 6x 6x   7x 7x 7x 7x 7x 7x     43x 43x 43x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x   30x   30x 30x             2584x       25x 25x       19x 19x                                              
import {printTree} from 'tree-dump/lib/printTree';
import {Cursor} from './Cursor';
import {stringify} from '../../../json-text/stringify';
import {CursorAnchor, SliceBehavior, SliceHeaderMask, SliceHeaderShift} from '../slice/constants';
import {EditorSlices} from './EditorSlices';
import {next, prev} from 'sonic-forest/lib/util';
import {isLetter, isPunctuation, isWhitespace} from './util';
import {Anchor} from '../rga/constants';
import {MarkerOverlayPoint} from '../overlay/MarkerOverlayPoint';
import {UndefEndIter, type UndefIterator} from '../../../util/iterator';
import {PersistedSlice} from '../slice/PersistedSlice';
import {ValueSyncStore} from '../../../util/events/sync-store';
import {formatType} from '../slice/util';
import {CommonSliceType, type SliceType} from '../slice';
import {tick} from '../../../json-crdt-patch';
import type {ChunkSlice} from '../util/ChunkSlice';
import type {Peritext} from '../Peritext';
import type {Point} from '../rga/Point';
import type {Range} from '../rga/Range';
import type {CharIterator, CharPredicate, Position, TextRangeUnit, ViewRange, ViewSlice} from './types';
import type {Printable} from 'tree-dump';
 
/**
 * For inline boolean ("Overwrite") slices, both range endpoints should be
 * attached to {@link Anchor.Before} as per the Peritext paper. This way, say
 * bold text, automatically extends to include the next character typed as
 * user types.
 *
 * @param range The range to be adjusted.
 */
const makeRangeExtendable = <T>(range: Range<T>): void => {
  Iif (range.end.anchor !== Anchor.Before || range.start.anchor !== Anchor.Before) {
    const start = range.start.clone();
    const end = range.end.clone();
    start.refBefore();
    end.refBefore();
    range.set(start, end);
  }
};
 
export class Editor<T = string> implements Printable {
  public readonly saved: EditorSlices<T>;
  public readonly extra: EditorSlices<T>;
  public readonly local: EditorSlices<T>;
 
  /**
   * Formatting which will be applied to the next inserted text. This is a
   * temporary store for formatting which is not yet applied to the text, but
   * will be if the cursor is not moved.
   */
  public readonly pending = new ValueSyncStore<Map<CommonSliceType | string | number, unknown>>(new Map());
 
  constructor(public readonly txt: Peritext<T>) {
    this.saved = new EditorSlices(txt, txt.savedSlices);
    this.extra = new EditorSlices(txt, txt.extraSlices);
    this.local = new EditorSlices(txt, txt.localSlices);
  }
 
  public text(): string {
    return this.txt.strApi().view();
  }
 
  // ------------------------------------------------------------------ cursors
 
  public addCursor(range: Range<T> = this.txt.rangeAt(0), anchor: CursorAnchor = CursorAnchor.Start): Cursor<T> {
    const cursor = this.txt.localSlices.ins<Cursor<T>, typeof Cursor>(
      range,
      SliceBehavior.Cursor,
      anchor,
      undefined,
      Cursor,
    );
    return cursor;
  }
 
  /**
   * Cursor is the the current user selection. It can be a caret or a range. If
   * range is collapsed to a single point, it is a *caret*.
   *
   * Returns the first cursor in the text and removes all other cursors. If
   * there is no cursor, creates one and inserts it at the start of the text.
   * To work with multiple cursors, use `.cursors()` method.
   */
  public get cursor(): Cursor<T> {
    let cursor: Cursor<T> | undefined;
    for (let i: Cursor<T> | undefined, iterator = this.cursors0(); (i = iterator()); )
      if (!cursor) cursor = i;
      else this.local.del(i);
    return cursor ?? this.addCursor();
  }
 
  public cursors0(): UndefIterator<Cursor<T>> {
    const iterator = this.txt.localSlices.iterator0();
    return () => {
      const slice = iterator();
      return slice instanceof Cursor ? slice : void 0;
    };
  }
 
  public cursors() {
    return new UndefEndIter(this.cursors0());
  }
 
  public forCursor(callback: (cursor: Cursor<T>) => void): void {
    for (let cursor: Cursor<T> | undefined, i = this.cursors0(); (cursor = i()); ) callback(cursor);
  }
 
  /**
   * @returns Returns `true` if there is at least one cursor in the document.
   */
  public hasCursor(): boolean {
    return !!this.cursors0()();
  }
 
  /**
   * @returns Returns the exact number of cursors in the document.
   */
  public cursorCount(): number {
    let cnt = 0;
    for (const i = this.cursors0(); i(); ) cnt++;
    return cnt;
  }
 
  /**
   * Returns relative count of cursors (cardinality).
   *
   * @returns 0 if there are no cursors, 1 if there is exactly one cursor, 2 if
   *     there are more than one cursor.
   */
  public cursorCard(): 0 | 1 | 2 {
    const i = this.cursors0();
    return !i() ? 0 : !i() ? 1 : 2;
  }
 
  public delCursor(cursor: Cursor<T>): void {
    this.local.del(cursor);
  }
 
  public delCursors(): void {
    for (let cursor: Cursor<T> | undefined, i = this.cursors0(); (cursor = i()); ) this.delCursor(cursor);
  }
 
  /**
   * Ensures there is no range selection. If user has selected a range,
   * the contents is removed and the cursor is set at the start of the range
   * as caret.
   */
  public collapseCursor(cursor: Cursor<T>): void {
    this.delRange(cursor);
    cursor.collapseToStart();
  }
 
  public collapseCursors(): void {
    for (let i = this.cursors0(), cursor = i(); cursor; cursor = i()) this.collapseCursor(cursor);
  }
 
  // ------------------------------------------------------------- text editing
 
  /**
   * Ensures there is exactly one cursor. If the cursor is a range, contents
   * inside the range is deleted and cursor is collapsed to a single point.
   *
   * @returns A single cursor collapsed to a single point.
   */
  public caret(): Cursor<T> {
    const cursor = this.cursor;
    Iif (!cursor.isCollapsed()) this.delRange(cursor);
    return cursor;
  }
 
  /**
   * Insert inline text at current cursor position. If cursor selects a range,
   * the range is removed and the text is inserted at the start of the range.
   */
  public insert0(cursor: Cursor<T>, text: string): void {
    Iif (!text) return;
    if (!cursor.isCollapsed()) this.delRange(cursor);
    const after = cursor.start.clone();
    after.refAfter();
    const txt = this.txt;
    const textId = txt.ins(after.id, text);
    const shift = text.length - 1;
    const point = txt.point(shift ? tick(textId, shift) : textId, Anchor.After);
    cursor.set(point, point, CursorAnchor.Start);
  }
 
  /**
   * Inserts text at the cursor positions and collapses cursors, if necessary.
   * The applies any pending inline formatting to the inserted text.
   */
  public insert(text: string): void {
    if (!this.hasCursor()) this.addCursor();
    for (let cursor: Cursor<T> | undefined, i = this.cursors0(); (cursor = i()); ) {
      this.insert0(cursor, text);
      const pending = this.pending.value;
      Iif (pending.size) {
        this.pending.next(new Map());
        const start = cursor.start.clone();
        start.step(-text.length);
        const range = this.txt.range(start, cursor.end.clone());
        for (const [type, data] of pending) this.toggleRangeExclFmt(range, type, data);
      }
    }
  }
 
  /**
   * Deletes the previous character at current cursor positions. If cursors
   * select a range, deletes the whole range.
   */
  public del(step: number = -1): void {
    this.delete(step, 'char');
  }
 
  public delRange(range: Range<T>): void {
    const txt = this.txt;
    const overlay = txt.overlay;
    const contained = overlay.findContained(range);
    for (const slice of contained)
      Iif (slice instanceof PersistedSlice && slice.behavior !== SliceBehavior.Cursor) slice.del();
    txt.delStr(range);
  }
 
  /**
   * Deletes one or more units of text in all cursors. If cursor is a range,
   * deletes the whole range.
   *
   * @param step Number of units to delete.
   * @param unit A unit of deletion: "char", "word", "line".
   */
  public delete(step: number, unit: 'char' | 'word' | 'line'): void {
    const txt = this.txt;
    for (let i = this.cursors0(), cursor = i(); cursor; cursor = i()) {
      if (!cursor.isCollapsed()) {
        this.collapseCursor(cursor);
        return;
      }
      let point1 = cursor.start.clone();
      let point2 = point1.clone();
      if (step > 0) point2 = this.skip(point2, step, unit);
      else if (step < 0) point1 = this.skip(point1, step, unit);
      else if (step === 0) {
        point1 = this.skip(point1, -1, unit);
        point2 = this.skip(point2, 1, unit);
      }
      const range = txt.range(point1, point2);
      this.delRange(range);
      point1.refAfter();
      cursor.set(point1);
    }
  }
 
  // ----------------------------------------------------------------- movement
 
  /**
   * Returns an iterator through visible text, one `step`, one character at a
   * time, starting from a given {@link Point}.
   *
   * @param start The starting point.
   * @param step Number of visible characters to skip.
   * @returns The next visible character iterator.
   */
  public walk(start: Point<T>, step: number = 1): CharIterator<T> {
    let point: Point<T> | undefined = start.clone();
    return () => {
      if (!point) return;
      const char = step > 0 ? point.rightChar() : point.leftChar();
      if (!char) return (point = undefined);
      const end = point.step(step);
      if (end) point = undefined;
      return char;
    };
  }
 
  /**
   * Returns a forward iterator through visible text, one character at a time,
   * starting from a given {@link Point}.
   *
   * @param start The starting point.
   * @param chunk Chunk to start from.
   * @returns The next visible character iterator.
   */
  public fwd(start: Point<T>): CharIterator<T> {
    return this.walk(start, 1);
  }
 
  /**
   * Returns a backward iterator through visible text, one character at a time,
   * starting from a given {@link Point}.
   *
   * @param start The starting point.
   * @param chunk Chunk to start from.
   * @returns The previous visible character iterator.
   */
  public bwd(start: Point<T>): CharIterator<T> {
    return this.walk(start, -1);
  }
 
  /**
   * Skips a word in an arbitrary direction. A word is defined by the `predicate`
   * function, which returns `true` if the character is part of the word.
   *
   * @param iterator Character iterator.
   * @param predicate Predicate function to match characters, returns `true` if
   *     the character is part of the word.
   * @param firstLetterFound Whether the first letter has already been found. If
   *     not, will skip any characters until the first letter, which is matched
   *     by the `predicate` is found.
   * @returns Point after the last skipped character.
   */
  private skipWord(
    iterator: CharIterator<T>,
    predicate: CharPredicate<string>,
    firstLetterFound: boolean,
  ): Point<T> | undefined {
    let next: ChunkSlice<T> | undefined;
    let prev: ChunkSlice<T> | undefined;
    while ((next = iterator())) {
      const char = (next.view() as string)[0];
      if (firstLetterFound) {
        if (!predicate(char)) break;
      } else if (predicate(char)) firstLetterFound = true;
      prev = next;
    }
    if (!prev) return;
    return this.txt.point(prev.id(), Anchor.After);
  }
 
  /**
   * Hard skips line, skips to the next "\n" newline character.
   *
   * @param iterator Character iterator.
   * @returns Point after the last skipped character.
   */
  private skipLine(iterator: CharIterator<T>): Point<T> | undefined {
    let next: ChunkSlice<T> | undefined;
    let prev: ChunkSlice<T> | undefined;
    while ((next = iterator())) {
      const char = (next.view() as string)[0];
      if (char === '\n') break;
      prev = next;
    }
    if (!prev) return;
    return this.txt.point(prev.id(), Anchor.After);
  }
 
  /**
   * End of word iterator (eow). Skips a word forward. A word is defined by the
   * `predicate` function, which returns `true` if the character is part of the
   * word.
   *
   * @param point Point from which to start skipping.
   * @param predicate Character class to skip.
   * @param firstLetterFound Whether the first letter has already been found. If
   *        not, will skip any characters until the first letter, which is
   *        matched by the `predicate` is found.
   * @returns Point after the last character skipped.
   */
  public eow(
    point: Point<T>,
    predicate: CharPredicate<string> = isLetter,
    firstLetterFound: boolean = false,
  ): Point<T> {
    return this.skipWord(this.fwd(point), predicate, firstLetterFound) || point;
  }
 
  /**
   * Beginning of word iterator (bow). Skips a word backward. A word is defined
   * by the `predicate` function, which returns `true` if the character is part
   * of the word.
   *
   * @param point Point from which to start skipping.
   * @param predicate Character class to skip.
   * @param firstLetterFound Whether the first letter has already been found. If
   *        not, will skip any characters until the first letter, which is
   *        matched by the `predicate` is found.
   * @returns Point after the last character skipped.
   */
  public bow(
    point: Point<T>,
    predicate: CharPredicate<string> = isLetter,
    firstLetterFound: boolean = false,
  ): Point<T> {
    const bwd = this.bwd(point);
    const endPoint = this.skipWord(bwd, predicate, firstLetterFound);
    if (endPoint) endPoint.anchor = Anchor.Before;
    return endPoint || point;
  }
 
  /** Find end of line, starting from given point. */
  public eol(point: Point<T>): Point<T> {
    return this.skipLine(this.fwd(point)) || this.end();
  }
 
  /** Find beginning of line, starting from given point. */
  public bol(point: Point<T>): Point<T> {
    const bwd = this.bwd(point);
    const endPoint = this.skipLine(bwd);
    if (endPoint) endPoint.anchor = Anchor.Before;
    return endPoint || this.start();
  }
 
  /**
   * Find end of block, starting from given point. Overlay should be refreshed
   * before calling this method.
   */
  public eob(point: Point<T>): Point<T> {
    const txt = this.txt;
    const overlay = txt.overlay;
    point = point.clone();
    point.halfstep(1);
    if (point.isAbsEnd()) return point;
    let overlayPoint = overlay.getOrNextHigher(point);
    if (!overlayPoint) return this.end();
    if (point.cmp(overlayPoint) === 0) overlayPoint = next(overlayPoint);
    while (!(overlayPoint instanceof MarkerOverlayPoint) && overlayPoint) overlayPoint = next(overlayPoint);
    if (overlayPoint instanceof MarkerOverlayPoint) {
      const point = overlayPoint.clone();
      point.refAfter();
      return point;
    } else return this.end();
  }
 
  /**
   * Find beginning of block, starting from given point. Overlay should be
   * refreshed before calling this method.
   */
  public bob(point: Point<T>): Point<T> {
    const overlay = this.txt.overlay;
    point = point.clone();
    point.halfstep(-1);
    if (point.isAbsStart()) return point;
    let overlayPoint = overlay.getOrNextLower(point);
    if (!overlayPoint) return this.start();
    while (!(overlayPoint instanceof MarkerOverlayPoint) && overlayPoint) overlayPoint = prev(overlayPoint);
    if (overlayPoint instanceof MarkerOverlayPoint) {
      const point = overlayPoint.clone();
      point.refBefore();
      return point;
    } else return this.start();
  }
 
  /**
   * Move a point given number of steps in a specified direction. The unit of
   * one move step is defined by the `unit` parameter.
   *
   * @param point The point to start from.
   * @param steps Number of steps to move. Negative number moves backward.
   * @param unit The unit of move per step: "char", "word", "line", etc.
   * @returns The destination point after the move.
   */
  public skip(point: Point<T>, steps: number, unit: TextRangeUnit): Point<T> {
    Iif (!steps) return point;
    switch (unit) {
      case 'point': {
        const p = point.clone();
        return p.halfstep(steps), p;
      }
      case 'char': {
        const p = point.clone();
        return p.step(steps), p;
      }
      case 'word': {
        if (steps > 0) for (let i = 0; i < steps; i++) point = this.eow(point);
        else for (let i = 0; i < -steps; i++) point = this.bow(point);
        return point;
      }
      case 'line': {
        if (steps > 0) for (let i = 0; i < steps; i++) point = this.eol(point);
        else for (let i = 0; i < -steps; i++) point = this.bol(point);
        return point;
      }
      case 'block': {
        if (steps > 0) for (let i = 0; i < steps; i++) point = this.eob(point);
        else for (let i = 0; i < -steps; i++) point = this.bob(point);
        return point;
      }
      case 'all':
        return steps > 0 ? this.end() : this.start();
    }
  }
 
  /**
   * Move all cursors given number of units.
   *
   * @param steps Number of steps to move.
   * @param unit The unit of move per step: "char", "word", "line".
   * @param endpoint 0 for "focus", 1 for "anchor", 2 for both.
   * @param collapse Whether to collapse the range to a single point.
   */
  public move(steps: number, unit: TextRangeUnit, endpoint: 0 | 1 | 2 = 0, collapse: boolean = true): void {
    this.forCursor((cursor) => {
      switch (endpoint) {
        case 0: {
          let point = cursor.focus();
          point = this.skip(point, steps, unit);
          if (collapse) cursor.set(point);
          else cursor.setEndpoint(point, 0);
          break;
        }
        case 1: {
          let point = cursor.anchor();
          point = this.skip(point, steps, unit);
          Iif (collapse) cursor.set(point);
          else cursor.setEndpoint(point, 1);
          break;
        }
        case 2: {
          const start = this.skip(cursor.start, steps, unit);
          const end = collapse ? start.clone() : this.skip(cursor.end, steps, unit);
          cursor.set(start, end);
          break;
        }
      }
    });
  }
 
  // ---------------------------------------------------------------- selection
 
  /**
   * Leaves only the first cursor, and sets it selection to the whole text.
   *
   * @returns Returns `true` if the selection was successful.
   */
  public selectAll(): boolean {
    const range = this.txt.rangeAll();
    Iif (!range) return false;
    this.cursor.setRange(range);
    return true;
  }
 
  /**
   * Selects a word by extending the selection to the left and right of the point.
   *
   * @param point Point to the right of which is the starting character of the word.
   * @returns Range which contains the word.
   */
  public rangeWord(point: Point<T>): Range<T> | undefined {
    const char = point.rightChar() || point.leftChar();
    Iif (!char) return;
    const c = String(char.view())[0];
    const predicate: CharPredicate<string> = isLetter(c) ? isLetter : isWhitespace(c) ? isWhitespace : isPunctuation;
    const start = this.bow(point, predicate, true);
    const end = this.eow(point, predicate, true);
    return this.txt.range(start, end);
  }
 
  /**
   * Returns a range by expanding the selection to the left and right of the
   * given point.
   *
   * @param point Point from which to start range expansion.
   * @param unit Unit of the range expansion.
   * @returns Range which contains the specified unit.
   */
  public range(point: Point<T>, unit: TextRangeUnit): Range<T> | undefined {
    if (unit === 'word') return this.rangeWord(point);
    const point1 = this.skip(point, -1, unit);
    const point2 = this.skip(point, 1, unit);
    return this.txt.range(point1, point2);
  }
 
  public select(unit: TextRangeUnit): void {
    this.forCursor((cursor) => {
      const range = this.range(cursor.start, unit);
      if (range) cursor.set(range.start, range.end, CursorAnchor.Start);
      else Ethis.delCursors;
    });
  }
 
  public selectAt(at: Position<T>, unit: TextRangeUnit | ''): void {
    this.cursor.set(this.point(at));
    if (unit) this.select(unit);
  }
 
  // --------------------------------------------------------------- formatting
 
  protected toggleRangeExclFmt(
    range: Range<T>,
    type: CommonSliceType | string | number,
    data?: unknown,
    store: EditorSlices<T> = this.saved,
  ): void {
    Iif (range.isCollapsed()) throw new Error('Range is collapsed');
    const txt = this.txt;
    const overlay = txt.overlay;
    const [complete] = overlay.stat(range, 1e6);
    const needToRemoveFormatting = complete.has(type);
    makeRangeExtendable(range);
    const contained = overlay.findContained(range);
    for (const slice of contained) Iif (slice instanceof PersistedSlice && slice.type === type) slice.del();
    Iif (needToRemoveFormatting) {
      overlay.refresh();
      const [complete2, partial2] = overlay.stat(range, 1e6);
      const needsErase = complete2.has(type) || partial2.has(type);
      Iif (needsErase) store.slices.insErase(range, type);
    } else {
      Iif (range.start.isAbs()) {
        const start = txt.pointStart();
        Iif (!start) return;
        Iif (start.cmpSpatial(range.end) >= 0) return;
        range.start = start;
      }
      Iif (range.end.isAbs()) {
        const end = txt.pointEnd();
        Iif (!end) return;
        Iif (end.cmpSpatial(range.start) <= 0) return;
        range.end = end;
      }
      store.slices.insOverwrite(range, type, data);
    }
  }
 
  public toggleExclFmt(
    type: CommonSliceType | string | number,
    data?: unknown,
    store: EditorSlices<T> = this.saved,
  ): void {
    // TODO: handle mutually exclusive slices (<sub>, <sub>)
    this.txt.overlay.refresh();
    CURSORS: for (let i = this.cursors0(), cursor = i(); cursor; cursor = i()) {
      Iif (cursor.isCollapsed()) {
        const pending = this.pending.value;
        if (pending.has(type)) pending.delete(type);
        else pending.set(type, data);
        this.pending.next(pending);
        continue CURSORS;
      }
      this.toggleRangeExclFmt(cursor, type, data, store);
    }
  }
 
  public eraseFormatting(store: EditorSlices<T> = this.saved): void {
    const overlay = this.txt.overlay;
    for (let i = this.cursors0(), cursor = i(); cursor; cursor = i()) {
      overlay.refresh();
      const contained = overlay.findContained(cursor);
      for (const slice of contained) {
        Iif (slice instanceof PersistedSlice) {
          switch (slice.behavior) {
            case SliceBehavior.One:
            case SliceBehavior.Many:
            case SliceBehavior.Erase:
              slice.del();
          }
        }
      }
      overlay.refresh();
      const overlapping = overlay.findOverlapping(cursor);
      for (const slice of overlapping) {
        switch (slice.behavior) {
          case SliceBehavior.One:
          case SliceBehavior.Many: {
            store.insErase(slice.type);
          }
        }
      }
    }
  }
 
  public clearFormatting(store: EditorSlices<T> = this.saved): void {
    const overlay = this.txt.overlay;
    overlay.refresh();
    for (let i = this.cursors0(), cursor = i(); cursor; cursor = i()) {
      const overlapping = overlay.findOverlapping(cursor);
      for (const slice of overlapping) store.del(slice.id);
    }
  }
 
  public split(type?: SliceType, data?: unknown, slices: EditorSlices<T> = this.saved): void {
    for (let i = this.cursors0(), cursor = i(); cursor; cursor = i()) {
      this.collapseCursor(cursor);
      Iif (type === void 0) {
        // TODO: detect current block type
        type = CommonSliceType.p;
      }
      slices.insMarker(type, data);
      cursor.move(1);
    }
  }
 
  // ---------------------------------------------------------- export / import
 
  public export(range: Range<T>): ViewRange {
    const r = range.range();
    r.start.refBefore();
    r.end.refAfter();
    const text = r.text();
    const offset = r.start.viewPos();
    const viewSlices: ViewSlice[] = [];
    const view: ViewRange = [text, offset, viewSlices];
    const txt = this.txt;
    const overlay = txt.overlay;
    const slices = overlay.findOverlapping(r);
    for (const slice of slices) {
      const isSavedSlice = slice.id.sid === txt.model.clock.sid;
      if (!isSavedSlice) continue;
      const behavior = slice.behavior;
      switch (behavior) {
        case SliceBehavior.One:
        case SliceBehavior.Many:
        case SliceBehavior.Erase:
        case SliceBehavior.Marker: {
          const {behavior, type, start, end} = slice;
          const header: number =
            (behavior << SliceHeaderShift.Behavior) +
            (start.anchor << SliceHeaderShift.X1Anchor) +
            (end.anchor << SliceHeaderShift.X2Anchor);
          const viewSlice: ViewSlice = [header, start.viewPos(), end.viewPos(), type];
          const data = slice.data();
          Iif (data !== void 0) viewSlice.push(data);
          viewSlices.push(viewSlice);
        }
      }
    }
    return view;
  }
 
  public import(pos: number, view: ViewRange): void {
    const [text, offset, slices] = view;
    const txt = this.txt;
    const length = slices.length;
    const splits: ViewSlice[] = [];
    const annotations: ViewSlice[] = [];
    const texts: string[] = [];
    let start = 0;
    for (let i = 0; i < length; i++) {
      const slice = slices[i];
      const [header, x1] = slice;
      const behavior: SliceBehavior = (header & SliceHeaderMask.Behavior) >>> SliceHeaderShift.Behavior;
      if (behavior === SliceBehavior.Marker) {
        const end = x1 - offset;
        texts.push(text.slice(start, end));
        start = end + 1;
        splits.push(slice);
      } else annotations.push(slice);
    }
    const lastText = text.slice(start);
    const splitLength = splits.length;
    start = pos;
    for (let i = 0; i < splitLength; i++) {
      const str = texts[i];
      const split = splits[i];
      if (str) {
        txt.insAt(start, str);
        start += str.length;
      }
      if (split) {
        const [, , , type, data] = split;
        const after = txt.pointAt(start);
        after.refAfter();
        txt.savedSlices.insMarkerAfter(after.id, type, data);
        start += 1;
      }
    }
    if (lastText) txt.insAt(start, lastText);
    const annotationsLength = annotations.length;
    for (let i = 0; i < annotationsLength; i++) {
      const slice = annotations[i];
      const [header, x1, x2, type, data] = slice;
      const anchor1: Anchor = (header & SliceHeaderMask.X1Anchor) >>> SliceHeaderShift.X1Anchor;
      const anchor2: Anchor = (header & SliceHeaderMask.X2Anchor) >>> SliceHeaderShift.X2Anchor;
      const behavior: SliceBehavior = (header & SliceHeaderMask.Behavior) >>> SliceHeaderShift.Behavior;
      const x1Src = x1 - offset;
      const x2Src = x2 - offset;
      const x1Capped = Math.max(0, x1Src);
      const x2Capped = Math.min(text.length, x2Src);
      const x1Dest = x1Capped + pos;
      const annotationLength = x2Capped - x1Capped;
      const range = txt.rangeAt(x1Dest, annotationLength);
      if (!!x1Dest && anchor1 === Anchor.After) range.start.refAfter();
      // else range.start.refBefore();
      if (anchor2 === Anchor.Before) range.end.refBefore();
      // else range.end.refAfter();
      if (range.end.isAbs()) range.end.refAfter();
      txt.savedSlices.ins(range, behavior, type, data);
    }
  }
 
  // ------------------------------------------------------------------ various
 
  public point(at: Position<T>): Point<T> {
    return typeof at === 'number' ? this.txt.pointAt(at) : Array.isArray(at) ? this.txt.pointAt(at[0], at[1]) : at;
  }
 
  public end(): Point<T> {
    const txt = this.txt;
    return txt.pointEnd() ?? txt.pointAbsEnd();
  }
 
  public start(): Point<T> {
    const txt = this.txt;
    return txt.pointStart() ?? txt.pointAbsStart();
  }
 
  // ---------------------------------------------------------------- Printable
 
  public toString(tab: string = ''): string {
    const pending = this.pending.value;
    const pendingFormatted = {} as any;
    for (const [type, data] of pending) pendingFormatted[formatType(type)] = data;
    return (
      'Editor' +
      printTree(tab, [
        (tab) =>
          'cursors' +
          printTree(
            tab,
            [...this.cursors()].map((cursor) => (tab) => cursor.toString(tab)),
          ),
        () => `pending ${stringify(pendingFormatted)}`,
      ])
    );
  }
}