@driftsys/markspec 0.11.0 → 0.12.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.
Files changed (176) hide show
  1. package/README.md +9 -0
  2. package/esm/ast/normalize.d.ts +4 -5
  3. package/esm/ast/normalize.d.ts.map +1 -1
  4. package/esm/ast/normalize.js +6 -37
  5. package/esm/collect/mod.d.ts +29 -9
  6. package/esm/collect/mod.d.ts.map +1 -1
  7. package/esm/collect/mod.js +36 -10
  8. package/esm/compiler/mod.d.ts.map +1 -1
  9. package/esm/compiler/mod.js +2 -6
  10. package/esm/config/markspec.d.ts +5 -3
  11. package/esm/config/markspec.d.ts.map +1 -1
  12. package/esm/config/mod.d.ts.map +1 -1
  13. package/esm/config/mod.js +47 -5
  14. package/esm/discovery/mod.d.ts +24 -8
  15. package/esm/discovery/mod.d.ts.map +1 -1
  16. package/esm/discovery/mod.js +57 -21
  17. package/esm/discovery/projects.d.ts +111 -0
  18. package/esm/discovery/projects.d.ts.map +1 -0
  19. package/esm/discovery/projects.js +242 -0
  20. package/esm/formatter/entry_body.d.ts +84 -0
  21. package/esm/formatter/entry_body.d.ts.map +1 -0
  22. package/esm/formatter/entry_body.js +291 -0
  23. package/esm/formatter/md_equiv.d.ts +6 -5
  24. package/esm/formatter/md_equiv.d.ts.map +1 -1
  25. package/esm/formatter/md_equiv.js +6 -5
  26. package/esm/formatter/mod.d.ts +16 -9
  27. package/esm/formatter/mod.d.ts.map +1 -1
  28. package/esm/formatter/mod.js +327 -53
  29. package/esm/formatter/tab_markers.d.ts +15 -0
  30. package/esm/formatter/tab_markers.d.ts.map +1 -0
  31. package/esm/formatter/tab_markers.js +133 -0
  32. package/esm/gates/mod.d.ts.map +1 -1
  33. package/esm/gates/mod.js +6 -5
  34. package/esm/lint/runner.d.ts.map +1 -1
  35. package/esm/lint/runner.js +4 -4
  36. package/esm/lock/check.d.ts.map +1 -1
  37. package/esm/lock/check.js +2 -1
  38. package/esm/lock/edge_drift.d.ts +2 -0
  39. package/esm/lock/edge_drift.d.ts.map +1 -1
  40. package/esm/lock/edge_drift.js +4 -0
  41. package/esm/lock/mod.d.ts +1 -1
  42. package/esm/lock/mod.d.ts.map +1 -1
  43. package/esm/lock/mod.js +1 -1
  44. package/esm/lock/upstream_deps.js +1 -1
  45. package/esm/mod.d.ts +11 -6
  46. package/esm/mod.d.ts.map +1 -1
  47. package/esm/mod.js +9 -6
  48. package/esm/model/mod.d.ts +22 -1
  49. package/esm/model/mod.d.ts.map +1 -1
  50. package/esm/model/mod.js +10 -0
  51. package/esm/parser/code_regions.d.ts +29 -0
  52. package/esm/parser/code_regions.d.ts.map +1 -0
  53. package/esm/parser/code_regions.js +38 -0
  54. package/esm/parser/markdown.d.ts.map +1 -1
  55. package/esm/parser/markdown.js +103 -40
  56. package/esm/parser/mod.d.ts.map +1 -1
  57. package/esm/parser/mod.js +7 -1
  58. package/esm/parser/translate.d.ts.map +1 -1
  59. package/esm/parser/translate.js +5 -0
  60. package/esm/refs/mod.d.ts +6 -2
  61. package/esm/refs/mod.d.ts.map +1 -1
  62. package/esm/refs/mod.js +15 -21
  63. package/esm/reporter/mod.d.ts.map +1 -1
  64. package/esm/reporter/mod.js +2 -2
  65. package/esm/sync/mapping.d.ts +4 -3
  66. package/esm/sync/mapping.d.ts.map +1 -1
  67. package/esm/sync/mapping.js +52 -9
  68. package/esm/util/display_id.d.ts +20 -0
  69. package/esm/util/display_id.d.ts.map +1 -0
  70. package/esm/util/display_id.js +19 -0
  71. package/esm/util/fence.d.ts +20 -29
  72. package/esm/util/fence.d.ts.map +1 -1
  73. package/esm/util/fence.js +42 -50
  74. package/esm/util/modals.d.ts +6 -0
  75. package/esm/util/modals.d.ts.map +1 -1
  76. package/esm/util/modals.js +37 -0
  77. package/esm/validator/body_blocks.d.ts +2 -1
  78. package/esm/validator/body_blocks.d.ts.map +1 -1
  79. package/esm/validator/body_blocks.js +80 -2
  80. package/esm/validator/corpus.d.ts +6 -0
  81. package/esm/validator/corpus.d.ts.map +1 -1
  82. package/esm/validator/corpus.js +16 -4
  83. package/esm/validator/mod.d.ts +1 -1
  84. package/esm/validator/mod.d.ts.map +1 -1
  85. package/esm/validator/mod.js +1 -1
  86. package/esm/validator/pipeline.d.ts +6 -4
  87. package/esm/validator/pipeline.d.ts.map +1 -1
  88. package/esm/validator/pipeline.js +24 -19
  89. package/package.json +1 -1
  90. package/script/ast/normalize.d.ts +4 -5
  91. package/script/ast/normalize.d.ts.map +1 -1
  92. package/script/ast/normalize.js +5 -36
  93. package/script/collect/mod.d.ts +29 -9
  94. package/script/collect/mod.d.ts.map +1 -1
  95. package/script/collect/mod.js +38 -10
  96. package/script/compiler/mod.d.ts.map +1 -1
  97. package/script/compiler/mod.js +1 -5
  98. package/script/config/markspec.d.ts +5 -3
  99. package/script/config/markspec.d.ts.map +1 -1
  100. package/script/config/mod.d.ts.map +1 -1
  101. package/script/config/mod.js +47 -5
  102. package/script/discovery/mod.d.ts +24 -8
  103. package/script/discovery/mod.d.ts.map +1 -1
  104. package/script/discovery/mod.js +56 -20
  105. package/script/discovery/projects.d.ts +111 -0
  106. package/script/discovery/projects.d.ts.map +1 -0
  107. package/script/discovery/projects.js +250 -0
  108. package/script/formatter/entry_body.d.ts +84 -0
  109. package/script/formatter/entry_body.d.ts.map +1 -0
  110. package/script/formatter/entry_body.js +296 -0
  111. package/script/formatter/md_equiv.d.ts +6 -5
  112. package/script/formatter/md_equiv.d.ts.map +1 -1
  113. package/script/formatter/md_equiv.js +6 -5
  114. package/script/formatter/mod.d.ts +16 -9
  115. package/script/formatter/mod.d.ts.map +1 -1
  116. package/script/formatter/mod.js +324 -50
  117. package/script/formatter/tab_markers.d.ts +15 -0
  118. package/script/formatter/tab_markers.d.ts.map +1 -0
  119. package/script/formatter/tab_markers.js +141 -0
  120. package/script/gates/mod.d.ts.map +1 -1
  121. package/script/gates/mod.js +15 -14
  122. package/script/lint/runner.d.ts.map +1 -1
  123. package/script/lint/runner.js +3 -3
  124. package/script/lock/check.d.ts.map +1 -1
  125. package/script/lock/check.js +2 -1
  126. package/script/lock/edge_drift.d.ts +2 -0
  127. package/script/lock/edge_drift.d.ts.map +1 -1
  128. package/script/lock/edge_drift.js +5 -0
  129. package/script/lock/mod.d.ts +1 -1
  130. package/script/lock/mod.d.ts.map +1 -1
  131. package/script/lock/mod.js +2 -1
  132. package/script/lock/upstream_deps.js +1 -1
  133. package/script/mod.d.ts +11 -6
  134. package/script/mod.d.ts.map +1 -1
  135. package/script/mod.js +23 -5
  136. package/script/model/mod.d.ts +22 -1
  137. package/script/model/mod.d.ts.map +1 -1
  138. package/script/model/mod.js +11 -0
  139. package/script/parser/code_regions.d.ts +29 -0
  140. package/script/parser/code_regions.d.ts.map +1 -0
  141. package/script/parser/code_regions.js +41 -0
  142. package/script/parser/markdown.d.ts.map +1 -1
  143. package/script/parser/markdown.js +102 -39
  144. package/script/parser/mod.d.ts.map +1 -1
  145. package/script/parser/mod.js +7 -1
  146. package/script/parser/translate.d.ts.map +1 -1
  147. package/script/parser/translate.js +5 -0
  148. package/script/refs/mod.d.ts +6 -2
  149. package/script/refs/mod.d.ts.map +1 -1
  150. package/script/refs/mod.js +14 -20
  151. package/script/reporter/mod.d.ts.map +1 -1
  152. package/script/reporter/mod.js +1 -1
  153. package/script/sync/mapping.d.ts +4 -3
  154. package/script/sync/mapping.d.ts.map +1 -1
  155. package/script/sync/mapping.js +52 -9
  156. package/script/util/display_id.d.ts +20 -0
  157. package/script/util/display_id.d.ts.map +1 -0
  158. package/script/util/display_id.js +22 -0
  159. package/script/util/fence.d.ts +20 -29
  160. package/script/util/fence.d.ts.map +1 -1
  161. package/script/util/fence.js +47 -54
  162. package/script/util/modals.d.ts +6 -0
  163. package/script/util/modals.d.ts.map +1 -1
  164. package/script/util/modals.js +38 -0
  165. package/script/validator/body_blocks.d.ts +2 -1
  166. package/script/validator/body_blocks.d.ts.map +1 -1
  167. package/script/validator/body_blocks.js +80 -2
  168. package/script/validator/corpus.d.ts +6 -0
  169. package/script/validator/corpus.d.ts.map +1 -1
  170. package/script/validator/corpus.js +16 -3
  171. package/script/validator/mod.d.ts +1 -1
  172. package/script/validator/mod.d.ts.map +1 -1
  173. package/script/validator/mod.js +2 -1
  174. package/script/validator/pipeline.d.ts +6 -4
  175. package/script/validator/pipeline.d.ts.map +1 -1
  176. package/script/validator/pipeline.js +24 -19
