@mark1russell7/typeset 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/text/rope.ts CHANGED
@@ -1,12 +1,18 @@
1
1
  /**
2
2
  * The `Text` rope: a persistent balanced tree of strings with the width and the length of each subtree. An edit makes a
3
- * new rope. The new rope shares the subtrees that do not change. A width function gives the width of a run of text. The
4
- * rope uses it only for the leaves and for the windows at the seams. Thus an edit uses it of the order of `log n` times.
3
+ * new rope. The new rope shares the subtrees that do not change. The tree is the `summary-tree` record of
4
+ * `@mark1russell7/collections`, and this module gives it the summary of a text.
5
+ *
6
+ * A width function gives the width of a run of text. The rope uses it only for the leaves and for the windows at the
7
+ * seams. Thus an edit uses it of the order of `log n` times. The rope keeps the widths of the short windows, so an edit
8
+ * measures only the windows that it changes. `Text.from` clears this memory.
5
9
  *
6
10
  * The seams are exact when the width function obeys the separator law. For each text `p + s + q` with a separator `s`:
7
11
  * `width(p + s + q) = width(p + s) + width(s + q) - width(s)`. The model of `@mark1russell7/typeset/fonts` obeys it for a space and a
8
12
  * tab. It shapes each word alone, and its kerning goes only between two adjacent glyphs.
9
13
  */
14
+ import * as Tree from "@mark1russell7/collections/summary-tree";
15
+ import type { SummarySpec, SummaryTreeRecord } from "@mark1russell7/collections/summary-tree";
10
16
  import type { WidthOf } from "../breaking/paragraph.ts";
11
17
 
12
18
  /** The options of a rope. */
@@ -20,7 +26,7 @@ export interface TextOptions {
20
26
  readonly chunk?: number;
21
27
  }
22
28
 
