@rohal12/spindle 0.59.32 → 0.60.0

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.
Files changed (51) hide show
  1. package/README.md +20 -18
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +635 -98
  4. package/dist/pkg/story-variables.js +830 -54
  5. package/dist/pkg/tooling.js +1 -0
  6. package/package.json +4 -2
  7. package/src/action-registry.ts +84 -2
  8. package/src/automation/load-yaml.ts +10 -55
  9. package/src/automation/runner.ts +2 -14
  10. package/src/automation/types.ts +2 -8
  11. package/src/components/PassageDialog.tsx +8 -3
  12. package/src/components/dialog-close-context.ts +10 -0
  13. package/src/components/macros/Checkbox.tsx +2 -1
  14. package/src/components/macros/Cycle.tsx +2 -1
  15. package/src/components/macros/Listbox.tsx +2 -1
  16. package/src/components/macros/Radiobutton.tsx +3 -1
  17. package/src/components/macros/detached-body.tsx +19 -8
  18. package/src/components/macros/input-macro.ts +2 -1
  19. package/src/define-macro.ts +42 -16
  20. package/src/display-only.ts +30 -0
  21. package/src/format/format-passage.ts +626 -0
  22. package/src/format/placeholders.ts +316 -0
  23. package/src/format/prettier.ts +62 -0
  24. package/src/format/segment.ts +126 -0
  25. package/src/headless.ts +81 -1
  26. package/src/hooks/use-action.ts +31 -9
  27. package/src/index.tsx +16 -4
  28. package/src/js-lexer.ts +36 -6
  29. package/src/markup/code-end.ts +97 -41
  30. package/src/markup/parse.ts +6 -6
  31. package/src/observe/observable-text.ts +147 -0
  32. package/src/observe/observe.ts +160 -0
  33. package/src/store.ts +1 -0
  34. package/src/story-api.ts +21 -1
  35. package/src/story-context-passage.ts +132 -0
  36. package/src/tooling.ts +23 -1
  37. package/src/triggers.ts +32 -8
  38. package/src/twine-editor/builtin-macros.ts +11 -0
  39. package/src/twine-editor/commands.ts +173 -0
  40. package/src/twine-editor/highlight.ts +471 -0
  41. package/src/twine-editor/icons.ts +35 -0
  42. package/src/twine-editor/index.ts +19 -0
  43. package/src/twine-editor/mode.ts +137 -0
  44. package/src/twine-editor/references.ts +34 -0
  45. package/src/twine-editor/snippets.ts +74 -0
  46. package/src/twine-editor/toolbar.ts +85 -0
  47. package/src/types-drift-check.ts +12 -0
  48. package/src/utils/field-checks.ts +46 -0
  49. package/types/headless.d.ts +43 -2
  50. package/types/index.d.ts +71 -0
  51. package/types/tooling.d.ts +68 -0