@@ -33,6 +33,8 @@ const render_js_1 = require("../ast/render.js");
33
33
  const normalize_js_1 = require("../ast/normalize.js");
34
34
  const equivalence_js_1 = require("../ast/equivalence.js");
35
35
  const prose_js_1 = require("./prose.js");
36
+ const entry_body_js_1 = require("./entry_body.js");
37
+ const tab_markers_js_1 = require("./tab_markers.js");
36
38
  const dprint_js_1 = require("./dprint.js");
37
39
  const md_equiv_js_1 = require("./md_equiv.js");
38
40
  /**
@@ -54,7 +56,7 @@ function isSentenceInitial(line, offset) {
54
56
  *
55
57
  * The pass skips:
56
58
  *
57
- * - Fenced code blocks (between paired ``` or ~~~ markers) — code is
59
+ * - CommonMark fenced code blocks and inline-code spans — code is
58
60
  * verbatim per round-trip invariants (spec §5.1).
59
61
  * - Lines indented by four or more spaces (or a tab) — conservatively
60
62
  * captures indented code blocks and attribute trailers, both of which
@@ -63,21 +65,12 @@ function isSentenceInitial(line, offset) {
63
65
  * @remarks Not called by `format()` as of SP3 Task 5 — body modal
64
66
  * normalization moved to `normalizeBodyAst` in the AST pass (spec-correct
65
67
  * verbatim-boundary handling). Retained as an exported symbol because
66
- * `mod_test.ts` tests it directly and `core/ast/normalize.ts` documents
67
- * the intentional duplication until a follow-up collapses the two. Do NOT
68
+ * `mod_test.ts` tests it directly. Both entry points delegate to the same
69
+ * AST-backed prose normalizer. Do NOT
68
70
  * delete — external callers may depend on this export.
69
71
  */
