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

77% Statements 479/622
63.63% Branches 161/253
76% Functions 57/75
79.44% Lines 398/501

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 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 113960x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x                                                     60x 6x                 60x                   3370x   3370x   3370x 3370x 3370x 3370x       666x           1956x             1956x                         13527x 11673x 6x 13527x       18421x 18421x 34336x 34336x                 2295x             552x                                 48x 60x 48x                             547x       566x                 1173x 1173x       14x                                           564x 564x 564x 564x 564x 564x 564x 564x 564x 564x 564x               552x 552x 552x 564x 564x 564x 564x               552x               153x       1829x 1829x 1829x 1829x   1829x                     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                         168x                     78x 78x 78x 78x 78x                                                           12x 12x 12x 12x           30x 30x 30x 60x 60x 60x 60x           54x 54x 54x 54x 168x 168x 168x 168x 168x 168x 168x 132x                     78x 78x 78x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 48x 48x 48x 48x 48x 48x 48x           30x 30x 30x 30x       102x 78x 78x 78x 78x     24x 24x 24x       24x 24x                                                                                                                                                                             90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 150x 150x 84x 84x         84x   84x     84x 84x 84x 84x       90x                     24x 24x 24x 24x 24x 48x 48x 24x 24x 24x       24x 24x 24x 24x       24x       70x 70x 70x 70x 70x 62x 62x 62x 62x 32x 32x 26x 26x 26x 3x   23x         70x 22x 22x 22x   70x 70x 70x 70x 70x 70x 71x 71x 71x 71x 71x 22x 22x 22x 22x 49x   70x 70x 70x 70x 22x 22x 22x 18x 18x   22x 22x 22x 22x 22x 22x     70x 70x 70x   70x 70x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x   49x   49x 49x   70x       6x 6x 6x 12x 12x             2632x       25x 25x       19x 19x                                              
import {Cursor} from './Cursor';
import {Anchor} from '../rga/constants';
import {formatType} from '../slice/util';
import {EditorSlices} from './EditorSlices';
import {next, prev} from 'sonic-forest/lib/util';
import {printTree} from 'tree-dump/lib/printTree';
import {createRegistry} from '../registry/registry';
import {PersistedSlice} from '../slice/PersistedSlice';
import {stringify} from '../../../json-text/stringify';
import {CommonSliceType, type SliceTypeSteps, type SliceType, type SliceTypeStep} from '../slice';
import {isLetter, isPunctuation, isWhitespace, stepsEqual} from './util';
import {ValueSyncStore} from '../../../util/events/sync-store';
import {MarkerOverlayPoint} from '../overlay/MarkerOverlayPoint';
import {UndefEndIter, type UndefIterator} from '../../../util/iterator';
import {tick, Timespan, type ITimespanStruct} from '../../../json-crdt-patch';
import {CursorAnchor, SliceBehavior, SliceHeaderMask, SliceHeaderShift, SliceTypeCon} from '../slice/constants';
import type {Point} from '../rga/Point';
import type {Range} from '../rga/Range';
import type {Printable} from 'tree-dump';
import type {Peritext} from '../Peritext';
import type {ChunkSlice} from '../util/ChunkSlice';
import type {MarkerSlice} from '../slice/MarkerSlice';
import type {SliceRegistry} from '../registry/SliceRegistry';
import type {
  CharIterator,
  CharPredicate,
  Position,
  TextRangeUnit,
  ViewStyle,
  ViewRange,
  ViewSlice,
  EditorUi,
} from './types';
 
