@rohal12/spindle 0.64.31 → 0.64.32

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/code-check.ts CHANGED
@@ -55,7 +55,11 @@ import {
55
55
  type PassageTarget,
56
56
  } from './components/macros/macro-args';
57
57
  import { subMacroParameters } from './components/macros/option-utils';
58
- import { readPassageBody, splitArgSpans } from './components/macros/arg-utils';
58
+ import {
59
+ readPassageBody,
60
+ readWholeQuoted,
61
+ splitArgSpans,
62
+ } from './components/macros/arg-utils';
59
63
  import { effectiveNamedDefinitions, NameMap } from './utils/macro-names';
60
64
  import { hasOwn } from './utils/namespace';
61
65
  import { isBuiltinBlockMacro, isRawMacro } from './markup/ast';
@@ -111,13 +115,14 @@ export interface PieceBase {
111
115
  * For the code or text of a quoted string with escapes (a `\"`), whose
112
116
  * characters are not where `offset` plus their index says: the offset of
113
117
  * each character in the source, and of the end of the text, so that
114
- * `sourceOffsets[i]` is where character `i` of `code` or `text` is. Absent
118
+ * `sourceOffsets[i]` is where character `i` of `code`, `text` or a passage
119
+ * `name` is. The final entry maps the end boundary. Absent
115
120
  * when `offset + i` is (see {@link pieceOffset}).
116
121
  */
117
122
  sourceOffsets?: readonly number[];
118
123
  }
119
124
 
120
- /** Where character `index` of the code or text of `piece` is in the source. */
125
+ /** Where boundary `index` of a piece's code, text or name is in the source. */
121
126
  export function pieceOffset(piece: PieceBase, index: number): number {
122
127
  return piece.sourceOffsets?.[index] ?? piece.offset + index;
123
128
  }
@@ -128,7 +133,9 @@ function extentOf(piece: Piece): number {
128
133
  ? piece.code.length
129
134
  : piece.kind === 'text'
130
135
  ? piece.text.length
131
- : piece.length;
136
+ : piece.kind === 'passage'
137
+ ? piece.name.length
138
+ : piece.length;
132
139
  }
133
140
 
134
141
  /** A piece found in a markup that is written out, for an error to point at. */