70
72
  function normalizeModalKeywords(markdown) {
71
- const lines = markdown.split("\n");
72
- (0, fence_js_1.walkProseLines)(markdown, (line, i) => {
73
- // Indented-code / attribute-trailer lines aren't prose either.
74
- if (/^( {4}|\t)/.test(line))
75
- return;
76
- let normalized = line.replace(modals_js_1.RFC2119_MODAL_RE, (m) => m.toLowerCase());
77
- normalized = normalized.replace(modals_js_1.EARS_KEYWORD_RE, (m, _g1, offset) => isSentenceInitial(normalized, offset) ? m : m.toLowerCase());
78
- lines[i] = normalized;
79
- });
80
- return lines.join("\n");
73
+ return (0, modals_js_1.normalizeProseModals)(markdown);
81
74
  }
82
75
  /**
83
76
  * Canonical front-matter key order per ADR-007. Core keys first, then
@@ -228,18 +221,71 @@ function emitBodyViaAst(lines, file, diagnostics, cachedEntries, proseFormat) {
228
221
  // Process bottom-to-top so splices don't shift earlier entry positions.
229
222
  const sorted = [...entries].sort((a, b) => b.location.line - a.location.line);
230
223
  for (const entry of sorted) {
224
+ const protectedRanges = (0, tab_markers_js_1.protectedTabRanges)(lines);
225
+ const start = entry.location.line - 1;
226
+ if (protectedRanges.some((range) => start >= range.start && start < range.end))
227
+ continue;
228
+ const children = protectedRanges.filter((range, index) => range.start > start && range.start < (entry.endLine ?? start) &&
229
+ !protectedRanges.some((outer, other) => other !== index &&
230
+ outer.start < range.start && outer.end >= range.end));
231
+ if (children.length > 0) {
232
+ // Format the parent's prose with each refused child represented by a
233
+ // verbatim block, then restore the original child lines.
234
+ const end = entry.endLine;
235
+ const fragment = lines.slice(start, end);
236
+ const indent = (0, entry_body_js_1.contentColumn)(lines[start], entry.location.column - 1);
237
+ const replacements = [];
238
+ for (const child of children.toReversed()) {
239
+ const childEnd = Math.min(child.end, end);
240
+ let token = "<!-- markspec-preserved-child -->";
241
+ while (lines.some((line) => line.includes(token)) ||
242
+ replacements.some((r) => r.token === token))
243
+ token = token.replace(" -->", "- -->");
244
+ replacements.push({
245
+ token,
246
+ original: lines.slice(child.start, childEnd),
247
+ });
248
+ fragment.splice(child.start - start, childEnd - child.start, " ".repeat(indent) + token, "");
249
+ }
250
+ const nestedDiagnostics = [];
251
+ emitBodyViaAst(fragment, file, nestedDiagnostics, undefined, proseFormat);
252
+ for (const { token, original } of replacements) {
253
+ const at = fragment.findIndex((line) => line.trim() === token);
254
+ if (at < 0)
255
+ throw new Error("Preserved child placeholder was lost");
256
+ let after = at + 1;
257
+ while (after < fragment.length && fragment[after].trim() === "") {
258
+ after++;
259
+ }
260
+ fragment.splice(at, after - at, ...original);
261
+ }
262
+ diagnostics.push(...nestedDiagnostics.map((d) => ({
263
+ ...d,
264
+ location: d.location
265
+ ? { ...d.location, line: d.location.line + start }
266
+ : undefined,
267
+ })));
268
+ if (fragment.join("\n") !== lines.slice(start, end).join("\n")) {
269
+ lines.splice(start, end - start, ...fragment);
270
+ bodyChanged = true;
271
+ }
272
+ continue;
273
+ }
231
274
  if (!entry.body.trim())
232
275
  continue; // empty or whitespace-only body
233
- const indent = (entry.location.column - 1) + 2; // marker column (0-based) + 2 spaces = list-item continuation indent
276
+ // List-item continuation indent: the item's content column, which
277
+ // counts every space and tab after the marker (#865).
278
+ const indent = (0, entry_body_js_1.contentColumn)(lines[entry.location.line - 1] ?? "", entry.location.column - 1);
234
279
  const indentStr = " ".repeat(indent);
235
280
  const titleLineIdx = entry.location.line - 1; // 0-based
236
281
  // Locate the body segment in `lines` — between the title line and
237
282
  // the attr block start (or item end when there is no attr block).
238
- const range = findAttributeBlockRange(lines, entry.location.line, indent);
283
+ const itemEndFloor = entry.endLine ?? 0;
284
+ const range = findAttributeBlockRange(lines, entry.location.line, indent, itemEndFloor);
239
285
  const bodyStart = titleLineIdx + 1;
240
286
  const bodyEnd = range
241
287
  ? range.start
242
- : findItemEnd(lines, titleLineIdx, indent);
288
+ : findItemEnd(lines, titleLineIdx, indent, itemEndFloor);
243
289
  if (bodyEnd <= bodyStart)
244
290
  continue; // no body lines to replace
245
291
  // Route the body through the canonical AST: build → normalize
@@ -370,6 +416,97 @@ function stampDisciplineFrozen(value, today) {
370
416
  }
371
417
  return value;
372
418
  }
419
+ /**
420
+ * Normalize tab markers before any pass can stamp or splice their entries.
421
+ * Compare whole documents so a neighbouring list cannot become a child.
422
+ */
423
+ function normalizeTabMarkers(markdown, options, diagnostics) {
424
+ const lines = markdown.split("\n");
425
+ const original = [...lines];
426
+ const markers = (0, tab_markers_js_1.tabMarkers)(lines).sort((a, b) => b.start - a.start);
427
+ if (markers.length === 0)
428
+ return markdown;
429
+ const accepted = new Set();
430
+ const refused = new Set();
431
+ for (const marker of markers) {
432
+ const before = lines.join("\n");
433
+ const candidate = [...lines];
434
+ const title = lines[marker.start];
435
+ const indent = (0, entry_body_js_1.contentColumn)(title, marker.column);
436
+ const delta = indent - (marker.column + 2);
437
+ candidate[marker.start] = title.slice(0, marker.column) + "- " +
438
+ title.slice(marker.column + 1 + marker.whitespace.length);
439
+ for (let i = marker.start + 1; i < marker.end; i++) {
440
+ if (candidate[i].startsWith(" ".repeat(indent))) {
441
+ candidate[i] = candidate[i].slice(delta);
442
+ }
443
+ }
444
+ const after = candidate.join("\n");
445
+ const beforeEntries = (0, markdown_js_1.parseMarkdown)(before).entries;
446
+ const afterEntries = (0, markdown_js_1.parseMarkdown)(after).entries;
447
+ const identitiesKept = beforeEntries.length === afterEntries.length &&
448
+ beforeEntries.every((entry, i) => entry.displayId === afterEntries[i].displayId &&
449
+ entry.id === afterEntries[i].id);
450
+ const containsRefused = [...refused].some((start) => start > marker.start && start < marker.end);
451
+ if (containsRefused || !(0, md_equiv_js_1.markdownSemanticallyEquivalent)(before, after) ||
452
+ !identitiesKept) {
453
+ // Refusing an enclosing entry must also undo admitted changes to its
454
+ // descendants. No identities have been stamped at this point.
455
+ lines.splice(marker.start, marker.end - marker.start, ...original.slice(marker.start, marker.end));
456
+ for (const start of accepted) {
457
+ if (start >= marker.start && start < marker.end)
458
+ accepted.delete(start);
459
+ }
460
+ refused.add(marker.start);
461
+ diagnostics.push({
462
+ code: "MSL-F013",
463
+ severity: "warning",
464
+ message: "Tab-separated entry marker cannot be normalized without " +
465
+ "changing CommonMark structure; kept the entry unchanged",
466
+ location: {
467
+ file: options?.file ?? "<unknown>",
468
+ line: marker.start + 1,
469
+ column: marker.column + 1,
470
+ },
471
+ });
472
+ continue;
473
+ }
474
+ lines.splice(0, lines.length, ...candidate);
475
+ accepted.add(marker.start);
476
+ }
477
+ const indexedStarts = new Set((0, markdown_js_1.parseMarkdown)(lines.join("\n")).entries.map((entry) => entry.location.line - 1));
478
+ for (const start of [...accepted].sort((a, b) => b - a)) {
479
+ // Re-read extents after each nested splice. Admission itself never
480
+ // changes line counts, so earlier title positions remain valid.
481
+ const marker = (0, tab_markers_js_1.entryListItems)(lines).find((item) => item.start === start);
482
+ // Nested entries are outside the parser's top-level entry index. Format
483
+ // their normalized item separately, then restore the enclosing indent.
484
+ if (marker.container.start !== marker.start &&
485
+ !indexedStarts.has(marker.container.start)) {
486
+ const prefix = " ".repeat(marker.column);
487
+ const fragment = lines.slice(marker.start, marker.end)
488
+ .map((line) => line.startsWith(prefix) ? line.slice(prefix.length) : line)
489
+ .join("\n");
490
+ const nested = formatEntries(fragment, options);
491
+ const replacement = nested.output.split("\n")
492
+ .map((line) => line === "" ? "" : prefix + line);
493
+ lines.splice(marker.start, marker.end - marker.start, ...replacement);
494
+ diagnostics.push(...nested.diagnostics.map((diagnostic) => ({
495
+ ...diagnostic,
496
+ ...(diagnostic.location
497
+ ? {
498
+ location: {
499
+ ...diagnostic.location,
500
+ line: diagnostic.location.line + marker.start,
501
+ column: diagnostic.location.column + marker.column,
502
+ },
503
+ }
504
+ : {}),
505
+ })));
506
+ }
507
+ }
508
+ return lines.join("\n");
509
+ }
373
510
  /**
374
511
  * Format a Markdown string — normalize attribute blocks,
375
512
  * fix indentation, enforce canonical ordering.
@@ -379,6 +516,20 @@ function stampDisciplineFrozen(value, today) {
379
516
  * @returns Format result with output text and diagnostics
380
517
  */