23
- /** The summary of a subtree: its length, its width, and the two ends that a seam measures again. */
29
+ /** The summary of a run of text: its length, its width, and the two ends that a seam measures again. */
24
30
  interface Summary {
25
31
  /** The count of UTF-16 code units. */
26
32
  readonly length: number;
@@ -35,65 +41,69 @@ interface Summary {
35
41
  readonly tailWidth: number;
36
42
  }
37
43
 
38
- interface Leaf extends Summary {
39
- readonly kind: "leaf";
40
- readonly text: string;
41
- readonly height: 0;
42
- }
43
-
44
- interface Branch extends Summary {
45
- readonly kind: "branch";
46
- readonly left: Node;
47
- readonly right: Node;
48
- readonly height: number;
49
- }
50
-
51
- type Node = Leaf | Branch;
44
+ /** The summary of the empty text. */
45
+ const noText: Summary = { length: 0, width: 0, separated: false, head: "", headWidth: 0, tail: "", tailWidth: 0 };
52
46
 
53
47
  /** The shared state of the ropes of one width function and one set of options. */
54
48
  interface Context {
55
49
  readonly width: WidthOf;
56
50
  readonly separators: string;
57
51
  readonly chunk: number;
52
+ readonly spec: SummarySpec<string, Summary>;
53
+ /** The widths of the short windows. An edit gives the tree new paths, and most windows on these paths do not change. */
54
+ readonly windows: Map<string, number>;
58
55
  }
59
56
 
60
- function isSeparator(context: Context, code: number): boolean {
61
- for (let i = 0; i < context.separators.length; i++) if (context.separators.charCodeAt(i) === code) return true;
57
+ /** The largest count of windows in the memory of a context. */
58
+ const windowLimit = 16_384;
59
+
60
+ /** This function gives the width of a window. A window longer than a leaf stays out of the memory. */
61
+ function windowWidth(context: Context, window: string): number {
62
+ if (window.length > context.chunk) return context.width(window);
63
+ const known = context.windows.get(window);
64
+ if (known !== undefined) return known;
65
+ const width = context.width(window);
66
+ if (context.windows.size >= windowLimit) context.windows.clear();
67
+ context.windows.set(window, width);
68
+ return width;
69
+ }
70
+
71
+ function isSeparator(separators: string, code: number): boolean {
72
+ for (let i = 0; i < separators.length; i++) if (separators.charCodeAt(i) === code) return true;
62
73
  return false;
63
74
  }
64
75
 
65
- function leafOf(context: Context, text: string): Leaf {
66
- const width = context.width(text);
76
+ function summaryOfLeaf(context: Context, text: string): Summary {
77
+ const { separators } = context;
78
+ const whole = context.width(text);
67
79
  let first = -1;
68
80
  let last = -1;
69
81
  for (let i = 0; i < text.length; i++) {
70
- if (!isSeparator(context, text.charCodeAt(i))) continue;
82
+ if (!isSeparator(separators, text.charCodeAt(i))) continue;
71
83
  if (first < 0) first = i;
72
84
  last = i;
73
85
  }
74
- if (first < 0) return { kind: "leaf", text, height: 0, length: text.length, width, separated: false, head: text, headWidth: width, tail: text, tailWidth: width };
86
+ if (first < 0) return { length: text.length, width: whole, separated: false, head: text, headWidth: whole, tail: text, tailWidth: whole };
75
87
  const head = text.slice(0, first + 1);
76
88
  const tail = text.slice(last);
77
- return { kind: "leaf", text, height: 0, length: text.length, width, separated: true, head, headWidth: context.width(head), tail, tailWidth: context.width(tail) };
89
+ return { length: text.length, width: whole, separated: true, head, headWidth: windowWidth(context, head), tail, tailWidth: windowWidth(context, tail) };
78
90
  }
79
91
 
80
92
  /**
81
- * This function makes the branch of two subtrees. It measures one window: the tail of the left side and the head of the right
82
- * side. The separator law then gives the width of all the text from the widths of the two sides.
93
+ * This function gives the summary of two runs in the order of the text. It measures one window: the tail of the left run and
94
+ * the head of the right run. The separator law then gives the width of all the text from the widths of the two runs.
83
95
  */
84
- function branchOf(context: Context, left: Node, right: Node): Branch {
96
+ function combine(context: Context, left: Summary, right: Summary): Summary {
97
+ if (left.length === 0) return right;
98
+ if (right.length === 0) return left;
85
99
  const seam = left.tail + right.head;
86
- const seamWidth = context.width(seam);
100
+ const seamWidth = windowWidth(context, seam);
87
101
  let width: number;
88
102
  if (!left.separated && !right.separated) width = seamWidth;
89
103
  else if (!left.separated) width = right.width - right.headWidth + seamWidth;
90
104
  else if (!right.separated) width = left.width - left.tailWidth + seamWidth;
91
105
  else width = left.width + right.width - left.tailWidth - right.headWidth + seamWidth;
92
106
  return {
93
- kind: "branch",
94
- left,
95
- right,
96
- height: Math.max(left.height, right.height) + 1,
97
107
  length: left.length + right.length,
98
108
  width,
99
109
  separated: left.separated || right.separated,
@@ -104,104 +114,58 @@ function branchOf(context: Context, left: Node, right: Node): Branch {
104
114
  };
105
115
  }
106
116
 
107
- /** This function joins two trees in the order of the text and keeps the heights of the two children within 1. */
108
- function join(context: Context, left: Node | undefined, right: Node | undefined): Node | undefined {
109
- if (left === undefined) return right;
110
- if (right === undefined) return left;
111
- if (left.kind === "leaf" && right.kind === "leaf" && left.length + right.length <= context.chunk) return leafOf(context, left.text + right.text);
112
- if (left.height > right.height + 1) {
113
- const branch = left as Branch;
114
- const joined = join(context, branch.right, right)!;
115
- if (joined.height <= branch.left.height + 1) return branchOf(context, branch.left, joined);
116
- return rotateLeft(context, branch.left, joined as Branch);
117
- }
118
- if (right.height > left.height + 1) {
119
- const branch = right as Branch;
120
- const joined = join(context, left, branch.left)!;
121
- if (joined.height <= branch.right.height + 1) return branchOf(context, joined, branch.right);
122
- return rotateRight(context, joined as Branch, branch.right);
123
- }
124
- return branchOf(context, left, right);
125
- }
126
-
127
- /** This function balances the branch of `left` and `heavy`, when `heavy` is 2 levels higher than `left`. */
128
- function rotateLeft(context: Context, left: Node, heavy: Branch): Branch {
129
- if (heavy.left.height <= heavy.right.height) return branchOf(context, branchOf(context, left, heavy.left), heavy.right);
130
- const middle = heavy.left as Branch;
131
- return branchOf(context, branchOf(context, left, middle.left), branchOf(context, middle.right, heavy.right));
132
- }
133
-
134
- /** This function balances the branch of `heavy` and `right`, when `heavy` is 2 levels higher than `right`. */
135
- function rotateRight(context: Context, heavy: Branch, right: Node): Branch {
136
- if (heavy.right.height <= heavy.left.height) return branchOf(context, heavy.left, branchOf(context, heavy.right, right));
137
- const middle = heavy.right as Branch;
138
- return branchOf(context, branchOf(context, heavy.left, middle.left), branchOf(context, middle.right, right));
139
- }
117
+ /** The contexts of each width function. Two ropes join only when their trees have the same spec. */
118
+ const contexts = new WeakMap<WidthOf, Map<string, Context>>();
140
119
 
141
- /** This function divides a tree at the UTF-16 offset `at` into the text before and the text after. */
142
- function split(context: Context, node: Node | undefined, at: number): [Node | undefined, Node | undefined] {
143
- if (node === undefined) return [undefined, undefined];
144
- if (at <= 0) return [undefined, node];
145
- if (at >= node.length) return [node, undefined];
146
- if (node.kind === "leaf") return [leafOf(context, node.text.slice(0, at)), leafOf(context, node.text.slice(at))];
147
- if (at === node.left.length) return [node.left, node.right];
148
- if (at < node.left.length) {
149
- const [before, after] = split(context, node.left, at);
150
- return [before, join(context, after, node.right)];
151
- }
152
- const [before, after] = split(context, node.right, at - node.left.length);
153
- return [join(context, node.left, before), after];
120
+ function contextOf(width: WidthOf, separators: string, chunk: number): Context {
121
+ const own = contexts.get(width) ?? new Map<string, Context>();
122
+ contexts.set(width, own);
123
+ const key = `${chunk}/${separators}`;
124
+ const known = own.get(key);
125
+ if (known !== undefined) return known;
126
+ const spec: SummarySpec<string, Summary> = {
127
+ monoid: { empty: noText, combine: (left, right) => combine(context, left, right) },
128
+ measure: (leaf) => summaryOfLeaf(context, leaf),
129
+ merge: (left, right) => (left.length + right.length <= chunk ? left + right : undefined),
130
+ };
131
+ const context: Context = { width, separators, chunk, spec, windows: new Map() };
132
+ own.set(key, context);
133
+ return context;
154
134
  }
155
135
 
156
136
  /** This function gives the end of the next leaf of `text` from `start`: after a separator when it can, and not in a surrogate pair. */
157
137
  function chunkEnd(context: Context, text: string, start: number): number {
158
138
  const limit = start + context.chunk;
159
139
  if (limit >= text.length) return text.length;
160
- for (let i = limit - 1; i >= start + context.chunk / 2; i--) if (isSeparator(context, text.charCodeAt(i))) return i + 1;
140
+ for (let i = limit - 1; i >= start + context.chunk / 2; i--) if (isSeparator(context.separators, text.charCodeAt(i))) return i + 1;
161
141
  const code = text.charCodeAt(limit - 1);
162
142
  return code >= 0xd800 && code <= 0xdbff ? limit - 1 : limit;
163
143
  }
164
144
 
165
- /** This function makes a balanced tree of a text: leaves of at most `chunk` code units, and then a level of branches at a time. */
166
- function build(context: Context, text: string): Node | undefined {
167
- let level: Node[] = [];
145
+ /** This function divides a text into leaves of at most `chunk` code units. */
146
+ function chunksOf(context: Context, text: string): string[] {
147
+ const out: string[] = [];
168
148
  for (let start = 0; start < text.length; ) {
169
149
  const end = chunkEnd(context, text, start);
170
- level.push(leafOf(context, text.slice(start, end)));
150
+ out.push(text.slice(start, end));
171
151
  start = end;
172
152
  }
173
- if (level.length === 0) return undefined;
174
- while (level.length > 1) {
175
- const next: Node[] = [];
176
- for (let i = 0; i + 1 < level.length; i += 2) next.push(branchOf(context, level[i]!, level[i + 1]!));
177
- if (level.length % 2 === 1) next.push(level[level.length - 1]!);
178
- level = next;
179
- }
180
- return level[0];
181
- }
182
-
183
- function leaves(node: Node | undefined, out: string[]): string[] {
184
- if (node === undefined) return out;
185
- const stack: Node[] = [node];
186
- while (stack.length > 0) {
187
- const top = stack.pop()!;
188
- if (top.kind === "leaf") out.push(top.text);
189
- else stack.push(top.right, top.left);
190
- }
191
153
  return out;
192
154
  }
193
155
 
156
+ const lengthOf = (summary: Summary): number => summary.length;
157
+
194
158
  /**
195
159
  * A text with its width: a persistent balanced rope. Each edit gives a new `Text` and does not change this one. The offsets
196
160
  * are in UTF-16 code units, as the offsets of a JavaScript string.
197
161
  */
198
162
  export class Text {
199
163
  readonly #context: Context;
200
- readonly #root: Node | undefined;
164
+ readonly #tree: SummaryTreeRecord<string, Summary>;
201
165
 
202
- private constructor(context: Context, root: Node | undefined) {
166
+ private constructor(context: Context, tree: SummaryTreeRecord<string, Summary>) {
203
167
  this.#context = context;
204
- this.#root = root;
168
+ this.#tree = tree;
205
169
  }
206
170
 
207
171
  /** This function makes the rope of `text` with the width function `width`. */
@@ -213,41 +177,47 @@ export class Text {
213
177
  const code = separators.charCodeAt(i);
214
178
  if (code >= 0xd800 && code <= 0xdfff) throw new RangeError("a separator is one UTF-16 code unit, not a half of a surrogate pair");
215
179
  }
216
- const context: Context = { width, separators, chunk };
217
- return new Text(context, build(context, text));
180
+ const context = contextOf(width, separators, chunk);
181
+ // A new rope measures again: the width function can change its result when a font loads
182
+ context.windows.clear();
183
+ return new Text(context, Tree.of(context.spec, chunksOf(context, text)));
218
184
  }
219
185
 
220
186
  /** The count of UTF-16 code units of the text. */
221
187
  get length(): number {
222
- return this.#root?.length ?? 0;
188
+ return Tree.summary(this.#tree).length;
223
189
  }
224
190
 
225
191
  /** The width of the text. It is equal to the width of the flat string when the width function obeys the separator law. */
226
192
  get width(): number {
227
- return this.#root?.width ?? 0;
193
+ return Tree.summary(this.#tree).width;
228
194
  }
229
195
 
230
196
  /** The height of the tree: 0 for a text of one leaf. The tests use it to examine the balance. */
231
197
  get height(): number {
232
- return this.#root?.height ?? 0;
198
+ return Math.max(0, Tree.height(this.#tree) - 1);
233
199
  }
234
200
 
235
201
  /** This function gives the flat string. */
236
202
  toString(): string {
237
- return leaves(this.#root, []).join("");
203
+ return this.chunks().join("");
238
204
  }
239
205
 
240
206
  /** This function gives the strings of the leaves in the order of the text. */
241
207
  chunks(): string[] {
242
- return leaves(this.#root, []);
208
+ return Tree.toArray(this.#tree);
243
209
  }
244
210
 
245
211
  /** This function gives the text from `start` to `end`, as a new rope. */
246
212
  slice(start: number, end: number = this.length): Text {
247
213
  this.#check(start, end);
248
- const [, after] = split(this.#context, this.#root, start);
249
- const [middle] = split(this.#context, after, end - start);
250
- return new Text(this.#context, middle);
214
+ if (start === end) return new Text(this.#context, Tree.slice(this.#tree, 0, 0));
215
+ const first = Tree.locate(this.#tree, lengthOf, start)!;
216
+ const last = Tree.locate(this.#tree, lengthOf, end - 1)!;
217
+ const stop = first.offset + end - start;
218
+ const middle = Tree.slice(this.#tree, first.index, last.index + 1);
219
+ if (first.index === last.index) return new Text(this.#context, Tree.set(middle, 0, first.leaf.slice(first.offset, stop)));
220
+ return new Text(this.#context, Tree.set(Tree.set(middle, -1, last.leaf.slice(0, last.offset + 1)), 0, first.leaf.slice(first.offset)));
251
221
  }
252
222
 
253
223
  /** This function gives the width of the text from `start` to `end`. */
@@ -257,11 +227,8 @@ export class Text {
257
227
 
258
228
  /** This function gives this text and then `other`. The two ropes must have the same width function and options. */
259
229
  concat(other: Text): Text {
260
- const context = other.#context;
261
- if (context.width !== this.#context.width || context.separators !== this.#context.separators || context.chunk !== this.#context.chunk) {
262
- throw new TypeError("the two ropes have different width functions or options");
263
- }
264
- return new Text(this.#context, join(this.#context, this.#root, other.#root));
230
+ if (other.#context !== this.#context) throw new TypeError("the two ropes have different width functions or options");
231
+ return new Text(this.#context, Tree.concat(this.#tree, other.#tree));
265
232
  }
266
233
 
267
234
  /** This function puts `text` at the offset `at`. */
@@ -277,10 +244,25 @@ export class Text {
277
244
  /** This function puts `text` in place of the text from `start` to `end`. */
278
245
  replace(start: number, end: number, text: string): Text {
279
246
  this.#check(start, end);
280
- const [before, rest] = split(this.#context, this.#root, start);
281
- const [, after] = split(this.#context, rest, end - start);
282
- const middle = build(this.#context, text);
283
- return new Text(this.#context, join(this.#context, join(this.#context, before, middle), after));
247
+ if (start === end && text.length === 0) return this;
248
+ const size = Tree.size(this.#tree);
249
+ if (size === 0) return Text.from(text, this.#context.width, this.#context);
250
+ const first = Tree.locate(this.#tree, lengthOf, start) ?? this.#lastPlace();
251
+ const last = start === end ? first : Tree.locate(this.#tree, lengthOf, end - 1)!;
252
+ const lastEnd = start === end ? first.offset : last.offset + 1;
253
+ const fresh = first.leaf.slice(0, first.offset) + text + last.leaf.slice(lastEnd);
254
+ const leaves = chunksOf(this.#context, fresh);
255
+ // One long leaf in place of one leaf changes only a path. A short leaf goes through the seams, so that it can merge
256
+ if (first.index === last.index && leaves.length === 1 && leaves[0]!.length * 2 >= this.#context.chunk) {
257
+ return new Text(this.#context, Tree.set(this.#tree, first.index, leaves[0]!));
258
+ }
259
+ return new Text(this.#context, Tree.splice(this.#tree, first.index, last.index - first.index + 1, leaves));
260
+ }
261
+
262
+ /** This function gives the place after the last code unit: the end of the last leaf. */
263
+ #lastPlace(): { index: number; leaf: string; offset: number } {
264
+ const leaf = Tree.at(this.#tree, -1)!;
265
+ return { index: Tree.size(this.#tree) - 1, leaf, offset: leaf.length };
284
266
  }
285
267
 
286
268
  #check(start: number, end: number): void {