/**
 * 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());
 
  public registry: SliceRegistry = createRegistry();
 
  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 the first cursor in the document, if any.
   *
   * @returns Returns the first cursor in the document, or `undefined` if there
   *     are no cursors.
   */
  public getCursor(): undefined | Cursor<T> {
    return this.hasCursor() ? this.cursor : void 0;
  }
 
  /**
   * @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): ITimespanStruct | undefined {
    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 span = new Timespan(textId.sid, textId.time, text.length);
    const shift = text.length - 1;
    const point = txt.point(shift ? tick(textId, shift) : textId, Anchor.After);
    cursor.set(point, point, CursorAnchor.Start);
    return span;
  }
 
  /**
   * 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): ITimespanStruct[] {
    const spans: ITimespanStruct[] = [];
    if (!this.hasCursor()) this.addCursor();
    for (let cursor: Cursor<T> | undefined, i = this.cursors0(); (cursor = i()); ) {
      const span = this.insert0(cursor, text);
      if (span) spans.push(span);
      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);
      }
    }
    return spans;
  }
 
  /**
   * 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, ui?: EditorUi<T>): 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 = ui?.eol?.(point, 1) ?? this.eol(point);
        else for (let i = 0; i < -steps; i++) point = ui?.eol?.(point, -1) ?? this.bol(point);
        return point;
      }
      case 'vert': {
        return ui?.vert?.(point, steps) || 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,
    ui?: EditorUi<T>,
  ): void {
    this.forCursor((cursor) => {
      switch (endpoint) {
        case 0: {
          let point = cursor.focus();
          point = this.skip(point, steps, unit, ui);
          if (collapse) cursor.set(point);
          else cursor.setEndpoint(point, 0);
          break;
        }
        case 1: {
          let point = cursor.anchor();
          point = this.skip(point, steps, unit, ui);
          Iif (collapse) cursor.set(point);
          else cursor.setEndpoint(point, 1);
          break;
        }
        case 2: {
          const start = this.skip(cursor.start, steps, unit, ui);
          const end = collapse ? start.clone() : this.skip(cursor.end, steps, unit, ui);
          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, ui?: EditorUi<T>): Range<T> | undefined {
    if (unit === 'word') return this.rangeWord(point);
    const point1 = this.skip(point, -1, unit, ui);
    const point2 = this.skip(point, 1, unit, ui);
    return this.txt.range(point1, point2);
  }
 
  public select(unit: TextRangeUnit, ui?: EditorUi<T>): void {
    this.forCursor((cursor) => {
      const range = this.range(cursor.start, unit, ui);
      if (range) cursor.set(range.start, range.end, CursorAnchor.Start);
      else Ethis.delCursors;
    });
  }
 
  public selectAt(at: Position<T>, unit: TextRangeUnit | '', ui?: EditorUi<T>): void {
    this.cursor.set(this.point(at));
    if (unit) this.select(unit, ui);
  }
 
  // --------------------------------------------------------------- formatting
 
  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);
    }
  }
 
  // -------------------------------------------------------- inline 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.insOne(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);
    }
  }
 
  // --------------------------------------------------------- block formatting
 
  /**
   * Returns block split marker of the block inside which the point is located.
   *
   * @param point The point to get the marker at.
   * @returns The split marker at the point, if any.
   */
  public getMarker(point: Point<T>): MarkerSlice<T> | undefined {
    return this.txt.overlay.getOrNextLowerMarker(point)?.marker;
  }
 
  /**
   * Returns the block type at the given point. Block type is a nested array of
   * tags, e.g. `['p']`, `['blockquote', 'p']`, `['ul', 'li', 'p']`, etc.
   *
   * @param point The point to get the block type at.
   * @returns Current block type at the point.
   */
  public getBlockType(point: Point<T>): [type: SliceTypeSteps, marker?: MarkerSlice<T> | undefined] {
    const marker = this.getMarker(point);
    Iif (!marker) return [[SliceTypeCon.p]];
    let steps = marker?.type ?? [SliceTypeCon.p];
    Iif (!Array.isArray(steps)) steps = [steps];
    return [steps, marker];
  }
 
  /**
   * Insert a block split at the start of the document. The start of the
   * document is defined as immediately after all deleted characters starting
   * from the beginning of the document, or as the ABS start of the document if
   * there are no deleted characters.
   *
   * @param type The type of the marker.
   * @returns The inserted marker slice.
   */
  public insStartMarker(type: SliceType): MarkerSlice<T> {
    const txt = this.txt;
    const start = txt.pointStart() ?? txt.pointAbsStart();
    start.refAfter();
    return this.txt.savedSlices.insMarkerAfter(start.id, type);
  }
 
  /**
   * Find the block split marker which contains the point and sets the block
   * type of the marker. If there is no block split marker at the point, a new
   * block split marker is inserted at the beginning of the document with the
   * specified block type.
   *
   * @param point The point at which to set the block type.
   * @param type The new block type.
   * @returns The marker slice at the point, or a new marker slice if there is none.
   */
  public setBlockType(point: Point<T>, type: SliceType): MarkerSlice<T> {
    const marker = this.getMarker(point);
    if (marker) {
      marker.update({type});
      return marker;
    }
    return this.insStartMarker(type);
  }
 
  public getContainerPath(steps: SliceTypeSteps): SliceTypeSteps {
    const registry = this.registry;
    const length = steps.length;
    for (let i = length - 1; i >= 0; i--) {
      const step = steps[i];
      const tag = Array.isArray(step) ? step[0] : step;
      const isContainer = registry.isContainer(tag);
      if (isContainer) return steps.slice(0, i + 1);
    }
    return [];
  }
 
  public getDeepestCommonContainer(steps1: SliceTypeSteps, steps2: SliceTypeSteps): number {
    const length1 = steps1.length;
    const length2 = steps2.length;
    const min = Math.min(length1, length2);
    for (let i = 0; i < min; i++) {
      const step1 = steps1[i];
      const step2 = steps2[i];
      const tag1 = Array.isArray(step1) ? step1[0] : step1;
      const tag2 = Array.isArray(step2) ? step2[0] : step2;
      const disc1 = Array.isArray(step1) ? step1[1] : 0;
      const disc2 = Array.isArray(step2) ? step2[1] : 0;
      if (tag1 !== tag2 || disc1 !== disc2) return i - 1;
      if (!this.registry.isContainer(tag1)) return i - 1;
    }
    return min;
  }
 
  /**
   * @param at Point at which split block split happens.
   * @param slices The slices set to use.
   * @returns True if a marker was inserted, false if it was updated.
   */
  public splitAt(at: Point<T>, slices: EditorSlices<T> = this.saved): boolean {
    const [type, marker] = this.getBlockType(at);
    const prevMarker = marker ? this.getMarker(marker.start.copy((p) => p.halfstep(-1))) : void 0;
    if (marker && prevMarker) {
      const rangeFromMarker = this.txt.range(marker.start, at);
      const noLeadingText = rangeFromMarker.length() <= 1;
      if (noLeadingText) {
        const markerSteps = marker.typeSteps();
        const prevMarkerSteps = prevMarker.typeSteps();
        if (markerSteps.length > 1) {
          const areMarkerTypesEqual = stepsEqual(markerSteps, prevMarkerSteps);
          if (areMarkerTypesEqual) {
            const i = this.getDeepestCommonContainer(markerSteps, prevMarkerSteps);
            if (i >= 0) {
              const newType = [...markerSteps];
              const step = newType[i];
              const tag = Array.isArray(step) ? step[0] : step;
              const disc = Array.isArray(step) ? step[1] : 0;
              newType[i] = [tag, (disc + 1) % 8];
              marker.update({type: newType});
              return false;
            }
          }
        }
      }
    }
    const containerPath = this.getContainerPath(type);
    const newType = containerPath.concat([CommonSliceType.p]);
    slices.insMarker(newType);
    return true;
  }
 
  public split(type?: SliceType, data?: unknown, slices: EditorSlices<T> = this.saved): void {
    if (type === void 0) {
      for (let i = this.cursors0(), cursor = i(); cursor; cursor = i()) {
        this.collapseCursor(cursor);
        const didInsertMarker = this.splitAt(cursor.start, slices);
        if (didInsertMarker) cursor.move(1);
      }
    } else {
      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);
      }
    }
  }
 
  public setStartMarker(type: SliceType, data?: unknown, slices: EditorSlices<T> = this.saved): MarkerSlice<T> {
    const after = this.txt.pointStart() ?? this.txt.pointAbsStart();
    after.refAfter();
    Iif (Array.isArray(type) && type.length === 1) type = type[0];
    return slices.slices.insMarkerAfter(after.id, type, data);
  }
 
  public tglMarkerAt(
    point: Point<T>,
    type: SliceType,
    data?: unknown,
    slices: EditorSlices<T> = this.saved,
    def: SliceTypeStep = SliceTypeCon.p,
  ): void {
    const overlay = this.txt.overlay;
    const markerPoint = overlay.getOrNextLowerMarker(point);
    if (markerPoint) {
      const marker = markerPoint.marker;
      const tag = marker.tag();
      Iif (!Array.isArray(type)) type = [type];
      const typeTag = type[type.length - 1];
      Iif (tag === typeTag) type = [...type.slice(0, -1), def];
      Iif (Array.isArray(type) && type.length === 1) type = type[0];
      marker.update({type});
    } else this.setStartMarker(type, data, slices);
  }
 
  public updMarkerAt(point: Point<T>, type: SliceType, data?: unknown, slices: EditorSlices<T> = this.saved): void {
    const overlay = this.txt.overlay;
    const markerPoint = overlay.getOrNextLowerMarker(point);
    if (markerPoint) {
      const marker = markerPoint.marker;
      Iif (Array.isArray(type) && type.length === 1) type = type[0];
      marker.update({type});
    } else this.setStartMarker(type, data, slices);
  }
 
  /**
   * Toggle the type of a block split between the slice type and the default
   * (paragraph) block type.
   *
   * @param type Slice type to toggle.
   * @param data Custom data of the slice.
   */
  public tglMarker(
    type: SliceType,
    data?: unknown,
    slices: EditorSlices<T> = this.saved,
    def: SliceTypeStep = SliceTypeCon.p,
  ): void {
    for (let i = this.cursors0(), cursor = i(); cursor; cursor = i())
      this.tglMarkerAt(cursor.start, type, data, slices, def);
  }
 
  /**
   * Update the type of a block split at all cursor positions.
   *
   * @param type Slice type to set.
   * @param data Custom data of the slice.
   * @param slices The slices set to use, if new marker is inserted at the start
   *     of the document.
   */
  public updMarker(type: SliceType, data?: unknown, slices: EditorSlices<T> = this.saved): void {
    for (let i = this.cursors0(), cursor = i(); cursor; cursor = i())
      this.updMarkerAt(cursor.start, type, data, slices);
  }
 
  public delMarker(): void {
    const markerPoints = new Set<MarkerOverlayPoint<T>>();
    for (let i = this.cursors0(), cursor = i(); cursor; cursor = i()) {
      const markerPoint = this.txt.overlay.getOrNextLowerMarker(cursor.start);
      Iif (markerPoint) markerPoints.add(markerPoint);
    }
    for (const markerPoint of markerPoints) {
      const boundary = markerPoint.marker.boundary();
      this.delRange(boundary);
    }
  }
 
  // ---------------------------------------------------------- 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;
  }
 
  /**
   * "Copy formatting-only", copies inline formatting applied to the selected
   * range.
   *
   * @param range Range copy formatting from, normally a single visible character.
   * @returns A list of serializable inline formatting applied to the selected range.
   */
  public exportStyle(range: Range<T>): ViewStyle[] {
    const formatting: ViewStyle[] = [];
    const txt = this.txt;
    const overlay = txt.overlay;
    const slices = overlay.findOverlapping(range);
    for (const slice of slices) {
      const isSavedSlice = slice.id.sid === txt.model.clock.sid;
      if (!isSavedSlice) continue;
      Iif (!slice.contains(range)) continue;
      const behavior = slice.behavior;
      switch (behavior) {
        case SliceBehavior.One:
        case SliceBehavior.Many:
        case SliceBehavior.Erase: {
          const sliceFormatting: ViewStyle = [behavior, slice.type];
          const data = slice.data();
          Iif (data !== void 0) sliceFormatting.push(data);
          formatting.push(sliceFormatting);
        }
      }
    }
    return formatting;
  }
 
  public import(pos: number, view: ViewRange): number {
    let [text, offset, slices] = view;
    const txt = this.txt;
    let removeFirstMarker = false;
    const firstSlice = slices[0];
    if (firstSlice) {
      const [header, x1, , type] = firstSlice;
      const behavior: SliceBehavior = (header & SliceHeaderMask.Behavior) >>> SliceHeaderShift.Behavior;
      const isBlockSplitMarker = behavior === SliceBehavior.Marker;
      if (isBlockSplitMarker) {
        const markerStartsAtZero = x1 - offset === 0;
        if (markerStartsAtZero) {
          const point = txt.pointAt(pos);
          const markerBefore = txt.overlay.getOrNextLowerMarker(point);
          if (markerBefore) {
            if (markerBefore.type() === type) removeFirstMarker = true;
          } else {
            if (type === CommonSliceType.p) removeFirstMarker = true;
          }
        }
      }
    }
    if (removeFirstMarker) {
      text = text.slice(1);
      offset += 1;
      slices = slices.slice(1);
    }
    const length = slices.length;
    const splits: ViewSlice[] = [];
    const annotations: ViewSlice[] = [];
    const texts: string[] = [];
    let curr = 0;
    for (let i = 0; i < length; i++) {
      const slice = slices[i];
      const [header, x1] = slice;
      const behavior: SliceBehavior = (header & SliceHeaderMask.Behavior) >>> SliceHeaderShift.Behavior;
      const isBlockSplitMarker = behavior === SliceBehavior.Marker;
      if (isBlockSplitMarker) {
        const end = x1 - offset;
        texts.push(text.slice(curr, end));
        curr = end + 1;
        splits.push(slice);
      } else annotations.push(slice);
    }
    const lastText = text.slice(curr);
    const splitLength = splits.length;
    curr = pos;
    for (let i = 0; i < splitLength; i++) {
      const str = texts[i];
      const split = splits[i];
      if (str) {
        txt.insAt(curr, str);
        curr += str.length;
      }
      if (split) {
        const [, , , type, data] = split;
        const after = txt.pointAt(curr);
        after.refAfter();
        txt.savedSlices.insMarkerAfter(after.id, type, data);
        curr += 1;
      }
    }
    if (lastText) {
      txt.insAt(curr, lastText);
      curr += lastText.length;
    }
    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);
    }
    return curr - pos;
  }
 
  public importStyle(range: Range<T>, formatting: ViewStyle[]): void {
    const txt = this.txt;
    const length = formatting.length;
    for (let i = 0; i < length; i++) {
      const [behavior, type, data] = formatting[i];
      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)}`,
      ])
    );
  }
}