prettier-plugin-mmd 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { parse, visitorKeys } from "@mmd-toolkit/parser";
2
2
  import { builders, printer, utils } from "prettier/doc";
3
+ import { Marked } from "marked";
3
4
  import { util } from "prettier";
4
5
  //#region src/printers/collections.ts
5
6
  /**
@@ -446,7 +447,7 @@ function semicolonRulesOf(source) {
446
447
  const terminators = new Set(body.body.filter((item) => item.type === "RailroadRule").map((item) => item.range[1] - 1));
447
448
  rules = {
448
449
  kind: "required",
449
- verbatimStyleLines: true,
450
+ verbatimStyleLines: "word",
450
451
  grammatical: /* @__PURE__ */ new Set([...terminators, ...source.root.comments.filter((comment) => comment.mark === ";").map((comment) => comment.range[0])])
451
452
  };
452
453
  break;
@@ -461,7 +462,7 @@ function semicolonRulesOf(source) {
461
462
  rules = {
462
463
  kind: "text",
463
464
  grammatical,
464
- verbatimStyleLines: true
465
+ verbatimStyleLines: "semicolon"
465
466
  };
466
467
  break;
467
468
  }
@@ -807,16 +808,16 @@ function findStyleWord(text) {
807
808
  }
808
809
  /** Diagrams whose grammatical punctuation needs complete word-line protection. */
809
810
  function usesVerbatimStyleLines(source) {
810
- return semicolonRulesOf(source).verbatimStyleLines;
811
+ return semicolonRulesOf(source).verbatimStyleLines !== false;
811
812
  }
812
813
  /** Verbatim word lines, computed once for protected grammatical punctuation. */
813
814
  const verbatimStyleLinesBySource = /* @__PURE__ */ new WeakMap();
814
815
  /**
815
- * Railroad and Wardley keep complete source lines containing a common line-rule
816
- * word after global directives are omitted. Keeping every statement and comment
817
- * protects required terminators, ABNF comment marks and Wardley link-label
818
- * openers without predicting which semicolon the line rule selects. A removed directive
819
- * can join a word across physical lines; all those lines stay together
816
+ * Railroad keeps word lines before joining can select a required terminator;
817
+ * Wardley keeps only lines already containing a semicolon. Both read the line
818
+ * after global directives are omitted. Keeping complete statements and comments
819
+ * protects native punctuation without predicting which semicolon is selected.
820
+ * A removed directive can join a word across physical lines; all those lines stay together
820
821
  * (common.md, Where a directive is; docs/railroad.md and docs/wardley.md,
821
822
  * Semicolons).
822
823
  */