@@ -167,6 +174,12 @@ interface MacroPiece extends LabeledPiece {
167
174
  export interface PassagePiece extends MacroPiece {
168
175
  kind: 'passage';
169
176
  name: string;
177
+ /**
178
+ * Decoded name boundaries in the original source, including the end before
179
+ * closing quotes. Quotes/escapes do not change the whole-argument offset
180
+ * and length. Both UTF-16 units of a code-point escape map to its start.
181
+ */
182
+ sourceOffsets?: readonly number[];
170
183
  /** A known navigation target, rather than included/dialog content. */
171
184
  navigation?: true;
172
185
  }
@@ -530,13 +543,26 @@ export function* codeAndText(
530
543
  if (close > t + 1) {
531
544
  const text = src.slice(token.end, tokens[close]!.start);
532
545
  const written = text.trim();
546
+ const at = token.end + text.indexOf(written);
547
+ const nameValue = readPassageBody(written);
548
+ const sourceOffsets =
549
+ readWholeQuoted(written) !== null
550
+ ? escapeOffsets(
551
+ written.slice(1, -1),
552
+ at + 1,
553
+ nameValue,
554
+ 'quotes',
555
+ true,
556
+ )
557
+ : undefined;
533
558
  yield {
534
559
  kind: 'passage',
535
- name: readPassageBody(written),
536
- offset: token.end + text.indexOf(written),
560
+ name: nameValue,
561
+ offset: at,
537
562
  length: written.length,
538
563
  macro: name,
539
564
  label: src.slice(token.start, token.end),
565
+ ...(sourceOffsets && { sourceOffsets }),
540
566
  };
541
567
  }
542
568
  }
@@ -702,7 +728,7 @@ function nestedPiece(
702
728
  ): Piece {
703
729
  const offset = toRoot(piece.offset);
704
730
  const nested = { offset, nested: true as const, where };
705
- if (piece.kind === 'passage' || piece.kind === 'argument-error') {
731
+ if (piece.kind === 'argument-error') {
706
732
  const length = toRoot(piece.offset + piece.length) - offset;
707
733
  return { ...piece, ...nested, length };
708
734
  }
@@ -712,9 +738,15 @@ function nestedPiece(
712
738
  : toRoot(piece.offset + extent) - offset !== extent
713
739
  ? Array.from({ length: extent + 1 }, (_, i) => toRoot(piece.offset + i))
714
740
  : undefined;
715
- return sourceOffsets
741
+ const mapped = sourceOffsets
716
742
  ? { ...piece, ...nested, sourceOffsets }
717
743
  : { ...piece, ...nested };
744
+ return mapped.kind === 'passage'
745
+ ? {
746
+ ...mapped,
747
+ length: toRoot(piece.offset + mapped.length) - offset,
748
+ }
749
+ : mapped;
718
750
  }
719
751
 
720
752
  /** How the string of an argument is unescaped, which its escapes depend on. */
@@ -754,13 +786,15 @@ function escapeAt(
754
786
  * written as `raw` from `at` on (its escapes are those of `escapes`), is in
755
787
  * the source, and where the text ends. A character that an escape stands for
756
788
  * is where the escape begins. None when the text is where its length says, or
757
- * is not that string.
789
+ * is not that string. With `includeLinear`, return the map even without
790
+ * escapes (a passage piece's offset includes the opening quote).
758
791
  */
759
792
  export function escapeOffsets(
760
793
  raw: string,
761
794
  at: number,
762
795
  value: string,
763
796
  escapes: Escapes,
797
+ includeLinear = false,
764
798
  ): number[] | undefined {
765
799
  const offsets: number[] = [];
766
800
  let escaped = false;
@@ -778,8 +812,16 @@ export function escapeOffsets(
778
812
  escaped = true;
779
813
  i += escape.length;
780
814
  }
815
+ // A trailing line continuation emits no character but still moves the
816
+ // decoded string's end boundary to the closing quote.
817
+ while (raw[i] === '\\') {
818
+ const escape = escapeAt(raw, i, escapes);
819
+ if (!escape || escape.text.length !== 0) break;
820
+ escaped = true;
821
+ i += escape.length;
822
+ }
781
823
  offsets.push(at + i);
782
- return escaped ? offsets : undefined;
824
+ return escaped || includeLinear ? offsets : undefined;
783
825
  }
784
826
 
785
827
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
@@ -894,13 +936,24 @@ function* valuePieces(
894
936
  const [start, end] = span;
895
937
  const written = args.slice(start, end);
896
938
  /** The name as written (quotes included), at the argument. */
897
- const passage = (passageName: string): PassagePiece => ({
939
+ const passage = (
940
+ passageName: string,
941
+ at: number,
942
+ mode: Escapes = escapes,
943
+ ): PassagePiece => ({
898
944
  kind: 'passage',
899
945
  name: passageName,
900
946
  offset: offset + start,
901
947
  length: end - start,
902
948
  macro: name,
903
949
  label,
950
+ sourceOffsets: escapeOffsets(
951
+ args.slice(at - offset),
952
+ at,
953
+ passageName,
954
+ mode,
955
+ true,
956
+ ),
904
957
  ...(navigation.includes(param.name) && { navigation: true as const }),
905
958
  });
906
959
  const goal = codeGoal(param);
@@ -908,7 +961,7 @@ function* valuePieces(
908
961
  // A name written out, else an expression naming one
909
962
  const target = passageTarget(value);
910
963
  if (target.kind === 'name') {
911
- yield passage(target.name);
964
+ yield passage(target.name, offset + start + 1, 'javascript');
912
965
  continue;
913
966
  }
914
967
  }
@@ -949,7 +1002,7 @@ function* valuePieces(
949
1002
  if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
950
1003
  yield piece;
951
1004
  } else if (holds === 'passage') {
952
- yield passage(value);
1005
+ yield passage(value, at);
953
1006
  } else if (holds === 'markup') {
954
1007
  const piece = textPiece(
955
1008
  value,
@@ -13,12 +13,16 @@ defineMacro({
13
13
  render(_props, ctx) {
14
14
  const label = ctx.args.label ?? '';
15
15
 
16
- const action = useVariableAction(ctx, {
17
- type: 'checkbox',
18
- label: label || ctx.varName || '',
19
- value: !!ctx.value,
20
- perform: (v) => ctx.setValue!(v !== undefined ? !!v : !ctx.getValue!()),
21
- });
16
+ const action = useVariableAction(
17
+ ctx,
18
+ {
19
+ type: 'checkbox',
20
+ label: label || ctx.varName || '',
21
+ value: !!ctx.value,
22
+ perform: (v) => ctx.setValue!(v !== undefined ? !!v : !ctx.getValue!()),
23
+ },
24
+ (control) => (control as HTMLInputElement).checked,
25
+ );
22
26
 
23
27
  return (
24
28
  <label
@@ -13,14 +13,18 @@ defineMacro({
13
13
  render({ children = [] }, ctx) {
14
14
  const options = ctx.extractOptions(children);
15
15
 
16
- const action = useVariableAction(ctx, {
17
- type: 'listbox',
18
- label: ctx.varName!,
19
- options,
20
- perform: (v) => {
21
- if (v !== undefined) ctx.setValue!(String(v));
16
+ const action = useVariableAction(
17
+ ctx,
18
+ {
19
+ type: 'listbox',
20
+ label: ctx.varName!,
21
+ options,
22
+ perform: (v) => {
23
+ if (v !== undefined) ctx.setValue!(String(v));
24
+ },
22
25
  },
23
- });
26
+ (control) => control.value,
27
+ );
24
28
 
25
29
  return (
26
30
  <select
@@ -17,13 +17,32 @@ defineMacro({
17
17
  const label = ctx.args.label ?? '';
18
18
  // One group per variable in each view (see ViewScopeContext)
19
19
  const view = ctx.hooks.useContext(ViewScopeContext);
20
+ const initialValue = ctx.hooks.useRef(ctx.value);
20
21
 
21
- const action = useVariableAction(ctx, {
22
- type: 'radiobutton',
23
- key: `$${ctx.varName}:${radioValue}`,
24
- label: label || radioValue,
25
- perform: () => ctx.setValue!(radioValue),
26
- });
22
+ const action = useVariableAction(
23
+ ctx,
24
+ {
25
+ type: 'radiobutton',
26
+ key: `$${ctx.varName}:${radioValue}`,
27
+ label: label || radioValue,
28
+ perform: () => ctx.setValue!(radioValue),
29
+ },
30
+ (control) => {
31
+ const radio = control as HTMLInputElement;
32
+ const group = radio.form?.elements.namedItem(radio.name) as
33
+ RadioNodeList | HTMLInputElement | null;
34
+ const selected =
35
+ group &&
36
+ ('length' in group
37
+ ? (Array.from(group).find(
38
+ (node) => (node as HTMLInputElement).checked,
39
+ ) as HTMLInputElement | undefined)
40
+ : group.checked
41
+ ? group
42
+ : undefined);
43
+ return selected ? selected.value : initialValue.current;
44
+ },
45
+ );
27
46
 
28
47
  return (
29
48
  <label
@@ -1,5 +1,8 @@
1
1
  import { h } from 'preact';
2
+ import { useCallback, useLayoutEffect, useRef, useState } from 'preact/hooks';
2
3
  import { defineMacro, type MacroContext } from '../../define-macro';
4
+ import { useStoryStore } from '../../store';
5
+ import { subscribeVariableWrites } from '../../utils/variable-writes';
3
6
  import {
4
7
  actionAttributes,
5
8
  useControlAction,
@@ -14,24 +17,195 @@ export const VARIABLE_PARAMETER = {
14
17
  required: true,
15
18
  } as const;
16
19
 
20
+ type FormControl = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
21
+
22
+ interface ResetReader {
23
+ element: FormControl;
24
+ prepare: () => {
25
+ read: (snapshot: FormControl) => () => void;
26
+ off: () => void;
27
+ };
28
+ }
29
+ const formResets = new WeakMap<
30
+ HTMLFormElement,
31
+ {
32
+ readers: Set<ResetReader>;
33
+ reset: (event: Event) => void;
34
+ }
35
+ >();
36
+
37
+ /** Read every reset value before any binding write can trigger a rerender. */
38
+ function subscribeFormReset(
39
+ form: HTMLFormElement,
40
+ read: ResetReader,
41
+ ): () => void {
42
+ let subscription = formResets.get(form);
43
+ if (!subscription) {
44
+ const readers = new Set<ResetReader>();
45
+ const reset = (event: Event) => {
46
+ const pending = Array.from(readers, (reader) => ({
47
+ reader,
48
+ ...reader.prepare(),
49
+ }));
50
+ // Trusted reset events can run microtasks before their default action.
51
+ // A task sees the native values and the final cancellation state.
52
+ setTimeout(() => {
53
+ for (const { off } of pending) off();
54
+ if (event.defaultPrevented) return;
55
+ // An unrelated store write can already have rerendered the live
56
+ // controls. Let a detached form recover their native defaults,
57
+ // including number sanitization, select fallback and radio groups.
58
+ const snapshot = form.ownerDocument.createElement('form');
59
+ const restoreDefaults = snapshot.reset.bind(snapshot);
60
+ const controls = pending.map(({ reader, read }) => {
61
+ const element = reader.element.cloneNode(true) as FormControl;
62
+ element.removeAttribute('form');
63
+ snapshot.appendChild(element);
64
+ return { read, element };
65
+ });
66
+ restoreDefaults();
67
+ const commits = controls.map(({ read, element }) => read(element));
68
+ for (const commit of commits) commit();
69
+ }, 0);
70
+ };
71
+ subscription = { readers, reset };
72
+ formResets.set(form, subscription);
73
+ form.addEventListener('reset', subscription.reset);
74
+ }
75
+ const { readers, reset } = subscription;
76
+ readers.add(read);
77
+ return () => {
78
+ readers.delete(read);
79
+ if (readers.size === 0) {
80
+ form.removeEventListener('reset', reset);
81
+ formResets.delete(form);
82
+ }
83
+ };
84
+ }
85
+
86
+ /** Native defaults belong to the binding's initial rendered control value. */
87
+ function setResetDefault(control: FormControl): void {
88
+ if (control.tagName === 'SELECT') {
89
+ const options = Array.from((control as HTMLSelectElement).options);
90
+ const selected = options.map((option) => option.selected);
91
+ options.forEach((option, i) => (option.defaultSelected = selected[i]!));
92
+ } else if (
93
+ control.tagName === 'INPUT' &&
94
+ ['checkbox', 'radio'].includes((control as HTMLInputElement).type)
95
+ ) {
96
+ (control as HTMLInputElement).defaultChecked = (
97
+ control as HTMLInputElement
98
+ ).checked;
99
+ } else {
100
+ (control as HTMLInputElement | HTMLTextAreaElement).defaultValue =
101
+ control.value;
102
+ }
103
+ }
104
+
17
105
  /**
18
106
  * Register the automation action of a macro bound to a story variable: keyed
19
107
  * by the variable (or `key`), with the variable's value unless `action`
20
108
  * gives another.
21
109
  */
22
110
  export function useVariableAction(
23
- ctx: Pick<MacroContext, 'id' | 'varName' | 'value'>,
111
+ ctx: Pick<MacroContext, 'id' | 'varName' | 'value' | 'setValue' | 'getValue'>,
24
112
  action: Omit<UseActionOptions, 'key' | 'authorId' | 'variable'> & {
25
113
  key?: string;
26
114
  },
115
+ onReset?: (control: FormControl) => unknown,
27
116
  ): ReturnType<typeof useControlAction> {
28
- return useControlAction({
117
+ const registered = useControlAction({
29
118
  key: `$${ctx.varName}`,
30
119
  authorId: ctx.id,
31
120
  variable: ctx.varName,
32
121
  value: ctx.value,
33
122
  ...action,
34
123
  });
124
+ const control = useRef<FormControl | null>(null);
125
+ const [, refresh] = useState(0);
126
+ const initialized = useRef<FormControl | null>(null);
127
+ const subscription = useRef<{
128
+ element: FormControl;
129
+ form: HTMLFormElement;
130
+ off: () => void;
131
+ } | null>(null);
132
+ const resetValue = useRef({
133
+ read: onReset,
134
+ set: ctx.setValue,
135
+ get: ctx.getValue,
136
+ name: ctx.varName,
137
+ });
138
+ resetValue.current = {
139
+ read: onReset,
140
+ set: ctx.setValue,
141
+ get: ctx.getValue,
142
+ name: ctx.varName,
143
+ };
144
+ const ref = useCallback(
145
+ (element: Element | null) => {
146
+ control.current = element as FormControl | null;
147
+ registered.ref(element);
148
+ },
149
+ [registered.ref],
150
+ );
151
+ // Reattach after commits in case the control's form owner changed.
152
+ useLayoutEffect(() => {
153
+ const element = control.current;
154
+ const form = element?.form;
155
+ if (
156
+ subscription.current?.element === element &&
157
+ subscription.current?.form === form
158
+ )
159
+ return;
160
+ subscription.current?.off();
161
+ subscription.current = null;
162
+ if (!element || !onReset) return;
163
+ if (initialized.current !== element) {
164
+ setResetDefault(element);
165
+ initialized.current = element;
166
+ }
167
+ if (!form) return;
168
+ subscription.current = {
169
+ element,
170
+ form,
171
+ off: subscribeFormReset(form, {
172
+ element,
173
+ prepare: () => {
174
+ const before = resetValue.current.get!();
175
+ let changed = false;
176
+ const offWrite = subscribeVariableWrites(
177
+ resetValue.current.name!.split('.'),
178
+ () => (changed = true),
179
+ );
180
+ const offStore = useStoryStore.subscribe(() => {
181
+ changed ||= !Object.is(resetValue.current.get!(), before);
182
+ });
183
+ return {
184
+ off: () => {
185
+ offWrite();
186
+ offStore();
187
+ },
188
+ read: (snapshot) => {
189
+ // Decide before any reset commits, including other controls of
190
+ // this binding. No-op writes and changes away and back count too.
191
+ const value = changed
192
+ ? undefined
193
+ : resetValue.current.read!(snapshot);
194
+ return () => {
195
+ if (control.current !== element || element.form !== form)
196
+ return;
197
+ // A trusted reset may have undone a handler's earlier render.
198
+ if (changed) refresh((version) => version + 1);
199
+ else resetValue.current.set!(value);
200
+ };
201
+ },
202
+ };
203
+ },
204
+ }),
205
+ };
206
+ });
207
+ useLayoutEffect(() => () => subscription.current?.off(), []);
208
+ return { ...registered, ref };
35
209
  }
36
210
 
37
211
  /**
@@ -56,13 +230,7 @@ export function defineInputMacro(
56
230
  { name: 'placeholder', type: 'string', holds: 'text' },
57
231
  ],
58
232
  render(_props, ctx) {
59
- const placeholder = ctx.args.placeholder ?? '';
60
-
61
- const action = useVariableAction(ctx, {
62
- type: name,
63
- label: placeholder || ctx.varName!,
64
- perform: (v) => ctx.setValue!(toValue(v)),
65
- });
233
+ const { placeholder = '' } = ctx.args;
66
234
 
67
235
  // What the reader last typed. A number input reports an unfinished
68
236
  // number ("-", "2e") as an empty value, so the text is kept for as
@@ -76,6 +244,19 @@ export function defineInputMacro(
76
244
  ? typed.current
77
245
  : display(ctx.value);
78
246
 
247
+ const action = useVariableAction(
248
+ ctx,
249
+ {
250
+ type: name,
251
+ label: placeholder || ctx.varName!,
252
+ perform: (v) => ctx.setValue!(toValue(v)),
253
+ },
254
+ (control) => {
255
+ typed.current = control.value;
256
+ return toValue(control.value);
257
+ },
258
+ );
259
+
79
260
  return h(type ? 'input' : 'textarea', {
80
261
  type,
81
262
  ...actionAttributes(action, ctx),
@@ -278,17 +278,36 @@ function readGroup(
278
278
  let [text, at] = trimmed(src ?? '', srcAt);
279
279
  // A lone word is the passage of {include inline}, not its flag
280
280
  const alone = !params.some((p) => p.type !== 'flag' && p.required);
281
- for (const flag of params.filter((p) => p.type === 'flag')) {
282
- const rest = src === null ? null : takeFlag(text, flag.name, alone);
283
- args[flag.name] = rest !== null;
284
- if (rest) {
285
- const flagSpan: Span =
286
- rest[0] > 0
287
- ? [0, text.indexOf(flag.name) + flag.name.length]
288
- : [text.lastIndexOf(flag.name), text.length];
289
- toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
290
- [text, at] = trimmed(slice(text, rest), at + rest[0]);
281
+ const flags = params.filter((p) => p.type === 'flag');
282
+ for (const flag of flags) args[flag.name] = false;
283
+ const byName = new Map(flags.map((flag) => [flag.name, flag]));
284
+ // Consume from the boundaries in source order, independently of declaration
285
+ // order. Prefer the trailing flag when a required lone argument must remain.
286
+ while (text && byName.size) {
287
+ const parts = terms(text);
288
+ if (parts.length === 0) break;
289
+ let changed = false;
290
+ for (const name of [
291
+ slice(text, parts[parts.length - 1]!),
292
+ slice(text, parts[0]!),
293
+ ]) {
294
+ const flag = byName.get(name);
295
+ if (!flag || args[flag.name]) continue;
296
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
297
+ if (rest) {
298
+ args[flag.name] = true;
299
+ byName.delete(flag.name);
300
+ changed = true;
301
+ const flagSpan: Span =
302
+ rest[0] > 0
303
+ ? [0, text.indexOf(flag.name) + flag.name.length]
304
+ : [text.lastIndexOf(flag.name), text.length];
305
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
306
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
307
+ break;
308
+ }
291
309
  }
310
+ if (!changed) break;
292
311
  }
293
312
  const positional = params.filter((p) => p.type !== 'flag');
294
313
  if (positional.length === 0) return;
@@ -47,6 +47,7 @@ import {
47
47
  displayOnlyError,
48
48
  } from './display-only';
49
49
  import { NameSet } from './utils/macro-names';
50
+ import { notifyVariableWrite } from './utils/variable-writes';
50
51
  import {
51
52
  checkParameterTypes,
52
53
  registerMacro,
@@ -254,6 +255,7 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
254
255
  ctx.setValue = displayOnly
255
256
  ? refuse
256
257
  : (value: unknown) => {
258
+ notifyVariableWrite(segments);
257
259
  // The commit mutation code uses, which keeps the references among
258
260
  // variables: a write to a draft copies only the path written, and
259
261
  // other variables sharing the object would keep the old one.
@@ -189,6 +189,17 @@ function joinSpans(
189
189
  return out + text.slice(last);
190
190
  }
191
191
 
192
+ /** Collapse the trailing blank lines without probing every whitespace suffix. */
193
+ function trimBlankLines(text: string): string {
194
+ let end = text.length;
195
+ let newline = false;
196
+ while (end > 0 && /[ \t\n]/.test(text[end - 1]!)) {
197
+ newline ||= text[end - 1] === '\n';
198
+ end--;
199
+ }
200
+ return newline ? text.slice(0, end) + '\n' : text;
201
+ }
202
+
192
203
  async function formatLf(
193
204
  text: string,
194
205
  options: PassageFormatOptions,
@@ -201,7 +212,7 @@ async function formatLf(
201
212
  const format = options.kind === 'script' ? formatJS : formatCSS;
202
213
  const code = body.trim();
203
214
  const formatted = await format(code, prettier, prettierOptions);
204
- return (formatted ?? code).trim().replace(/\n*$/, '\n');
215
+ return (formatted ?? code).trim() + '\n';
205
216
  }
206
217
 
207
218
  const isBlock = options.isBlock ?? defaultIsBlock(body, options.blockMacros);
@@ -217,17 +228,18 @@ async function formatLf(
217
228
  const literalMarkers = new Set<string>();
218
229
  const fenced = markdownLines(body, isBlock, new Set(['codeFenced']));
219
230
  const literalHtml = whitespaceSensitiveLines(body, isBlock);
220
- body = body
221
- .split('\n')
222
- .map((line, index) => {
223
- if (!fenced.has(index) && !literalHtml.has(index)) return line;
224
- const marker = `${literalSentinel}L${literalLines.size}${literalSentinel}`;
225
- literalLines.set(marker, line);
226
- literalMarkers.add(marker);
227
- return (line.match(/^[ \t]*/)?.[0] ?? '') + marker;
228
- })
229
- .join('\n')
230
- .replace(/(?:[ \t]*\n)+[ \t]*$/, '\n');
231
+ body = trimBlankLines(
232
+ body
233
+ .split('\n')
234
+ .map((line, index) => {
235
+ if (!fenced.has(index) && !literalHtml.has(index)) return line;
236
+ const marker = `${literalSentinel}L${literalLines.size}${literalSentinel}`;
237
+ literalLines.set(marker, line);
238
+ literalMarkers.add(marker);
239
+ return (line.match(/^[ \t]*/)?.[0] ?? '') + marker;
240
+ })
241
+ .join('\n'),
242
+ );
231
243
  const lines: string[] = [];
232
244
  /** Indices in lines whose trailing two spaces are a hard line break. */
233
245
  const hardBreakLines = new Set<number>();
@@ -359,12 +371,12 @@ async function formatLf(
359
371
  // normalized by indentMacros) and ensure single trailing newline
360
372
  let output = lines
361
373
  .map((l, i) =>
362
- hardBreakLines.has(i) || preservedLines.has(i)
363
- ? l
364
- : l.replace(/\s+$/, ''),
374
+ hardBreakLines.has(i) || preservedLines.has(i) ? l : l.trimEnd(),
365
375
  )
366
376
  .join('\n');
367
- output = output.replace(/\n*$/, '\n');
377
+ let end = output.length;
378
+ while (end > 0 && output[end - 1] === '\n') end--;
379
+ output = output.slice(0, end) + '\n';
368
380
 
369
381
  return replaceAll(
370
382
  output
@@ -613,7 +625,7 @@ function indentMacros(
613
625
  (body.keepRelative ? line.col - (isRoot ? 0 : body.minCol) : 0);
614
626
  }
615
627
  outCol.push(col);
616
- const hardBreak = / {2,}$/.test(lines[i]!) && info[i + 1] ? ' ' : '';
628
+ const hardBreak = lines[i]!.endsWith(' ') && info[i + 1] ? ' ' : '';
617
629
  result.push(' '.repeat(col) + line.text + hardBreak);
618
630
  }
619
631