381
518
  function format(markdown, options) {
519
+ const diagnostics = [];
520
+ const ending = (0, line_endings_js_1.detectLineEnding)(markdown);
521
+ const prepared = normalizeTabMarkers((0, line_endings_js_1.normalizeLineEndings)(markdown), options, diagnostics);
522
+ const result = formatEntries(prepared, options);
523
+ const output = (0, line_endings_js_1.applyLineEnding)(result.output, ending);
524
+ return {
525
+ output,
526
+ diagnostics: [...diagnostics, ...result.diagnostics],
527
+ changed: output !== markdown,
528
+ preservedRanges: (0, tab_markers_js_1.protectedTabRanges)((0, line_endings_js_1.normalizeLineEndings)(output).split("\n")),
529
+ };
530
+ }
531
+ /** Run the entry and prose passes after tab-marker admission. */
532
+ function formatEntries(markdown, options) {
382
533
  const file = options?.file ?? "<unknown>";
383
534
  // Detect the source file's line-ending convention up front so we can
384
535
  // restore it on write-back. The rest of the formatter operates on a
@@ -397,13 +548,16 @@ function format(markdown, options) {
397
548
  // `normalizeBodyAst` (more spec-correct: respects §2.5 verbatim
398
549
  // boundaries and per-node sentence-initial context). `normalizeModalKeywords`
399
550
  // stays exported/defined for other callers/tests but is not invoked here.
400
- const body = rawBody;
401
- const { entries } = (0, markdown_js_1.parseMarkdown)(body, { file });
402
551
  const diagnostics = [...fm.diagnostics];
552
+ // Drop empty-valued trailer lines (`Id:`, `Satisfies:`) before the main
553
+ // pass; left in place they demote the whole trailer block to body code.
554
+ const repaired = removeEmptyTrailerLines(rawBody, (0, markdown_js_1.parseMarkdown)(rawBody, { file }).entries, diagnostics);
555
+ const body = repaired ?? rawBody;
556
+ const { entries } = (0, markdown_js_1.parseMarkdown)(body, { file });
403
557
  // ADR-029: the whole-document Markdown pass is Markdown-only. Gate on the
404
558
  // file extension HERE so the invariant has one home — a caller that wires
405
- // formatMarkdownProse without its own guard (e.g. a future write tool, or
406
- // formatSource forwarding options with a source-file label) cannot silently
559
+ // formatMarkdownProse without its own guard (e.g. a future write tool
560
+ // forwarding options with a source-file label) cannot silently
407
561
  // reflow a source file's doc comment as Markdown. The CommonMark-semantic
408
562
  // gate cannot catch that class, so it must be prevented, not detected. The
409
563
  // CLI/LSP call-site guards remain as defense-in-depth.
@@ -416,13 +570,31 @@ function format(markdown, options) {
416
570
  return { output: markdown, diagnostics, changed: false };
417
571
  }
418
572
  const lines = body.split("\n");
419
- let changed = false;
573
+ let changed = repaired !== undefined;
420
574
  // Process bottom-to-top so line splicing doesn't shift earlier entries.
421
575
  const sorted = [...entries].sort((a, b) => b.location.line - a.location.line);
422
576
  const genUlid = options?.generateUlid ?? ulid_1.ulid;
577
+ const protectedRanges = (0, tab_markers_js_1.protectedTabRanges)(lines);
423
578
  for (const entry of sorted) {
424
- const indent = (entry.location.column - 1) + 2;
425
- let attrs = [...entry.rawAttributes];
579
+ if (protectedRanges.some((range) => entry.location.line - 1 >= range.start &&
580
+ entry.location.line - 1 < range.end))
581
+ continue;
582
+ const indent = (0, entry_body_js_1.contentColumn)(lines[entry.location.line - 1] ?? "", entry.location.column - 1);
583
+ // `entry.endLine` comes from the parse of the unedited buffer. Entries
584
+ // are processed bottom to top, so only this entry's own edits move its
585
+ // end; the change in line count since here measures them.
586
+ const lengthAtStart = lines.length;
587
+ const itemEndFloor = () => entry.endLine === undefined
588
+ ? 0
589
+ : entry.endLine + (lines.length - lengthAtStart);
590
+ const existingTrailer = protectedRanges.length > 0
591
+ ? findAttributeBlockRange(lines, entry.location.line, indent, itemEndFloor(), protectedRanges)
592
+ : undefined;
593
+ let attrs = protectedRanges.length > 0
594
+ ? existingTrailer
595
+ ? (0, attributes_js_1.parseAttributes)(lines.slice(existingTrailer.start, existingTrailer.end))
596
+ : []
597
+ : [...entry.rawAttributes];
426
598
  const titleLineIdx = entry.location.line - 1;
427
599
  // #686: a title that soft-wraps onto extra physical lines is a single
428
600
  // Markdown paragraph, but the line-based passes here and in
@@ -436,7 +608,7 @@ function format(markdown, options) {
436
608
  // attribute block so a malformed entry with no blank line before its
437
609
  // trailer cannot swallow it.
438
610
  if (titleLineIdx >= 0 && titleLineIdx < lines.length) {
439
- const attrRange = findAttributeBlockRange(lines, entry.location.line, indent);
611
+ const attrRange = findAttributeBlockRange(lines, entry.location.line, indent, itemEndFloor());
440
612
  const limit = attrRange ? attrRange.start : lines.length;
441
613
  let titleEnd = titleLineIdx;
442
614
  while (titleEnd + 1 < limit && lines[titleEnd + 1].trim() !== "") {
@@ -518,7 +690,7 @@ function format(markdown, options) {
518
690
  if (attrs.length === 0)
519
691
  continue;
520
692
  const normalized = sortAttributes(expandCsvValues(attrs));
521
- const range = findAttributeBlockRange(lines, entry.location.line, indent);
693
+ const range = findAttributeBlockRange(lines, entry.location.line, indent, itemEndFloor(), protectedRanges);
522
694
  if (range) {
523
695
  // Replace existing attribute block.
524
696
  const newBlock = renderAttributeBlock(normalized, indent);
@@ -530,7 +702,7 @@ function format(markdown, options) {
530
702
  }
531
703
  else {
532
704
  // No attribute block — insert one after the entry body.
533
- const insertLine = findEntryBodyEnd(lines, entry, indent);
705
+ const insertLine = findEntryBodyEnd(lines, entry, indent, itemEndFloor());
534
706
  const newBlock = renderAttributeBlock(normalized, indent);
535
707
  lines.splice(insertLine, 0, "", ...newBlock.split("\n"));
536
708
  changed = true;
@@ -571,10 +743,32 @@ function format(markdown, options) {
571
743
  : entries;
572
744
  const extents = proseEntries.map((e) => {
573
745
  const start = e.location.line - 1;
574
- const entryIndent = (e.location.column - 1) + 2;
575
- return { start, end: findItemEnd(collapsedLines, start, entryIndent) };
746
+ const entryIndent = (0, entry_body_js_1.contentColumn)(collapsedLines[start] ?? "", e.location.column - 1);
747
+ return {
748
+ start,
749
+ end: findItemEnd(collapsedLines, start, entryIndent, e.endLine ?? 0),
750
+ };
576
751
  });
577
- const prose = (0, prose_js_1.formatProseSegments)(collapsedLines, extents, proseFormat);
752
+ if ((0, tab_markers_js_1.tabMarkers)(collapsedLines).length > 0) {
753
+ // Title-only entry items are outside the entry index. Keep their list
754
+ // context too: isolated prose formatting can move adjacent entries.
755
+ const indexedStarts = new Set(proseEntries.map((entry) => entry.location.line - 1));
756
+ extents.push(...(0, tab_markers_js_1.entryListItems)(collapsedLines)
757
+ .filter((item) => !indexedStarts.has(item.start))
758
+ .map((item) => item.listContext));
759
+ extents.push(...(0, tab_markers_js_1.protectedTabRanges)(collapsedLines, true));
760
+ }
761
+ extents.sort((a, b) => a.start - b.start);
762
+ const merged = [];
763
+ for (const extent of extents) {
764
+ const previous = merged.at(-1);
765
+ if (previous && extent.start <= previous.end) {
766
+ previous.end = Math.max(previous.end, extent.end);
767
+ }
768
+ else
769
+ merged.push({ ...extent });
770
+ }
771
+ const prose = (0, prose_js_1.formatProseSegments)(collapsedLines, merged, proseFormat);
578
772
  if (prose.changed)
579
773
  changed = true;
580
774
  for (const fallback of prose.fallbacks) {
@@ -637,16 +831,12 @@ function renderFrontMatter(attrs) {
637
831
  */
638
832
  function collapseBlankLines(lines) {
639
833
  const out = [];
640
- let inFence = false;
834
+ const fencedLines = (0, fence_js_1.fencedCodeLines)(lines.join("\n"));
835
+ const protectedRanges = (0, tab_markers_js_1.protectedTabRanges)(lines, true);
641
836
  let prevBlank = false;
642
- for (const line of lines) {
643
- if (fence_js_1.FENCE_RE.test(line)) {
644
- out.push(line);
645
- inFence = !inFence;
646
- prevBlank = false;
647
- continue;
648
- }
649
- if (inFence) {
837
+ for (const [i, line] of lines.entries()) {
838
+ if (fencedLines.has(i) ||
839
+ protectedRanges.some((range) => i >= range.start && i < range.end)) {
650
840
  out.push(line);
651
841
  prevBlank = false;
652
842
  continue;
@@ -743,8 +933,8 @@ function sortAttributes(attributes) {
743
933
  * no trailing line-continuation characters.
744
934
  *
745
935
  * @param attributes - The attributes to render, in canonical order.
746
- * @param indent - Body indent for the entry (2 for list-wrapped entries,
747
- * 0 for entries inside source-file doc comments).
936
+ * @param indent - The 0-based list item content column, or 0 inside
937
+ * source-file doc comments.
748
938
  */
749
939
  function renderAttributeBlock(attributes, indent) {
750
940
  const prefix = " ".repeat(indent + 4);
@@ -755,18 +945,26 @@ function renderAttributeBlock(attributes, indent) {
755
945
  /**
756
946
  * Find the 0-based line index where a list item's content ends.
757
947
  * Exported for the ADR-029 prose pass (entry-extent computation).
758
- * Scans forward from the entry start, stopping at: a sibling list item
759
- * (`- ` at the entry's marker column), a line with less indent, or EOF.
948
+ * Scans forward from the later of the line after the entry start and
949
+ * `itemEndFloor` until a line has less indent than the content column, a
950
+ * conventional sibling marker is found, or EOF. Pass the parser's
951
+ * `Entry.endLine` as `itemEndFloor` so that a lazy continuation line
952
+ * inside the item does not end the scan early; the default `0` keeps
953
+ * the indentation-only scan.
760
954
  */
761
- function findItemEnd(lines, startIdx, indent) {
955
+ function findItemEnd(lines, startIdx, indent, itemEndFloor = 0) {
762
956
  const indentStr = " ".repeat(indent);
763
- // The marker column is indent - 2 (e.g., indent 2 → marker at column 0).
957
+ // Recognize sibling bullets with one space after the marker.
764
958
  const markerPrefix = " ".repeat(Math.max(0, indent - 2)) + "- ";
765
- for (let i = startIdx + 1; i < lines.length; i++) {
959
+ // `itemEndFloor` is the 0-based index just after the item's last content
960
+ // line, from the parser's `Entry.endLine`. The scan starts there, because
961
+ // an indentation scan ends the item early at a lazy continuation line
962
+ // (a paragraph line indented less than the item content).
963
+ for (let i = Math.max(startIdx + 1, itemEndFloor); i < lines.length; i++) {
766
964
  const line = lines[i];
767
965
  if (line.trim() === "")
768
966
  continue;
769
- // Sibling list item at same level
967
+ // Sibling with a one-space marker; wider markers use the indent check.
770
968
  if (line.startsWith(markerPrefix))
771
969
  return i;
772
970
  // Line with less indent than continuation
@@ -775,6 +973,79 @@ function findItemEnd(lines, startIdx, indent) {
775
973
  }
776
974
  return lines.length;
777
975
  }
976
+ /** A trailer-shaped line whose value may be empty: `Key:` or `Key: value`. */
977
+ const TRAILER_SHAPED_RE = /^[A-Z][A-Za-z-]*:(?:\s.*)?$/;
978
+ /** A trailer-shaped line with no value: `Key:` (spec §2 makes it MSL-P021). */
979
+ const EMPTY_TRAILER_RE = /^([A-Z][A-Za-z-]*):\s*$/;
980
+ /**
981
+ * Remove empty-valued `Key:` lines from each entry's trailing trailer block.
982
+ *
983
+ * An empty-valued line is not a valid trailer (spec §2, MSL-P021), so the
984
+ * parser treats the whole trailing block as body code. Left alone, the
985
+ * main pass would fence that block and append a fresh `Id:`, silently
986
+ * turning real trace links into inert body text. An empty value carries no
987
+ * information, so dropping the line is lossless: an `Id:` placeholder then
988
+ * gets stamped in place and the remaining trailers stay trailers.
989
+ *
990
+ * Only touches a block of contiguous lines at the very end of an entry,
991
+ * indented at least four columns past the entry body, in which every line
992
+ * is trailer-shaped. Emits one MSL-F001 info diagnostic per removed line.
993
+ *
994
+ * @returns The repaired text, or `undefined` when nothing was removed.
995
+ */
996
+ function removeEmptyTrailerLines(body, entries, diagnostics) {
997
+ const lines = body.split("\n");
998
+ let removedAny = false;
999
+ const sorted = [...entries].sort((a, b) => b.location.line - a.location.line);
1000
+ const protectedRanges = (0, tab_markers_js_1.protectedTabRanges)(lines);
1001
+ for (const entry of sorted) {
1002
+ if (protectedRanges.some((range) => entry.location.line - 1 >= range.start &&
1003
+ entry.location.line - 1 < range.end))
1004
+ continue;
1005
+ const indent = (0, entry_body_js_1.contentColumn)(lines[entry.location.line - 1] ?? "", entry.location.column - 1);
1006
+ const startIdx = entry.location.line - 1;
1007
+ let end = findItemEnd(lines, startIdx, indent, entry.endLine ?? 0);
1008
+ while (end > startIdx && lines[end - 1].trim() === "")
1009
+ end--;
1010
+ let start = end;
1011
+ while (start - 1 > startIdx && lines[start - 1].trim() !== "" &&
1012
+ !protectedRanges.some((range) => start - 1 >= range.start && start - 1 < range.end))
1013
+ start--;
1014
+ if (start >= end || start - 1 <= startIdx)
1015
+ continue;
1016
+ const trailerIndent = " ".repeat(indent + 4);
1017
+ const block = lines.slice(start, end);
1018
+ if (protectedRanges.some((range) => range.start > startIdx && start < range.end && end > range.start))
1019
+ continue;
1020
+ const isTrailerBlock = block.every((l) => l.startsWith(trailerIndent) && TRAILER_SHAPED_RE.test(l.trim()));
1021
+ if (!isTrailerBlock)
1022
+ continue;
1023
+ const kept = block.filter((l) => !EMPTY_TRAILER_RE.test(l.trim()));
1024
+ if (kept.length === block.length)
1025
+ continue;
1026
+ for (const l of block) {
1027
+ const key = EMPTY_TRAILER_RE.exec(l.trim())?.[1];
1028
+ if (key === undefined)
1029
+ continue;
1030
+ diagnostics.push({
1031
+ code: "MSL-F001",
1032
+ severity: "info",
1033
+ message: `removed empty '${key}:' trailer line from ${entry.displayId}`,
1034
+ location: entry.location,
1035
+ });
1036
+ }
1037
+ if (kept.length > 0) {
1038
+ lines.splice(start, end - start, ...kept);
1039
+ }
1040
+ else {
1041
+ // Whole block was placeholders: drop it and its leading blank line.
1042
+ const from = lines[start - 1].trim() === "" ? start - 1 : start;
1043
+ lines.splice(from, end - from);
1044
+ }
1045
+ removedAny = true;
1046
+ }
1047
+ return removedAny ? lines.join("\n") : undefined;
1048
+ }
778
1049
  /**
779
1050
  * Find the 0-based line range [start, end) of the attribute block
780
1051
  * for an entry starting at the given line.
@@ -782,9 +1053,9 @@ function findItemEnd(lines, startIdx, indent) {
782
1053
  * Scans forward from the entry start to find the list item boundary,
783
1054
  * then walks backwards to find the contiguous trailing attribute block.
784
1055
  */
785
- function findAttributeBlockRange(lines, entryStartLine, indent) {
1056
+ function findAttributeBlockRange(lines, entryStartLine, indent, itemEndFloor = 0, preservedRanges = []) {
786
1057
  const startIdx = entryStartLine - 1;
787
- const itemEnd = findItemEnd(lines, startIdx, indent);
1058
+ const itemEnd = findItemEnd(lines, startIdx, indent, itemEndFloor);
788
1059
  // Walk backwards from itemEnd, skip trailing blank lines.
789
1060
  let scanEnd = itemEnd;
790
1061
  while (scanEnd > startIdx && lines[scanEnd - 1].trim() === "") {
@@ -795,6 +1066,9 @@ function findAttributeBlockRange(lines, entryStartLine, indent) {
795
1066
  // Walk backwards collecting attribute lines.
796
1067
  let attrStart = scanEnd;
797
1068
  for (let i = scanEnd - 1; i > startIdx; i--) {
1069
+ if (preservedRanges.some((range) => i >= range.start && i < range.end)) {
1070
+ break;
1071
+ }
798
1072
  const trimmed = lines[i].trim();
799
1073
  if (trimmed === "")
800
1074
  break;
@@ -813,9 +1087,9 @@ function findAttributeBlockRange(lines, entryStartLine, indent) {
813
1087
  * Find the 0-based line index where a new attribute block should be inserted
814
1088
  * (after the last non-blank body line of the entry).
815
1089
  */
816
- function findEntryBodyEnd(lines, entry, indent) {
1090
+ function findEntryBodyEnd(lines, entry, indent, itemEndFloor = 0) {
817
1091
  const startIdx = entry.location.line - 1;
818
- const itemEnd = findItemEnd(lines, startIdx, indent);
1092
+ const itemEnd = findItemEnd(lines, startIdx, indent, itemEndFloor);
819
1093
  let insertAt = itemEnd;
820
1094
  while (insertAt > startIdx && lines[insertAt - 1].trim() === "") {
821
1095
  insertAt--;
@@ -0,0 +1,15 @@
1
+ import type { EntryExtent } from "./prose.js";
2
+ /** An entry title and the list context that controls its indentation. */
3
+ export interface EntryListItem extends EntryExtent {
4
+ readonly column: number;
5
+ readonly whitespace: string;
6
+ readonly container: EntryExtent;
7
+ readonly listContext: EntryExtent;
8
+ }
9
+ /** Find actual unordered list items, excluding code, HTML, and task lists. */
10
+ export declare function entryListItems(lines: readonly string[]): EntryListItem[];
11
+ /** Find entry list items with a tab in the whitespace after the marker. */
12
+ export declare function tabMarkers(lines: readonly string[]): EntryListItem[];
13
+ /** Ranges kept out of every formatter pass after a tab rewrite is refused. */
14
+ export declare function protectedTabRanges(lines: readonly string[], preserveListContext?: boolean): EntryExtent[];
15
+ //# sourceMappingURL=tab_markers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tab_markers.d.ts","sourceRoot":"","sources":["../../src/formatter/tab_markers.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAI9C,yEAAyE;AACzE,MAAM,WAAW,aAAc,SAAQ,WAAW;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC;IAChC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;CACnC;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,aAAa,EAAE,CAoFxE;AAED,2EAA2E;AAC3E,wBAAgB,UAAU,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,aAAa,EAAE,CAKpE;AAED,8EAA8E;AAC9E,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,mBAAmB,UAAQ,GAC1B,WAAW,EAAE,CA4Cf"}