@@ -825,13 +826,15 @@ function findVerbatimStyleLines(source) {
825
826
  if (cached !== void 0) return cached;
826
827
  const lines = /* @__PURE__ */ new Set();
827
828
  verbatimStyleLinesBySource.set(source, lines);
828
- if (!usesVerbatimStyleLines(source)) return lines;
829
+ const rule = semicolonRulesOf(source).verbatimStyleLines;
830
+ if (rule === false) return lines;
829
831
  let lineStart = source.root.body.range[0];
830
832
  let position = lineStart;
831
833
  const parts = [];
832
834
  /** Retains every source line contributing to this directive-free line. */
833
835
  function finishLine(end) {
834
- if (findStyleWord(parts.join("")) !== -1) {
836
+ const line = parts.join("");
837
+ if ((rule === "word" || line.includes(";")) && findStyleWord(line) !== -1) {
835
838
  let start = lineStartOf(source, lineStart);
836
839
  while (start <= end) {
837
840
  lines.add(start);
@@ -1394,12 +1397,14 @@ function toAtom(token) {
1394
1397
  * `-> "b" e - satisfies -> f;g` has the target `f;g`, and the joined line has
1395
1398
  * the target `fg`. Such a statement is kept as written (docs/sequence.md and
1396
1399
  * docs/class.md, Multi-line statements). This is the one decision about
1397
- * joining lines that every layout takes.
1400
+ * joining lines that every layout takes. A caller that keeps line breaks
1401
+ * between its structural tokens can ignore trivia in this check; semicolon
1402
+ * line protections still apply.
1398
1403
  */
1399
- function spansLinesThatCannotJoin(source, start, end) {
1404
+ function spansLinesThatCannotJoin(source, start, end, options = {}) {
1400
1405
  const text = source.text.slice(start, end);
1401
1406
  if (!text.includes("\n")) return false;
1402
- if (text.includes(";") || findTriviaBetween(source, start, end).length > 0) return true;
1407
+ if (text.includes(";") || !options.ignoresTrivia && findTriviaBetween(source, start, end).length > 0) return true;
1403
1408
  return findSemicolonLines(source).has(lineStartOf(source, end - 1));
1404
1409
  }
1405
1410
  /**
@@ -1425,6 +1430,41 @@ function keptAsWritten(start, end) {
1425
1430
  };
1426
1431
  }
1427
1432
  /**
1433
+ * The physical line that completes a block header aligns with its statement,
1434
+ * so the body remains one level deeper. A value spanning that line stays whole
1435
+ * (docs/state.md, Composite states; docs/requirement.md, Bodies).
1436
+ */
1437
+ function alignBlockOpeningLine(source, layout, opening) {
1438
+ const start = lineStartOf(source, opening);
1439
+ if (layout.atoms.some((atom) => atom.start < start && start < atom.end)) return layout;
1440
+ const first = layout.atoms.find((atom) => start <= atom.start && atom.start <= opening);
1441
+ return first === void 0 ? layout : {
1442
+ ...layout,
1443
+ outdented: /* @__PURE__ */ new Set([...layout.outdented, first.start])
1444
+ };
1445
+ }
1446
+ /**
1447
+ * Some grammars require a non-LF whitespace run to start before a retained LF.
1448
+ * Keep each first gap-line tail, including complete trivia, while later lines
1449
+ * use ordinary continuation columns (diagrams/requirement.md, Whitespace;
1450
+ * docs/xychart.md, Multi-line statements).
1451
+ */
1452
+ function keepFirstGapLineTails(source, atoms) {
1453
+ return atoms.map((atom, index) => {
1454
+ const next = atoms[index + 1];
1455
+ if (next === void 0) return atom;
1456
+ for (let end = atom.end; end < next.start;) {
1457
+ const part = readGapElement(source, end);
1458
+ if (part.element.kind === "lineTerminator") return {
1459
+ ...atom,
1460
+ end
1461
+ };
1462
+ end = part.end;
1463
+ }
1464
+ return atom;
1465
+ });
1466
+ }
1467
+ /**
1428
1468
  * Where a layout ends: the end of its last atom. The statements of the body
1429
1469
  * start after the header, which holds more than the keyword where the header
1430
1470
  * has a direction or an orientation.
@@ -1451,11 +1491,11 @@ function layoutKeywordHeader(source, keyword) {
1451
1491
  * `formatsTriviaLines` instead keeps the line breaks while formatting the
1452
1492
  * tokens and trivia with the caller's statement and continuation indentation.
1453
1493
  */
1454
- function layoutEmptyDescriptionBlock(source, start, end, formatsTriviaLines = false) {
1455
- if (!formatsTriviaLines && spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
1494
+ function layoutEmptyDescriptionBlock(source, start, end, formatsTriviaLines = false, opening) {
1495
+ if (!formatsTriviaLines && spansLinesThatCannotJoin(source, start, end)) return spaceDescriptionOpening(source, start, keptAsWritten(start, end), opening);
1456
1496
  return {
1457
1497
  atoms: collectAtoms(source, start, end, [], []).filter((atom) => source.text.slice(atom.start, atom.end).trim() !== ""),
1458
- rules: /* @__PURE__ */ new Map(),
1498
+ rules: descriptionOpeningRules(source, start, opening),
1459
1499
  outdented: /* @__PURE__ */ new Set(),
1460
1500
  lineBreaks: formatsTriviaLines ? "kept" : "joined"
1461
1501
  };
@@ -1469,13 +1509,14 @@ function layoutEmptyDescriptionBlock(source, start, end, formatsTriviaLines = fa
1469
1509
  * whose ranges are exactly those of the brace tokens. Their intervening gap
1470
1510
  * is the compacted interior, also used by state-kept-lines.ts.
1471
1511
  */
1472
- function layoutCompactEmptyDescriptionBlock(source, start, end) {
1512
+ function layoutCompactEmptyDescriptionBlock(source, start, end, opening) {
1473
1513
  if (findTriviaBetween(source, start, end).length > 0 || spansLinesThatCannotJoin(source, start, end)) return null;
1474
1514
  const closing = expectToken(findTokenEndingBefore(source, end), "the closing empty description brace");
1475
1515
  expectValue(closing, "}");
1516
+ const layout = layoutEmptyDescriptionBlock(source, start, end, false, opening);
1476
1517
  return {
1477
- ...layoutEmptyDescriptionBlock(source, start, end),
1478
- rules: /* @__PURE__ */ new Map([[closing.range[0], "none"]]),
1518
+ ...layout,
1519
+ rules: new Map([...layout.rules, [closing.range[0], "none"]]),
1479
1520
  joinedBefore: /* @__PURE__ */ new Set([closing.range[0]])
1480
1521
  };
1481
1522
  }
@@ -1484,13 +1525,15 @@ function layoutCompactEmptyDescriptionBlock(source, start, end) {
1484
1525
  * its original layout. Keeping the fallback lazy preserves the caller's
1485
1526
  * trivia and continuation layout without building it for a compact block.
1486
1527
  */
1487
- function layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, originalLayout) {
1488
- return layoutCompactEmptyDescriptionBlock(source, start, end) ?? originalLayout();
1528
+ function layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, originalLayout, opening) {
1529
+ return layoutCompactEmptyDescriptionBlock(source, start, end, opening) ?? originalLayout();
1489
1530
  }
1490
1531
  /**
1491
- * The layout of an `accDescr { ... }` statement: the lines of its text are
1492
- * kept as written and its `}` stands at the level of the statement (the
1493
- * rules document of the diagram type, Accessibility statements). A closed block
1532
+ * The layout of an `accDescr { ... }` statement: its text stands one level
1533
+ * inside the statement and its `}` stands at the statement's level (the
1534
+ * rules document of the diagram type, Accessibility statements). Callers set
1535
+ * `preservesBodyColumns` where raw text also controls membership or box reading.
1536
+ * A closed block
1494
1537
  * without text prints `{}` unless trivia requires its existing layout. The
1495
1538
  * text is a value of `valueTypes`. The block is closed unless the statement
1496
1539
  * says that it is not, as in an XY chart, where a block that is not closed
@@ -1516,30 +1559,75 @@ function layoutDescriptionBlock(source, statement, end, valueTypes, options = {}
1516
1559
  }
1517
1560
  valueRange = hasText ? [from, to] : null;
1518
1561
  }
1519
- if (valueRange === null) {
1520
- /** Keeps the existing empty-block trivia and continuation layout. */
1521
- function originalLayout() {
1522
- return layoutEmptyDescriptionBlock(source, start, end, options.formatsEmptyTrivia);
1523
- }
1524
- return statement.closed !== false ? layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, originalLayout) : originalLayout();
1525
- }
1526
1562
  const block = {
1527
1563
  range: statement.range,
1528
1564
  value: statement.value,
1529
1565
  closed: statement.closed ?? true,
1530
1566
  ...options.opening === void 0 ? {} : { opening: options.opening }
1531
1567
  };
1532
- const closing = findAccDescrBlockClosing(source, block);
1568
+ let layout;
1569
+ if (valueRange === null) {
1570
+ /** Keeps the existing empty-block trivia and continuation layout. */
1571
+ function originalLayout() {
1572
+ return layoutEmptyDescriptionBlock(source, start, end, options.formatsEmptyTrivia, options.opening);
1573
+ }
1574
+ layout = statement.closed !== false ? layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, originalLayout, options.opening) : originalLayout();
1575
+ } else {
1576
+ const closing = findAccDescrBlockClosing(source, block);
1577
+ layout = {
1578
+ atoms: collectAtoms(source, start, end, collectValueNodes(statement, valueTypes).map((value) => value === statement.value ? {
1579
+ ...value,
1580
+ range: valueRange
1581
+ } : value), findAccDescrBlockStretches(source, block, valueRange, options.keepsTrailingTrivia)),
1582
+ rules: descriptionOpeningRules(source, start, options.opening),
1583
+ outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing]),
1584
+ lineBreaks: "kept"
1585
+ };
1586
+ }
1587
+ return options.preservesBodyColumns ? layout : indentDescriptionLines(source, block, layout);
1588
+ }
1589
+ /**
1590
+ * Separate the description keyword from its brace in ordinary whitespace;
1591
+ * interior contacts remain authored (docs/info.md, Description blocks).
1592
+ */
1593
+ function descriptionOpeningRules(source, start, opening) {
1594
+ const brace = expectToken(findDescriptionOpening(source, expectToken(findTokenStartingAt(source, start), "the description keyword"), opening), "the description opener");
1595
+ expectValue(brace, "{");
1596
+ return /* @__PURE__ */ new Map([[brace.range[0], "space"]]);
1597
+ }
1598
+ /**
1599
+ * Expose only a plain same-line keyword/brace gap inside a retained header.
1600
+ * The rest of its atom stays whole, including empty-body trivia. Protected
1601
+ * line readings take precedence (docs/c4.md, Empty description blocks).
1602
+ */
1603
+ function spaceDescriptionOpening(source, start, layout, opening) {
1604
+ const keyword = expectToken(findTokenStartingAt(source, start), "accDescr");
1605
+ const brace = expectToken(findDescriptionOpening(source, keyword, opening), "the description opener");
1606
+ if (brace.value !== "{" || ![...source.text.slice(keyword.range[1], brace.range[0])].every((character) => character === " " || character === " ")) return layout;
1607
+ const atoms = [];
1608
+ for (const atom of layout.atoms) {
1609
+ if (atom.doc !== void 0 || atom.start > keyword.range[0] || atom.end < brace.range[1] || spansLinesThatCannotJoin(source, atom.start, atom.end, { ignoresTrivia: true })) {
1610
+ atoms.push(atom);
1611
+ continue;
1612
+ }
1613
+ atoms.push({
1614
+ ...atom,
1615
+ end: keyword.range[1]
1616
+ }, {
1617
+ ...atom,
1618
+ start: brace.range[0]
1619
+ });
1620
+ }
1533
1621
  return {
1534
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, valueTypes).map((value) => value === statement.value ? {
1535
- ...value,
1536
- range: valueRange
1537
- } : value), findAccDescrBlockStretches(source, block, valueRange, options.keepsTrailingTrivia)),
1538
- rules: /* @__PURE__ */ new Map(),
1539
- outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing]),
1540
- lineBreaks: "kept"
1622
+ ...layout,
1623
+ atoms,
1624
+ rules: new Map([...layout.rules, [brace.range[0], "space"]])
1541
1625
  };
1542
1626
  }
1627
+ /** The authored opener, or the next structural token after the keyword. */
1628
+ function findDescriptionOpening(source, keyword, opening) {
1629
+ return opening === void 0 ? findStructuralToken(source, keyword.range[1]) : findTokenStartingAt(source, opening);
1630
+ }
1543
1631
  /** Fails when a token that the tree implies is missing. */
1544
1632
  function expectToken(token, what) {
1545
1633
  if (token === void 0) throw new Error(`prettier-plugin-mmd: no token for ${what}`);
@@ -1550,19 +1638,66 @@ function expectValue(token, value) {
1550
1638
  if (token.value !== value) throw new Error(`prettier-plugin-mmd: expected the token ${JSON.stringify(value)}, found ${JSON.stringify(token.value)} at offset ${token.range[0]}`);
1551
1639
  }
1552
1640
  /**
1553
- * The stretch of an `accDescr { ... }` block that is printed exactly as
1554
- * written: from the `{` to the end of its text and of the comments and
1555
- * directives after the text, when the text starts on a later line than the
1556
- * `{`. Its lines keep their columns (docs/flowchart.md, Multi-line values),
1557
- * the first one included, and comment lines among them stay where they
1558
- * are. The whitespace after the `{` is read with the `{`, so the text on
1641
+ * Align ordinary description text after LF without changing its contents or
1642
+ * line breaks. The Db setter drops this indentation. Directives and removed
1643
+ * line feeds keep their source, and atoms outside the body stay untouched
1644
+ * (docs/timeline.md, Multi-line values; docs/pie.md, Description blocks).
1645
+ * Callers whose Db also stores the raw description as a member keep their
1646
+ * original layout instead (docs/flowchart.md, Multi-line values).
1647
+ */
1648
+ function indentDescriptionLines(source, block, layout) {
1649
+ const opening = expectToken(findDescriptionOpening(source, expectToken(findTokenStartingAt(source, block.range[0]), "the description keyword"), block.opening), "the description opener");
1650
+ const closing = findAccDescrBlockClosing(source, block);
1651
+ const bodyEnd = closing ?? block.range[1];
1652
+ const atoms = [];
1653
+ const keptBreaksBefore = new Set(layout.keptBreaksBefore);
1654
+ const outdented = new Set(layout.outdented);
1655
+ if (closing !== null) outdented.add(closing);
1656
+ for (const atom of layout.atoms) {
1657
+ if (atom.end <= opening.range[1] || atom.start >= bodyEnd) {
1658
+ atoms.push(atom);
1659
+ continue;
1660
+ }
1661
+ const trivia = findTriviaBetween(source, atom.start, atom.end);
1662
+ let start = atom.start;
1663
+ for (let offset = Math.max(start, opening.range[1]); offset < Math.min(atom.end, bodyEnd); offset++) {
1664
+ if (source.text[offset] !== "\n") continue;
1665
+ if (trivia.some((item) => item.range[0] <= offset && offset < item.range[1]) || source.removedLineFeeds.has(offset)) continue;
1666
+ if (start < offset) atoms.push({
1667
+ start,
1668
+ end: offset
1669
+ });
1670
+ start = offset + 1;
1671
+ while (start < atom.end && (source.text[start] === " " || source.text[start] === " ")) start++;
1672
+ if (start < atom.end && source.text[start] !== "\n") keptBreaksBefore.add(start);
1673
+ offset = start - 1;
1674
+ }
1675
+ if (start < atom.end) atoms.push({
1676
+ ...atom,
1677
+ start
1678
+ });
1679
+ }
1680
+ return {
1681
+ ...layout,
1682
+ atoms,
1683
+ keptBreaksBefore,
1684
+ outdented
1685
+ };
1686
+ }
1687
+ /**
1688
+ * The retained stretch of an `accDescr { ... }` block: from the `{` to the
1689
+ * end of its text and following trivia when text starts on a later line.
1690
+ * Initially retain the complete interior, including margins and comment lines.
1691
+ * `indentDescriptionLines` then aligns safe lines; container descriptions keep
1692
+ * the raw columns that also supply membership (docs/flowchart.md, Multi-line
1693
+ * values). The whitespace after `{` is read with `{`, so text on
1559
1694
  * the line of the `{` is spaced as any other token. `valueRange` supplies the
1560
1695
  * printed bounds when a Literal's AST range includes exterior whitespace.
1561
1696
  * `keepsTrailingTrivia` also keeps trivia lines after an opener-line value,
1562
1697
  * without absorbing the closing brace (docs/c4.md, Description blocks).
1563
1698
  */
1564
1699
  function findAccDescrBlockStretches(source, statement, valueRange = statement.value?.range ?? null, keepsTrailingTrivia = false) {
1565
- const brace = expectToken(statement.opening === void 0 ? findStructuralToken(source, expectToken(findTokenStartingAt(source, statement.range[0]), "`accDescr`").range[1]) : findTokenStartingAt(source, statement.opening), "the `{` of an accDescr block");
1700
+ const brace = expectToken(statement.opening === void 0 ? findDescriptionOpening(source, expectToken(findTokenStartingAt(source, statement.range[0]), "`accDescr`")) : findTokenStartingAt(source, statement.opening), "the `{` of an accDescr block");
1566
1701
  expectValue(brace, "{");
1567
1702
  if (valueRange === null) return [];
1568
1703
  const lastTrivia = findTriviaBetween(source, valueRange[1], statement.range[1]).at(-1);
@@ -1576,7 +1711,7 @@ function findAccDescrBlockStretches(source, statement, valueRange = statement.va
1576
1711
  /**
1577
1712
  * The start of the `}` that closes an `accDescr` block, whose line starts
1578
1713
  * at the statement's indentation, or null when the block is not closed. The
1579
- * lines of its text are kept as written (see `findAccDescrBlockStretches`),
1714
+ * text range keeps its written limits (see `findAccDescrBlockStretches`),
1580
1715
  * and the whitespace before the `}` is neither in the text nor in the Db,
1581
1716
  * so the `}` lines up with the `accDescr` that it closes.
1582
1717
  */
@@ -1862,7 +1997,7 @@ function printAtoms(source, layout, indentation) {
1862
1997
  gapOffset = gap.trailing.range[1];
1863
1998
  }
1864
1999
  for (const line of gap.lines) {
1865
- breakCurrentLine(line.blankBefore, false, indentation.trivia ?? alignedIndentation);
2000
+ breakCurrentLine(line.blankBefore, false, alignedIndentation ?? indentation.trivia);
1866
2001
  currentWrittenBreak = keepsBreaks ? literalBreaksBetween(source, gapOffset, line.run.range[0]) : void 0;
1867
2002
  current = [line.run.doc];
1868
2003
  currentEndsWithWhitespace = line.run.endsWithWhitespace;
@@ -2520,9 +2655,11 @@ function layoutBlockRow(source, statements) {
2520
2655
  if (statements.some((statement, index) => index > 0 && readGap(source, statements[index - 1].range[1], statement.range[0], true).breaksLine)) return keptAsWritten(statements[0].range[0], statements.at(-1).range[1]);
2521
2656
  const rules = /* @__PURE__ */ new Map();
2522
2657
  const atoms = [];
2658
+ let lineBreaks = "joined";
2523
2659
  for (const [index, statement] of statements.entries()) {
2524
2660
  const layout = layoutBlockStatement(source, statement);
2525
2661
  appendItems(atoms, layout.atoms);
2662
+ if (layout.lineBreaks === "kept") lineBreaks = "kept";
2526
2663
  for (const [offset, rule] of layout.rules) rules.set(offset, rule);
2527
2664
  if (index > 0) rules.set(statement.range[0], "space");
2528
2665
  }
@@ -2530,7 +2667,7 @@ function layoutBlockRow(source, statements) {
2530
2667
  atoms,
2531
2668
  rules,
2532
2669
  outdented: /* @__PURE__ */ new Set(),
2533
- lineBreaks: "joined"
2670
+ lineBreaks
2534
2671
  };
2535
2672
  }
2536
2673
  /**
@@ -2549,16 +2686,20 @@ function layoutCompositeHead(source, composite) {
2549
2686
  outdented: /* @__PURE__ */ new Set(),
2550
2687
  lineBreaks: "joined"
2551
2688
  };
2552
- if (spansLinesThatCannotJoin(source, keyword.range[0], head.range[1])) return keptAsWritten(keyword.range[0], head.range[1]);
2689
+ const start = keyword.range[0];
2690
+ const end = head.range[1];
2691
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
2692
+ if (keepsLineBreaks && (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
2553
2693
  const layout = layoutBlockStatement(source, head);
2694
+ const atoms = [{
2695
+ start: keyword.range[0],
2696
+ end: keyword.range[1]
2697
+ }, ...layout.atoms];
2554
2698
  return {
2555
- atoms: [{
2556
- start: keyword.range[0],
2557
- end: keyword.range[1]
2558
- }, ...layout.atoms],
2699
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
2559
2700
  rules: new Map([...layout.rules, [head.range[0], "none"]]),
2560
2701
  outdented: /* @__PURE__ */ new Set(),
2561
- lineBreaks: "joined"
2702
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
2562
2703
  };
2563
2704
  }
2564
2705
  /** Where the line that opens a composite ends, and the `end` that closes it. */
@@ -2575,17 +2716,21 @@ function findCompositeBounds(source, composite) {
2575
2716
  * The layout of a statement, from its start to the end of its range.
2576
2717
  *
2577
2718
  * - A statement written over several lines stands on one line where the
2578
- * lexer reads the line break as whitespace; one with a comment or a
2579
- * directive in it, or a `;`, is kept as written (see
2580
- * `spansLinesThatCannotJoin`; docs/block.md, Multi-line statements).
2719
+ * lexer reads the line break as whitespace. Trivia keeps structural gaps
2720
+ * broken with ordinary continuation columns; semicolon lines and joining
2721
+ * regions retain their layout (docs/block.md, Multi-line statements).
2581
2722
  * - The rules of the gaps are those of docs/block.md: Columns and space,
2582
2723
  * Shapes, Edges, and Styles.
2583
2724
  */
2584
2725
  function layoutBlockStatement(source, statement) {
2585
2726
  const start = statement.range[0];
2586
2727
  const end = statement.range[1];
2587
- if (statement.type === "BlockAccDescrBlockStatement") return layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, () => layoutEmptyDescriptionBlock(source, start, end));
2588
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
2728
+ if (statement.type === "BlockAccDescrBlockStatement") return layoutDescriptionBlock(source, {
2729
+ ...statement,
2730
+ value: null
2731
+ }, end, blockValueNodeTypes, { formatsEmptyTrivia: true });
2732
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
2733
+ if (keepsLineBreaks && (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
2589
2734
  const rules = /* @__PURE__ */ new Map();
2590
2735
  const kept = [];
2591
2736
  switch (statement.type) {
@@ -2607,11 +2752,12 @@ function layoutBlockStatement(source, statement) {
2607
2752
  break;
2608
2753
  default: throw new Error(`prettier-plugin-mmd: unknown statement ${JSON.stringify(statement)}`);
2609
2754
  }
2755
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, blockValueNodeTypes), kept);
2610
2756
  return {
2611
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, blockValueNodeTypes), kept),
2757
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
2612
2758
  rules,
2613
2759
  outdented: /* @__PURE__ */ new Set(),
2614
- lineBreaks: "joined"
2760
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
2615
2761
  };
2616
2762
  }
2617
2763
  /**
@@ -3108,7 +3254,7 @@ function layoutBlockOpening$2(source, statement, opening) {
3108
3254
  * break inside a statement is whitespace to the lexer only after
3109
3255
  * `direction` and after the `:` of `accTitle` and `accDescr`
3110
3256
  * (diagrams/class.md, The statement context); one with a comment or a
3111
- * directive in it is kept as written (see `spansLinesThatCannotJoin`). The
3257
+ * directive keeps its line breaks and aligns structural continuations. The
3112
3258
  * lines of an `accDescr { ... }` block are lines of its text, and are
3113
3259
  * kept (docs/class.md, Multi-line values).
3114
3260
  * - A relation has one space on each side of its arrow and of its
@@ -3122,49 +3268,59 @@ function layoutBlockOpening$2(source, statement, opening) {
3122
3268
  */
3123
3269
  function layoutClassStatement(source, statement, end) {
3124
3270
  const start = statement.range[0];
3125
- if (statement.type !== "ClassAccDescrBlockStatement" && spansLinesThatCannotJoin(source, start, end)) return {
3126
- atoms: [{
3127
- start,
3128
- end
3129
- }],
3130
- rules: /* @__PURE__ */ new Map(),
3131
- outdented: /* @__PURE__ */ new Set(),
3132
- lineBreaks: "kept"
3133
- };
3134
- const values = collectValueNodes(statement, classValueNodeTypes);
3135
3271
  if (statement.type === "ClassAccDescrBlockStatement") {
3136
3272
  const block = {
3137
3273
  range: statement.range,
3138
3274
  value: statement.value,
3139
3275
  closed: true
3140
3276
  };
3141
- /** Builds the existing value, trivia and closing-brace layout. */
3142
- function originalLayout() {
3277
+ /** Keeps the block's line breaks, including those around empty trivia. */
3278
+ function layoutExpandedBlock() {
3143
3279
  const closing = findAccDescrBlockClosing(source, block);
3144
- return {
3145
- atoms: collectAtoms(source, start, end, values, findAccDescrBlockStretches(source, block)),
3146
- rules: /* @__PURE__ */ new Map(),
3280
+ return indentDescriptionLines(source, block, {
3281
+ atoms: collectAtoms(source, start, end, collectValueNodes(statement, classValueNodeTypes), findAccDescrBlockStretches(source, block)),
3282
+ rules: descriptionOpeningRules(source, start),
3147
3283
  outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing]),
3148
3284
  lineBreaks: "kept"
3149
- };
3285
+ });
3150
3286
  }
3151
- return statement.value === null ? layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, originalLayout) : originalLayout();
3287
+ return statement.value === null ? layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, layoutExpandedBlock) : layoutExpandedBlock();
3152
3288
  }
3289
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
3290
+ if (keepsLineBreaks && (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return {
3291
+ atoms: [{
3292
+ start,
3293
+ end
3294
+ }],
3295
+ rules: /* @__PURE__ */ new Map(),
3296
+ outdented: /* @__PURE__ */ new Set(),
3297
+ lineBreaks: "kept"
3298
+ };
3299
+ const values = collectValueNodes(statement, classValueNodeTypes);
3153
3300
  const kept = [
3154
3301
  ...findGenericStretches(source, statement, end),
3155
- ...findMemberStretches(statement),
3302
+ ...findMemberStretches(source, statement),
3156
3303
  ...findBlankLabelStretches(source, statement),
3157
3304
  ...findOpenNameStretches(source, statement)
3158
3305
  ];
3306
+ if (statement.type === "ClassCallbackStatement" && statement.callback.type === "ClassLiteral") {
3307
+ const opening = expectToken(findStructuralToken(source, statement.callback.range[1]), "the `(` after a callback name");
3308
+ expectValue(opening, "(");
3309
+ kept.push({
3310
+ start: statement.callback.range[0],
3311
+ end: opening.range[1]
3312
+ });
3313
+ }
3159
3314
  const keepsDirectionValue = (statement.type === "ClassAccTitleStatement" || statement.type === "ClassAccDescrStatement") && source.text.slice(start, statement.value.range[0]).includes("\n") && holdsDirection(source, {
3160
3315
  range: statement.range,
3161
3316
  text: statement.value.value
3162
3317
  }, { caseSensitive: true });
3318
+ const atoms = collectAtoms(source, start, end, values.filter((value) => !kept.some((stretch) => containsRange(stretch, value))), kept);
3163
3319
  return {
3164
- atoms: collectAtoms(source, start, end, values.filter((value) => !kept.some((stretch) => containsRange(stretch, value))), kept),
3320
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
3165
3321
  rules: statementRules$8(source, statement),
3166
3322
  outdented: /* @__PURE__ */ new Set(),
3167
- lineBreaks: keepsDirectionValue ? "kept" : "joined"
3323
+ lineBreaks: keepsLineBreaks || keepsDirectionValue ? "kept" : "joined"
3168
3324
  };
3169
3325
  }
3170
3326
  /**
@@ -3241,20 +3397,43 @@ function findBlankLabelStretches(source, statement) {
3241
3397
  }];
3242
3398
  }
3243
3399
  /**
3244
- * The member lines of a statement, each printed as written: the member of
3245
- * a member statement. The whitespace after a visibility mark is part of
3400
+ * The member of a member statement, retaining its values while ordinary
3401
+ * method padding uses its planned layout. Whitespace after a visibility mark is part of
3246
3402
  * the member's name in the Db (diagrams/class.md, Building the summary):
3247
3403
  * `+ foo()` has the name ` foo`, and `+foo()` the name `foo`.
3248
3404
  */
3249
- function findMemberStretches(statement) {
3405
+ function findMemberStretches(source, statement) {
3250
3406
  if (statement.type !== "ClassMemberStatement" || statement.member === null) return [];
3251
3407
  const { range } = statement.member;
3252
3408
  return [{
3253
3409
  start: range[0],
3254
- end: range[1]
3410
+ end: range[1],
3411
+ doc: statement.member.type === "ClassMethod" ? printClassMethod(source, statement.member) : void 0
3255
3412
  }];
3256
3413
  }
3257
3414
  /**
3415
+ * Method fields already exclude harmless exterior padding. Keep their contents
3416
+ * and classifier tails, formatting only the gaps around the AST fields
3417
+ * (diagrams/class.md, Member lines; docs/class.md, Member lines).
3418
+ */
3419
+ function printClassMethod(source, method) {
3420
+ const [start, end] = method.range;
3421
+ const text = source.text.slice(start, end);
3422
+ if (method.textBefore !== null || method.textAfter !== null || text.includes("\n") || text.includes("\u2028") || text.includes("\u2029") || text.includes(";") || findClassSemicolonLines(source).has(lineStartOf(source, start)) || findTriviaBetween(source, start, end).length > 0) return void 0;
3423
+ const atoms = collectAtoms(source, start, end, collectValueNodes(method, classValueNodeTypes), []);
3424
+ const rules = /* @__PURE__ */ new Map();
3425
+ for (const atom of atoms.slice(1)) rules.set(atom.start, atom.start === method.returnType?.range[0] ? "space" : "none");
3426
+ return printAtoms(source, {
3427
+ atoms,
3428
+ rules,
3429
+ outdented: /* @__PURE__ */ new Set(),
3430
+ lineBreaks: "joined"
3431
+ }, {
3432
+ statement: "",
3433
+ continuation: ""
3434
+ }).doc;
3435
+ }
3436
+ /**
3258
3437
  * The generic types of the class names of a node before `end`, each from
3259
3438
  * its first `~` to its second, as written: the whitespace between the two
3260
3439
  * `~` is part of the type in the Db (diagrams/class.md, Building the
@@ -3422,7 +3601,7 @@ function printClass(path, options, print, source) {
3422
3601
  const node = path.node;
3423
3602
  switch (node.type) {
3424
3603
  case "ClassDiagram": return withSignificantIndentation(printDiagram$6(path, bodyOptions, print, source, node), options);
3425
- case "ClassMethod":
3604
+ case "ClassMethod": return printClassMethod(source, node) ?? printAsWritten(source, node.range[0], node.range[1]);
3426
3605
  case "ClassAttribute":
3427
3606
  case "ClassAnnotation": return printAsWritten(source, node.range[0], node.range[1]);
3428
3607
  }
@@ -3476,7 +3655,7 @@ function printNamespace(path, options, print, source, statement, depth) {
3476
3655
  }
3477
3656
  /**
3478
3657
  * Prints a class statement with its member body: the line of the class with
3479
- * its `{`, the member lines one level deeper, each as written, and the `}`
3658
+ * its `{`, the member lines one level deeper using their own layouts, and the `}`
3480
3659
  * (docs/class.md, Member bodies).
3481
3660
  */
3482
3661
  function printMemberBlock(path, options, print, source, statement, depth) {
@@ -3752,7 +3931,7 @@ function findC4KeptLines(source) {
3752
3931
  const line = lineStartOf(source, directive.range[0]);
3753
3932
  const end = lineEndOf(source, directive.range[1]);
3754
3933
  const next = nonDirectiveTokens[findFirstIndex(nonDirectiveTokens, (token) => token.range[0] >= line)];
3755
- if (next !== void 0 && next.range[0] < end) verbatim.add(line);
3934
+ if (next !== void 0 && next.range[0] < end) joined.add(line);
3756
3935
  }
3757
3936
  const kept = {
3758
3937
  joined,
@@ -3818,15 +3997,47 @@ function addNameListRules(source, names, rules) {
3818
3997
  /**
3819
3998
  * The rules of a `classDef` or `style` statement: its names are separated by
3820
3999
  * `,` without whitespace, and the first style stands after one space. The
3821
- * styles are printed as written, and the whitespace between them and the `,`
3822
- * is as in the source.
4000
+ * default style/comma gaps follow the source. Safe ER and requirement units
4001
+ * instead use no space before a comma and one after it (docs/er.md and
4002
+ * docs/requirement.md, Styles and classes).
3823
4003
  */
3824
- function styleStatementRules(source, names, styles) {
4004
+ function styleStatementRules(source, names, styles, compactStyles = false) {
3825
4005
  const rules = /* @__PURE__ */ new Map();
3826
4006
  addNameListRules(source, names, rules);
3827
4007
  rules.set(styles[0].range[0], "space");
4008
+ if (compactStyles) for (let index = 1; index < styles.length; index++) {
4009
+ const comma = expectToken(findStructuralToken(source, styles[index - 1].range[1]), "the comma between styles");
4010
+ rules.set(comma.range[0], "none");
4011
+ rules.set(styles[index].range[0], "space");
4012
+ }
3828
4013
  return rules;
3829
4014
  }
4015
+ /** Keep property and value text, changing only the first colon's padding. */
4016
+ function printStyleUnitSpacing(source, style) {
4017
+ const colon = source.text.indexOf(":", style.range[0]);
4018
+ if (colon <= style.range[0] || colon >= style.range[1]) return printAsWritten(source, ...style.range);
4019
+ let propertyEnd = colon;
4020
+ while (source.text[propertyEnd - 1] === " " || source.text[propertyEnd - 1] === " ") propertyEnd--;
4021
+ if (propertyEnd === style.range[0]) return printAsWritten(source, ...style.range);
4022
+ let valueStart = colon + 1;
4023
+ while (source.text[valueStart] === " " || source.text[valueStart] === " ") valueStart++;
4024
+ return [
4025
+ printAsWritten(source, style.range[0], propertyEnd),
4026
+ ":",
4027
+ valueStart < style.range[1] ? [" ", printAsWritten(source, valueStart, style.range[1])] : ""
4028
+ ];
4029
+ }
4030
+ /**
4031
+ * ER and requirement discard simple same-line style-unit padding. Keep trivia,
4032
+ * physical/Unicode line boundaries and complete semicolon-sensitive lines on
4033
+ * their original path (diagrams/er.md and diagrams/requirement.md, Style context).
4034
+ */
4035
+ function styleUnitsCanCompact(source, start, end, styles) {
4036
+ return styles.every((style) => {
4037
+ const text = source.text.slice(...style.range);
4038
+ return !text.includes("\n") && !text.includes("\u2028") && !text.includes("\u2029");
4039
+ }) && !source.text.slice(lineStartOf(source, start), lineEndOf(source, end)).includes(";") && findTriviaBetween(source, start, end).length === 0;
4040
+ }
3830
4041
  /**
3831
4042
  * The rules of a `class` statement: the names of the entities and the
3832
4043
  * classes are lists separated by `,` without whitespace, and the first class
@@ -3916,13 +4127,33 @@ function layoutC4Header(source, diagram) {
3916
4127
  const start = diagram.range[0];
3917
4128
  const keyword = expectToken(findTokenStartingAt(source, start), "the C4 header");
3918
4129
  const end = diagram.beforeBody.at(-1)?.range[1] ?? keyword.range[1];
3919
- if (findTriviaBetween(source, start, end).length > 0) return keptAsWritten(start, end);
3920
- return {
4130
+ const layout = findTriviaBetween(source, start, end).length > 0 ? keptAsWritten(start, end) : {
3921
4131
  atoms: collectAtoms(source, start, end, [], []),
3922
4132
  rules: /* @__PURE__ */ new Map(),
3923
4133
  outdented: /* @__PURE__ */ new Set(),
3924
4134
  lineBreaks: "joined"
3925
4135
  };
4136
+ return indentC4BeforeBody(source, diagram.beforeBody, layout);
4137
+ }
4138
+ /**
4139
+ * Null blocks before a body use ordinary description columns without changing
4140
+ * their adjacency or line breaks. Protected source stays written (ast/c4.md,
4141
+ * C4Diagram and C4BoundaryStatement; docs/c4.md, Empty description blocks).
4142
+ */
4143
+ function indentC4BeforeBody(source, blocks, layout) {
4144
+ let aligned = layout;
4145
+ for (const block of blocks) {
4146
+ const text = source.text.slice(...block.range);
4147
+ if (text.includes(";") || holdsJoiningRegion(source, ...block.range)) continue;
4148
+ aligned = spaceDescriptionOpening(source, block.range[0], aligned);
4149
+ if (!text.includes("\n")) continue;
4150
+ aligned = indentDescriptionLines(source, {
4151
+ range: block.range,
4152
+ value: block.value,
4153
+ closed: true
4154
+ }, aligned);
4155
+ }
4156
+ return aligned;
3926
4157
  }
3927
4158
  /** The boundary braces, outside arguments and beforeBody blocks. */
3928
4159
  function c4BoundaryBraces(source, statement) {
@@ -3944,11 +4175,11 @@ function layoutC4Call(source, statement, end) {
3944
4175
  const start = statement.range[0];
3945
4176
  const opening = findTokenEndingBefore(source, end);
3946
4177
  if (statement.type === "C4BoundaryStatement" && opening?.value === "{") {
3947
- const previous = expectToken(findTokenEndingBefore(source, opening.range[0]), "the end of a C4 boundary call");
4178
+ const previous = expectToken(findTokensBetween(source, start, opening.range[0]).findLast((token) => token.type !== "Directive"), "the end of a C4 boundary call");
3948
4179
  const gap = source.text.slice(previous.range[1], opening.range[0]);
3949
- if (gap.includes("\n") && gap.trim() === "" && !gap.includes("\u2028") && !gap.includes("\u2029") && findTriviaBetween(source, start, end).length === 0) {
4180
+ if (gap.includes("\n") && gap.trim() === "" && !gap.includes("\u2028") && !gap.includes("\u2029") && findTriviaBetween(source, previous.range[1], opening.range[0]).length === 0) {
3950
4181
  const head = layoutC4Call(source, statement, previous.range[1]);
3951
- return {
4182
+ return alignBlockOpeningLine(source, {
3952
4183
  ...head,
3953
4184
  atoms: [...head.atoms, {
3954
4185
  start: opening.range[0],
@@ -3956,11 +4187,72 @@ function layoutC4Call(source, statement, end) {
3956
4187
  }],
3957
4188
  rules: new Map([...head.rules, [opening.range[0], "space"]]),
3958
4189
  joinedBefore: /* @__PURE__ */ new Set([...head.joinedBefore ?? [], opening.range[0]])
3959
- };
4190
+ }, previous.range[0]);
3960
4191
  }
3961
4192
  }
3962
- if (findTriviaBetween(source, start, end).length > 0 || spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
4193
+ if (spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true })) return keptAsWritten(start, end);
3963
4194
  const values = collectValueNodes(statement, c4ValueNodeTypes).filter((value) => value.range[1] <= end);
4195
+ const namedAttributes = statement.arguments.filter((argument) => argument?.type === "C4NamedAttribute");
4196
+ const atoms = splitC4EmptyEntryTokens(source, collectAtoms(source, start, end, values, findC4CallStretches(source, statement, end, values)));
4197
+ const rules = /* @__PURE__ */ new Map();
4198
+ const outdented = /* @__PURE__ */ new Set();
4199
+ const joinedBefore = /* @__PURE__ */ new Set();
4200
+ const keptBreaksBefore = /* @__PURE__ */ new Set();
4201
+ const bareStarts = /* @__PURE__ */ new Set();
4202
+ const bareEnds = /* @__PURE__ */ new Set();
4203
+ for (const argument of statement.arguments) {
4204
+ if (argument?.type !== "C4Literal") continue;
4205
+ bareStarts.add(argument.range[0]);
4206
+ bareEnds.add(argument.range[1]);
4207
+ }
4208
+ for (let index = 1; index < atoms.length; index++) {
4209
+ const previous = atoms[index - 1];
4210
+ const atom = atoms[index];
4211
+ const before = source.text.slice(previous.start, previous.end);
4212
+ const text = source.text.slice(atom.start, atom.end);
4213
+ const gap = source.text.slice(previous.end, atom.start);
4214
+ const sensitivePrefix = bareStarts.has(atom.start) && (text.startsWith("\"") || text.startsWith("$"));
4215
+ const afterDelimiter = before === "(" || before.endsWith(",");
4216
+ const beforeComma = text.startsWith(",");
4217
+ const inBeforeBody = statement.type === "C4BoundaryStatement" && statement.beforeBody.some((block) => block.range[0] <= atom.start && atom.end <= block.range[1]);
4218
+ const afterCall = statement.type === "C4BoundaryStatement" && atom.start >= (statement.beforeBody[0]?.range[0] ?? end - 1);
4219
+ const namedGap = namedAttributes.some((argument) => argument.range[0] <= previous.start && atom.end <= argument.range[1]);
4220
+ if (namedGap && gap.includes("\n")) keptBreaksBefore.add(atom.start);
4221
+ const keepsPhysicalLine = gap.includes("\n") && !afterCall && !namedGap;
4222
+ const keepsCommaGap = beforeComma && !bareEnds.has(previous.end) && before !== "(";
4223
+ if (keepsPhysicalLine || sensitivePrefix || keepsCommaGap || !inBeforeBody && !afterCall && !afterDelimiter && !beforeComma && before !== "$" && text !== "=" && before !== "=" && text !== "{") {
4224
+ if (gap !== "") atoms[index] = {
4225
+ start: previous.end,
4226
+ end: atom.end
4227
+ };
4228
+ rules.set(previous.end, "none");
4229
+ continue;
4230
+ }
4231
+ if (afterCall && findTriviaBetween(source, previous.end, atom.start).length === 0) joinedBefore.add(atom.start);
4232
+ if (text === "{" && atom.end === end) {
4233
+ outdented.add(atom.start);
4234
+ rules.set(atom.start, "space");
4235
+ } else if (afterDelimiter) rules.set(atom.start, before !== "(" && text !== ")" && !beforeComma ? "space" : "none");
4236
+ else if (namedGap && (text === "=" || before === "=")) rules.set(atom.start, "space");
4237
+ else if (beforeComma || text === ")" || before === "$" || text === "=" || before === "=") rules.set(atom.start, "none");
4238
+ }
4239
+ const layout = indentC4BeforeBody(source, statement.type === "C4BoundaryStatement" ? statement.beforeBody : [], {
4240
+ atoms,
4241
+ rules,
4242
+ outdented,
4243
+ lineBreaks: "kept",
4244
+ joinedBefore,
4245
+ keptBreaksBefore
4246
+ });
4247
+ return statement.type === "C4BoundaryStatement" && opening?.value === "{" ? alignBlockOpeningLine(source, layout, opening.range[0]) : layout;
4248
+ }
4249
+ /**
4250
+ * Preserve semicolon-bearing null blocks and textual line prefixes through
4251
+ * their last semicolon. A prefix can cross a value, which must stay whole
4252
+ * (common.md, Style and classDef lines; docs/c4.md, Line rule and semicolons).
4253
+ */
4254
+ function findC4CallStretches(source, statement, end, values) {
4255
+ const start = statement.range[0];
3964
4256
  const kept = [];
3965
4257
  if (statement.type === "C4BoundaryStatement") {
3966
4258
  for (const block of statement.beforeBody) if (source.text.slice(...block.range).includes(";")) kept.push({
@@ -3968,10 +4260,6 @@ function layoutC4Call(source, statement, end) {
3968
4260
  end: block.range[1]
3969
4261
  });
3970
4262
  }
3971
- for (const argument of statement.arguments) if (argument?.type === "C4NamedAttribute" && source.text.slice(...argument.range).includes("\n")) kept.push({
3972
- start: argument.range[0],
3973
- end: argument.range[1]
3974
- });
3975
4263
  for (let line = lineStartOf(source, start); line < end;) {
3976
4264
  const lineEnd = semicolonSegmentEnd(source, line);
3977
4265
  const last = source.text.lastIndexOf(";", Math.min(end, lineEnd) - 1);
@@ -3999,51 +4287,25 @@ function layoutC4Call(source, statement, end) {
3999
4287
  };
4000
4288
  else stretches.push(stretch);
4001
4289
  }
4002
- const atoms = collectAtoms(source, start, end, values, stretches).flatMap((atom) => {
4290
+ return stretches;
4291
+ }
4292
+ /** Expose the padding in an opening empty-entry token (tokens/c4.md). */
4293
+ function splitC4EmptyEntryTokens(source, atoms) {
4294
+ const split = [];
4295
+ for (const atom of atoms) {
4003
4296
  const token = findTokenStartingAt(source, atom.start);
4004
- return token?.type === "Punctuator" && token.value.startsWith("(") && token.value.endsWith(",") ? [{
4005
- start: atom.start,
4006
- end: atom.start + 1
4007
- }, {
4008
- start: atom.end - 1,
4009
- end: atom.end
4010
- }] : [atom];
4011
- });
4012
- const rules = /* @__PURE__ */ new Map();
4013
- const joinedBefore = /* @__PURE__ */ new Set();
4014
- const bareStarts = new Set(statement.arguments.filter((argument) => argument?.type === "C4Literal").map((argument) => argument.range[0]));
4015
- const bareEnds = new Set(statement.arguments.filter((argument) => argument?.type === "C4Literal").map((argument) => argument.range[1]));
4016
- for (let index = 1; index < atoms.length; index++) {
4017
- const previous = atoms[index - 1];
4018
- const atom = atoms[index];
4019
- const before = source.text.slice(previous.start, previous.end);
4020
- const text = source.text.slice(atom.start, atom.end);
4021
- const gap = source.text.slice(previous.end, atom.start);
4022
- const sensitivePrefix = bareStarts.has(atom.start) && (text.startsWith("\"") || text.startsWith("$"));
4023
- const afterDelimiter = before === "(" || before.endsWith(",");
4024
- const beforeComma = text.startsWith(",");
4025
- const inBeforeBody = statement.type === "C4BoundaryStatement" && statement.beforeBody.some((block) => block.range[0] <= atom.start && atom.end <= block.range[1]);
4026
- const afterCall = statement.type === "C4BoundaryStatement" && atom.start >= (statement.beforeBody[0]?.range[0] ?? end - 1);
4027
- if (gap.includes("\n") && !afterCall || sensitivePrefix || beforeComma && !bareEnds.has(previous.end) && before !== "(" || !inBeforeBody && !afterCall && !afterDelimiter && !beforeComma && before !== "$" && text !== "=" && before !== "=" && text !== "{") {
4028
- if (gap !== "") atoms[index] = {
4029
- start: previous.end,
4297
+ if (token?.type === "Punctuator" && token.value.startsWith("(") && token.value.endsWith(",")) {
4298
+ split.push({
4299
+ start: atom.start,
4300
+ end: atom.start + 1
4301
+ });
4302
+ split.push({
4303
+ start: atom.end - 1,
4030
4304
  end: atom.end
4031
- };
4032
- rules.set(previous.end, "none");
4033
- continue;
4034
- }
4035
- if (afterCall) joinedBefore.add(atom.start);
4036
- if (text === "{" && atom.end === end) rules.set(atom.start, "space");
4037
- else if (afterDelimiter) rules.set(atom.start, before !== "(" && text !== ")" && !beforeComma ? "space" : "none");
4038
- else if (beforeComma || text === ")" || before === "$" || text === "=" || before === "=") rules.set(atom.start, "none");
4305
+ });
4306
+ } else split.push(atom);
4039
4307
  }
4040
- return {
4041
- atoms,
4042
- rules,
4043
- outdented: /* @__PURE__ */ new Set(),
4044
- lineBreaks: "kept",
4045
- joinedBefore
4046
- };
4308
+ return split;
4047
4309
  }
4048
4310
  /**
4049
4311
  * Title separators consume one character, unlike colon text. A multiline
@@ -4055,32 +4317,36 @@ function layoutC4Text(source, statement) {
4055
4317
  const [start, end] = statement.range;
4056
4318
  if (keptSemicolonPrefixEnd(source, start) > start) return keptAsWritten(start, end);
4057
4319
  if (statement.type === "C4AccDescrBlockStatement") {
4058
- if (findTriviaBetween(source, start, end).some((item) => item.type === "Directive") || source.text.slice(start, end).includes(";")) return keptAsWritten(start, end);
4320
+ if (source.text.slice(start, end).includes(";")) return keptAsWritten(start, end);
4059
4321
  return layoutDescriptionBlock(source, statement, end, c4ValueNodeTypes, { keepsTrailingTrivia: true });
4060
4322
  }
4061
- if (findTriviaBetween(source, start, end).length > 0 || spansLinesThatCannotJoin(source, start, end) || source.text.slice(start, end).includes("\n") && c4DirectionIn(statement.value?.value ?? "")) return keptAsWritten(start, end);
4062
- if (statement.type === "C4TitleStatement" || statement.type === "C4AccDescriptionStatement") {
4063
- const separator = expectToken(findTokenStartingAt(source, start), "a C4 title keyword").range[1];
4064
- if (source.text[separator] === "\u2028" || source.text[separator] === "\u2029") return keptAsWritten(start, end);
4323
+ if (source.text.slice(start, end).includes("\n") && c4DirectionIn(statement.value?.value ?? "")) return keptAsWritten(start, end);
4324
+ if (statement.type === "C4AccTitleStatement" || statement.type === "C4AccDescrStatement") {
4325
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
4326
+ if (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true })) return keptAsWritten(start, end);
4327
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, c4ValueNodeTypes), []);
4065
4328
  return {
4066
- atoms: [{
4067
- start,
4068
- end: separator
4069
- }, {
4070
- start: separator + 1,
4071
- end
4072
- }],
4073
- rules: /* @__PURE__ */ new Map([[separator + 1, "space"]]),
4329
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
4330
+ rules: statement.value === null ? /* @__PURE__ */ new Map() : accessibilityRules(source, {
4331
+ range: statement.range,
4332
+ value: statement.value
4333
+ }),
4074
4334
  outdented: /* @__PURE__ */ new Set(),
4075
- lineBreaks: "joined"
4335
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
4076
4336
  };
4077
4337
  }
4338
+ if (findTriviaBetween(source, start, end).length > 0 || spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
4339
+ const separator = expectToken(findTokenStartingAt(source, start), "a C4 title keyword").range[1];
4340
+ if (source.text[separator] === "\u2028" || source.text[separator] === "\u2029") return keptAsWritten(start, end);
4078
4341
  return {
4079
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, c4ValueNodeTypes), []),
4080
- rules: statement.value === null ? /* @__PURE__ */ new Map() : accessibilityRules(source, {
4081
- range: statement.range,
4082
- value: statement.value
4083
- }),
4342
+ atoms: [{
4343
+ start,
4344
+ end: separator
4345
+ }, {
4346
+ start: separator + 1,
4347
+ end
4348
+ }],
4349
+ rules: /* @__PURE__ */ new Map([[separator + 1, "space"]]),
4084
4350
  outdented: /* @__PURE__ */ new Set(),
4085
4351
  lineBreaks: "joined"
4086
4352
  };
@@ -4345,73 +4611,44 @@ function layoutUsecaseStatement(source, statement, end) {
4345
4611
  */
4346
4612
  function layoutUsecaseAccessibility(source, statement, end) {
4347
4613
  const start = statement.range[0];
4614
+ if (statement.type === "UsecaseAccDescrBlockStatement") {
4615
+ const layout = layoutDescriptionBlock(source, statement, end, usecaseValueNodeTypes, {
4616
+ trimValueEdges: true,
4617
+ formatsEmptyTrivia: true,
4618
+ keepsTrailingTrivia: true
4619
+ });
4620
+ return {
4621
+ ...layout,
4622
+ atoms: protectSemicolonPrefixes(source, start, end, layout.atoms)
4623
+ };
4624
+ }
4348
4625
  const keyword = expectToken(findStructuralToken(source, start), "the accessibility keyword");
4349
- const separator = expectToken(findStructuralToken(source, keyword.range[1]), "the accessibility colon or brace");
4626
+ const separator = expectToken(findStructuralToken(source, keyword.range[1]), "the accessibility colon");
4350
4627
  const valueRange = trimmedLiteralRange(source, statement.value);
4351
4628
  const rules = /* @__PURE__ */ new Map();
4352
- const outdented = /* @__PURE__ */ new Set();
4353
4629
  const joinedBefore = /* @__PURE__ */ new Set();
4354
- let atoms = [{
4630
+ const atoms = [{
4355
4631
  start: keyword.range[0],
4356
4632
  end: keyword.range[1]
4633
+ }, {
4634
+ start: separator.range[0],
4635
+ end: separator.range[1]
4357
4636
  }];
4358
- let lineBreaks = "kept";
4359
- if (statement.type !== "UsecaseAccDescrBlockStatement") {
4637
+ rules.set(separator.range[0], "none");
4638
+ if (valueRange !== null) {
4360
4639
  atoms.push({
4361
- start: separator.range[0],
4362
- end: separator.range[1]
4640
+ start: valueRange[0],
4641
+ end: valueRange[1]
4363
4642
  });
4364
- rules.set(separator.range[0], "none");
4365
- if (valueRange !== null) {
4366
- atoms.push({
4367
- start: valueRange[0],
4368
- end: valueRange[1]
4369
- });
4370
- rules.set(valueRange[0], "space");
4371
- joinedBefore.add(valueRange[0]);
4372
- }
4373
- } else {
4374
- if (valueRange === null && spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
4375
- const block = {
4376
- range: statement.range,
4377
- value: statement.value,
4378
- closed: true
4379
- };
4380
- const closing = findAccDescrBlockClosing(source, block);
4381
- if (closing === null) throw new Error("prettier-plugin-mmd: an unclosed usecase description block");
4382
- const stretches = findAccDescrBlockStretches(source, block, valueRange);
4383
- if (stretches.length > 0) appendItems(atoms, stretches);
4384
- else {
4385
- atoms.push({
4386
- start: separator.range[0],
4387
- end: separator.range[1]
4388
- });
4389
- if (valueRange !== null) {
4390
- atoms.push({
4391
- start: valueRange[0],
4392
- end: valueRange[1]
4393
- });
4394
- joinedBefore.add(valueRange[0]);
4395
- }
4396
- }
4397
- atoms.push({
4398
- start: closing,
4399
- end
4400
- });
4401
- outdented.add(closing);
4402
- if (valueRange === null) {
4403
- rules.set(closing, "none");
4404
- joinedBefore.add(closing);
4405
- lineBreaks = "joined";
4406
- }
4643
+ rules.set(valueRange[0], "space");
4644
+ joinedBefore.add(valueRange[0]);
4407
4645
  }
4408
- atoms = protectSemicolonPrefixes(source, start, end, atoms);
4409
4646
  return {
4410
- atoms,
4647
+ atoms: protectSemicolonPrefixes(source, start, end, atoms),
4411
4648
  rules,
4412
- outdented,
4649
+ outdented: /* @__PURE__ */ new Set(),
4413
4650
  joinedBefore,
4414
- lineBreaks
4651
+ lineBreaks: "kept"
4415
4652
  };
4416
4653
  }
4417
4654
  /** Trims exterior common whitespace while keeping complete embedded trivia. */
@@ -4789,26 +5026,35 @@ function layoutBlockOpening$1(source, statement, opening) {
4789
5026
  * lexer reads the line break as whitespace, which it does only after the
4790
5027
  * `:` of `accTitle` and `accDescr`, between `direction` and its value, and
4791
5028
  * inside the statements of the style context (diagrams/er.md, The
4792
- * statement context); one with a comment or a directive in it is kept as
4793
- * written (see `spansLinesThatCannotJoin`). The lines of an `accDescr`
4794
- * block are lines of its text, and are kept (docs/er.md, Multi-line
4795
- * values).
5029
+ * statement context); comments and directives keep line breaks while
5030
+ * structural continuations align. The lines of an `accDescr`
5031
+ * block keep their line breaks and align one level inside the statement,
5032
+ * except inside subgraphs, where raw text also supplies membership
5033
+ * (docs/er.md, Multi-line values).
4796
5034
  * - A relationship has one space around its three units and its `:`
4797
5035
  * (docs/er.md, Relationship spacing).
4798
5036
  * - The classes after `:::` and in the lists of `class`, `classDef`, and
4799
5037
  * `style` statements are separated by `,` without whitespace
4800
5038
  * (docs/er.md, Entities and Styles and classes).
4801
5039
  */
4802
- function layoutErStatement(source, statement, end) {
5040
+ function layoutErStatement(source, statement, end, preservesDescriptionColumns) {
4803
5041
  const start = statement.range[0];
4804
- if (statement.type === "ErAccDescrBlockStatement") return layoutDescriptionBlock(source, statement, end, erValueNodeTypes);
4805
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
5042
+ if (statement.type === "ErAccDescrBlockStatement") return layoutDescriptionBlock(source, statement, end, erValueNodeTypes, { preservesBodyColumns: preservesDescriptionColumns });
5043
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
5044
+ if (keepsLineBreaks && (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
4806
5045
  const kept = findKeptStretches$1(source, statement);
5046
+ const styles = (statement.type === "ErStyleStatement" || statement.type === "ErClassDefStatement") && styleUnitsCanCompact(source, start, end, statement.styles) ? statement.styles : [];
5047
+ for (const style of styles) kept.push({
5048
+ start: style.range[0],
5049
+ end: style.range[1],
5050
+ doc: printStyleUnitSpacing(source, style)
5051
+ });
5052
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, erValueNodeTypes), kept);
4807
5053
  return {
4808
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, erValueNodeTypes), kept),
4809
- rules: statementRules$7(source, statement),
5054
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
5055
+ rules: statementRules$7(source, statement, styles.length > 0),
4810
5056
  outdented: /* @__PURE__ */ new Set(),
4811
- lineBreaks: "joined"
5057
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
4812
5058
  };
4813
5059
  }
4814
5060
  /**
@@ -4840,12 +5086,14 @@ function findEndingSemicolonStretches(source, statement) {
4840
5086
  }
4841
5087
  /**
4842
5088
  * The layout of an attribute: its type, `?`, name, keys, and comment on one
4843
- * line (docs/er.md, Attribute spacing). An attribute with a comment or a
4844
- * directive between its parts, written over lines, is kept as written.
5089
+ * line (docs/er.md, Attribute spacing). Comments and directives keep the line
5090
+ * breaks, while structural gaps still take continuation indentation. Joining
5091
+ * regions and textual semicolon boundaries retain their complete source.
4845
5092
  */
4846
5093
  function layoutAttribute(source, attribute) {
4847
5094
  const [start, end] = attribute.range;
4848
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
5095
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
5096
+ if (keepsLineBreaks && (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
4849
5097
  const rules = /* @__PURE__ */ new Map([[attribute.name.range[0], "space"]]);
4850
5098
  for (const token of findTokensBetween(source, start, end)) if (isStructural(source, token) && token.value === "?") rules.set(token.range[0], "none");
4851
5099
  for (const [index, key] of attribute.keys.entries()) {
@@ -4858,7 +5106,7 @@ function layoutAttribute(source, attribute) {
4858
5106
  atoms: collectAtoms(source, start, end, collectValueNodes(attribute, erValueNodeTypes), []),
4859
5107
  rules,
4860
5108
  outdented: /* @__PURE__ */ new Set(),
4861
- lineBreaks: "joined"
5109
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
4862
5110
  };
4863
5111
  }
4864
5112
  /**
@@ -4869,7 +5117,7 @@ function findStructuralTokenBefore(source, offset, lowerBound) {
4869
5117
  return findTokensBetween(source, lowerBound, offset).filter((token) => isStructural(source, token)).at(-1);
4870
5118
  }
4871
5119
  /** The gap rules of a statement. */
4872
- function statementRules$7(source, statement) {
5120
+ function statementRules$7(source, statement, compactStyles = false) {
4873
5121
  switch (statement.type) {
4874
5122
  case "ErEntityStatement": {
4875
5123
  const rules = entityHeaderRules(source, statement);
@@ -4882,8 +5130,8 @@ function statementRules$7(source, statement) {
4882
5130
  }
4883
5131
  case "ErRelationshipStatement": return relationshipRules$1(source, statement);
4884
5132
  case "ErDirectionStatement": return directionRules(source, statement);
4885
- case "ErClassDefStatement": return styleStatementRules(source, statement.cssClasses, statement.styles);
4886
- case "ErStyleStatement": return styleStatementRules(source, statement.entities, statement.styles);
5133
+ case "ErClassDefStatement": return styleStatementRules(source, statement.cssClasses, statement.styles, compactStyles);
5134
+ case "ErStyleStatement": return styleStatementRules(source, statement.entities, statement.styles, compactStyles);
4887
5135
  case "ErClassStatement": return classStatementRules(source, statement.entities, statement.cssClasses);
4888
5136
  case "ErAccTitleStatement":
4889
5137
  case "ErAccDescrStatement": return accessibilityRules(source, statement);
@@ -5038,10 +5286,11 @@ function printEr(path, options, print, source) {
5038
5286
  case "subgraph": return printSubgraph$1(path, options, print, source, classified.statement, depth);
5039
5287
  case "entity":
5040
5288
  if (hasAttributeBlock(source, classified.statement)) return printAttributeBlock(path, options, print, source, classified.statement, depth);
5041
- return printLine$6(source, options, layoutErStatement(source, classified.statement, node.range[1]), depth);
5042
- case "simple": return printLine$6(source, options, layoutErStatement(source, classified.statement, node.range[1]), depth);
5289
+ break;
5290
+ case "simple": break;
5043
5291
  default: throw new Error(`prettier-plugin-mmd: unknown kind of statement ${JSON.stringify(classified)}`);
5044
5292
  }
5293
+ return printLine$6(source, options, layoutErStatement(source, classified.statement, node.range[1], depth > 1), depth);
5045
5294
  }
5046
5295
  /** Prints a statement laid out on its lines at `depth`. */
5047
5296
  function printLine$6(source, options, layout, depth) {
@@ -5736,7 +5985,7 @@ function classifyAgentflowStatement(statement) {
5736
5985
  }
5737
5986
  }
5738
5987
  /** Agentflow statements use flowchart's shared graph spacing and atom printer. */
5739
- function layoutStatement$1(source, statement, end) {
5988
+ function layoutStatement$1(source, statement, end, preservesDescriptionColumns) {
5740
5989
  const start = statement.range[0];
5741
5990
  if (statement.type === "AgentflowConnectorStatement") return layoutContainerHeader(source, statement, end);
5742
5991
  const accessibility = layoutGraphAccessibility(source, statement, end, findAgentflowKeptLines(source));
@@ -5761,6 +6010,7 @@ function layoutStatement$1(source, statement, end) {
5761
6010
  case "AgentflowAccDescrBlockStatement":
5762
6011
  appendItems(kept, findAccDescrBlockStretches(source, statement));
5763
6012
  if (!statement.closed) return keptAsWritten(start, end);
6013
+ for (const [position, rule] of descriptionOpeningRules(source, start)) rules.set(position, rule);
5764
6014
  break;
5765
6015
  case "AgentflowVertexStatement": walk(statement, (node) => {
5766
6016
  if (node.type === "AgentflowShape") addShapeRules(source, node, rules);
@@ -5770,10 +6020,11 @@ function layoutStatement$1(source, statement, end) {
5770
6020
  const layout = layoutRange(source, start, end, collectValueNodes(statement, agentflowValueNodeTypes), kept, rules);
5771
6021
  if (statement.type === "AgentflowAccDescrBlockStatement") {
5772
6022
  const closing = findAccDescrBlockClosing(source, statement);
5773
- return {
6023
+ const descriptionLayout = {
5774
6024
  ...layout,
5775
6025
  outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing])
5776
6026
  };
6027
+ return preservesDescriptionColumns ? descriptionLayout : indentDescriptionLines(source, statement, descriptionLayout);
5777
6028
  }
5778
6029
  return layout;
5779
6030
  }
@@ -5804,9 +6055,8 @@ function printAgentflow(path, options, print, source) {
5804
6055
  if (classified === null) throw new Error("prettier-plugin-mmd: an unexpected Agentflow node");
5805
6056
  if (classified.kind === "container") return printContainer(path, bodyOptions, print, source, classified.statement);
5806
6057
  const statement = classified.statement;
5807
- const layout = layoutStatement$1(source, statement, findPrintedEnd$1(source, statement));
5808
6058
  const depth = depthOf$3(path);
5809
- return printAtoms(source, layout, {
6059
+ return printAtoms(source, layoutStatement$1(source, statement, findPrintedEnd$1(source, statement), depth > 1), {
5810
6060
  statement: indentationOf(bodyOptions, depth),
5811
6061
  continuation: indentationOf(bodyOptions, depth + 1)
5812
6062
  }).doc;
@@ -6087,20 +6337,21 @@ function layoutSubgraphHeader(source, subgraph, headerEnd) {
6087
6337
  * The layout of a statement other than a subgraph, from its start to
6088
6338
  * `end` (see `findPrintedEnd`).
6089
6339
  */
6090
- function layoutStatement(source, statement, end) {
6340
+ function layoutStatement(source, statement, end, preservesDescriptionColumns) {
6091
6341
  const start = statement.range[0];
6092
6342
  const accessibility = layoutGraphAccessibility(source, statement, end, findFlowchartKeptLines(source));
6093
6343
  if (accessibility !== null) return accessibility;
6094
6344
  if (holdsJoiningRegion(source, start, end)) return keptAsWritten(start, end);
6095
6345
  const kept = findKeptStretches(source, statement, end);
6096
6346
  const values = collectValueNodes(statement, valueNodeTypes);
6097
- const rules = statement.type === "FlowchartVertexStatement" ? vertexStatementRules(source, statement) : /* @__PURE__ */ new Map();
6098
- return {
6347
+ const rules = statement.type === "FlowchartVertexStatement" ? vertexStatementRules(source, statement) : statement.type === "FlowchartAccDescrBlockStatement" ? descriptionOpeningRules(source, start) : /* @__PURE__ */ new Map();
6348
+ const layout = {
6099
6349
  atoms: collectAtoms(source, start, end, values, kept),
6100
6350
  rules,
6101
6351
  outdented: findOutdentedAtoms(source, statement),
6102
6352
  lineBreaks: "kept"
6103
6353
  };
6354
+ return statement.type === "FlowchartAccDescrBlockStatement" && !preservesDescriptionColumns ? indentDescriptionLines(source, statement, layout) : layout;
6104
6355
  }
6105
6356
  /**
6106
6357
  * The atoms of a statement whose line starts at the statement's
@@ -6237,9 +6488,8 @@ function printFlowchart(path, options, print, source) {
6237
6488
  case "FlowchartSubgraphStatement": return printSubgraph(path, bodyOptions, print, source, node);
6238
6489
  default: {
6239
6490
  const statement = node;
6240
- const layout = layoutStatement(source, statement, findPrintedEnd(source, statement));
6241
6491
  const depth = depthOf$2(path);
6242
- return printAtoms(source, layout, {
6492
+ return printAtoms(source, layoutStatement(source, statement, findPrintedEnd(source, statement), depth > 1), {
6243
6493
  statement: indentationOf(bodyOptions, depth),
6244
6494
  continuation: indentationOf(bodyOptions, depth + 1)
6245
6495
  }).doc;
@@ -6427,25 +6677,27 @@ function isAtLineEnd$1(source, offset) {
6427
6677
  * - A statement written over several lines stands on one line where the
6428
6678
  * lexer reads the line break as whitespace, which it does only right after
6429
6679
  * a keyword and before a part of a statement (diagrams/gantt.md, The
6430
- * statement context); one with a comment or a directive in it is kept as
6431
- * written (see `spansLinesThatCannotJoin`). The lines of an `accDescr`
6432
- * block are lines of its text, and are kept (docs/gantt.md, Accessibility
6433
- * statements).
6680
+ * statement context). Trivia keeps structural click/day/list/accessibility
6681
+ * gaps broken, with ordinary continuation columns; raw line values,
6682
+ * semicolon lines and joining regions keep their original layout
6683
+ * (docs/gantt.md, Multi-line statements).
6434
6684
  * - The rules of the gaps are those of docs/gantt.md: Task data, Settings,
6435
6685
  * Lists, Click statements, and Accessibility statements.
6436
6686
  */
6437
6687
  function layoutGanttStatement(source, statement, end) {
6438
6688
  const start = statement.range[0];
6439
6689
  if (statement.type === "GanttAccDescrBlockStatement") return layoutDescriptionBlock(source, statement, end, ganttValueNodeTypes);
6440
- if (spansLinesThatCannotJoin(source, start, end) || holdsCaseIgnoredSeparator(source, statement, end)) return keptAsWritten(start, end);
6690
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
6691
+ const formatsTriviaLines = statement.type === "GanttClickStatement" || statement.type === "GanttWeekdayStatement" || statement.type === "GanttWeekendStatement" || statement.type === "GanttIncludesStatement" || statement.type === "GanttExcludesStatement" || statement.type === "GanttAccTitleStatement" || statement.type === "GanttAccDescrStatement";
6692
+ if (keepsLineBreaks && (!formatsTriviaLines || holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true })) || holdsCaseIgnoredSeparator(source, statement, end)) return keptAsWritten(start, end);
6441
6693
  const atoms = collectAtoms(source, start, end, collectValueNodes(statement, ganttValueNodeTypes), []);
6442
6694
  const remainder = findBlankRemainder$1(source, statement);
6443
6695
  if (remainder !== null) atoms.push(remainder);
6444
6696
  return {
6445
- atoms,
6697
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
6446
6698
  rules: statementRules$6(source, statement, atoms, remainder),
6447
6699
  outdented: /* @__PURE__ */ new Set(),
6448
- lineBreaks: "joined"
6700
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
6449
6701
  };
6450
6702
  }
6451
6703
  /**
@@ -6746,25 +6998,27 @@ function isAtLineEnd(source, offset) {
6746
6998
  *
6747
6999
  * - A statement written over several lines stands on one line where the
6748
7000
  * lexer reads the line break as whitespace, which it does only right after
6749
- * a keyword (diagrams/journey.md, The statement context); one with a
6750
- * comment or a directive in it is kept as written (see
6751
- * `spansLinesThatCannotJoin`). The lines of an `accDescr` block are lines
6752
- * of its text, and are kept (docs/journey.md, Accessibility statements).
7001
+ * a keyword (diagrams/journey.md, The statement context). Accessibility
7002
+ * line trivia keeps its breaks with ordinary continuation columns; titles,
7003
+ * sections and protected regions keep their original layout
7004
+ * (docs/journey.md, Multi-line statements).
6753
7005
  * - The rules of the gaps are those of docs/journey.md: Task data, Titles and
6754
7006
  * sections, and Accessibility statements.
6755
7007
  */
6756
7008
  function layoutJourneyStatement(source, statement, end) {
6757
7009
  const start = statement.range[0];
6758
7010
  if (statement.type === "JourneyAccDescrBlockStatement") return layoutDescriptionBlock(source, statement, end, journeyValueNodeTypes);
6759
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
7011
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
7012
+ const formatsTriviaLines = statement.type === "JourneyAccTitleStatement" || statement.type === "JourneyAccDescrStatement";
7013
+ if (keepsLineBreaks && (!formatsTriviaLines || holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
6760
7014
  const atoms = collectAtoms(source, start, end, collectValueNodes(statement, journeyValueNodeTypes), []);
6761
7015
  const remainder = findBlankRemainder(source, statement);
6762
7016
  if (remainder !== null) atoms.push(remainder);
6763
7017
  return {
6764
- atoms,
7018
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
6765
7019
  rules: statementRules$5(source, statement, atoms, remainder),
6766
7020
  outdented: /* @__PURE__ */ new Set(),
6767
- lineBreaks: "joined"
7021
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
6768
7022
  };
6769
7023
  }
6770
7024
  /** The gap rules of a statement, by the start of the atom after the gap. */
@@ -7586,7 +7840,8 @@ function findQuadrantKeptLines(source) {
7586
7840
  /**
7587
7841
  * The node types of a quadrant chart whose text is a value, printed as
7588
7842
  * written: a title, a text of an accessibility statement, a coordinate, and a
7589
- * style (QuadrantLiteral); the text of an axis or of a quadrant and the name
7843
+ * style (QuadrantLiteral), with ordinary style-colon padding normalized below;
7844
+ * the text of an axis or of a quadrant and the name
7590
7845
  * of a point (QuadrantLabel), whose whitespace is in the Db; the name of a
7591
7846
  * class of `classDef` (QuadrantIdentifier); and the class name of a point
7592
7847
  * (Identifier). They have no child fields; `tests/value-nodes.test.ts` checks
@@ -7603,22 +7858,49 @@ const quadrantValueNodeTypes = /* @__PURE__ */ new Set([
7603
7858
  *
7604
7859
  * - A statement written over several lines stands on one line where the
7605
7860
  * lexer reads the line break as whitespace (diagrams/quadrant.md, Lexical
7606
- * structure, Line breaks); one with a comment or a directive in it, or a
7607
- * `;`, is kept as written (see `spansLinesThatCannotJoin`). The lines of an
7608
- * `accDescr` block are lines of its text, and are kept (docs/quadrant.md,
7609
- * Titles and accessibility statements).
7861
+ * structure, Line breaks). Point and accessibility line trivia keeps its
7862
+ * breaks with ordinary continuation columns; semicolon lines, joining
7863
+ * regions and other statements retain their layout (docs/quadrant.md,
7864
+ * Multi-line statements).
7610
7865
  * - The rules of the gaps are those of docs/quadrant.md: Keywords and texts,
7611
7866
  * Axes, Points, Styles, and Titles and accessibility statements.
7612
7867
  */
7613
7868
  function layoutQuadrantStatement(source, statement, end) {
7614
7869
  const start = statement.range[0];
7615
7870
  if (statement.type === "QuadrantAccDescrBlockStatement") return layoutDescriptionBlock(source, statement, end, quadrantValueNodeTypes);
7616
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
7871
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
7872
+ const formatsTriviaLines = statement.type === "QuadrantPointStatement" || statement.type === "QuadrantAccTitleStatement" || statement.type === "QuadrantAccDescrStatement";
7873
+ if (keepsLineBreaks && (!formatsTriviaLines || holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
7874
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, quadrantValueNodeTypes), []);
7875
+ const styleStarts = new Set(statement.type === "QuadrantPointStatement" || statement.type === "QuadrantClassDefStatement" ? statement.styles.map((style) => style.range[0]) : []);
7876
+ const styledAtoms = atoms.map((atom) => styleStarts.has(atom.start) ? formatStyleAtom(source, atom) : atom);
7617
7877
  return {
7618
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, quadrantValueNodeTypes), []),
7878
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, styledAtoms) : styledAtoms,
7619
7879
  rules: statementRules$4(source, statement),
7620
7880
  outdented: /* @__PURE__ */ new Set(),
7621
- lineBreaks: "joined"
7881
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
7882
+ };
7883
+ }
7884
+ /**
7885
+ * Ordinary style name/colon/value boundaries have one form. Keep the source
7886
+ * range and value bytes; trivia, line rules and suffix forms stay opaque
7887
+ * (docs/quadrant.md, Styles).
7888
+ */
7889
+ function formatStyleAtom(source, atom) {
7890
+ const text = source.text.slice(atom.start, atom.end);
7891
+ const colon = text.indexOf(":");
7892
+ if (colon < 0 || text.includes(":", colon + 1) || text.includes(";") || findTriviaBetween(source, atom.start, atom.end).length > 0 || holdsJoiningRegion(source, atom.start, atom.end) || findSemicolonLines(source).has(lineStartOf(source, atom.start)) || [...text].some((character) => character !== " " && character !== " " && isWhitespace(character))) return atom;
7893
+ let nameEnd = colon;
7894
+ while (text[nameEnd - 1] === " " || text[nameEnd - 1] === " ") nameEnd--;
7895
+ let valueStart = colon + 1;
7896
+ while (text[valueStart] === " " || text[valueStart] === " ") valueStart++;
7897
+ return {
7898
+ ...atom,
7899
+ doc: [
7900
+ text.slice(0, nameEnd),
7901
+ ": ",
7902
+ text.slice(valueStart)
7903
+ ]
7622
7904
  };
7623
7905
  }
7624
7906
  /** The gap rules of a statement, by the start of the atom after the gap. */
@@ -7902,42 +8184,51 @@ function findBlockBraces(source, statement) {
7902
8184
  * `:::` and the `,` between them (docs/requirement.md, Bodies and Class
7903
8185
  * lists). A statement written over lines, where the lexer reads the line
7904
8186
  * break as whitespace, stands on one line; one with a comment or a directive
7905
- * in it is kept as written (see `spansLinesThatCannotJoin`).
8187
+ * in it keeps its line breaks and aligns structural continuations.
7906
8188
  */
7907
8189
  function layoutBlockOpening(source, statement, opening) {
7908
8190
  const start = statement.range[0];
7909
8191
  const end = opening.range[1];
7910
- if (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
8192
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
8193
+ if (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true })) return keptAsWritten(start, end);
7911
8194
  const rules = /* @__PURE__ */ new Map([[statement.name.range[0], "space"], [opening.range[0], "space"]]);
7912
8195
  addClassListRules(source, statement.cssClasses, statement.name.range[1], rules);
7913
- return {
7914
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, requirementValueNodeTypes).filter((value) => value.range[1] <= opening.range[0]), []),
8196
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, requirementValueNodeTypes).filter((value) => value.range[1] <= opening.range[0]), []);
8197
+ return alignBlockOpeningLine(source, {
8198
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
7915
8199
  rules,
7916
8200
  outdented: /* @__PURE__ */ new Set(),
7917
- lineBreaks: "joined"
7918
- };
8201
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
8202
+ }, opening.range[0]);
7919
8203
  }
7920
8204
  /**
7921
8205
  * The layout of an item of a body. A field is printed on one line: its
7922
8206
  * keyword, the `:` touching it, and its value after one space; a field
7923
8207
  * written over lines, where the lexer reads the line break as whitespace,
7924
- * stands on one line too, and one with a comment or a directive in it is kept
7925
- * as written. An empty description block, which mermaid.js does not read, is
8208
+ * stands on one line too. Comments and directives retain line breaks while
8209
+ * structural continuations align. An empty description block, which mermaid.js
8210
+ * does not read, is
7926
8211
  * compacted with the shared empty-block layout (docs/requirement.md, Fields
7927
8212
  * and Empty description blocks).
7928
8213
  */
7929
8214
  function layoutBodyItem(source, item) {
7930
8215
  const [start, end] = item.range;
7931
- if (item.type === "RequirementIgnoredText") return layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, () => layoutEmptyDescriptionBlock(source, start, end));
7932
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
8216
+ if (item.type === "RequirementIgnoredText") return layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, () => indentDescriptionLines(source, {
8217
+ range: item.range,
8218
+ value: null,
8219
+ closed: true
8220
+ }, layoutEmptyDescriptionBlock(source, start, end, true)));
8221
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
8222
+ if (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true })) return keptAsWritten(start, end);
7933
8223
  const colon = expectToken(findStructuralToken(source, expectToken(findStructuralToken(source, start), "a field").range[1]), "the `:` of a field");
7934
8224
  expectValue(colon, ":");
7935
8225
  const value = expectToken(findStructuralToken(source, colon.range[1]), "the value of a field");
8226
+ const atoms = collectAtoms(source, start, end, collectValueNodes(item, requirementValueNodeTypes), []);
7936
8227
  return {
7937
- atoms: collectAtoms(source, start, end, collectValueNodes(item, requirementValueNodeTypes), []),
8228
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
7938
8229
  rules: /* @__PURE__ */ new Map([[colon.range[0], "none"], [value.range[0], "space"]]),
7939
8230
  outdented: /* @__PURE__ */ new Set(),
7940
- lineBreaks: "joined"
8231
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
7941
8232
  };
7942
8233
  }
7943
8234
  /**
@@ -7946,25 +8237,35 @@ function layoutBodyItem(source, item) {
7946
8237
  *
7947
8238
  * - A statement written over several lines stands on one line where the
7948
8239
  * lexer reads the line break as whitespace (diagrams/requirement.md, The
7949
- * statement context); one with a comment or a directive in it, or a `;`, is
7950
- * kept as written (see `spansLinesThatCannotJoin`). The lines of an
8240
+ * statement context); comments and directives keep line breaks while
8241
+ * structural continuations align. Semicolon boundaries and joining regions
8242
+ * keep their source. The lines of an
7951
8243
  * `accDescr` block are lines of its text, and are kept (docs/requirement.md,
7952
8244
  * Accessibility statements). A `class` statement is laid out as
7953
8245
  * `joinsClassStatement` says.
7954
- * - A relationship has one space between its units (docs/requirement.md,
7955
- * Relationship spacing).
8246
+ * - A relationship has one space between its units. Comments and directives
8247
+ * prevent joining its lines, while the existing atoms still align structural
8248
+ * gaps. Joining regions and textual semicolon boundaries keep their source
8249
+ * (docs/requirement.md, Relationship spacing).
7956
8250
  * - The other statements follow the rules shared with an ER diagram (see
7957
8251
  * `statement-rules.ts`).
7958
8252
  */
7959
8253
  function layoutRequirementStatement(source, statement, end) {
7960
8254
  const start = statement.range[0];
7961
8255
  if (statement.type === "RequirementAccDescrBlockStatement") return layoutDescriptionBlock(source, statement, end, requirementValueNodeTypes);
7962
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
8256
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
8257
+ if (keepsLineBreaks && (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
8258
+ const styles = (statement.type === "RequirementStyleStatement" || statement.type === "RequirementClassDefStatement") && styleUnitsCanCompact(source, start, end, statement.styles) ? statement.styles : [];
8259
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, requirementValueNodeTypes), styles.map((style) => ({
8260
+ start: style.range[0],
8261
+ end: style.range[1],
8262
+ doc: printStyleUnitSpacing(source, style)
8263
+ })));
7963
8264
  return {
7964
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, requirementValueNodeTypes), []),
7965
- rules: statementRules$3(source, statement),
8265
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
8266
+ rules: statementRules$3(source, statement, styles.length > 0),
7966
8267
  outdented: /* @__PURE__ */ new Set(),
7967
- lineBreaks: statement.type === "RequirementClassStatement" && !joinsClassStatement(source, statement) ? "kept" : "joined"
8268
+ lineBreaks: keepsLineBreaks || statement.type === "RequirementClassStatement" && !joinsClassStatement(source, statement) ? "kept" : "joined"
7968
8269
  };
7969
8270
  }
7970
8271
  /**
@@ -7988,12 +8289,12 @@ function isStyleWord(name) {
7988
8289
  return name.name !== "" && [...name.name].every((character) => character >= "a" && character <= "z" || character >= "A" && character <= "Z" || character >= "0" && character <= "9" || character === "_");
7989
8290
  }
7990
8291
  /** The gap rules of a statement that holds no body. */
7991
- function statementRules$3(source, statement) {
8292
+ function statementRules$3(source, statement, compactStyles = false) {
7992
8293
  switch (statement.type) {
7993
8294
  case "RequirementRelationshipStatement": return relationshipRules(source, statement);
7994
8295
  case "RequirementDirectionStatement": return directionRules(source, statement);
7995
- case "RequirementStyleStatement": return styleStatementRules(source, statement.names, statement.styles);
7996
- case "RequirementClassDefStatement": return styleStatementRules(source, statement.cssClasses, statement.styles);
8296
+ case "RequirementStyleStatement": return styleStatementRules(source, statement.names, statement.styles, compactStyles);
8297
+ case "RequirementClassDefStatement": return styleStatementRules(source, statement.cssClasses, statement.styles, compactStyles);
7997
8298
  case "RequirementClassStatement": return classStatementRules(source, statement.names, statement.cssClasses);
7998
8299
  case "RequirementClassShorthandStatement": {
7999
8300
  const rules = /* @__PURE__ */ new Map();
@@ -8347,22 +8648,23 @@ function layoutBlockHeader(source, start, end, text) {
8347
8648
  * - A statement written over several lines stands on one line: a line
8348
8649
  * break inside a statement comes after whitespace, and the lexer reads
8349
8650
  * the two as whitespace (diagrams/sequence.md, The statement context,
8350
- * rule 2). One with a comment or a directive in it is kept as written
8351
- * (see `isKeptAsWritten`); the lines of an `accDescr { ... }` block are
8352
- * lines of its text, and are kept (docs/sequence.md, Multi-line
8353
- * statements).
8651
+ * rule 2). Comments and directives keep line breaks while structural
8652
+ * continuations align; the lines of an `accDescr { ... }` block are
8653
+ * lines of its text: keep their breaks and align their safe indentation
8654
+ * (docs/sequence.md, Multi-line statements).
8354
8655
  * - A title is laid out by `layoutTitle`.
8355
8656
  * - A message has one space before and after its arrow (docs/sequence.md,
8356
8657
  * Arrow spacing).
8357
8658
  * - A `:` before a text touches what comes before it and has one space
8358
8659
  * after it when a text follows (docs/sequence.md, Colons).
8359
- * - The lines of an `accDescr { ... }` block whose text starts on a later
8360
- * line than the `{` are kept as written, and its `}` stands at the level
8361
- * of the statement (docs/sequence.md, Multi-line values).
8660
+ * - Later lines of an `accDescr { ... }` block align one level inside the
8661
+ * statement without joining their text. Its `}` stands at the level of
8662
+ * the statement (docs/sequence.md, Multi-line values).
8362
8663
  */
8363
8664
  function layoutSequenceStatement(source, statement, end) {
8364
8665
  const start = statement.range[0];
8365
- if (isKeptAsWritten(source, statement, end)) return {
8666
+ const keepsLineBreaks = statement.type !== "SequenceAccDescrBlockStatement" && spansLinesThatCannotJoin(source, start, end);
8667
+ if (keepsLineBreaks && (statement.type === "SequenceTitleStatement" || holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return {
8366
8668
  atoms: [{
8367
8669
  start,
8368
8670
  end
@@ -8383,39 +8685,24 @@ function layoutSequenceStatement(source, statement, end) {
8383
8685
  /** Builds the existing value, trivia and closing-brace layout. */
8384
8686
  function originalLayout() {
8385
8687
  const closing = findAccDescrBlockClosing(source, block);
8386
- return {
8688
+ return indentDescriptionLines(source, block, {
8387
8689
  atoms: collectAtoms(source, start, end, values, findAccDescrBlockStretches(source, block)),
8388
- rules: /* @__PURE__ */ new Map(),
8690
+ rules: descriptionOpeningRules(source, start),
8389
8691
  outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing]),
8390
8692
  lineBreaks: "kept"
8391
- };
8693
+ });
8392
8694
  }
8393
8695
  return statement.value === null && statement.closed ? layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, originalLayout) : originalLayout();
8394
8696
  }
8697
+ const atoms = collectAtoms(source, start, end, values, tail);
8395
8698
  return {
8396
- atoms: collectAtoms(source, start, end, values, tail),
8699
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
8397
8700
  rules: statementRules$2(source, statement),
8398
8701
  outdented: /* @__PURE__ */ new Set(),
8399
- lineBreaks: "joined"
8702
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
8400
8703
  };
8401
8704
  }
8402
8705
  /**
8403
- * Whether a statement is kept as written, from its start to `end`: it is
8404
- * written over several lines, and a comment or a directive lies in it
8405
- * (docs/sequence.md, Multi-line statements). Such a statement cannot stand
8406
- * on one line, and its lines are part of it only through the whitespace at
8407
- * their ends (diagrams/sequence.md, The statement context, rule 2), which
8408
- * the formatter does not write. A title with a comment line between its
8409
- * keyword and its text is one: the comment line is removed before the
8410
- * lexer reads the text (common.md, Comment lines), so the line after it is
8411
- * the title. The lines of an `accDescr { ... }` block are lines of its
8412
- * text, kept by its own layout.
8413
- */
8414
- function isKeptAsWritten(source, statement, end) {
8415
- if (statement.type === "SequenceAccDescrBlockStatement") return false;
8416
- return spansLinesThatCannotJoin(source, statement.range[0], end);
8417
- }
8418
- /**
8419
8706
  * The layout of a title: its keyword with the directives right after it,
8420
8707
  * one space for the one whitespace character that follows them, and the
8421
8708
  * rest as written (docs/sequence.md, Title). The title of the Db keeps the
@@ -9055,8 +9342,9 @@ function layoutStateHeader(source, keyword) {
9055
9342
  * The layout of the line that opens a body, from the start of a statement
9056
9343
  * to the end of its `{`. The `{` stands on the line of the name, after one
9057
9344
  * space; a `{` written on the next line is moved there (docs/state.md,
9058
- * Composite states). Such a line is kept as written when it is written
9059
- * over several lines and holds a comment or a directive, when text that
9345
+ * Composite states). Comments and directives keep line breaks while structural
9346
+ * continuations align. Such a line is kept as written when joining regions or
9347
+ * semicolons protect it, when text that
9060
9348
  * mermaid.js does not read stands before its `{` and is read by its place
9061
9349
  * (see `hasReadOtherwiseTextBeforeBody`), or when it follows a state name
9062
9350
  * (see `isStateNameStatement`).
@@ -9064,15 +9352,17 @@ function layoutStateHeader(source, keyword) {
9064
9352
  function layoutBodyOpening(source, statement, opening, followsStateName) {
9065
9353
  const start = statement.range[0];
9066
9354
  const end = opening.range[1];
9067
- if (spansLinesThatCannotJoin(source, start, end) || hasReadOtherwiseTextBeforeBody(statement) || followsStateName) return keptAsWritten(start, end);
9355
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
9356
+ if (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }) || hasReadOtherwiseTextBeforeBody(statement) || followsStateName) return keptAsWritten(start, end);
9068
9357
  const rules = /* @__PURE__ */ new Map([[opening.range[0], "space"]]);
9069
9358
  if (statement.type === "StateAliasDefinitionStatement") addAliasHeaderRules(source, statement, rules);
9070
- return {
9071
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, stateValueNodeTypes).filter((value) => value.range[1] <= opening.range[0]), []),
9359
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, stateValueNodeTypes).filter((value) => value.range[1] <= opening.range[0]), []);
9360
+ return alignBlockOpeningLine(source, {
9361
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
9072
9362
  rules,
9073
- outdented: /* @__PURE__ */ new Set(),
9074
- lineBreaks: "joined"
9075
- };
9363
+ outdented: /* @__PURE__ */ new Set([opening.range[0]]),
9364
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
9365
+ }, opening.range[0]);
9076
9366
  }
9077
9367
  /**
9078
9368
  * Whether a `{` stands in the text between `start` and `end`, outside its
@@ -9099,9 +9389,10 @@ function holdsBrace(source, start, end) {
9099
9389
  * `as`, the position of a note, `classDef` and `style` and their names,
9100
9390
  * `scale`, `direction`, and the `:` of `accTitle` and `accDescr`
9101
9391
  * (diagrams/state.md, Lexical structure); one with a comment or a
9102
- * directive in it is kept as written (see `spansLinesThatCannotJoin`). The
9103
- * lines of an `accDescr { ... }` block and of a note over lines are lines
9104
- * of their texts, and are kept (docs/state.md, Multi-line values).
9392
+ * directive keeps its line breaks and aligns structural continuations. The
9393
+ * lines of an `accDescr { ... }` block and of a note remain separate;
9394
+ * ordinary note paragraph margins follow their own layout (docs/state.md,
9395
+ * Multi-line values and Notes).
9105
9396
  * - A transition has one space on each side of its arrow (docs/state.md,
9106
9397
  * Arrow spacing).
9107
9398
  * - The `:` of a description or a label has one space on each side
@@ -9109,7 +9400,7 @@ function holdsBrace(source, start, end) {
9109
9400
  * - What follows the id of a note, and the second description of an alias
9110
9401
  * definition, are kept as written (docs/state.md, Notes and Aliases).
9111
9402
  */
9112
- function layoutStateStatement(source, statement, end, followsStateName) {
9403
+ function layoutStateStatement(source, statement, end, followsStateName, noteIndentation) {
9113
9404
  const start = statement.range[0];
9114
9405
  if (followsStateName && holdsBrace(source, start, end)) return keptAsWritten(start, end);
9115
9406
  if (statement.type === "StateAccDescrBlockStatement") {
@@ -9117,17 +9408,18 @@ function layoutStateStatement(source, statement, end, followsStateName) {
9117
9408
  /** Builds the existing value, trivia and closing-brace layout. */
9118
9409
  function originalLayout() {
9119
9410
  const closing = findAccDescrBlockClosing(source, block);
9120
- return {
9411
+ return indentDescriptionLines(source, block, {
9121
9412
  atoms: collectAtoms(source, start, end, collectValueNodes(block, stateValueNodeTypes), findAccDescrBlockStretches(source, block)),
9122
- rules: /* @__PURE__ */ new Map(),
9413
+ rules: descriptionOpeningRules(source, start),
9123
9414
  outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing]),
9124
9415
  lineBreaks: "kept"
9125
- };
9416
+ });
9126
9417
  }
9127
9418
  return statement.value === null && statement.closed ? layoutCompactEmptyDescriptionBlockWithFallback(source, start, end, originalLayout) : originalLayout();
9128
9419
  }
9129
- if (statement.type === "StateNoteStatement" && isNoteOverLines(source, statement)) return layoutNoteOverLines(source, statement, end);
9130
- if (spansLinesThatCannotJoin(source, start, end) || (statement.type === "StateCompositeStatement" || statement.type === "StateAliasDefinitionStatement") && hasReadOtherwiseTextBeforeBody(statement)) return keptAsWritten(start, end);
9420
+ if (statement.type === "StateNoteStatement" && isNoteOverLines(source, statement)) return layoutNoteOverLines(source, statement, end, noteIndentation);
9421
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
9422
+ if (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }) || (statement.type === "StateCompositeStatement" || statement.type === "StateAliasDefinitionStatement") && hasReadOtherwiseTextBeforeBody(statement)) return keptAsWritten(start, end);
9131
9423
  const kept = [
9132
9424
  ...findNoteStretches(statement, end),
9133
9425
  ...findSecondDescriptionStretches(source, statement, end),
@@ -9137,11 +9429,12 @@ function layoutStateStatement(source, statement, end, followsStateName) {
9137
9429
  range: statement.range,
9138
9430
  text: statement.value.value
9139
9431
  });
9432
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, stateValueNodeTypes).filter((value) => !kept.some((stretch) => stretch.start <= value.range[0] && value.range[1] <= stretch.end)), kept);
9140
9433
  return {
9141
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, stateValueNodeTypes).filter((value) => !kept.some((stretch) => stretch.start <= value.range[0] && value.range[1] <= stretch.end)), kept),
9434
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
9142
9435
  rules: statementRules$1(source, statement),
9143
9436
  outdented: /* @__PURE__ */ new Set(),
9144
- lineBreaks: keepsDirectionValue ? "kept" : "joined"
9437
+ lineBreaks: keepsLineBreaks || keepsDirectionValue ? "kept" : "joined"
9145
9438
  };
9146
9439
  }
9147
9440
  /**
@@ -9335,28 +9628,121 @@ function findNoteStretches(statement, end) {
9335
9628
  }];
9336
9629
  }
9337
9630
  /**
9338
- * The layout of a note over lines: its keyword, position, and id, its text
9339
- * on the lines after them as written, and `end note` at the level of the
9340
- * note (docs/state.md, Multi-line values). The text is kept from the line
9341
- * break after the id to the line of `end note`, with the whitespace and the
9342
- * empty lines at its ends; the whitespace after the id on the line of the
9343
- * note is dropped. A note whose `end note` does not start its line, or
9344
- * whose text starts on the line of the id, is printed from its id by the
9345
- * gap rules, with its line breaks kept.
9631
+ * A multiline note keeps its lines and aligns eligible paragraph margins one
9632
+ * level inside its header. Protected text retains its complete written span;
9633
+ * `end note` aligns with the header (docs/state.md, Notes). A note whose
9634
+ * `end note` does not start its line, or whose text starts on the line of
9635
+ * the id, is printed from its id by the gap rules, with line breaks kept.
9346
9636
  */
9347
- function layoutNoteOverLines(source, statement, end) {
9637
+ function layoutNoteOverLines(source, statement, end, indentation) {
9348
9638
  const endKeyword = expectToken(findStructuralTokenEndingBefore(source, expectToken(findTokenEndingBefore(source, statement.range[1]), "the `note` of an `end note`").range[0]), "the `end` of an `end note`");
9349
9639
  const text = findNoteTextStretch(source, statement, endKeyword);
9640
+ const lines = text === null ? null : noteTextLines(source, statement, text, indentation);
9350
9641
  return {
9351
- atoms: collectAtoms(source, statement.range[0], end, collectValueNodes(statement, stateValueNodeTypes), text === null ? [] : [text]),
9642
+ atoms: collectAtoms(source, statement.range[0], end, collectValueNodes(statement, stateValueNodeTypes), text === null ? [] : [text]).flatMap((atom) => lines !== null && atom.start === text?.start && atom.end === text.end ? lines : [atom]),
9352
9643
  rules: text === null ? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map([[text.start, "none"]]),
9353
9644
  outdented: /* @__PURE__ */ new Set([endKeyword.range[0]]),
9354
9645
  lineBreaks: "kept"
9355
9646
  };
9356
9647
  }
9357
9648
  /**
9358
- * The stretch of a note over lines that is printed as written: from the
9359
- * line break after its id to the line break before the line of `end note`,
9649
+ * Align eligible paragraph bodies, or only the first physical body line whose
9650
+ * ASCII margin Mermaid trims. Embedded forms keep their full source. Explicit
9651
+ * ASCII columns avoid introducing Markdown-significant tabs with useTabs
9652
+ * (docs/state.md, Notes).
9653
+ */
9654
+ function noteTextLines(source, statement, text, indentation) {
9655
+ if (source.text[text.start] !== "\n" || source.text.slice(statement.range[0], text.start).includes("\n") || source.text.slice(...statement.range).includes(";") || findTriviaBetween(source, ...statement.range).length > 0 || holdsJoiningRegion(source, ...statement.range)) return null;
9656
+ return paragraphNoteTextLines(source, text, indentation) ?? firstNoteTextLine(source, text, indentation);
9657
+ }
9658
+ /**
9659
+ * A single paragraph aligns its content rows, including inline emphasis,
9660
+ * same-line code and inline `<br/>`. Outer blank rows retain their exact text;
9661
+ * block syntax and markup that can own later margins remain protected.
9662
+ */
9663
+ function paragraphNoteTextLines(source, text, indentation) {
9664
+ const lines = [];
9665
+ const contentRows = [];
9666
+ let sawContent = false;
9667
+ let endedParagraph = false;
9668
+ let contentEnd = text.end;
9669
+ while (contentEnd > text.start + 1 && " \n".includes(source.text[contentEnd - 1])) contentEnd--;
9670
+ for (let offset = text.start + 1; offset <= text.end;) {
9671
+ const nextBreak = source.text.indexOf("\n", offset);
9672
+ const end = nextBreak < 0 ? text.end : Math.min(nextBreak, text.end);
9673
+ let start = offset;
9674
+ while (source.text[start] === " " || source.text[start] === " ") start++;
9675
+ if (start >= end) {
9676
+ lines.push({
9677
+ start: offset,
9678
+ end,
9679
+ writtenIndentation: ""
9680
+ });
9681
+ endedParagraph ||= sawContent;
9682
+ offset = end + 1;
9683
+ continue;
9684
+ }
9685
+ const margin = source.text.slice(offset, start);
9686
+ const content = source.text.slice(start, end);
9687
+ if (endedParagraph || sawContent && margin.includes(" ") || content.startsWith("<br/>") || [...content.split("<br/>").join("")].some((character) => "~[]<>\\".includes(character) || character !== " " && isWhitespace(character)) || end < contentEnd && source.text.slice(end - 2, end) === " ") return null;
9688
+ sawContent = true;
9689
+ contentRows.push(content);
9690
+ lines.push({
9691
+ start,
9692
+ end,
9693
+ writtenIndentation: indentation
9694
+ });
9695
+ offset = end + 1;
9696
+ }
9697
+ if (!sawContent) return null;
9698
+ return isParagraphNoteText(indentation.length < 4 ? contentRows.join("\n") : source.text.slice(text.start + 1, text.end)) ? lines : null;
9699
+ }
9700
+ /**
9701
+ * Use Mermaid's Markdown lexer in an isolated instance. Other consumers of
9702
+ * Marked cannot change these defaults through marked.use (docs/state.md, Notes).
9703
+ */
9704
+ const noteMarkdown = new Marked({
9705
+ gfm: true,
9706
+ breaks: false,
9707
+ pedantic: false
9708
+ });
9709
+ /** Only supported paragraph tokens permit changing physical line margins. */
9710
+ function isParagraphNoteText(text) {
9711
+ const tokens = noteMarkdown.lexer(text.trim());
9712
+ const paragraph = tokens[0];
9713
+ return tokens.length === 1 && paragraph.type === "paragraph" && paragraph.tokens !== void 0 && paragraph.tokens.every(isMarginIndependentNoteToken);
9714
+ }
9715
+ /** Token forms that permit changing surrounding paragraph line margins. */
9716
+ function isMarginIndependentNoteToken(token) {
9717
+ switch (token.type) {
9718
+ case "text": return !token.raw.includes("`");
9719
+ case "em":
9720
+ case "strong": return token.tokens !== void 0 && token.tokens.every(isMarginIndependentNoteToken);
9721
+ case "codespan":
9722
+ case "link": return !token.raw.includes("\n");
9723
+ case "html": return token.raw === "<br/>" && token.block === false;
9724
+ default: return false;
9725
+ }
9726
+ }
9727
+ /** A nonblank first physical row loses its leading space/tab padding in the Db. */
9728
+ function firstNoteTextLine(source, text, indentation) {
9729
+ let start = text.start + 1;
9730
+ while (source.text[start] === " " || source.text[start] === " ") start++;
9731
+ const lineEnd = lineEndOf(source, text.start + 1);
9732
+ if (start >= text.end || start >= lineEnd || isWhitespace(source.text[start])) return null;
9733
+ const end = Math.min(lineEnd, text.end);
9734
+ return [{
9735
+ start,
9736
+ end,
9737
+ writtenIndentation: indentation
9738
+ }, ...end < text.end ? [{
9739
+ start: end,
9740
+ end: text.end
9741
+ }] : []];
9742
+ }
9743
+ /**
9744
+ * The body stretch initially collected as one atom: from the line break after
9745
+ * its id to the line break before the line of `end note`,
9360
9746
  * or null where text other than comments and directives follows the id on
9361
9747
  * its line or `end note` does not start its line.
9362
9748
  */
@@ -9520,13 +9906,8 @@ function printState(path, options, print, source) {
9520
9906
  if (classified === null) throw new Error(`prettier-plugin-mmd: ${node.type} is no node of a state diagram that is printed`);
9521
9907
  const depth = depthOf(path);
9522
9908
  const followsStateName = isStateNameStatement(path.previous);
9523
- switch (classified.kind) {
9524
- case "body":
9525
- if (hasBodyBlock(source, classified.statement)) return printBodyBlock(path, options, print, source, classified.statement, depth, followsStateName);
9526
- return printLine$1(source, options, layoutStateStatement(source, classified.statement, findStatePrintedEnd(source, classified.statement), followsStateName), depth);
9527
- case "simple": return printLine$1(source, options, layoutStateStatement(source, classified.statement, findStatePrintedEnd(source, classified.statement), followsStateName), depth);
9528
- default: throw new Error(`prettier-plugin-mmd: unknown kind of statement ${JSON.stringify(classified)}`);
9529
- }
9909
+ if (classified.kind === "body" && hasBodyBlock(source, classified.statement)) return printBodyBlock(path, options, print, source, classified.statement, depth, followsStateName);
9910
+ return printLine$1(source, options, layoutStateStatement(source, classified.statement, findStatePrintedEnd(source, classified.statement), followsStateName, " ".repeat(options.tabWidth * (depth + 1))), depth);
9530
9911
  }
9531
9912
  /** Prints a statement laid out on its lines at `depth`. */
9532
9913
  function printLine$1(source, options, layout, depth) {
@@ -9651,7 +10032,7 @@ function layoutCommonLine(source, statement, isTitle) {
9651
10032
  * Shared block edges and aligned closer, followed by retained hidden suffixes
9652
10033
  * (docs/pie.md, Description blocks; docs/gitgraph.md, Title and common values).
9653
10034
  */
9654
- function layoutCommonDescription(source, statement, valueTypes) {
10035
+ function layoutCommonDescription(source, statement, valueTypes, options = {}) {
9655
10036
  const [start, end] = statement.range;
9656
10037
  const closing = findTokensBetween(source, start, statement.textAfter?.at(0)?.range[0] ?? end).findLast((token) => isStructural(source, token) && token.value === "}");
9657
10038
  const blockEnd = expectToken(closing, "the description closer").range[1];
@@ -9663,6 +10044,7 @@ function layoutCommonDescription(source, statement, valueTypes) {
9663
10044
  const opener = expectToken(findStructuralToken(source, start), "accDescr");
9664
10045
  const brace = expectToken(findStructuralToken(source, statement.textBeforeOpen?.at(-1)?.range[1] ?? opener.range[1]), "the description opener");
9665
10046
  let layout = layoutDescriptionBlock(source, block, blockEnd, valueTypes, {
10047
+ ...options,
9666
10048
  keepsTrailingTrivia: true,
9667
10049
  formatsEmptyTrivia: true,
9668
10050
  trimValueEdges: true,
@@ -9904,7 +10286,7 @@ function layoutTreeviewStatement(source, item, column, boxMode, drawing) {
9904
10286
  lineBreaks: "kept",
9905
10287
  joinedBefore: findTriviaBetween(source, keyword.range[1], brace.range[0]).length === 0 ? /* @__PURE__ */ new Set([brace.range[0]]) : /* @__PURE__ */ new Set()
9906
10288
  };
9907
- } else layout = layoutCommonDescription(source, content, treeviewValueNodeTypes);
10289
+ } else layout = layoutCommonDescription(source, content, treeviewValueNodeTypes, { preservesBodyColumns: boxMode });
9908
10290
  const gap = drawing?.keptOpenerGaps.get(item);
9909
10291
  if (gap !== void 0) layout = {
9910
10292
  ...layout,
@@ -10177,13 +10559,14 @@ function printTreeview(path, options, _print, source) {
10177
10559
  if (line.item.type === "TreeviewIgnoredText" && drawing !== void 0) return drawing.decorations.get(line.item);
10178
10560
  const head = line.item.type === "TreeviewNode" ? drawing?.heads.get(line.item) ?? "" : "";
10179
10561
  const after = line.item.type === "TreeviewNode" ? drawing?.trailingDecorations.get(line.item) ?? [] : [];
10562
+ const descriptionIndentation = line.item.type === "TreeviewAccDescrBlockStatement" ? significantIndentationOf(options, boxMode ? 1 : line.depth + 1) : "";
10180
10563
  return [
10181
10564
  placements.get(line).head,
10182
10565
  head,
10183
10566
  printAtoms(source, layouts.get(line), {
10184
10567
  statement: boxMode ? "" : significantIndentationOf(options, line.depth),
10185
- continuation: "",
10186
- trivia: ""
10568
+ continuation: descriptionIndentation,
10569
+ trivia: descriptionIndentation
10187
10570
  }).doc,
10188
10571
  ...after.flatMap((decoration) => {
10189
10572
  const guide = drawing.decorations.get(decoration);
@@ -10321,7 +10704,7 @@ function hasTrailingIndentation(source, start, end) {
10321
10704
  return false;
10322
10705
  }
10323
10706
  /** Ordinary row components join; trivia and protected segments keep their lines. */
10324
- function layoutTreemapStatement(source, statement, column) {
10707
+ function layoutTreemapStatement(source, statement, column, continuationPadding) {
10325
10708
  const [start, end] = treemapStatementRange(statement);
10326
10709
  let layout;
10327
10710
  switch (statement.type) {
@@ -10352,9 +10735,18 @@ function layoutTreemapStatement(source, statement, column) {
10352
10735
  atoms: atoms.map((atom, index) => {
10353
10736
  const previous = atoms[index - 1];
10354
10737
  const hasEarlierIndentation = previous !== void 0 && hasTrailingIndentation(source, previous.end, atom.start);
10738
+ const styleContinuation = statement.type === "TreemapClassDefStatement" && statement.style?.range[0] === atom.start && !hasEarlierIndentation;
10739
+ let writtenIndentation = column;
10740
+ if (hasEarlierIndentation || findTokenStartingAt(source, atom.start)?.value === ":::" || statement.type !== "TreemapClassDefStatement" && statement.classSelector?.range[0] === atom.start) writtenIndentation = "";
10741
+ else if (styleContinuation) writtenIndentation += continuationPadding;
10742
+ if (styleContinuation) return {
10743
+ ...atom,
10744
+ statementPadding: continuationPadding,
10745
+ writtenIndentation
10746
+ };
10355
10747
  return {
10356
10748
  ...atom,
10357
- writtenIndentation: hasEarlierIndentation || findTokenStartingAt(source, atom.start)?.value === ":::" || statement.type !== "TreemapClassDefStatement" && statement.classSelector?.range[0] === atom.start ? "" : column
10749
+ writtenIndentation
10358
10750
  };
10359
10751
  }),
10360
10752
  rules,
@@ -10394,11 +10786,17 @@ function printTreemap(path, options, _print, source) {
10394
10786
  } : placeLeadingDirectives(source, line.leading, column.length, options.useTabs ? " " : " ")];
10395
10787
  }));
10396
10788
  const relocatedWhitespace = lines.map((line, index) => [lines[index - 1]?.range[1] ?? keyword.range[1], line.range[0]]);
10397
- const block = printBlock(lines.map((line) => [placements.get(line).head, ...line.statements.flatMap((statement, index) => [index === 0 ? "" : printAsWritten(source, treemapStatementRange(line.statements[index - 1])[1], treemapStatementRange(statement)[0]), printAtoms(source, layoutTreemapStatement(source, statement, significantIndentationOf(options, line.depth)), {
10398
- statement: significantIndentationOf(options, line.depth),
10399
- continuation: "",
10400
- trivia: ""
10401
- }).doc])]), source, {
10789
+ const block = printBlock(lines.map((line) => {
10790
+ const column = significantIndentationOf(options, line.depth);
10791
+ return [placements.get(line).head, ...line.statements.flatMap((statement, index) => {
10792
+ const descriptionIndentation = statement.type === "TreemapAccDescrBlockStatement" ? significantIndentationOf(options, line.depth + 1) : "";
10793
+ return [index === 0 ? "" : printAsWritten(source, treemapStatementRange(line.statements[index - 1])[1], treemapStatementRange(statement)[0]), printAtoms(source, layoutTreemapStatement(source, statement, column, significantIndentationOf(options, 1)), {
10794
+ statement: column,
10795
+ continuation: descriptionIndentation,
10796
+ trivia: descriptionIndentation
10797
+ }).doc];
10798
+ })];
10799
+ }), source, {
10402
10800
  statements: lines,
10403
10801
  start: keyword.range[1],
10404
10802
  end: source.text.length,
@@ -10537,69 +10935,27 @@ function layoutTimelineHeader(source, keyword) {
10537
10935
  * not one of them (see `layoutEvents`).
10538
10936
  * - A title, a section, and an accessibility statement written over several
10539
10937
  * lines stand on one line where the lexer reads the line break as
10540
- * whitespace, which it does only right after a keyword; one with a comment
10541
- * or a directive in it is kept as written (see
10542
- * `spansLinesThatCannotJoin`). The lines of an `accDescr` block are lines
10543
- * of its text, and are kept (docs/timeline.md, Accessibility statements).
10938
+ * whitespace, which it does only right after a keyword. Accessibility line
10939
+ * trivia keeps its breaks with ordinary continuation columns; titles,
10940
+ * sections, events and protected regions retain their original layout
10941
+ * (docs/timeline.md, Multi-line statements).
10544
10942
  */
10545
10943
  function layoutTimelineStatement(source, statement, end) {
10546
10944
  const start = statement.range[0];
10547
10945
  switch (statement.type) {
10548
- case "TimelineAccDescrBlockStatement": return layoutTimelineDescriptionBlock(source, statement, end);
10946
+ case "TimelineAccDescrBlockStatement": return layoutDescriptionBlock(source, statement, end, timelineValueNodeTypes);
10549
10947
  case "TimelinePeriodStatement":
10550
10948
  case "TimelineEventStatement": return layoutEvents(source, statement, end);
10551
10949
  }
10552
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
10950
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
10951
+ const formatsTriviaLines = statement.type === "TimelineAccTitleStatement" || statement.type === "TimelineAccDescrStatement";
10952
+ if (keepsLineBreaks && (!formatsTriviaLines || holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
10953
+ const atoms = collectAtoms(source, start, end, collectValueNodes(statement, timelineValueNodeTypes), []);
10553
10954
  return {
10554
- atoms: collectAtoms(source, start, end, collectValueNodes(statement, timelineValueNodeTypes), []),
10955
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
10555
10956
  rules: textStatementRules(source, statement),
10556
10957
  outdented: /* @__PURE__ */ new Set(),
10557
- lineBreaks: "joined"
10558
- };
10559
- }
10560
- /**
10561
- * Align description lines one level inside their statement. Indentation after
10562
- * LF is absent from the Db, so normalize those columns while preserving written
10563
- * line breaks and trailing whitespace (docs/timeline.md, Multi-line values).
10564
- * Reuse the shared block layout, splitting its retained atoms only at those safe
10565
- * LFs; directives keep their complete written contents.
10566
- */
10567
- function layoutTimelineDescriptionBlock(source, statement, end) {
10568
- const layout = layoutDescriptionBlock(source, statement, end, timelineValueNodeTypes);
10569
- const atoms = [];
10570
- const keptBreaksBefore = /* @__PURE__ */ new Set();
10571
- const outdented = new Set(layout.outdented);
10572
- const closing = findAccDescrBlockClosing(source, {
10573
- range: statement.range,
10574
- value: statement.value,
10575
- closed: true
10576
- });
10577
- if (closing !== null) outdented.add(closing);
10578
- for (const atom of layout.atoms) {
10579
- const trivia = findTriviaBetween(source, atom.start, atom.end);
10580
- let start = atom.start;
10581
- for (let offset = atom.start; offset < atom.end; offset++) {
10582
- if (source.text[offset] !== "\n") continue;
10583
- if (trivia.some((item) => item.range[0] <= offset && offset < item.range[1]) || source.removedLineFeeds.has(offset)) continue;
10584
- if (start < offset) atoms.push({
10585
- start,
10586
- end: offset
10587
- });
10588
- start = offset + 1;
10589
- while (start < atom.end && (source.text[start] === " " || source.text[start] === " ")) start++;
10590
- if (start < atom.end && source.text[start] !== "\n") keptBreaksBefore.add(start);
10591
- offset = start - 1;
10592
- }
10593
- if (start < atom.end) atoms.push({
10594
- ...atom,
10595
- start
10596
- });
10597
- }
10598
- return {
10599
- ...layout,
10600
- atoms,
10601
- keptBreaksBefore,
10602
- outdented
10958
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
10603
10959
  };
10604
10960
  }
10605
10961
  /** The gap rules of a title, a section, or an accessibility statement. */
@@ -10733,23 +11089,26 @@ function valueNodesOf(statement) {
10733
11089
  * The layout of a header (docs/xychart.md, Header and orientation): the
10734
11090
  * keyword and the orientation after it, which stands after one space, also
10735
11091
  * where it was written on a later line after whitespace. A header with a
10736
- * comment or a directive over several lines is kept as written (see
10737
- * `spansLinesThatCannotJoin`).
11092
+ * comment or directive keeps its trivia breaks with continuation columns;
11093
+ * semicolon lines and joining regions retain their layout (docs/xychart.md,
11094
+ * Multi-line statements).
10738
11095
  */
10739
11096
  function layoutXychartHeader(source, header) {
10740
11097
  const [start, end] = header.range;
10741
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
11098
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
11099
+ if (keepsLineBreaks && (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
10742
11100
  const keyword = expectToken(findStructuralToken(source, start), "the header");
10743
11101
  const rules = /* @__PURE__ */ new Map();
10744
11102
  if (header.orientation !== null) {
10745
11103
  const orientation = expectToken(findStructuralToken(source, keyword.range[1]), "the orientation");
10746
11104
  rules.set(orientation.range[0], "space");
10747
11105
  }
11106
+ const atoms = collectAtoms(source, start, end, [], []);
10748
11107
  return {
10749
- atoms: collectAtoms(source, start, end, [], []),
11108
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
10750
11109
  rules,
10751
11110
  outdented: /* @__PURE__ */ new Set(),
10752
- lineBreaks: "joined"
11111
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
10753
11112
  };
10754
11113
  }
10755
11114
  /**
@@ -10758,21 +11117,25 @@ function layoutXychartHeader(source, header) {
10758
11117
  * - A statement written over several lines stands on one line where the
10759
11118
  * lexer reads the line break as whitespace (diagrams/xychart.md, Lexical
10760
11119
  * structure, Line breaks); one with a comment or a directive in it, or a
10761
- * `;`, is kept as written (see `spansLinesThatCannotJoin`). The lines of an
10762
- * `accDescr` block are lines of its text, and are kept (docs/xychart.md,
10763
- * Accessibility statements).
11120
+ * `;`, keeps its required line breaks. Ordinary exterior gaps take
11121
+ * continuation indentation; required line tails and protected regions stay
11122
+ * written.
11123
+ * Description-body lines align inside their block (docs/xychart.md,
11124
+ * Accessibility statements and Multi-line statements).
10764
11125
  * - The rules of the gaps are those of docs/xychart.md: Text units, Brackets
10765
11126
  * and commas, Ranges, Values and labels, and Accessibility statements.
10766
11127
  */
10767
11128
  function layoutXychartStatement(source, statement, end) {
10768
11129
  const start = statement.range[0];
10769
11130
  if (statement.type === "XychartAccDescrBlockStatement") return layoutDescriptionBlock(source, statement, end, descriptionBlockTextTypes);
10770
- if (spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
11131
+ const keepsLineBreaks = spansLinesThatCannotJoin(source, start, end);
11132
+ if (keepsLineBreaks && (holdsJoiningRegion(source, start, end) || spansLinesThatCannotJoin(source, start, end, { ignoresTrivia: true }))) return keptAsWritten(start, end);
11133
+ const atoms = collectAtoms(source, start, end, valueNodesOf(statement), []);
10771
11134
  return {
10772
- atoms: collectAtoms(source, start, end, valueNodesOf(statement), []),
11135
+ atoms: keepsLineBreaks ? keepFirstGapLineTails(source, atoms) : atoms,
10773
11136
  rules: statementRules(source, statement),
10774
11137
  outdented: /* @__PURE__ */ new Set(),
10775
- lineBreaks: "joined"
11138
+ lineBreaks: keepsLineBreaks ? "kept" : "joined"
10776
11139
  };
10777
11140
  }
10778
11141
  /** The gap rules of a statement, by the start of the atom after the gap. */
@@ -11615,6 +11978,7 @@ function layoutRadarStatement(source, statement) {
11615
11978
  const rules = /* @__PURE__ */ new Map();
11616
11979
  const outdented = /* @__PURE__ */ new Set();
11617
11980
  const joinedBefore = /* @__PURE__ */ new Set();
11981
+ const hasTrivia = findTriviaBetween(source, start, end).length > 0;
11618
11982
  for (const [index, atom] of atoms.entries()) {
11619
11983
  const previous = atoms[index - 1];
11620
11984
  if (previous === void 0) continue;
@@ -11623,7 +11987,7 @@ function layoutRadarStatement(source, statement) {
11623
11987
  const touches = token?.type === "Punctuator" || before?.value === "[" || before?.value === "{";
11624
11988
  rules.set(atom.start, touches ? "none" : "space");
11625
11989
  if (token?.value === "}") outdented.add(atom.start);
11626
- if (findTriviaBetween(source, previous.end, atom.start).length === 0 && !hidden.some((item) => item.range[0] === atom.start || item.range[1] === previous.end) && !hasSemicolon) joinedBefore.add(atom.start);
11990
+ if (!hasTrivia && !hidden.some((item) => item.range[0] === atom.start || item.range[1] === previous.end) && !hasSemicolon) joinedBefore.add(atom.start);
11627
11991
  }
11628
11992
  layout = {
11629
11993
  atoms,
@@ -11761,14 +12125,14 @@ function layoutEventmodelingStatement(source, statement, options) {
11761
12125
  function layoutComponents$1(source, statement, start, end, tabWidth) {
11762
12126
  const values = collectValueNodes(statement, eventmodelingValueNodeTypes).filter((node) => start <= node.range[0] && node.range[1] <= end);
11763
12127
  const kept = [];
12128
+ let blockOpening;
11764
12129
  walk(statement, (node) => {
11765
12130
  if ((node.type === "EventmodelingInlineData" || node.type === "EventmodelingDataBlock") && node.range[1] <= end) {
11766
12131
  const opening = expectToken(node.value?.type === "StringLiteral" ? findTokenStartingAt(source, node.value.range[0]) : findTokensBetween(source, node.range[0], node.range[1]).find((token) => token.type === "Punctuator" && token.value === "{"), "a data body");
11767
- const doc = node.type === "EventmodelingDataBlock" ? indentedDataBlock(source.text.slice(opening.range[0], node.range[1]), tabWidth) : void 0;
12132
+ if (node.type === "EventmodelingDataBlock") blockOpening = opening.range[0];
11768
12133
  kept.push({
11769
12134
  start: opening.range[0],
11770
- end: node.range[1],
11771
- doc
12135
+ end: node.range[1]
11772
12136
  });
11773
12137
  }
11774
12138
  });
@@ -11792,36 +12156,46 @@ function layoutComponents$1(source, statement, start, end, tabWidth) {
11792
12156
  }
11793
12157
  if (token?.value === "`") inTag = !inTag;
11794
12158
  }
11795
- let layout = protectHiddenGaps({
12159
+ const protectedLayout = protectHiddenGaps({
11796
12160
  atoms: protectSemicolonPrefixes(source, start, end, atoms),
11797
12161
  rules,
11798
12162
  outdented: /* @__PURE__ */ new Set(),
11799
12163
  lineBreaks: "kept",
11800
12164
  joinedBefore
11801
12165
  }, values.filter((node) => node.type === "EventmodelingIgnoredText"));
11802
- if (classifyEventmodelingStatement(statement).kind === "data") {
11803
- let paddedEnd = end;
11804
- while (source.text[paddedEnd] === " " || source.text[paddedEnd] === " ") paddedEnd++;
11805
- const last = layout.atoms.at(-1);
11806
- layout = {
11807
- ...layout,
11808
- atoms: [...layout.atoms.slice(0, -1), {
11809
- ...last,
11810
- end: paddedEnd,
11811
- doc: last.doc === void 0 ? void 0 : [last.doc, printAsWritten(source, last.end, paddedEnd)]
11812
- }]
11813
- };
11814
- }
12166
+ const layout = {
12167
+ ...protectedLayout,
12168
+ writtenGapsBefore: /* @__PURE__ */ new Set([...protectedLayout.writtenGapsBefore ?? [], ...writtenGapsBefore])
12169
+ };
12170
+ return classifyEventmodelingStatement(statement).kind === "data" ? layoutDataBody(source, layout, values, blockOpening, end, tabWidth) : layout;
12171
+ }
12172
+ /**
12173
+ * Aligns a data or note body and retains its required closing padding. Its
12174
+ * final atom is the required body, or a semicolon-protected span covering it.
12175
+ */
12176
+ function layoutDataBody(source, layout, values, blockOpening, end, tabWidth) {
12177
+ const body = layout.atoms.at(-1);
12178
+ const continuedHeader = !values.some((node) => node.type === "EventmodelingIgnoredText" && node.range[0] < body.start) && layout.atoms.some((atom, index) => {
12179
+ const previous = layout.atoms[index - 1];
12180
+ return previous !== void 0 && !layout.joinedBefore?.has(atom.start) && !layout.writtenGapsBefore?.has(atom.start) && readGap(source, previous.end, atom.start, true).breaksLine;
12181
+ });
12182
+ const bodyDoc = body.start === blockOpening && body.writtenIndentation === void 0 ? indentedDataBlock(source.text.slice(body.start, body.end), tabWidth * (continuedHeader ? 2 : 1)) : void 0;
12183
+ let paddedEnd = end;
12184
+ while (source.text[paddedEnd] === " " || source.text[paddedEnd] === " ") paddedEnd++;
11815
12185
  return {
11816
12186
  ...layout,
11817
- writtenGapsBefore: /* @__PURE__ */ new Set([...layout.writtenGapsBefore ?? [], ...writtenGapsBefore])
12187
+ atoms: [...layout.atoms.slice(0, -1), {
12188
+ ...body,
12189
+ end: paddedEnd,
12190
+ doc: bodyDoc === void 0 ? void 0 : [bodyDoc, printAsWritten(source, body.end, paddedEnd)]
12191
+ }]
11818
12192
  };
11819
12193
  }
11820
12194
  /**
11821
- * Only change a common ASCII-space margin whose space-separated words stay
11822
- * the same in Mermaid's data label. A new space on a later physical line
11823
- * adds a visible nonbreaking space; tabs, markup and padded openers also
11824
- * need their authored text (docs/eventmodeling.md, Data blocks).
12195
+ * Align nonblank body lines while keeping the space-separated words of
12196
+ * Mermaid's data label. A new space on a later physical line adds a visible
12197
+ * nonbreaking space; tabs, markup and padded openers need their authored text
12198
+ * (docs/eventmodeling.md, Data blocks).
11825
12199
  */
11826
12200
  function indentedDataBlock(text, tabWidth) {
11827
12201
  if (tabWidth === 0 || !text.startsWith("{\n") || !text.endsWith("\n}") || text.includes("<") || text.includes("&") || text.includes("%%{")) return void 0;
@@ -11831,19 +12205,16 @@ function indentedDataBlock(text, tabWidth) {
11831
12205
  while (row[margin] === " ") margin++;
11832
12206
  return margin;
11833
12207
  });
11834
- let commonMargin = Infinity;
12208
+ let hasContent = false;
11835
12209
  for (const [index, row] of rows.entries()) {
11836
12210
  if (row.trim() === "") continue;
12211
+ hasContent = true;
11837
12212
  const margin = margins[index];
11838
12213
  if (isWhitespace(row[margin]) || index > 0 && margin === 0) return void 0;
11839
- commonMargin = Math.min(commonMargin, margin);
11840
12214
  }
11841
- if (commonMargin === Infinity || commonMargin === tabWidth) return void 0;
11842
- const delta = tabWidth - commonMargin;
11843
- const indented = rows.map((row, index) => {
11844
- if (row.trim() === "") return row;
11845
- return " ".repeat(margins[index] + delta) + row.slice(margins[index]);
11846
- });
12215
+ if (!hasContent) return void 0;
12216
+ const indentation = " ".repeat(tabWidth);
12217
+ const indented = rows.map((row, index) => row.trim() === "" ? row : indentation + row.slice(margins[index]));
11847
12218
  return utils.replaceEndOfLine(`{\n${indented.join("\n")}\n}`);
11848
12219
  }
11849
12220
  //#endregion
@@ -12150,6 +12521,14 @@ function layoutRule(source, statement, values, hidden, grammaticalSemicolons, wr
12150
12521
  const rules = /* @__PURE__ */ new Map();
12151
12522
  const outdented = /* @__PURE__ */ new Set([end - 1]);
12152
12523
  const joinedBefore = /* @__PURE__ */ new Set();
12524
+ const alternativeBreaks = /* @__PURE__ */ new Set();
12525
+ if (!wrapsCalls && statement.definition.type === "RailroadChoiceExpression") {
12526
+ alternativeBreaks.add(statement.definition.range[0]);
12527
+ for (let index = 1; index < statement.definition.alternatives.length; index++) {
12528
+ const separator = expectToken(findStructuralToken(source, statement.definition.alternatives[index - 1].range[1]), "the separator between railroad alternatives");
12529
+ alternativeBreaks.add(separator.range[0]);
12530
+ }
12531
+ }
12153
12532
  const binary = /* @__PURE__ */ new Set([
12154
12533
  "=",
12155
12534
  "::=",
@@ -12165,7 +12544,7 @@ function layoutRule(source, statement, values, hidden, grammaticalSemicolons, wr
12165
12544
  const before = findTokenStartingAt(source, previous.start);
12166
12545
  rules.set(atom.start, token?.type === "Punctuator" && binary.has(token.value) || before?.type === "Punctuator" && (binary.has(before.value) || before.value === ",") ? "space" : "none");
12167
12546
  if (token?.type === "Punctuator" && (token.value === ")" || token.value === "]" || token.value === "}")) outdented.add(atom.start);
12168
- if (findTriviaBetween(source, previous.end, atom.start).length === 0 && !hidden.some((item) => item.range[0] === atom.start || item.range[1] === previous.end)) joinedBefore.add(atom.start);
12547
+ if (findTriviaBetween(source, previous.end, atom.start).length === 0 && !hidden.some((item) => item.range[0] === atom.start || item.range[1] === previous.end) && !(alternativeBreaks.has(atom.start) && source.text.slice(previous.end, atom.start).includes("\n"))) joinedBefore.add(atom.start);
12169
12548
  }
12170
12549
  walk(statement, (node) => {
12171
12550
  if (node.type !== "RailroadSequenceExpression") return;