@rohal12/spindle 0.59.33 → 0.60.1
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/README.md +1 -0
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +99 -49
- package/dist/pkg/story-variables.js +830 -54
- package/dist/pkg/tooling.js +1 -0
- package/package.json +4 -2
- package/src/format/format-passage.ts +626 -0
- package/src/format/placeholders.ts +316 -0
- package/src/format/prettier.ts +62 -0
- package/src/format/segment.ts +126 -0
- package/src/js-lexer.ts +36 -6
- package/src/markup/code-end.ts +97 -41
- package/src/markup/parse.ts +6 -6
- package/src/tooling.ts +23 -1
- package/src/twine-editor/builtin-macros.ts +11 -0
- package/src/twine-editor/commands.ts +173 -0
- package/src/twine-editor/highlight.ts +471 -0
- package/src/twine-editor/icons.ts +35 -0
- package/src/twine-editor/index.ts +19 -0
- package/src/twine-editor/mode.ts +137 -0
- package/src/twine-editor/references.ts +34 -0
- package/src/twine-editor/snippets.ts +74 -0
- package/src/twine-editor/toolbar.ts +85 -0
- package/src/types-drift-check.ts +12 -0
- package/types/tooling.d.ts +68 -0
|
@@ -9352,8 +9352,8 @@ var WORDS_BEFORE_STRING = /* @__PURE__ */ new Set([
|
|
|
9352
9352
|
* string may span lines, as quoted macro labels may: the parse reports
|
|
9353
9353
|
* what in it is no JavaScript.
|
|
9354
9354
|
*/
|
|
9355
|
-
function findCodeEnd(src, start, { goal = "expression", stop } = {}) {
|
|
9356
|
-
const end = scanCodeEnd(src, start, goal, stop);
|
|
9355
|
+
function findCodeEnd(src, start, { goal = "expression", stop, onRunOut } = {}) {
|
|
9356
|
+
const end = scanCodeEnd(src, start, goal, stop, onRunOut);
|
|
9357
9357
|
return end < 0 && !stop ? parsedCodeEnd(src, start, goal) : end;
|
|
9358
9358
|
}
|
|
9359
9359
|
/**
|
|
@@ -9379,7 +9379,12 @@ function parsedCodeEnd(src, start, goal) {
|
|
|
9379
9379
|
return -1;
|
|
9380
9380
|
}
|
|
9381
9381
|
/** `findCodeEnd` by the tokens: see there. */
|
|
9382
|
-
function scanCodeEnd(src, start, goal, stop) {
|
|
9382
|
+
function scanCodeEnd(src, start, goal, stop, onRunOut) {
|
|
9383
|
+
/** No end: the code runs to the end of `src`. */
|
|
9384
|
+
const ranOut = () => {
|
|
9385
|
+
onRunOut?.();
|
|
9386
|
+
return -1;
|
|
9387
|
+
};
|
|
9383
9388
|
const stack = [];
|
|
9384
9389
|
let prevEnd = -1;
|
|
9385
9390
|
let prevWord = false;
|
|
@@ -9395,11 +9400,12 @@ function scanCodeEnd(src, start, goal, stop) {
|
|
|
9395
9400
|
if (!/^Unterminated/.test(message) && !inTemplate) {
|
|
9396
9401
|
resumeAt = Math.max(tok.pos, from) + 1;
|
|
9397
9402
|
afterOperand = false;
|
|
9398
|
-
if (resumeAt >= src.length) return
|
|
9403
|
+
if (resumeAt >= src.length) return ranOut();
|
|
9399
9404
|
break;
|
|
9400
9405
|
}
|
|
9401
9406
|
const k = stack.lastIndexOf("${");
|
|
9402
|
-
if (!/^Unterminated template/.test(message) || k < 0 || templateSlip || stop) return -1;
|
|
9407
|
+
if (!/^Unterminated template/.test(message) || k < 0 || templateSlip || stop) return /^Unterminated/.test(message) && !/^Unterminated regular/.test(message) && !(/^Unterminated string/.test(message) && prevWord && tok.pos === prevEnd) ? ranOut() : -1;
|
|
9408
|
+
onRunOut?.();
|
|
9403
9409
|
templateSlip = true;
|
|
9404
9410
|
stack.length = k;
|
|
9405
9411
|
resumeAt = tok.pos;
|
|
@@ -9408,7 +9414,7 @@ function scanCodeEnd(src, start, goal, stop) {
|
|
|
9408
9414
|
}
|
|
9409
9415
|
if (tok.restarted && stack.includes("${")) return -1;
|
|
9410
9416
|
const t = tok.type;
|
|
9411
|
-
if (t === types$1.eof) return
|
|
9417
|
+
if (t === types$1.eof) return ranOut();
|
|
9412
9418
|
if (t === types$1.string && prevWord && tok.start === prevEnd) return -1;
|
|
9413
9419
|
prevWord = t === types$1.name && !WORDS_BEFORE_STRING.has(tok.value) || t === types$1.num;
|
|
9414
9420
|
prevEnd = tok.end;
|
|
@@ -9688,80 +9694,124 @@ var NON_STRING_QUOTE_PREFIX = /[\p{L}\p{N}_\\]/u;
|
|
|
9688
9694
|
function skipLiteral(input, i) {
|
|
9689
9695
|
const quote = input[i];
|
|
9690
9696
|
const template = quote === "`";
|
|
9697
|
+
let ranOut = false;
|
|
9691
9698
|
for (let j = i + 1; j < input.length;) {
|
|
9692
9699
|
const c = input[j];
|
|
9693
9700
|
if (c === "\\") j += 2;
|
|
9694
|
-
else if (c === quote) return
|
|
9695
|
-
|
|
9701
|
+
else if (c === quote) return {
|
|
9702
|
+
end: j + 1,
|
|
9703
|
+
ranOut
|
|
9704
|
+
};
|
|
9705
|
+
else if (!template && c === "\n") return {
|
|
9706
|
+
end: -1,
|
|
9707
|
+
ranOut
|
|
9708
|
+
};
|
|
9696
9709
|
else if (template && c === "$" && input[j + 1] === "{") {
|
|
9697
|
-
const close =
|
|
9698
|
-
|
|
9699
|
-
|
|
9710
|
+
const close = lenientRead(input, j + 2);
|
|
9711
|
+
ranOut || (ranOut = close.ranOut);
|
|
9712
|
+
if (close.end === -1) return {
|
|
9713
|
+
end: -1,
|
|
9714
|
+
ranOut
|
|
9715
|
+
};
|
|
9716
|
+
j = close.end + 1;
|
|
9700
9717
|
} else j++;
|
|
9701
9718
|
}
|
|
9702
|
-
return
|
|
9719
|
+
return {
|
|
9720
|
+
end: -1,
|
|
9721
|
+
ranOut: ranOut || template
|
|
9722
|
+
};
|
|
9703
9723
|
}
|
|
9704
9724
|
/**
|
|
9705
9725
|
* The closing `}` of braces read leniently from `i` (just past a `{`): braces
|
|
9706
9726
|
* count except inside string and template literals, and a quote that can't
|
|
9707
9727
|
* start a string (an apostrophe, or one not closed on its line) is text, as
|
|
9708
|
-
* is a backtick without a closing one.
|
|
9728
|
+
* is a backtick without a closing one. `onRunOut` is called when a line
|
|
9729
|
+
* appended to `input` could change the result (see `Lenient`).
|
|
9709
9730
|
*/
|
|
9710
|
-
function lenientClose(input, i) {
|
|
9731
|
+
function lenientClose(input, i, onRunOut) {
|
|
9732
|
+
const { end, ranOut } = lenientRead(input, i);
|
|
9733
|
+
if (ranOut) onRunOut?.();
|
|
9734
|
+
return end;
|
|
9735
|
+
}
|
|
9736
|
+
function lenientRead(input, i) {
|
|
9711
9737
|
if (memoInput !== input) {
|
|
9712
9738
|
memoInput = input;
|
|
9713
9739
|
memo.clear();
|
|
9714
9740
|
}
|
|
9715
|
-
let
|
|
9716
|
-
if (
|
|
9717
|
-
|
|
9718
|
-
memo.set(i,
|
|
9741
|
+
let read = memo.get(i);
|
|
9742
|
+
if (read === void 0) {
|
|
9743
|
+
read = scanLenient(input, i);
|
|
9744
|
+
memo.set(i, read);
|
|
9719
9745
|
}
|
|
9720
|
-
return
|
|
9746
|
+
return read;
|
|
9721
9747
|
}
|
|
9722
9748
|
var memoInput = "";
|
|
9723
9749
|
var memo = /* @__PURE__ */ new Map();
|
|
9724
9750
|
function scanLenient(input, i) {
|
|
9725
9751
|
let depth = 0;
|
|
9752
|
+
let ranOut = false;
|
|
9726
9753
|
while (i < input.length) {
|
|
9727
9754
|
const c = input[i];
|
|
9728
9755
|
if (c === "{") {
|
|
9729
9756
|
depth++;
|
|
9730
9757
|
i++;
|
|
9731
9758
|
} else if (c === "}") {
|
|
9732
|
-
if (depth === 0) return
|
|
9759
|
+
if (depth === 0) return {
|
|
9760
|
+
end: i,
|
|
9761
|
+
ranOut
|
|
9762
|
+
};
|
|
9733
9763
|
depth--;
|
|
9734
9764
|
i++;
|
|
9735
9765
|
} else if (c === "`" || (c === "\"" || c === "'") && !(i > 0 && NON_STRING_QUOTE_PREFIX.test(input[i - 1]))) {
|
|
9736
9766
|
const close = skipLiteral(input, i);
|
|
9737
|
-
|
|
9767
|
+
ranOut || (ranOut = close.ranOut);
|
|
9768
|
+
i = close.end === -1 ? i + 1 : close.end;
|
|
9738
9769
|
} else i++;
|
|
9739
9770
|
}
|
|
9740
|
-
return
|
|
9771
|
+
return {
|
|
9772
|
+
end: -1,
|
|
9773
|
+
ranOut: true
|
|
9774
|
+
};
|
|
9775
|
+
}
|
|
9776
|
+
/**
|
|
9777
|
+
* The JavaScript reader Spindle uses: js-lexer, then a lenient scan. With
|
|
9778
|
+
* `onOpenEnd`, it also reports code whose end depends on what follows the
|
|
9779
|
+
* input (see `OnOpenCodeEnd`); the ends it finds are the same.
|
|
9780
|
+
*/
|
|
9781
|
+
function jsCodeEnd(onOpenEnd) {
|
|
9782
|
+
return {
|
|
9783
|
+
closeBrace(input, codeStart, lenientStart) {
|
|
9784
|
+
let ranOut = false;
|
|
9785
|
+
const onRunOut = () => ranOut = true;
|
|
9786
|
+
const strict = findCodeEnd(input, codeStart, { onRunOut });
|
|
9787
|
+
const end = strict !== -1 ? strict : lenientClose(input, lenientStart, onRunOut);
|
|
9788
|
+
if (ranOut) onOpenEnd?.(input, codeStart);
|
|
9789
|
+
return end;
|
|
9790
|
+
},
|
|
9791
|
+
rawBodyEnd(input, bodyStart, name) {
|
|
9792
|
+
const closer = `\\{/${name}\\s*\\}`;
|
|
9793
|
+
const first = new RegExp(closer, "gi");
|
|
9794
|
+
first.lastIndex = bodyStart;
|
|
9795
|
+
const firstAt = first.exec(input)?.index ?? -1;
|
|
9796
|
+
if (firstAt === -1) return -1;
|
|
9797
|
+
const at = new RegExp(closer, "iy");
|
|
9798
|
+
let ranOut = false;
|
|
9799
|
+
const end = findCodeEnd(input, bodyStart, {
|
|
9800
|
+
goal: "statements",
|
|
9801
|
+
stop: (k) => {
|
|
9802
|
+
at.lastIndex = k;
|
|
9803
|
+
return at.test(input);
|
|
9804
|
+
},
|
|
9805
|
+
onRunOut: () => ranOut = true
|
|
9806
|
+
});
|
|
9807
|
+
if (end !== -1) return end;
|
|
9808
|
+
if (onOpenEnd && (ranOut || new RegExp(`\\{/${name}\\s*$`, "i").test(input))) onOpenEnd(input, bodyStart);
|
|
9809
|
+
return firstAt;
|
|
9810
|
+
}
|
|
9811
|
+
};
|
|
9741
9812
|
}
|
|
9742
9813
|
/** The JavaScript reader Spindle uses today: js-lexer, then a lenient scan. */
|
|
9743
|
-
var defaultCodeEnd =
|
|
9744
|
-
closeBrace(input, codeStart, lenientStart) {
|
|
9745
|
-
const end = findCodeEnd(input, codeStart);
|
|
9746
|
-
return end !== -1 ? end : lenientClose(input, lenientStart);
|
|
9747
|
-
},
|
|
9748
|
-
rawBodyEnd(input, bodyStart, name) {
|
|
9749
|
-
const closer = `\\{/${name}\\s*\\}`;
|
|
9750
|
-
const first = new RegExp(closer, "gi");
|
|
9751
|
-
first.lastIndex = bodyStart;
|
|
9752
|
-
const firstAt = first.exec(input)?.index ?? -1;
|
|
9753
|
-
if (firstAt === -1) return -1;
|
|
9754
|
-
const at = new RegExp(closer, "iy");
|
|
9755
|
-
const end = findCodeEnd(input, bodyStart, {
|
|
9756
|
-
goal: "statements",
|
|
9757
|
-
stop: (k) => {
|
|
9758
|
-
at.lastIndex = k;
|
|
9759
|
-
return at.test(input);
|
|
9760
|
-
}
|
|
9761
|
-
});
|
|
9762
|
-
return end === -1 ? firstAt : end;
|
|
9763
|
-
}
|
|
9764
|
-
};
|
|
9814
|
+
var defaultCodeEnd = jsCodeEnd();
|
|
9765
9815
|
//#endregion
|
|
9766
9816
|
//#region src/markup/code-attributes.ts
|
|
9767
9817
|
/**
|
|
@@ -9836,7 +9886,7 @@ var MarkupError = class extends Error {
|
|
|
9836
9886
|
this.name = "MarkupError";
|
|
9837
9887
|
}
|
|
9838
9888
|
};
|
|
9839
|
-
function run(source, startRule, options) {
|
|
9889
|
+
function run$1(source, startRule, options) {
|
|
9840
9890
|
const hooks = options.hooks ? {
|
|
9841
9891
|
...defaultHooks,
|
|
9842
9892
|
...options.hooks
|
|
@@ -9864,7 +9914,7 @@ function run(source, startRule, options) {
|
|
|
9864
9914
|
* so it has no errors of its own.
|
|
9865
9915
|
*/
|
|
9866
9916
|
function analyzeMarkup(source, options = {}) {
|
|
9867
|
-
const { tokens, errors, damage } =
|
|
9917
|
+
const { tokens, errors, damage } = scanMarkupTolerant(source, options);
|
|
9868
9918
|
const hooks = {
|
|
9869
9919
|
...defaultHooks,
|
|
9870
9920
|
...options.hooks
|
|
@@ -9910,7 +9960,7 @@ function pairingError(source, error) {
|
|
|
9910
9960
|
* malformed tag, such as an unclosed `{`, `[[` or attribute value.
|
|
9911
9961
|
*/
|
|
9912
9962
|
function tokenizeMarkup(source, options = {}) {
|
|
9913
|
-
return run(source, "Tokens", options);
|
|
9963
|
+
return run$1(source, "Tokens", options);
|
|
9914
9964
|
}
|
|
9915
9965
|
/**
|
|
9916
9966
|
* The `.class#id` selectors that start `source` at `at`, with the index just
|
|
@@ -9918,7 +9968,7 @@ function tokenizeMarkup(source, options = {}) {
|
|
|
9918
9968
|
* none). A selector name may hold `{$name}` interpolations, as in markup.
|
|
9919
9969
|
*/
|
|
9920
9970
|
function parseSelectors(source, at = 0) {
|
|
9921
|
-
const found = run(source.slice(at), "SelectorsPrefix", {});
|
|
9971
|
+
const found = run$1(source.slice(at), "SelectorsPrefix", {});
|
|
9922
9972
|
return {
|
|
9923
9973
|
...found,
|
|
9924
9974
|
end: at + found.end
|
|
@@ -9933,7 +9983,7 @@ function parseSelectors(source, at = 0) {
|
|
|
9933
9983
|
* markup the tokens are those of `tokenizeMarkup` and there are no errors.
|
|
9934
9984
|
*/
|
|
9935
9985
|
function tokenizeMarkupTolerant(source, options = {}) {
|
|
9936
|
-
const { tokens, errors } =
|
|
9986
|
+
const { tokens, errors } = scanMarkupTolerant(source, options);
|
|
9937
9987
|
return {
|
|
9938
9988
|
tokens,
|
|
9939
9989
|
errors
|
|
@@ -9941,10 +9991,10 @@ function tokenizeMarkupTolerant(source, options = {}) {
|
|
|
9941
9991
|
}
|
|
9942
9992
|
/**
|
|
9943
9993
|
* The tokens of tolerant tokenizing, the errors, and where the damage of
|
|
9944
|
-
* each error starts: the tag that is
|
|
9945
|
-
* (an attribute value) is after.
|
|
9994
|
+
* each error starts (`damage[i]` for `errors[i]`): the tag that is
|
|
9995
|
+
* malformed, which an error inside it (an attribute value) is after.
|
|
9946
9996
|
*/
|
|
9947
|
-
function
|
|
9997
|
+
function scanMarkupTolerant(source, options = {}) {
|
|
9948
9998
|
const tokens = [];
|
|
9949
9999
|
const errors = [];
|
|
9950
10000
|
const damage = [];
|
|
@@ -13236,6 +13286,725 @@ function discoverMacros(source) {
|
|
|
13236
13286
|
return found;
|
|
13237
13287
|
}
|
|
13238
13288
|
//#endregion
|
|
13289
|
+
//#region src/format/segment.ts
|
|
13290
|
+
var VOID_ELEMENTS = /* @__PURE__ */ new Set([
|
|
13291
|
+
"area",
|
|
13292
|
+
"base",
|
|
13293
|
+
"br",
|
|
13294
|
+
"col",
|
|
13295
|
+
"embed",
|
|
13296
|
+
"hr",
|
|
13297
|
+
"img",
|
|
13298
|
+
"input",
|
|
13299
|
+
"link",
|
|
13300
|
+
"meta",
|
|
13301
|
+
"param",
|
|
13302
|
+
"source",
|
|
13303
|
+
"track",
|
|
13304
|
+
"wbr"
|
|
13305
|
+
]);
|
|
13306
|
+
/**
|
|
13307
|
+
* Segment a passage body into regions: spindle (markdown/macros), html blocks, script blocks.
|
|
13308
|
+
*/
|
|
13309
|
+
function segmentRegions(body) {
|
|
13310
|
+
const lines = body.split("\n");
|
|
13311
|
+
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
|
|
13312
|
+
if (lines.length === 0) return [];
|
|
13313
|
+
const regions = [];
|
|
13314
|
+
let i = 0;
|
|
13315
|
+
while (i < lines.length) {
|
|
13316
|
+
const line = lines[i];
|
|
13317
|
+
const trimmed = line.trim();
|
|
13318
|
+
if (/^<script(\s|>)/i.test(trimmed)) {
|
|
13319
|
+
const block = blockLines(lines, i, /<\/script\s*>/i);
|
|
13320
|
+
regions.push({
|
|
13321
|
+
type: "script",
|
|
13322
|
+
lines: block
|
|
13323
|
+
});
|
|
13324
|
+
i += block.length;
|
|
13325
|
+
continue;
|
|
13326
|
+
}
|
|
13327
|
+
if (/^<svg(\s|>)/i.test(trimmed)) {
|
|
13328
|
+
const block = blockLines(lines, i, /<\/svg\s*>/i);
|
|
13329
|
+
regions.push({
|
|
13330
|
+
type: "svg",
|
|
13331
|
+
lines: block
|
|
13332
|
+
});
|
|
13333
|
+
i += block.length;
|
|
13334
|
+
continue;
|
|
13335
|
+
}
|
|
13336
|
+
if (/^<([a-zA-Z][\w-]*)/.test(trimmed)) {
|
|
13337
|
+
const tagName = trimmed.match(/^<([a-zA-Z][\w-]*)/)[1].toLowerCase();
|
|
13338
|
+
if (VOID_ELEMENTS.has(tagName) && !lines[i + 1]?.trim().startsWith("<")) {
|
|
13339
|
+
pushSpindleLine(regions, line);
|
|
13340
|
+
i++;
|
|
13341
|
+
continue;
|
|
13342
|
+
}
|
|
13343
|
+
if (new RegExp(`</${tagName}\\s*>`, "i").test(trimmed)) {
|
|
13344
|
+
pushSpindleLine(regions, line);
|
|
13345
|
+
i++;
|
|
13346
|
+
continue;
|
|
13347
|
+
}
|
|
13348
|
+
const htmlLines = [line];
|
|
13349
|
+
let depth = 1;
|
|
13350
|
+
i++;
|
|
13351
|
+
while (i < lines.length && depth > 0) {
|
|
13352
|
+
htmlLines.push(lines[i]);
|
|
13353
|
+
const opens = (lines[i].match(new RegExp(`<${tagName}(?:[\\s>]|$)`, "gi")) ?? []).length;
|
|
13354
|
+
const closes = (lines[i].match(new RegExp(`</${tagName}\\s*>`, "gi")) ?? []).length;
|
|
13355
|
+
depth += opens - closes;
|
|
13356
|
+
i++;
|
|
13357
|
+
}
|
|
13358
|
+
regions.push({
|
|
13359
|
+
type: "html",
|
|
13360
|
+
lines: htmlLines
|
|
13361
|
+
});
|
|
13362
|
+
continue;
|
|
13363
|
+
}
|
|
13364
|
+
pushSpindleLine(regions, line);
|
|
13365
|
+
i++;
|
|
13366
|
+
}
|
|
13367
|
+
return regions;
|
|
13368
|
+
}
|
|
13369
|
+
/**
|
|
13370
|
+
* The lines of the block that opens on line `start`: up to the first line
|
|
13371
|
+
* (the opening one included) that matches `close`, or to the end.
|
|
13372
|
+
*/
|
|
13373
|
+
function blockLines(lines, start, close) {
|
|
13374
|
+
let end = start;
|
|
13375
|
+
while (end < lines.length - 1 && !close.test(lines[end])) end++;
|
|
13376
|
+
return lines.slice(start, end + 1);
|
|
13377
|
+
}
|
|
13378
|
+
/** Append a line to the last spindle region, or create a new one. */
|
|
13379
|
+
function pushSpindleLine(regions, line) {
|
|
13380
|
+
const last = regions[regions.length - 1];
|
|
13381
|
+
if (last?.type === "spindle") last.lines.push(line);
|
|
13382
|
+
else regions.push({
|
|
13383
|
+
type: "spindle",
|
|
13384
|
+
lines: [line]
|
|
13385
|
+
});
|
|
13386
|
+
}
|
|
13387
|
+
//#endregion
|
|
13388
|
+
//#region src/format/prettier.ts
|
|
13389
|
+
/** The options the formatter gives Prettier unless the caller passes its own. */
|
|
13390
|
+
var DEFAULT_PRETTIER_OPTIONS = { tabWidth: 2 };
|
|
13391
|
+
async function run(code, prettier, options, overrides) {
|
|
13392
|
+
if (!prettier) return void 0;
|
|
13393
|
+
try {
|
|
13394
|
+
return await prettier.format(code, {
|
|
13395
|
+
...options ?? DEFAULT_PRETTIER_OPTIONS,
|
|
13396
|
+
...overrides
|
|
13397
|
+
});
|
|
13398
|
+
} catch {
|
|
13399
|
+
return;
|
|
13400
|
+
}
|
|
13401
|
+
}
|
|
13402
|
+
function formatJS(code, prettier, options) {
|
|
13403
|
+
return run(code, prettier, options, { parser: "babel" });
|
|
13404
|
+
}
|
|
13405
|
+
function formatCSS(code, prettier, options) {
|
|
13406
|
+
return run(code, prettier, options, { parser: "css" });
|
|
13407
|
+
}
|
|
13408
|
+
function formatHTML(code, prettier, options) {
|
|
13409
|
+
return run(code, prettier, options, {
|
|
13410
|
+
parser: "html",
|
|
13411
|
+
htmlWhitespaceSensitivity: "css"
|
|
13412
|
+
});
|
|
13413
|
+
}
|
|
13414
|
+
//#endregion
|
|
13415
|
+
//#region src/format/placeholders.ts
|
|
13416
|
+
/**
|
|
13417
|
+
* Read `text` with Spindle's own tokenizer (`tokenizeMarkupTolerant`), so the
|
|
13418
|
+
* formatter protects exactly what the runtime executes. A token inside an
|
|
13419
|
+
* HTML attribute value is reported too, with the attribute-safe placeholder
|
|
13420
|
+
* it needs, because it must not be reformatted either.
|
|
13421
|
+
*/
|
|
13422
|
+
function scanSpindleMarkup(text) {
|
|
13423
|
+
const tokens = [];
|
|
13424
|
+
const tags = [];
|
|
13425
|
+
const doBlocks = [];
|
|
13426
|
+
let open;
|
|
13427
|
+
const push = (t, inAttribute) => {
|
|
13428
|
+
const match = {
|
|
13429
|
+
start: t.start,
|
|
13430
|
+
end: t.end,
|
|
13431
|
+
token: text.slice(t.start, t.end)
|
|
13432
|
+
};
|
|
13433
|
+
if (inAttribute) match.inAttribute = true;
|
|
13434
|
+
tokens.push(match);
|
|
13435
|
+
};
|
|
13436
|
+
for (const t of tokenizeMarkupTolerant(text).tokens) if (t.type === "html") {
|
|
13437
|
+
tags.push({
|
|
13438
|
+
start: t.start,
|
|
13439
|
+
end: t.end
|
|
13440
|
+
});
|
|
13441
|
+
for (const attribute of t.attributeSpans) {
|
|
13442
|
+
if (attribute.valueStart === void 0 || attribute.valueEnd === void 0) continue;
|
|
13443
|
+
const value = text.slice(attribute.valueStart, attribute.valueEnd);
|
|
13444
|
+
if (!value.includes("{")) continue;
|
|
13445
|
+
for (const inner of tokenizeMarkupTolerant(value, { text: true }).tokens) if (inner.type === "macro" || inner.type === "variable" || inner.type === "expression") push({
|
|
13446
|
+
start: attribute.valueStart + inner.start,
|
|
13447
|
+
end: attribute.valueStart + inner.end
|
|
13448
|
+
}, true);
|
|
13449
|
+
}
|
|
13450
|
+
} else if (t.type !== "text") {
|
|
13451
|
+
if (t.type === "macro" && t.name === "do") {
|
|
13452
|
+
if (!t.isClose) open = t;
|
|
13453
|
+
else if (open) {
|
|
13454
|
+
doBlocks.push({
|
|
13455
|
+
start: open.start,
|
|
13456
|
+
end: t.end,
|
|
13457
|
+
bodyStart: open.end,
|
|
13458
|
+
bodyEnd: t.start
|
|
13459
|
+
});
|
|
13460
|
+
open = void 0;
|
|
13461
|
+
}
|
|
13462
|
+
}
|
|
13463
|
+
push(t);
|
|
13464
|
+
}
|
|
13465
|
+
return {
|
|
13466
|
+
tokens,
|
|
13467
|
+
tags,
|
|
13468
|
+
doBlocks
|
|
13469
|
+
};
|
|
13470
|
+
}
|
|
13471
|
+
/**
|
|
13472
|
+
* The ranges of the string and template literals of the JavaScript `code`
|
|
13473
|
+
* that span lines (outermost only): their line breaks are part of the value.
|
|
13474
|
+
*/
|
|
13475
|
+
function multilineJsLiterals(code) {
|
|
13476
|
+
const spans = [];
|
|
13477
|
+
let skipUntil = 0;
|
|
13478
|
+
lexJs(code, { literal(text, index, nesting) {
|
|
13479
|
+
if (nesting > 0 || index < skipUntil) return;
|
|
13480
|
+
const quote = text[0];
|
|
13481
|
+
if (quote === "`") {
|
|
13482
|
+
skipUntil = lexTemplate(code, index);
|
|
13483
|
+
if (code.slice(index, skipUntil).includes("\n")) spans.push([index, skipUntil]);
|
|
13484
|
+
} else if ((quote === "\"" || quote === "'") && text.includes("\n")) spans.push([index, index + text.length]);
|
|
13485
|
+
} }, "statements");
|
|
13486
|
+
return spans;
|
|
13487
|
+
}
|
|
13488
|
+
/** Whether an HTML tag (opening, closing or self-closing) overlaps the range. */
|
|
13489
|
+
function lineHasTag(tags, start, end) {
|
|
13490
|
+
return tags.some((tag) => tag.start < end && tag.end > start);
|
|
13491
|
+
}
|
|
13492
|
+
/**
|
|
13493
|
+
* Replace `<svg>…</svg>` blocks with HTML comment placeholders so Prettier
|
|
13494
|
+
* does not reformat them (CommonMark does not recognise multi-line SVG tags
|
|
13495
|
+
* as HTML blocks, so reformatted attributes break rendering).
|
|
13496
|
+
*/
|
|
13497
|
+
function replaceSvgBlocks(html) {
|
|
13498
|
+
const tokens = [];
|
|
13499
|
+
return {
|
|
13500
|
+
text: html.replace(/<svg[\s>][\s\S]*?<\/svg>/gi, (match) => {
|
|
13501
|
+
const idx = tokens.length;
|
|
13502
|
+
tokens.push(match);
|
|
13503
|
+
return `<!--SVG:${idx}-->`;
|
|
13504
|
+
}),
|
|
13505
|
+
tokens
|
|
13506
|
+
};
|
|
13507
|
+
}
|
|
13508
|
+
var SVG_PLACEHOLDERS = (i) => [`<!--SVG:${i}-->`];
|
|
13509
|
+
var SPINDLE_PLACEHOLDERS = (i) => [`<!--SP:${i}-->`, `__SP${i}__`];
|
|
13510
|
+
/**
|
|
13511
|
+
* Whether `text` (what a formatter made of the placeholdered text) holds
|
|
13512
|
+
* the placeholder of every one of `tokens` exactly once. If not, the
|
|
13513
|
+
* formatter lost, changed or copied one, and restoring the tokens would
|
|
13514
|
+
* lose or duplicate story text.
|
|
13515
|
+
*/
|
|
13516
|
+
function placeholdersIntact(text, tokens, placeholdersOf) {
|
|
13517
|
+
return tokens.every((_, index) => placeholdersOf(index).reduce((count, placeholder) => count + text.split(placeholder).length - 1, 0) === 1);
|
|
13518
|
+
}
|
|
13519
|
+
/** Whether `before` and `after` hold the same Spindle tokens, in the same order. */
|
|
13520
|
+
function sameSpindleTokens(before, after) {
|
|
13521
|
+
const tokensOf = (text) => scanSpindleMarkup(text).tokens.map((m) => m.token);
|
|
13522
|
+
const expected = tokensOf(before);
|
|
13523
|
+
const found = tokensOf(after);
|
|
13524
|
+
return expected.length === found.length && expected.every((t, i) => t === found[i]);
|
|
13525
|
+
}
|
|
13526
|
+
/**
|
|
13527
|
+
* Put each of `tokens` back in place of its placeholders (those that
|
|
13528
|
+
* `placeholdersOf` gives for its index): the first of each.
|
|
13529
|
+
*/
|
|
13530
|
+
function restorePlaceholders(text, tokens, placeholdersOf) {
|
|
13531
|
+
let result = text;
|
|
13532
|
+
tokens.forEach((token, index) => {
|
|
13533
|
+
for (const placeholder of placeholdersOf(index)) result = result.replace(placeholder, () => token);
|
|
13534
|
+
});
|
|
13535
|
+
return result;
|
|
13536
|
+
}
|
|
13537
|
+
/**
|
|
13538
|
+
* Restore SVG blocks from placeholders.
|
|
13539
|
+
*/
|
|
13540
|
+
function restoreSvgBlocks(text, tokens) {
|
|
13541
|
+
return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
|
|
13542
|
+
}
|
|
13543
|
+
/**
|
|
13544
|
+
* Replace Spindle tokens with placeholders.
|
|
13545
|
+
* Uses <!--SP:N--> in HTML content and __SPN__ in attribute values.
|
|
13546
|
+
*
|
|
13547
|
+
* Lines that contain Spindle tokens but no HTML tags are replaced as a
|
|
13548
|
+
* single whole-line placeholder so Prettier cannot split them. A token that
|
|
13549
|
+
* spans lines (a template literal with a line break) keeps its line break:
|
|
13550
|
+
* the lines it spans are one line here. A `{do}…{/do}` block is one token:
|
|
13551
|
+
* its body is JavaScript executed as written, which an HTML formatter must
|
|
13552
|
+
* not re-indent or re-flow.
|
|
13553
|
+
*/
|
|
13554
|
+
function replaceSpindleTokens(html) {
|
|
13555
|
+
const { tokens: found, tags, doBlocks } = scanSpindleMarkup(html);
|
|
13556
|
+
const units = [];
|
|
13557
|
+
const pushDoBlock = (block) => units.push({
|
|
13558
|
+
start: block.start,
|
|
13559
|
+
end: block.end,
|
|
13560
|
+
token: html.slice(block.start, block.end)
|
|
13561
|
+
});
|
|
13562
|
+
let doIndex = 0;
|
|
13563
|
+
for (const m of found) {
|
|
13564
|
+
for (let block = doBlocks[doIndex]; block && block.end <= m.start;) {
|
|
13565
|
+
pushDoBlock(block);
|
|
13566
|
+
block = doBlocks[++doIndex];
|
|
13567
|
+
}
|
|
13568
|
+
const open = doBlocks[doIndex];
|
|
13569
|
+
if (open && m.start >= open.start) continue;
|
|
13570
|
+
units.push(m);
|
|
13571
|
+
}
|
|
13572
|
+
for (; doIndex < doBlocks.length; doIndex++) pushDoBlock(doBlocks[doIndex]);
|
|
13573
|
+
units.sort((a, b) => a.start - b.start);
|
|
13574
|
+
const tokens = [];
|
|
13575
|
+
const resultLines = [];
|
|
13576
|
+
let unit = 0;
|
|
13577
|
+
let lineStart = 0;
|
|
13578
|
+
while (lineStart <= html.length) {
|
|
13579
|
+
let lineEnd = lineStart;
|
|
13580
|
+
const lineUnits = [];
|
|
13581
|
+
for (;;) {
|
|
13582
|
+
while (unit < units.length && units[unit].end <= lineEnd) unit++;
|
|
13583
|
+
const next = units[unit];
|
|
13584
|
+
const inside = next && next.start <= lineEnd ? next : void 0;
|
|
13585
|
+
if (inside) {
|
|
13586
|
+
lineUnits.push(inside);
|
|
13587
|
+
lineEnd = inside.end;
|
|
13588
|
+
unit++;
|
|
13589
|
+
continue;
|
|
13590
|
+
}
|
|
13591
|
+
if (lineEnd >= html.length || html[lineEnd] === "\n") break;
|
|
13592
|
+
lineEnd++;
|
|
13593
|
+
}
|
|
13594
|
+
const line = html.slice(lineStart, lineEnd);
|
|
13595
|
+
const indent = line.match(/^(\s*)/)?.[1] ?? "";
|
|
13596
|
+
if (lineUnits.length === 0) resultLines.push(line);
|
|
13597
|
+
else if (!lineHasTag(tags, lineStart, lineEnd)) {
|
|
13598
|
+
const idx = tokens.length;
|
|
13599
|
+
tokens.push(line.trim());
|
|
13600
|
+
resultLines.push(`${indent}<!--SP:${idx}-->`);
|
|
13601
|
+
} else {
|
|
13602
|
+
let replaced = "";
|
|
13603
|
+
let last = lineStart;
|
|
13604
|
+
for (const u of lineUnits) {
|
|
13605
|
+
const idx = tokens.length;
|
|
13606
|
+
tokens.push(u.token);
|
|
13607
|
+
replaced += html.slice(last, u.start) + (u.inAttribute ? `__SP${idx}__` : `<!--SP:${idx}-->`);
|
|
13608
|
+
last = u.end;
|
|
13609
|
+
}
|
|
13610
|
+
resultLines.push(replaced + html.slice(last, lineEnd));
|
|
13611
|
+
}
|
|
13612
|
+
lineStart = lineEnd + 1;
|
|
13613
|
+
}
|
|
13614
|
+
return {
|
|
13615
|
+
text: resultLines.join("\n"),
|
|
13616
|
+
tokens
|
|
13617
|
+
};
|
|
13618
|
+
}
|
|
13619
|
+
/**
|
|
13620
|
+
* Restore original Spindle tokens from placeholders.
|
|
13621
|
+
*/
|
|
13622
|
+
function restoreSpindleTokens(text, tokens) {
|
|
13623
|
+
return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
|
|
13624
|
+
}
|
|
13625
|
+
//#endregion
|
|
13626
|
+
//#region src/format/format-passage.ts
|
|
13627
|
+
/** Default dedenting sub-macros. */
|
|
13628
|
+
var DEFAULT_DEDENTING = /* @__PURE__ */ new Set([
|
|
13629
|
+
"else",
|
|
13630
|
+
"elseif",
|
|
13631
|
+
"next",
|
|
13632
|
+
"case",
|
|
13633
|
+
"default"
|
|
13634
|
+
]);
|
|
13635
|
+
/** The names of the macros the passage closes with `{/name}`: block macros it defines itself. */
|
|
13636
|
+
function closedMacroNames(text) {
|
|
13637
|
+
const found = /* @__PURE__ */ new Set();
|
|
13638
|
+
for (const t of tokenizeMarkupTolerant(text).tokens) if (t.type === "macro" && t.isClose) found.add(t.name.toLowerCase());
|
|
13639
|
+
return found;
|
|
13640
|
+
}
|
|
13641
|
+
/** The built-in block macros (and the block widgets the runtime has defined) plus those the passage closes. */
|
|
13642
|
+
function defaultIsBlock(text, extra = []) {
|
|
13643
|
+
const closed = closedMacroNames(text);
|
|
13644
|
+
for (const name of extra) closed.add(name.toLowerCase());
|
|
13645
|
+
return (name) => isBlockMacro(name) || closed.has(name.toLowerCase());
|
|
13646
|
+
}
|
|
13647
|
+
/**
|
|
13648
|
+
* Format the text of one passage.
|
|
13649
|
+
*
|
|
13650
|
+
* Rules:
|
|
13651
|
+
* 1. Indent content inside block macros by 2 spaces per nesting level
|
|
13652
|
+
* 2. Dedenting sub-macros (else, elseif, next, case, default) snap to parent indent level
|
|
13653
|
+
* 3. Remove trailing whitespace from each line, keeping Markdown hard breaks
|
|
13654
|
+
* (two trailing spaces) and list/code-fence indentation in prose
|
|
13655
|
+
* 4. Format `<script>` and HTML blocks, and the whole body of a script or
|
|
13656
|
+
* stylesheet passage, with Prettier (when given)
|
|
13657
|
+
* 5. Make the result end with a single newline, in the line-ending style of
|
|
13658
|
+
* the text
|
|
13659
|
+
*/
|
|
13660
|
+
async function formatPassage(body, options = {}) {
|
|
13661
|
+
if (body.charCodeAt(0) === 65279) return "" + await formatPassage(body.slice(1), options);
|
|
13662
|
+
const eol = dominantEol(body);
|
|
13663
|
+
const output = await formatLf(body.replace(/\r\n/g, "\n"), options);
|
|
13664
|
+
return eol === "\r\n" ? output.replace(/\n/g, "\r\n") : output;
|
|
13665
|
+
}
|
|
13666
|
+
/**
|
|
13667
|
+
* The text's line-ending style: whichever of CRLF and LF is more common,
|
|
13668
|
+
* the first one found when equally common. (Spindle's compiler normalizes
|
|
13669
|
+
* CRLF to LF, so the choice never changes what a story does.)
|
|
13670
|
+
*/
|
|
13671
|
+
function dominantEol(text) {
|
|
13672
|
+
const crlf = (text.match(/\r\n/g) ?? []).length;
|
|
13673
|
+
const lf = (text.match(/\n/g) ?? []).length - crlf;
|
|
13674
|
+
if (crlf !== lf) return crlf > lf ? "\r\n" : "\n";
|
|
13675
|
+
return text.indexOf("\r\n") !== -1 && text.indexOf("\r\n") < text.indexOf("\n") ? "\r\n" : "\n";
|
|
13676
|
+
}
|
|
13677
|
+
/** `text` with every `from` replaced by `to`, literally. */
|
|
13678
|
+
function replaceAll(text, from, to) {
|
|
13679
|
+
return text.split(from).join(to);
|
|
13680
|
+
}
|
|
13681
|
+
/**
|
|
13682
|
+
* Newline stand-in inside multiline Spindle tokens. A private-use character
|
|
13683
|
+
* absent from the document: not whitespace, so no line-based step touches it.
|
|
13684
|
+
*/
|
|
13685
|
+
function newlineSentinel(text) {
|
|
13686
|
+
for (let code = 57344; code <= 63743; code++) {
|
|
13687
|
+
const ch = String.fromCharCode(code);
|
|
13688
|
+
if (!text.includes(ch)) return ch;
|
|
13689
|
+
}
|
|
13690
|
+
throw new Error("no free private-use character for the newline stand-in");
|
|
13691
|
+
}
|
|
13692
|
+
/**
|
|
13693
|
+
* Join each multiline token (macro, interpolation or link, as the Spindle
|
|
13694
|
+
* runtime tokenizes it) onto its line with `sentinel` for its newlines. The
|
|
13695
|
+
* line-based formatting steps then see one line and cannot re-indent, wrap,
|
|
13696
|
+
* trim, segment or re-flow the runtime payload inside it.
|
|
13697
|
+
*
|
|
13698
|
+
* The body of a `{do}` macro is JavaScript, executed as written: a template
|
|
13699
|
+
* literal (or a string continued with a backslash) that spans lines is a
|
|
13700
|
+
* value, so its line breaks and the whitespace after them must survive
|
|
13701
|
+
* formatting. Those literals are joined too.
|
|
13702
|
+
*/
|
|
13703
|
+
function protectMultilineTokens(body, sentinel) {
|
|
13704
|
+
const { tokens, doBlocks } = scanSpindleMarkup(body);
|
|
13705
|
+
const spans = [];
|
|
13706
|
+
for (const m of tokens) if (m.token.includes("\n")) spans.push([m.start, m.end]);
|
|
13707
|
+
for (const block of doBlocks) for (const [a, b] of multilineJsLiterals(body.slice(block.bodyStart, block.bodyEnd))) spans.push([block.bodyStart + a, block.bodyStart + b]);
|
|
13708
|
+
return joinSpans(body, spans, sentinel);
|
|
13709
|
+
}
|
|
13710
|
+
/**
|
|
13711
|
+
* The JavaScript `code` with the line breaks of its multiline string and
|
|
13712
|
+
* template literals replaced by `sentinel`: re-indenting its lines then
|
|
13713
|
+
* leaves the literals' values as written.
|
|
13714
|
+
*/
|
|
13715
|
+
function joinJsLiterals(code, sentinel) {
|
|
13716
|
+
return joinSpans(code, multilineJsLiterals(code), sentinel);
|
|
13717
|
+
}
|
|
13718
|
+
/** `text` with the line breaks inside each of `spans` replaced by `sentinel`. */
|
|
13719
|
+
function joinSpans(text, spans, sentinel) {
|
|
13720
|
+
let out = "";
|
|
13721
|
+
let last = 0;
|
|
13722
|
+
for (const [a, b] of [...spans].sort((x, y) => x[0] - y[0])) {
|
|
13723
|
+
out += text.slice(last, a) + replaceAll(text.slice(a, b), "\n", sentinel);
|
|
13724
|
+
last = b;
|
|
13725
|
+
}
|
|
13726
|
+
return out + text.slice(last);
|
|
13727
|
+
}
|
|
13728
|
+
async function formatLf(text, options) {
|
|
13729
|
+
const { prettier, prettierOptions } = options;
|
|
13730
|
+
const body = text.replace(/(?:[ \t]*\n)+[ \t]*$/, "\n");
|
|
13731
|
+
if (options.kind === "script" || options.kind === "stylesheet") {
|
|
13732
|
+
const format = options.kind === "script" ? formatJS : formatCSS;
|
|
13733
|
+
const code = body.trim();
|
|
13734
|
+
return (await format(code, prettier, prettierOptions) ?? code).trim().replace(/\n*$/, "\n");
|
|
13735
|
+
}
|
|
13736
|
+
const isBlock = options.isBlock ?? defaultIsBlock(body, options.blockMacros);
|
|
13737
|
+
const isDedenting = options.isDedentingSubMacro ?? ((name) => DEFAULT_DEDENTING.has(name.toLowerCase()));
|
|
13738
|
+
const sentinel = newlineSentinel(body);
|
|
13739
|
+
const lines = [];
|
|
13740
|
+
/** Indices in lines whose trailing two spaces are a hard line break. */
|
|
13741
|
+
const hardBreakLines = /* @__PURE__ */ new Set();
|
|
13742
|
+
const regions = segmentRegions(protectMultilineTokens(body, sentinel));
|
|
13743
|
+
for (const region of regions) {
|
|
13744
|
+
if (region.type !== "spindle") region.lines = region.lines.map((l) => replaceAll(l, sentinel, "\n"));
|
|
13745
|
+
if (region.type === "script") {
|
|
13746
|
+
if (region.lines.length === 1) {
|
|
13747
|
+
lines.push(...region.lines);
|
|
13748
|
+
continue;
|
|
13749
|
+
}
|
|
13750
|
+
const innerCode = region.lines.slice(1, -1).join("\n");
|
|
13751
|
+
const formatted = await formatJS(innerCode.trim(), prettier, prettierOptions);
|
|
13752
|
+
if (formatted === void 0 || !sameSpindleTokens(innerCode, formatted)) {
|
|
13753
|
+
lines.push(...region.lines);
|
|
13754
|
+
continue;
|
|
13755
|
+
}
|
|
13756
|
+
lines.push(region.lines[0]);
|
|
13757
|
+
if (formatted.trim()) for (const fLine of joinJsLiterals(formatted.trim(), sentinel).split("\n")) lines.push(" " + fLine);
|
|
13758
|
+
lines.push(region.lines[region.lines.length - 1]);
|
|
13759
|
+
continue;
|
|
13760
|
+
}
|
|
13761
|
+
if (region.type === "svg") {
|
|
13762
|
+
lines.push(...region.lines);
|
|
13763
|
+
continue;
|
|
13764
|
+
}
|
|
13765
|
+
if (region.type === "html") {
|
|
13766
|
+
const htmlText = region.lines.join("\n");
|
|
13767
|
+
if (WHITESPACE_AS_WRITTEN.test(htmlText)) {
|
|
13768
|
+
lines.push(...region.lines);
|
|
13769
|
+
continue;
|
|
13770
|
+
}
|
|
13771
|
+
const { text: svgPlaceholdered, tokens: svgTokens } = replaceSvgBlocks(htmlText);
|
|
13772
|
+
const { text: placeholdered, tokens } = replaceSpindleTokens(svgPlaceholdered);
|
|
13773
|
+
const formatted = await formatHTML(placeholdered, prettier, prettierOptions);
|
|
13774
|
+
if (formatted === void 0 || !placeholdersIntact(formatted, tokens, SPINDLE_PLACEHOLDERS) || !placeholdersIntact(formatted, svgTokens, SVG_PLACEHOLDERS)) {
|
|
13775
|
+
lines.push(...region.lines);
|
|
13776
|
+
continue;
|
|
13777
|
+
}
|
|
13778
|
+
const restored = restoreSvgBlocks(restoreSpindleTokens(formatted.trim(), tokens.map((t) => replaceAll(t, "\n", sentinel))), svgTokens);
|
|
13779
|
+
for (const fLine of restored.split("\n")) lines.push(fLine);
|
|
13780
|
+
continue;
|
|
13781
|
+
}
|
|
13782
|
+
let indented = indentMacros(region.lines, isBlock, isDedenting);
|
|
13783
|
+
if (options.maxLineLength) indented = wrapLines(indented, options.maxLineLength);
|
|
13784
|
+
for (const line of indented) {
|
|
13785
|
+
if (line.endsWith(" ")) hardBreakLines.add(lines.length);
|
|
13786
|
+
lines.push(line);
|
|
13787
|
+
}
|
|
13788
|
+
}
|
|
13789
|
+
let output = lines.map((l, i) => hardBreakLines.has(i) ? l : l.replace(/\s+$/, "")).join("\n");
|
|
13790
|
+
output = output.replace(/\n*$/, "\n");
|
|
13791
|
+
return replaceAll(output, sentinel, "\n");
|
|
13792
|
+
}
|
|
13793
|
+
/** HTML whose whitespace renders as written: a `<pre>` or `<textarea>`, or a `white-space` style. */
|
|
13794
|
+
var WHITESPACE_AS_WRITTEN = /<(?:pre|textarea)[\s>]|white-space\s*:/i;
|
|
13795
|
+
/** A Markdown list item line (`- a`, `* a`, `+ a`, `1. a`, `1) a`). */
|
|
13796
|
+
var LIST_ITEM_REGEX = /^(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)/;
|
|
13797
|
+
/** A fenced code block delimiter. */
|
|
13798
|
+
var CODE_FENCE_REGEX = /^(?:`{3,}|~{3,})/;
|
|
13799
|
+
/**
|
|
13800
|
+
* Re-indent macro bodies by nesting depth.
|
|
13801
|
+
*
|
|
13802
|
+
* Each body is re-based so its least-indented line sits 2 spaces inside the
|
|
13803
|
+
* line that opened it. When the body contains Markdown whose meaning depends
|
|
13804
|
+
* on indentation (list items and their continuations, fenced code), every
|
|
13805
|
+
* line keeps its indentation relative to that base (top-level lines keep
|
|
13806
|
+
* their original indentation); otherwise all lines snap to the base, since
|
|
13807
|
+
* leading whitespace in Spindle's Markdown (indented code blocks are
|
|
13808
|
+
* disabled) is insignificant. Closing tags and dedenting sub-macros align
|
|
13809
|
+
* with their opening tag.
|
|
13810
|
+
*
|
|
13811
|
+
* Trailing whitespace is stripped, except that two or more trailing spaces
|
|
13812
|
+
* before a non-blank line (a Markdown hard line break) become exactly two.
|
|
13813
|
+
*/
|
|
13814
|
+
function indentMacros(lines, isBlock, isDedenting) {
|
|
13815
|
+
const macrosOnLine = macroTokensByLine(lines);
|
|
13816
|
+
const bodies = [{
|
|
13817
|
+
openLine: -1,
|
|
13818
|
+
minCol: Infinity,
|
|
13819
|
+
keepRelative: false
|
|
13820
|
+
}];
|
|
13821
|
+
const stack = [0];
|
|
13822
|
+
/** Per line: owning body, or the body it closes (`closes`), and its column. */
|
|
13823
|
+
const info = [];
|
|
13824
|
+
const openBody = (line) => {
|
|
13825
|
+
bodies.push({
|
|
13826
|
+
openLine: line,
|
|
13827
|
+
minCol: Infinity,
|
|
13828
|
+
keepRelative: false
|
|
13829
|
+
});
|
|
13830
|
+
stack.push(bodies.length - 1);
|
|
13831
|
+
};
|
|
13832
|
+
const currentBody = () => stack[stack.length - 1];
|
|
13833
|
+
const closeBody = () => stack.length > 1 ? stack.pop() : void 0;
|
|
13834
|
+
const addLine = (col, text) => {
|
|
13835
|
+
const body = bodies[currentBody()];
|
|
13836
|
+
body.minCol = Math.min(body.minCol, col);
|
|
13837
|
+
if (LIST_ITEM_REGEX.test(text) || CODE_FENCE_REGEX.test(text)) body.keepRelative = true;
|
|
13838
|
+
info.push({
|
|
13839
|
+
body: currentBody(),
|
|
13840
|
+
col,
|
|
13841
|
+
text
|
|
13842
|
+
});
|
|
13843
|
+
};
|
|
13844
|
+
for (let i = 0; i < lines.length; i++) {
|
|
13845
|
+
const lineText = lines[i];
|
|
13846
|
+
const trimmed = lineText.trim();
|
|
13847
|
+
if (trimmed === "") {
|
|
13848
|
+
info.push(null);
|
|
13849
|
+
continue;
|
|
13850
|
+
}
|
|
13851
|
+
const col = indentColumn(lineText);
|
|
13852
|
+
const lead = lineText.length - lineText.trimStart().length;
|
|
13853
|
+
const macros = macrosOnLine[i];
|
|
13854
|
+
const [first, ...rest] = macros;
|
|
13855
|
+
const startsWithMacro = first !== void 0 && first.start === lead;
|
|
13856
|
+
if (startsWithMacro && !first.isClose && isDedenting(first.name)) {
|
|
13857
|
+
const closed = closeBody();
|
|
13858
|
+
if (closed === void 0) addLine(col, trimmed);
|
|
13859
|
+
else info.push({
|
|
13860
|
+
body: currentBody(),
|
|
13861
|
+
closes: closed,
|
|
13862
|
+
col,
|
|
13863
|
+
text: trimmed
|
|
13864
|
+
});
|
|
13865
|
+
openBody(i);
|
|
13866
|
+
continue;
|
|
13867
|
+
}
|
|
13868
|
+
const closed = startsWithMacro && first.isClose ? closeBody() : void 0;
|
|
13869
|
+
if (closed === void 0) addLine(col, trimmed);
|
|
13870
|
+
else info.push({
|
|
13871
|
+
body: currentBody(),
|
|
13872
|
+
closes: closed,
|
|
13873
|
+
col,
|
|
13874
|
+
text: trimmed
|
|
13875
|
+
});
|
|
13876
|
+
if (startsWithMacro && !first.isClose && isBlock(first.name)) openBody(i);
|
|
13877
|
+
for (const macro of startsWithMacro ? rest : macros) if (macro.isClose && macro.start > lead) closeBody();
|
|
13878
|
+
}
|
|
13879
|
+
const outCol = [];
|
|
13880
|
+
const result = [];
|
|
13881
|
+
for (let i = 0; i < info.length; i++) {
|
|
13882
|
+
const line = info[i];
|
|
13883
|
+
if (!line) {
|
|
13884
|
+
outCol.push(0);
|
|
13885
|
+
result.push("");
|
|
13886
|
+
continue;
|
|
13887
|
+
}
|
|
13888
|
+
let col;
|
|
13889
|
+
if (line.closes !== void 0) col = outCol[bodies[line.closes].openLine];
|
|
13890
|
+
else {
|
|
13891
|
+
const body = bodies[line.body];
|
|
13892
|
+
const isRoot = body.openLine === -1;
|
|
13893
|
+
col = (isRoot ? 0 : outCol[body.openLine] + 2) + (body.keepRelative ? line.col - (isRoot ? 0 : body.minCol) : 0);
|
|
13894
|
+
}
|
|
13895
|
+
outCol.push(col);
|
|
13896
|
+
const hardBreak = / {2,}$/.test(lines[i]) && info[i + 1] ? " " : "";
|
|
13897
|
+
result.push(" ".repeat(col) + line.text + hardBreak);
|
|
13898
|
+
}
|
|
13899
|
+
return result;
|
|
13900
|
+
}
|
|
13901
|
+
/**
|
|
13902
|
+
* The macro tags on each of `lines`, as Spindle tokenizes the lines together
|
|
13903
|
+
* (`start` is the offset in the line). A tag spans one line here: the
|
|
13904
|
+
* multiline ones were joined onto their line.
|
|
13905
|
+
*/
|
|
13906
|
+
function macroTokensByLine(lines) {
|
|
13907
|
+
const byLine = lines.map(() => []);
|
|
13908
|
+
const starts = [];
|
|
13909
|
+
let offset = 0;
|
|
13910
|
+
for (const line of lines) {
|
|
13911
|
+
starts.push(offset);
|
|
13912
|
+
offset += line.length + 1;
|
|
13913
|
+
}
|
|
13914
|
+
let line = 0;
|
|
13915
|
+
for (const token of tokenizeMarkupTolerant(lines.join("\n")).tokens) {
|
|
13916
|
+
if (token.type !== "macro") continue;
|
|
13917
|
+
while (line + 1 < lines.length && starts[line + 1] <= token.start) line++;
|
|
13918
|
+
const lineStart = starts[line];
|
|
13919
|
+
byLine[line].push({
|
|
13920
|
+
...token,
|
|
13921
|
+
start: token.start - lineStart,
|
|
13922
|
+
end: token.end - lineStart
|
|
13923
|
+
});
|
|
13924
|
+
}
|
|
13925
|
+
return byLine;
|
|
13926
|
+
}
|
|
13927
|
+
/** Column of the first non-whitespace character, expanding tabs to 4-column stops. */
|
|
13928
|
+
function indentColumn(line) {
|
|
13929
|
+
let col = 0;
|
|
13930
|
+
for (const ch of line) if (ch === " ") col++;
|
|
13931
|
+
else if (ch === " ") col += 4 - col % 4;
|
|
13932
|
+
else break;
|
|
13933
|
+
return col;
|
|
13934
|
+
}
|
|
13935
|
+
/**
|
|
13936
|
+
* Wrap lines that exceed maxLen at word boundaries.
|
|
13937
|
+
* Preserves leading indentation. Skips pure macro lines and choice/link
|
|
13938
|
+
* lines, where wrapping would break syntax.
|
|
13939
|
+
*/
|
|
13940
|
+
function wrapLines(lines, maxLen) {
|
|
13941
|
+
const result = [];
|
|
13942
|
+
const javaScript = doBodyLines(lines);
|
|
13943
|
+
for (const [index, line] of lines.entries()) {
|
|
13944
|
+
if (line.length <= maxLen || javaScript.has(index)) {
|
|
13945
|
+
result.push(line);
|
|
13946
|
+
continue;
|
|
13947
|
+
}
|
|
13948
|
+
const trimmed = line.trim();
|
|
13949
|
+
if (trimmed === "" || /^\{[\/#.]/.test(trimmed) || /^\[\[/.test(trimmed) || /^\{choice\b/.test(trimmed) || /^\{choices\b/.test(trimmed)) {
|
|
13950
|
+
result.push(line);
|
|
13951
|
+
continue;
|
|
13952
|
+
}
|
|
13953
|
+
const wrapped = wordWrap(trimmed, maxLen, line.match(/^(\s*)/)?.[1] ?? "");
|
|
13954
|
+
if (line.endsWith(" ")) wrapped[wrapped.length - 1] += " ";
|
|
13955
|
+
result.push(...wrapped);
|
|
13956
|
+
}
|
|
13957
|
+
return result;
|
|
13958
|
+
}
|
|
13959
|
+
/** The indices of `lines` that hold part of a `{do}` body. */
|
|
13960
|
+
function doBodyLines(lines) {
|
|
13961
|
+
const found = /* @__PURE__ */ new Set();
|
|
13962
|
+
const text = lines.join("\n");
|
|
13963
|
+
for (const block of scanSpindleMarkup(text).doBlocks) {
|
|
13964
|
+
const first = text.slice(0, block.bodyStart).split("\n").length - 1;
|
|
13965
|
+
const last = text.slice(0, block.bodyEnd).split("\n").length - 1;
|
|
13966
|
+
for (let i = first; i <= last; i++) found.add(i);
|
|
13967
|
+
}
|
|
13968
|
+
return found;
|
|
13969
|
+
}
|
|
13970
|
+
/**
|
|
13971
|
+
* Wrap a single trimmed line at word boundaries, never inside a macro, an
|
|
13972
|
+
* interpolation or a link (as Spindle tokenizes the line).
|
|
13973
|
+
* Returns an array of lines with the given indent prefix applied.
|
|
13974
|
+
*/
|
|
13975
|
+
function wordWrap(text, maxLen, indent) {
|
|
13976
|
+
const lines = [];
|
|
13977
|
+
/** Whether the character is inside a token whose text must stay as written. */
|
|
13978
|
+
const inToken = new Array(text.length).fill(false);
|
|
13979
|
+
for (const token of tokenizeMarkupTolerant(text).tokens) {
|
|
13980
|
+
if (token.type === "text" || token.type === "html") continue;
|
|
13981
|
+
inToken.fill(true, token.start, token.end);
|
|
13982
|
+
}
|
|
13983
|
+
const room = maxLen - indent.length;
|
|
13984
|
+
let pos = 0;
|
|
13985
|
+
while (pos < text.length) {
|
|
13986
|
+
if (text.length - pos <= room) {
|
|
13987
|
+
lines.push(indent + text.slice(pos));
|
|
13988
|
+
break;
|
|
13989
|
+
}
|
|
13990
|
+
let breakIdx = -1;
|
|
13991
|
+
for (let i = pos + 1; i < text.length && i - pos <= room; i++) if (text[i] === " " && !inToken[i]) breakIdx = i;
|
|
13992
|
+
if (breakIdx === -1) {
|
|
13993
|
+
for (let i = pos + room + 1; i < text.length; i++) if (text[i] === " " && !inToken[i]) {
|
|
13994
|
+
breakIdx = i;
|
|
13995
|
+
break;
|
|
13996
|
+
}
|
|
13997
|
+
}
|
|
13998
|
+
if (breakIdx === -1) {
|
|
13999
|
+
lines.push(indent + text.slice(pos));
|
|
14000
|
+
break;
|
|
14001
|
+
}
|
|
14002
|
+
lines.push(indent + text.slice(pos, breakIdx));
|
|
14003
|
+
pos = breakIdx + 1;
|
|
14004
|
+
}
|
|
14005
|
+
return lines;
|
|
14006
|
+
}
|
|
14007
|
+
//#endregion
|
|
13239
14008
|
//#region src/components/macros/include-args.ts
|
|
13240
14009
|
/**
|
|
13241
14010
|
* The parameters of `{include}`. A standalone `inline` flag only counts
|
|
@@ -13385,8 +14154,15 @@ function blockLookup(macros) {
|
|
|
13385
14154
|
* The macros are those the markup may use, built-in and user-defined.
|
|
13386
14155
|
*/
|
|
13387
14156
|
function passagePieces(source, macros = []) {
|
|
14157
|
+
return passagePiecesOfTokens(source, macros, tokenizeMarkupTolerant(source).tokens);
|
|
14158
|
+
}
|
|
14159
|
+
/**
|
|
14160
|
+
* `passagePieces` for a caller that has the tokens of
|
|
14161
|
+
* `tokenizeMarkupTolerant(source)` already (the editor's highlighter). Not
|
|
14162
|
+
* part of the published tooling API.
|
|
14163
|
+
*/
|
|
14164
|
+
function passagePiecesOfTokens(source, macros, tokens) {
|
|
13388
14165
|
const all = [...macros];
|
|
13389
|
-
const { tokens } = tokenizeMarkupTolerant(source);
|
|
13390
14166
|
return [...passagePiecesOf(source, tokens, parameterLookup(all), { isBlock: blockLookup(all) })];
|
|
13391
14167
|
}
|
|
13392
14168
|
/**
|
|
@@ -13457,4 +14233,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
|
|
|
13457
14233
|
return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
|
|
13458
14234
|
}
|
|
13459
14235
|
//#endregion
|
|
13460
|
-
export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, discoverMacros, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, isBlockMacro, isSigil, lexJs, lexTemplate, pairMarkup, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
|
|
14236
|
+
export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, discoverMacros, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, lexJs, lexTemplate, pairMarkup, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
|