@@ -0,0 +1,626 @@
1
+ import { isBlockMacro } from '../markup/ast';
2
+ import { tokenizeMarkupTolerant } from '../markup/parse';
3
+ import type { MacroToken } from '../markup/tokens';
4
+ import { segmentRegions } from './segment';
5
+ import {
6
+ formatJS,
7
+ formatCSS,
8
+ formatHTML as formatHTMLPrettier,
9
+ type PrettierLike,
10
+ } from './prettier';
11
+ import {
12
+ multilineJsLiterals,
13
+ replaceSpindleTokens,
14
+ restoreSpindleTokens,
15
+ replaceSvgBlocks,
16
+ restoreSvgBlocks,
17
+ placeholdersIntact,
18
+ sameSpindleTokens,
19
+ SPINDLE_PLACEHOLDERS,
20
+ SVG_PLACEHOLDERS,
21
+ scanSpindleMarkup,
22
+ } from './placeholders';
23
+
24
+ export type { PrettierLike };
25
+
26
+ export interface PassageFormatOptions {
27
+ /** The passage's kind (default: 'normal'). A script or stylesheet passage is formatted whole as JavaScript or CSS. */
28
+ kind?: 'normal' | 'script' | 'stylesheet';
29
+ /**
30
+ * Prettier (`prettier` or `prettier/standalone` with the babel, estree,
31
+ * postcss and html plugins), for the code, styles and HTML in the passage.
32
+ * Without it, or where it throws, that text stays as written.
33
+ */
34
+ prettier?: PrettierLike;
35
+ /**
36
+ * The options Prettier is given (default: `{ tabWidth: 2 }`). They replace
37
+ * the default; the formatter sets `parser` (and HTML whitespace handling)
38
+ * itself. Standalone Prettier needs its `plugins` in every call: wrap
39
+ * `prettier` to add them rather than passing them here.
40
+ */
41
+ prettierOptions?: object;
42
+ /** Returns true if the named macro is a block/container macro (default: the built-in block macros and the names the passage closes with `{/name}`). Replaces that default whole; use `blockMacros` to add to it. */
43
+ isBlock?: (name: string) => boolean;
44
+ /** Names of block macros to add to the default `isBlock` (ignored when `isBlock` is given), such as the ones the story or a Twine editor knows. */
45
+ blockMacros?: Iterable<string>;
46
+ /** Returns true for sub-macros that dedent to parent level (default: else, elseif, next, case, default). */
47
+ isDedentingSubMacro?: (name: string) => boolean;
48
+ /** If set, wrap prose lines exceeding this character count. */
49
+ maxLineLength?: number;
50
+ }
51
+
52
+ /** Default dedenting sub-macros. */
53
+ const DEFAULT_DEDENTING = new Set([
54
+ 'else',
55
+ 'elseif',
56
+ 'next',
57
+ 'case',
58
+ 'default',
59
+ ]);
60
+
61
+ /** The names of the macros the passage closes with `{/name}`: block macros it defines itself. */
62
+ export function closedMacroNames(text: string): Set<string> {
63
+ const found = new Set<string>();
64
+ for (const t of tokenizeMarkupTolerant(text).tokens) {
65
+ if (t.type === 'macro' && t.isClose) found.add(t.name.toLowerCase());
66
+ }
67
+ return found;
68
+ }
69
+
70
+ /** The built-in block macros (and the block widgets the runtime has defined) plus those the passage closes. */
71
+ function defaultIsBlock(
72
+ text: string,
73
+ extra: Iterable<string> = [],
74
+ ): (name: string) => boolean {
75
+ const closed = closedMacroNames(text);
76
+ for (const name of extra) closed.add(name.toLowerCase());
77
+ return (name) => isBlockMacro(name) || closed.has(name.toLowerCase());
78
+ }
79
+
80
+ /**
81
+ * Format the text of one passage.
82
+ *
83
+ * Rules:
84
+ * 1. Indent content inside block macros by 2 spaces per nesting level
85
+ * 2. Dedenting sub-macros (else, elseif, next, case, default) snap to parent indent level
86
+ * 3. Remove trailing whitespace from each line, keeping Markdown hard breaks
87
+ * (two trailing spaces) and list/code-fence indentation in prose
88
+ * 4. Format `<script>` and HTML blocks, and the whole body of a script or
89
+ * stylesheet passage, with Prettier (when given)
90
+ * 5. Make the result end with a single newline, in the line-ending style of
91
+ * the text
92
+ */
93
+ export async function formatPassage(
94
+ body: string,
95
+ options: PassageFormatOptions = {},
96
+ ): Promise<string> {
97
+ // A byte order mark is not story text: format what follows it and keep the mark
98
+ if (body.charCodeAt(0) === 0xfeff) {
99
+ return '\uFEFF' + (await formatPassage(body.slice(1), options));
100
+ }
101
+ // Format with LF endings, then give the output the text's own style
102
+ const eol = dominantEol(body);
103
+ const output = await formatLf(body.replace(/\r\n/g, '\n'), options);
104
+ return eol === '\r\n' ? output.replace(/\n/g, '\r\n') : output;
105
+ }
106
+
107
+ /**
108
+ * The text's line-ending style: whichever of CRLF and LF is more common,
109
+ * the first one found when equally common. (Spindle's compiler normalizes
110
+ * CRLF to LF, so the choice never changes what a story does.)
111
+ */
112
+ function dominantEol(text: string): '\n' | '\r\n' {
113
+ const crlf = (text.match(/\r\n/g) ?? []).length;
114
+ const lf = (text.match(/\n/g) ?? []).length - crlf;
115
+ if (crlf !== lf) return crlf > lf ? '\r\n' : '\n';
116
+ return text.indexOf('\r\n') !== -1 &&
117
+ text.indexOf('\r\n') < text.indexOf('\n')
118
+ ? '\r\n'
119
+ : '\n';
120
+ }
121
+
122
+ /** `text` with every `from` replaced by `to`, literally. */
123
+ function replaceAll(text: string, from: string, to: string): string {
124
+ return text.split(from).join(to);
125
+ }
126
+
127
+ /**
128
+ * Newline stand-in inside multiline Spindle tokens. A private-use character
129
+ * absent from the document: not whitespace, so no line-based step touches it.
130
+ */
131
+ function newlineSentinel(text: string): string {
132
+ for (let code = 0xe000; code <= 0xf8ff; code++) {
133
+ const ch = String.fromCharCode(code);
134
+ if (!text.includes(ch)) return ch;
135
+ }
136
+ throw new Error('no free private-use character for the newline stand-in');
137
+ }
138
+
139
+ /**
140
+ * Join each multiline token (macro, interpolation or link, as the Spindle
141
+ * runtime tokenizes it) onto its line with `sentinel` for its newlines. The
142
+ * line-based formatting steps then see one line and cannot re-indent, wrap,
143
+ * trim, segment or re-flow the runtime payload inside it.
144
+ *
145
+ * The body of a `{do}` macro is JavaScript, executed as written: a template
146
+ * literal (or a string continued with a backslash) that spans lines is a
147
+ * value, so its line breaks and the whitespace after them must survive
148
+ * formatting. Those literals are joined too.
149
+ */
150
+ function protectMultilineTokens(body: string, sentinel: string): string {
151
+ const { tokens, doBlocks } = scanSpindleMarkup(body);
152
+ const spans: [number, number][] = [];
153
+ for (const m of tokens) {
154
+ if (m.token.includes('\n')) spans.push([m.start, m.end]);
155
+ }
156
+ for (const block of doBlocks) {
157
+ for (const [a, b] of multilineJsLiterals(
158
+ body.slice(block.bodyStart, block.bodyEnd),
159
+ )) {
160
+ spans.push([block.bodyStart + a, block.bodyStart + b]);
161
+ }
162
+ }
163
+ return joinSpans(body, spans, sentinel);
164
+ }
165
+
166
+ /**
167
+ * The JavaScript `code` with the line breaks of its multiline string and
168
+ * template literals replaced by `sentinel`: re-indenting its lines then
169
+ * leaves the literals' values as written.
170
+ */
171
+ function joinJsLiterals(code: string, sentinel: string): string {
172
+ return joinSpans(code, multilineJsLiterals(code), sentinel);
173
+ }
174
+
175
+ /** `text` with the line breaks inside each of `spans` replaced by `sentinel`. */
176
+ function joinSpans(
177
+ text: string,
178
+ spans: [number, number][],
179
+ sentinel: string,
180
+ ): string {
181
+ let out = '';
182
+ let last = 0;
183
+ for (const [a, b] of [...spans].sort((x, y) => x[0] - y[0])) {
184
+ out += text.slice(last, a) + replaceAll(text.slice(a, b), '\n', sentinel);
185
+ last = b;
186
+ }
187
+ return out + text.slice(last);
188
+ }
189
+
190
+ async function formatLf(
191
+ text: string,
192
+ options: PassageFormatOptions,
193
+ ): Promise<string> {
194
+ const { prettier, prettierOptions } = options;
195
+ // Trailing blank lines are not part of the passage's text
196
+ const body = text.replace(/(?:[ \t]*\n)+[ \t]*$/, '\n');
197
+
198
+ if (options.kind === 'script' || options.kind === 'stylesheet') {
199
+ const format = options.kind === 'script' ? formatJS : formatCSS;
200
+ const code = body.trim();
201
+ const formatted = await format(code, prettier, prettierOptions);
202
+ return (formatted ?? code).trim().replace(/\n*$/, '\n');
203
+ }
204
+
205
+ const isBlock = options.isBlock ?? defaultIsBlock(body, options.blockMacros);
206
+ const isDedenting =
207
+ options.isDedentingSubMacro ??
208
+ ((name: string) => DEFAULT_DEDENTING.has(name.toLowerCase()));
209
+ const sentinel = newlineSentinel(body);
210
+ const lines: string[] = [];
211
+ /** Indices in lines whose trailing two spaces are a hard line break. */
212
+ const hardBreakLines = new Set<number>();
213
+
214
+ // Segment into regions. Multiline tokens are joined onto
215
+ // one line first, so their inner lines are never taken for markup.
216
+ const regions = segmentRegions(protectMultilineTokens(body, sentinel));
217
+
218
+ for (const region of regions) {
219
+ if (region.type !== 'spindle') {
220
+ // Their text is verbatim, JS or HTML (protected by placeholders): undo the joining
221
+ region.lines = region.lines.map((l) => replaceAll(l, sentinel, '\n'));
222
+ }
223
+
224
+ if (region.type === 'script') {
225
+ // Same-line <script>…</script> — leave as written
226
+ if (region.lines.length === 1) {
227
+ lines.push(...region.lines);
228
+ continue;
229
+ }
230
+ // Inline <script> — format JS content between tags
231
+ const innerCode = region.lines.slice(1, -1).join('\n');
232
+ const formatted = await formatJS(
233
+ innerCode.trim(),
234
+ prettier,
235
+ prettierOptions,
236
+ );
237
+ // Without Prettier, where it fails, or where it changed a Spindle
238
+ // token (`{$a}` is an object literal to it), the region stays as written
239
+ if (formatted === undefined || !sameSpindleTokens(innerCode, formatted)) {
240
+ lines.push(...region.lines);
241
+ continue;
242
+ }
243
+ lines.push(region.lines[0]!);
244
+ if (formatted.trim()) {
245
+ // A literal's line breaks are its value: indent only the lines of code
246
+ for (const fLine of joinJsLiterals(formatted.trim(), sentinel).split(
247
+ '\n',
248
+ )) {
249
+ lines.push(' ' + fLine);
250
+ }
251
+ }
252
+ lines.push(region.lines[region.lines.length - 1]!);
253
+ continue;
254
+ }
255
+
256
+ if (region.type === 'svg') {
257
+ // SVG block — leave untouched (Prettier would break rendering)
258
+ lines.push(...region.lines);
259
+ continue;
260
+ }
261
+
262
+ if (region.type === 'html') {
263
+ const htmlText = region.lines.join('\n');
264
+ // Whitespace that renders as written: the runtime keeps a line break
265
+ // Prettier puts after `<pre>` (a browser's parser drops it), and
266
+ // Prettier cannot see a `white-space` style. Leave such HTML as written.
267
+ if (WHITESPACE_AS_WRITTEN.test(htmlText)) {
268
+ lines.push(...region.lines);
269
+ continue;
270
+ }
271
+ // HTML block — placeholder substitution + Prettier
272
+ const { text: svgPlaceholdered, tokens: svgTokens } =
273
+ replaceSvgBlocks(htmlText);
274
+ const { text: placeholdered, tokens } =
275
+ replaceSpindleTokens(svgPlaceholdered);
276
+ const formatted = await formatHTMLPrettier(
277
+ placeholdered,
278
+ prettier,
279
+ prettierOptions,
280
+ );
281
+ // Without Prettier, where it fails, or where it lost or moved a
282
+ // placeholder (it formats a `<style>` body as CSS, where `<!--SP:0-->`
283
+ // is no comment), the region stays as written
284
+ if (
285
+ formatted === undefined ||
286
+ !placeholdersIntact(formatted, tokens, SPINDLE_PLACEHOLDERS) ||
287
+ !placeholdersIntact(formatted, svgTokens, SVG_PLACEHOLDERS)
288
+ ) {
289
+ lines.push(...region.lines);
290
+ continue;
291
+ }
292
+ // A token's line breaks are its payload: keep them out of the line steps below
293
+ const restoredSpindle = restoreSpindleTokens(
294
+ formatted.trim(),
295
+ tokens.map((t) => replaceAll(t, '\n', sentinel)),
296
+ );
297
+ const restored = restoreSvgBlocks(restoredSpindle, svgTokens);
298
+ for (const fLine of restored.split('\n')) {
299
+ lines.push(fLine);
300
+ }
301
+ continue;
302
+ }
303
+
304
+ // Spindle/markdown region — apply macro indentation
305
+ let indented = indentMacros(region.lines, isBlock, isDedenting);
306
+ if (options.maxLineLength) {
307
+ indented = wrapLines(indented, options.maxLineLength);
308
+ }
309
+ for (const line of indented) {
310
+ if (line.endsWith(' ')) hardBreakLines.add(lines.length);
311
+ lines.push(line);
312
+ }
313
+ }
314
+ // Strip trailing whitespace (except Markdown hard breaks, already
315
+ // normalized by indentMacros) and ensure single trailing newline
316
+ let output = lines
317
+ .map((l, i) => (hardBreakLines.has(i) ? l : l.replace(/\s+$/, '')))
318
+ .join('\n');
319
+ output = output.replace(/\n*$/, '\n');
320
+
321
+ return replaceAll(output, sentinel, '\n');
322
+ }
323
+
324
+ /** HTML whose whitespace renders as written: a `<pre>` or `<textarea>`, or a `white-space` style. */
325
+ const WHITESPACE_AS_WRITTEN = /<(?:pre|textarea)[\s>]|white-space\s*:/i;
326
+
327
+ /** A Markdown list item line (`- a`, `* a`, `+ a`, `1. a`, `1) a`). */
328
+ const LIST_ITEM_REGEX = /^(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)/;
329
+
330
+ /** A fenced code block delimiter. */
331
+ const CODE_FENCE_REGEX = /^(?:`{3,}|~{3,})/;
332
+
333
+ /**
334
+ * A block macro body. Spindle renders each body's children as a separate
335
+ * Markdown document, so shifting all of a body's lines by the same amount
336
+ * never changes how it renders.
337
+ */
338
+ interface MacroBody {
339
+ /** Index of the line that opened this body; -1 for the region root. */
340
+ openLine: number;
341
+ /** Smallest original indentation column among the body's lines. */
342
+ minCol: number;
343
+ /** True if leading indentation may be Markdown syntax (lists, code fences). */
344
+ keepRelative: boolean;
345
+ }
346
+
347
+ /**
348
+ * Re-indent macro bodies by nesting depth.
349
+ *
350
+ * Each body is re-based so its least-indented line sits 2 spaces inside the
351
+ * line that opened it. When the body contains Markdown whose meaning depends
352
+ * on indentation (list items and their continuations, fenced code), every
353
+ * line keeps its indentation relative to that base (top-level lines keep
354
+ * their original indentation); otherwise all lines snap to the base, since
355
+ * leading whitespace in Spindle's Markdown (indented code blocks are
356
+ * disabled) is insignificant. Closing tags and dedenting sub-macros align
357
+ * with their opening tag.
358
+ *
359
+ * Trailing whitespace is stripped, except that two or more trailing spaces
360
+ * before a non-blank line (a Markdown hard line break) become exactly two.
361
+ */
362
+ function indentMacros(
363
+ lines: string[],
364
+ isBlock: (name: string) => boolean,
365
+ isDedenting: (name: string) => boolean,
366
+ ): string[] {
367
+ const macrosOnLine = macroTokensByLine(lines);
368
+ // Pass 1: assign each line to the body (Markdown document) it belongs to.
369
+ const bodies: MacroBody[] = [
370
+ { openLine: -1, minCol: Infinity, keepRelative: false },
371
+ ];
372
+ const stack: number[] = [0];
373
+ /** Per line: owning body, or the body it closes (`closes`), and its column. */
374
+ const info: ({
375
+ body: number;
376
+ closes?: number;
377
+ col: number;
378
+ text: string;
379
+ } | null)[] = [];
380
+
381
+ const openBody = (line: number) => {
382
+ bodies.push({ openLine: line, minCol: Infinity, keepRelative: false });
383
+ stack.push(bodies.length - 1);
384
+ };
385
+ const currentBody = () => stack[stack.length - 1]!;
386
+ const closeBody = (): number | undefined =>
387
+ stack.length > 1 ? stack.pop() : undefined;
388
+ const addLine = (col: number, text: string) => {
389
+ const body = bodies[currentBody()]!;
390
+ body.minCol = Math.min(body.minCol, col);
391
+ if (LIST_ITEM_REGEX.test(text) || CODE_FENCE_REGEX.test(text))
392
+ body.keepRelative = true;
393
+ info.push({ body: currentBody(), col, text });
394
+ };
395
+
396
+ for (let i = 0; i < lines.length; i++) {
397
+ const lineText = lines[i]!;
398
+ const trimmed = lineText.trim();
399
+
400
+ if (trimmed === '') {
401
+ info.push(null);
402
+ continue;
403
+ }
404
+ const col = indentColumn(lineText);
405
+
406
+ // The macro the line starts with, and the closers that follow it
407
+ const lead = lineText.length - lineText.trimStart().length;
408
+ const macros = macrosOnLine[i]!;
409
+ const [first, ...rest] = macros;
410
+ const startsWithMacro = first !== undefined && first.start === lead;
411
+
412
+ // Dedenting sub-macro: closes the previous branch, opens the next one
413
+ if (startsWithMacro && !first.isClose && isDedenting(first.name)) {
414
+ const closed = closeBody();
415
+ if (closed === undefined) addLine(col, trimmed);
416
+ else
417
+ info.push({
418
+ body: currentBody(),
419
+ closes: closed,
420
+ col,
421
+ text: trimmed,
422
+ });
423
+ openBody(i);
424
+ continue;
425
+ }
426
+
427
+ // Closing tag
428
+ const closed = startsWithMacro && first.isClose ? closeBody() : undefined;
429
+ if (closed === undefined) addLine(col, trimmed);
430
+ else
431
+ info.push({
432
+ body: currentBody(),
433
+ closes: closed,
434
+ col,
435
+ text: trimmed,
436
+ });
437
+
438
+ // Opening container tag
439
+ if (startsWithMacro && !first.isClose && isBlock(first.name)) {
440
+ openBody(i);
441
+ }
442
+
443
+ // Closing tags that appear later on the same line (not at the start,
444
+ // which is already handled by the close-at-start check above).
445
+ for (const macro of startsWithMacro ? rest : macros) {
446
+ if (macro.isClose && macro.start > lead) closeBody();
447
+ }
448
+ }
449
+
450
+ // Pass 2: compute output indentation.
451
+ const outCol: number[] = [];
452
+ const result: string[] = [];
453
+ for (let i = 0; i < info.length; i++) {
454
+ const line = info[i];
455
+ if (!line) {
456
+ outCol.push(0);
457
+ result.push('');
458
+ continue;
459
+ }
460
+ let col: number;
461
+ if (line.closes !== undefined) {
462
+ col = outCol[bodies[line.closes]!.openLine]!;
463
+ } else {
464
+ // The region root keeps its original indentation when it matters
465
+ const body = bodies[line.body]!;
466
+ const isRoot = body.openLine === -1;
467
+ const base = isRoot ? 0 : outCol[body.openLine]! + 2;
468
+ col =
469
+ base + (body.keepRelative ? line.col - (isRoot ? 0 : body.minCol) : 0);
470
+ }
471
+ outCol.push(col);
472
+ const hardBreak = / {2,}$/.test(lines[i]!) && info[i + 1] ? ' ' : '';
473
+ result.push(' '.repeat(col) + line.text + hardBreak);
474
+ }
475
+
476
+ return result;
477
+ }
478
+
479
+ /**
480
+ * The macro tags on each of `lines`, as Spindle tokenizes the lines together
481
+ * (`start` is the offset in the line). A tag spans one line here: the
482
+ * multiline ones were joined onto their line.
483
+ */
484
+ function macroTokensByLine(lines: string[]): MacroToken[][] {
485
+ const byLine: MacroToken[][] = lines.map(() => []);
486
+ const starts: number[] = [];
487
+ let offset = 0;
488
+ for (const line of lines) {
489
+ starts.push(offset);
490
+ offset += line.length + 1;
491
+ }
492
+ let line = 0;
493
+ for (const token of tokenizeMarkupTolerant(lines.join('\n')).tokens) {
494
+ if (token.type !== 'macro') continue;
495
+ while (line + 1 < lines.length && starts[line + 1]! <= token.start) line++;
496
+ const lineStart = starts[line]!;
497
+ byLine[line]!.push({
498
+ ...token,
499
+ start: token.start - lineStart,
500
+ end: token.end - lineStart,
501
+ });
502
+ }
503
+ return byLine;
504
+ }
505
+
506
+ /** Column of the first non-whitespace character, expanding tabs to 4-column stops. */
507
+ function indentColumn(line: string): number {
508
+ let col = 0;
509
+ for (const ch of line) {
510
+ if (ch === ' ') col++;
511
+ else if (ch === '\t') col += 4 - (col % 4);
512
+ else break;
513
+ }
514
+ return col;
515
+ }
516
+
517
+ // ---------------------------------------------------------------------------
518
+ // Line wrapping
519
+ // ---------------------------------------------------------------------------
520
+
521
+ /**
522
+ * Wrap lines that exceed maxLen at word boundaries.
523
+ * Preserves leading indentation. Skips pure macro lines and choice/link
524
+ * lines, where wrapping would break syntax.
525
+ */
526
+ function wrapLines(lines: string[], maxLen: number): string[] {
527
+ const result: string[] = [];
528
+ const javaScript = doBodyLines(lines);
529
+
530
+ for (const [index, line] of lines.entries()) {
531
+ // A `{do}` body is JavaScript: a line break there can change the program
532
+ if (line.length <= maxLen || javaScript.has(index)) {
533
+ result.push(line);
534
+ continue;
535
+ }
536
+
537
+ const trimmed = line.trim();
538
+
539
+ // Don't wrap empty lines, or lines that are purely structural (macros,
540
+ // links, choices)
541
+ if (
542
+ trimmed === '' ||
543
+ /^\{[\/#.]/.test(trimmed) || // closing/opening-only macro lines
544
+ /^\[\[/.test(trimmed) || // links
545
+ /^\{choice\b/.test(trimmed) || // choice macros
546
+ /^\{choices\b/.test(trimmed)
547
+ ) {
548
+ result.push(line);
549
+ continue;
550
+ }
551
+
552
+ // Determine the indentation prefix
553
+ const indentMatch = line.match(/^(\s*)/);
554
+ const indent = indentMatch?.[1] ?? '';
555
+
556
+ const wrapped = wordWrap(trimmed, maxLen, indent);
557
+ // Keep a Markdown hard break on the last wrapped line
558
+ if (line.endsWith(' ')) wrapped[wrapped.length - 1] += ' ';
559
+ result.push(...wrapped);
560
+ }
561
+
562
+ return result;
563
+ }
564
+
565
+ /** The indices of `lines` that hold part of a `{do}` body. */
566
+ function doBodyLines(lines: string[]): Set<number> {
567
+ const found = new Set<number>();
568
+ const text = lines.join('\n');
569
+ for (const block of scanSpindleMarkup(text).doBlocks) {
570
+ const first = text.slice(0, block.bodyStart).split('\n').length - 1;
571
+ const last = text.slice(0, block.bodyEnd).split('\n').length - 1;
572
+ for (let i = first; i <= last; i++) found.add(i);
573
+ }
574
+ return found;
575
+ }
576
+
577
+ /**
578
+ * Wrap a single trimmed line at word boundaries, never inside a macro, an
579
+ * interpolation or a link (as Spindle tokenizes the line).
580
+ * Returns an array of lines with the given indent prefix applied.
581
+ */
582
+ function wordWrap(text: string, maxLen: number, indent: string): string[] {
583
+ const lines: string[] = [];
584
+ /** Whether the character is inside a token whose text must stay as written. */
585
+ const inToken = new Array<boolean>(text.length).fill(false);
586
+ for (const token of tokenizeMarkupTolerant(text).tokens) {
587
+ if (token.type === 'text' || token.type === 'html') continue;
588
+ inToken.fill(true, token.start, token.end);
589
+ }
590
+ const room = maxLen - indent.length;
591
+ let pos = 0;
592
+
593
+ while (pos < text.length) {
594
+ if (text.length - pos <= room) {
595
+ lines.push(indent + text.slice(pos));
596
+ break;
597
+ }
598
+
599
+ // Find the last space at or before the limit that isn't inside a token
600
+ let breakIdx = -1;
601
+ for (let i = pos + 1; i < text.length && i - pos <= room; i++) {
602
+ if (text[i] === ' ' && !inToken[i]) breakIdx = i;
603
+ }
604
+
605
+ // If no break point found before the limit, look for the next space after
606
+ if (breakIdx === -1) {
607
+ for (let i = pos + room + 1; i < text.length; i++) {
608
+ if (text[i] === ' ' && !inToken[i]) {
609
+ breakIdx = i;
610
+ break;
611
+ }
612
+ }
613
+ }
614
+
615
+ // No break point at all — emit the whole thing
616
+ if (breakIdx === -1) {
617
+ lines.push(indent + text.slice(pos));
618
+ break;
619
+ }
620
+
621
+ lines.push(indent + text.slice(pos, breakIdx));
622
+ pos = breakIdx + 1;
623
+ }
624
+
625
+ return lines;
626
+ }