prettier-plugin-mmd 0.4.1 → 0.5.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,4 +1,4 @@
1
- import { parse, visitorKeys } from "@mmd-toolkit/parser";
1
+ import { parse, traverseNodes, visitorKeys } from "@mmd-toolkit/parser";
2
2
  import { builders, printer, utils } from "prettier/doc";
3
3
  import { Marked } from "marked";
4
4
  import { util } from "prettier";
@@ -23,6 +23,17 @@ function maxOf(values) {
23
23
  for (const value of values) maximum = Math.max(maximum, value);
24
24
  return maximum;
25
25
  }
26
+ /** The nodes of the tree below `root`, `root` included, that `matches` selects, in source order. */
27
+ function findNodes(root, matches) {
28
+ const found = [];
29
+ traverseNodes(root, {
30
+ enterNode(node) {
31
+ if (matches(node)) found.push(node);
32
+ },
33
+ leaveNode() {}
34
+ });
35
+ return found;
36
+ }
26
37
  //#endregion
27
38
  //#region src/printers/source.ts
28
39
  /**
@@ -519,10 +530,10 @@ function findLinesWithOwnSemicolons(source) {
519
530
  const lines = /* @__PURE__ */ new Set();
520
531
  /** Adds the lines of the `;` characters in a range. */
521
532
  function addSemicolonsIn(range) {
522
- for (let offset = range[0]; offset < range[1]; offset++) if (text[offset] === ";" && !rules.grammatical.has(offset)) lines.add(lineStartOf(source, offset));
533
+ for (let offset = range[0]; offset < range[1]; offset++) if (text[offset] === ";" && !rules.grammatical.has(offset) && !isDroppedSemicolon(source, offset)) lines.add(lineStartOf(source, offset));
523
534
  }
524
535
  for (const token of root.tokens) if (token.value !== ";") addSemicolonsIn(token.range);
525
- else if (!rules.grammatical.has(token.range[0]) && (rules.kind === "text" || source.ignoredSemicolons.has(token.range[0]) && (rules.kind === "required" || !isLastOnItsLine(source, token.range[0])))) lines.add(lineStartOf(source, token.range[0]));
536
+ else if (!rules.grammatical.has(token.range[0]) && (rules.kind === "text" && !isDroppedSemicolon(source, token.range[0]) || source.ignoredSemicolons.has(token.range[0]) && (rules.kind === "required" || !isLastOnItsLine(source, token.range[0])))) lines.add(lineStartOf(source, token.range[0]));
526
537
  for (const comment of root.comments) addSemicolonsIn(comment.range);
527
538
  for (const offset of source.ignoredSemicolons) if (rules.kind === "required" || !isLastOnItsLine(source, offset)) lines.add(lineStartOf(source, offset));
528
539
  return lines;
@@ -635,28 +646,143 @@ function isNextToSemicolon(source, offset) {
635
646
  }
636
647
  /**
637
648
  * Whether nothing but whitespace follows the `;` at `offset` on its line: no
638
- * token, comment, or directive starts after it before the line ends. A `;`
639
- * that the line rule ignores and that ends its line can be dropped only
649
+ * token that holds more than whitespace, comment, or directive starts after it
650
+ * before the line ends (a style holds the whitespace after an ignored `;`). A
651
+ * `;` that the line rule ignores and that ends its line can be dropped only
640
652
  * where it is optional (see `isDroppedSemicolon`).
641
653
  */
642
654
  function isLastOnItsLine(source, offset) {
643
655
  const lineEnd = lineEndOf(source, offset);
644
- return findTokensBetween(source, offset + 1, lineEnd).length === 0 && findTriviaBetween(source, offset + 1, lineEnd).length === 0;
656
+ return findTokensBetween(source, offset + 1, lineEnd).every((token) => source.text.slice(...token.range).trim() === "") && findTriviaBetween(source, offset + 1, lineEnd).length === 0;
645
657
  }
646
658
  /**
647
659
  * Whether the printer drops the `;` at `offset`: one that the line rule
648
660
  * ignores at the end of its line, which is dropped as a `;` that separates
649
- * statements is, since mermaid.js removes it from the text. Not one right
650
- * after a comment: with whitespace after it, the `;` lies inside the comment,
651
- * which is printed as written, and a `;` that was dropped only when it stands
652
- * outside the comment would make a second formatting differ from the first
653
- * (ast.md, Comment). Not one in a diagram type where no `;` separates
654
- * statements: there the line that holds it is kept as written, with the `;`.
655
- * Required punctuation is never dropped, including selected semicolons in a
656
- * diagram with required terminators (see `semicolonRulesOf`).
661
+ * statements is, since mermaid.js removes it from the text, and the `;` that
662
+ * ends a `classDef` or `style` statement (see `styleSemicolonsOf`). Not one
663
+ * right after a comment: with whitespace after it, the `;` lies inside the
664
+ * comment, which is printed as written, and a `;` that was dropped only when
665
+ * it stands outside the comment would make a second formatting differ from the
666
+ * first (ast.md, Comment). Not one in a diagram type where no `;` separates
667
+ * statements, unless it ends such a statement: there the line that holds it is
668
+ * kept as written, with the `;`. Required punctuation is never dropped,
669
+ * including selected semicolons in a diagram with required terminators (see
670
+ * `semicolonRulesOf`).
657
671
  */
658
672
  function isDroppedSemicolon(source, offset) {
659
- return semicolonRulesOf(source).kind === "separators" && source.ignoredSemicolons.has(offset) && isLastOnItsLine(source, offset) && !source.root.comments.some((comment) => comment.range[1] === offset);
673
+ if (!isLastOnItsLine(source, offset) || source.root.comments.some((comment) => comment.range[1] === offset)) return false;
674
+ const { kind } = semicolonRulesOf(source);
675
+ if (source.ignoredSemicolons.has(offset)) return kind === "separators" || kind === "text" && endsStyleStatement(source, offset);
676
+ return kind === "text" && styleSemicolonsOf(source).terminators.has(offset);
677
+ }
678
+ /**
679
+ * Whether the text from `start` to `end` holds a `;` that the printer keeps:
680
+ * every `;` but one that it drops (see `isDroppedSemicolon`). A decision that
681
+ * the printed text would make again on a second formatting reads the text as
682
+ * it is printed, without the dropped `;`.
683
+ */
684
+ function holdsKeptSemicolon(source, start, end) {
685
+ for (let offset = source.text.indexOf(";", start); offset !== -1 && offset < end; offset = source.text.indexOf(";", offset + 1)) if (!isDroppedSemicolon(source, offset)) return true;
686
+ return false;
687
+ }
688
+ /**
689
+ * The offset of the `;` that ends a treemap `classDef` statement with a style,
690
+ * or undefined: the `;` that the line rule ignores right after the statement;
691
+ * or the last character of the statement, ignoring whitespace, which is the `;`
692
+ * unit of the statement, or a `;` that the line rule ignores and that the style
693
+ * holds together with the whitespace after it.
694
+ */
695
+ function endingSemicolonOf(source, range, style) {
696
+ if (style === null) return void 0;
697
+ const [, end] = range;
698
+ if (source.ignoredSemicolons.has(end)) return end;
699
+ let last = end;
700
+ while (last > style.range[0] && isWhitespace(source.text[last - 1])) last--;
701
+ return source.text[last - 1] === ";" ? last - 1 : void 0;
702
+ }
703
+ /**
704
+ * The node types of the `classDef` and `style` statements whose `;` may be
705
+ * dropped.
706
+ */
707
+ const styleStatementTypes = /* @__PURE__ */ new Set([
708
+ "ClassClassDefStatement",
709
+ "ClassStyleStatement",
710
+ "StateClassDefStatement",
711
+ "StateStyleStatement",
712
+ "ErClassDefStatement",
713
+ "ErStyleStatement",
714
+ "RequirementClassDefStatement",
715
+ "RequirementStyleStatement",
716
+ "BlockClassDefStatement",
717
+ "BlockStyleStatement",
718
+ "VennStyleStatement",
719
+ "UsecaseClassDefStatement",
720
+ "UsecaseStyleStatement",
721
+ "TreemapClassDefStatement"
722
+ ]);
723
+ const styleSemicolonsBySource = /* @__PURE__ */ new WeakMap();
724
+ /** The `;` of the style statements of a source. */
725
+ function styleSemicolonsOf(source) {
726
+ const cached = styleSemicolonsBySource.get(source);
727
+ if (cached !== void 0) return cached;
728
+ const ends = /* @__PURE__ */ new Set();
729
+ const terminators = /* @__PURE__ */ new Set();
730
+ /**
731
+ * Adds the `;` unit that ends a statement, when the statement has a style
732
+ * and no directive stands right before the `;`, with at most whitespace
733
+ * between: it is printed with the style as written, with the `;`.
734
+ */
735
+ function addUnitTerminator(statement, style) {
736
+ const last = findTokenEndingBefore(source, statement.range[1]);
737
+ if (last?.value !== ";" || last.type !== "Punctuator" || style === void 0 || style === null) return;
738
+ let before = last.range[0];
739
+ while (before > style.range[0] && isWhitespace(source.text[before - 1])) before--;
740
+ if (findDirectiveEndingAt(source, before) === void 0) terminators.add(last.range[0]);
741
+ }
742
+ for (const node of findNodes(source.root.body, (candidate) => styleStatementTypes.has(candidate.type))) {
743
+ ends.add(node.range[1]);
744
+ if (node.type === "TreemapClassDefStatement") {
745
+ addUnitTerminator(node, node.style);
746
+ const semicolon = endingSemicolonOf(source, node.range, node.style);
747
+ if (semicolon !== void 0 && source.ignoredSemicolons.has(semicolon)) ends.add(semicolon);
748
+ continue;
749
+ }
750
+ if (source.text.slice(...node.range).includes("#")) continue;
751
+ if (node.type === "ErClassDefStatement" || node.type === "ErStyleStatement") addUnitTerminator(node, node.styles.at(-1));
752
+ else if (node.type === "StateClassDefStatement" || node.type === "StateStyleStatement" || node.type === "BlockClassDefStatement") {
753
+ const style = node.styles.findLast((item) => item !== null);
754
+ if (style === void 0 || style === null) continue;
755
+ const text = source.text.slice(...style.range);
756
+ if (text.endsWith(";") && text.indexOf(";") === text.length - 1 && text.slice(0, -1).trim() !== "") terminators.add(style.range[1] - 1);
757
+ }
758
+ }
759
+ const found = {
760
+ ends,
761
+ terminators
762
+ };
763
+ styleSemicolonsBySource.set(source, found);
764
+ return found;
765
+ }
766
+ /**
767
+ * Whether the `;` that the line rule ignores at `offset` ends a `classDef` or
768
+ * `style` statement: only whitespace and directives lie between the end of the
769
+ * statement and the `;`.
770
+ */
771
+ function endsStyleStatement(source, offset) {
772
+ const { ends } = styleSemicolonsOf(source);
773
+ let position = offset;
774
+ while (position > 0) {
775
+ if (ends.has(position)) return true;
776
+ const directive = findDirectiveEndingAt(source, position);
777
+ if (directive !== void 0) {
778
+ position = directive.range[0];
779
+ continue;
780
+ }
781
+ const character = source.text[position - 1];
782
+ if (character === "\n" || !isWhitespace(character)) return false;
783
+ position--;
784
+ }
785
+ return false;
660
786
  }
661
787
  /**
662
788
  * The offset where the line that holds `offset` starts: after the last line
@@ -920,15 +1046,22 @@ function semicolonSegmentEnd(source, offset) {
920
1046
  while (stop > protectedEnd && isWhitespace(source.text[stop - 1])) stop--;
921
1047
  return stop;
922
1048
  }
1049
+ /**
1050
+ * The offset of the last `;` that the printer keeps (see `isDroppedSemicolon`)
1051
+ * before `end`, or -1 where there is none.
1052
+ */
1053
+ function lastKeptSemicolonBefore(source, end) {
1054
+ for (let offset = source.text.lastIndexOf(";", end - 1); offset !== -1; offset = offset === 0 ? -1 : source.text.lastIndexOf(";", offset - 1)) if (!isDroppedSemicolon(source, offset)) return offset;
1055
+ return -1;
1056
+ }
923
1057
  /** The end of the protected prefix on the segment holding `offset`. */
924
1058
  function keptSemicolonPrefixEnd(source, offset) {
925
- const end = semicolonSegmentEnd(source, offset);
926
- const semicolon = source.text.lastIndexOf(";", end - 1);
1059
+ const semicolon = lastKeptSemicolonBefore(source, semicolonSegmentEnd(source, offset));
927
1060
  return semicolon >= offset ? semicolon + 1 : offset;
928
1061
  }
929
1062
  //#endregion
930
1063
  //#region src/printers/gap.ts
931
- const { replaceEndOfLine: replaceEndOfLine$1 } = utils;
1064
+ const { replaceEndOfLine: replaceEndOfLine$2 } = utils;
932
1065
  /**
933
1066
  * Reads the source between `start` and `end`.
934
1067
  *
@@ -984,6 +1117,7 @@ function readGap(source, start, end, keepsSeparators, options = {}) {
984
1117
  bareMarker: line.parts.some((part) => part.item.type === "Comment" && part.item.mark === "%%" && !isCommentLine(source.text, source.root, part.item)),
985
1118
  percentBraceGaps: countGapsBeforePercentBrace(source, line.parts),
986
1119
  singlePercent: line.parts.some((part) => part.item.type === "Comment" && part.item.mark === "%"),
1120
+ startsWithCommentLine: startsWithCommentLine(source, line.parts),
987
1121
  commentLinesOnly: line.parts.some((part) => part.item.type === "Comment") && line.parts.every((part) => part.item.type === "Directive" || part.item.type === "Comment" && isCommentLine(source.text, source.root, part.item))
988
1122
  });
989
1123
  emptyLineSeen = false;
@@ -995,6 +1129,7 @@ function readGap(source, start, end, keepsSeparators, options = {}) {
995
1129
  leading: toRun(source, last.parts, last.spaceAfter, false),
996
1130
  leadingDirectivesOnly: last.parts.length > 0 && last.parts.every((part) => part.item.type === "Directive"),
997
1131
  leadingIndentation: indentationBefore(source, last),
1132
+ leadingStartsWithCommentLine: startsWithCommentLine(source, last.parts),
998
1133
  leadingPercentBraceGaps: countGapsBeforePercentBrace(source, last.parts),
999
1134
  blankAfter: emptyLineSeen,
1000
1135
  breaksLine: true,
@@ -1036,6 +1171,7 @@ function readSingleLine(source, line, endsText, keepsInlineDirectivesWithPreviou
1036
1171
  lines: [],
1037
1172
  leading: toRun(source, after, line.spaceAfter, false),
1038
1173
  leadingDirectivesOnly: false,
1174
+ leadingStartsWithCommentLine: false,
1039
1175
  leadingPercentBraceGaps: null,
1040
1176
  leadingIndentation: "",
1041
1177
  blankAfter: false,
@@ -1211,6 +1347,11 @@ function isFollowedByJoiningRegion(source, offset) {
1211
1347
  }
1212
1348
  return false;
1213
1349
  }
1350
+ /** Whether the first part is a comment that is a comment line. */
1351
+ function startsWithCommentLine(source, parts) {
1352
+ const first = parts.at(0)?.item;
1353
+ return first?.type === "Comment" && isCommentLine(source.text, source.root, first);
1354
+ }
1214
1355
  /** Makes an empty scanned line. */
1215
1356
  function newLine() {
1216
1357
  return {
@@ -1266,7 +1407,7 @@ function toRun(source, parts, spaceAfter, keepsSeparatorsBeforeItems, dropsSepar
1266
1407
  * its inner lines keep their source columns.
1267
1408
  */
1268
1409
  function printItem(source, item) {
1269
- return replaceEndOfLine$1(source.text.slice(item.range[0], item.range[1]));
1410
+ return replaceEndOfLine$2(source.text.slice(item.range[0], item.range[1]));
1270
1411
  }
1271
1412
  /**
1272
1413
  * Whether a text ends with a space or a tab, the characters that Prettier
@@ -1584,7 +1725,7 @@ function layoutDescriptionBlock(source, statement, end, valueTypes, options = {}
1584
1725
  lineBreaks: "kept"
1585
1726
  };
1586
1727
  }
1587
- return options.preservesBodyColumns ? layout : indentDescriptionLines(source, block, layout);
1728
+ return formatDescriptionBlock(source, block, layout, options.preservesBodyColumns);
1588
1729
  }
1589
1730
  /**
1590
1731
  * Separate the description keyword from its brace in ordinary whitespace;
@@ -1637,13 +1778,62 @@ function expectToken(token, what) {
1637
1778
  function expectValue(token, value) {
1638
1779
  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]}`);
1639
1780
  }
1781
+ /** Whether a character ends a line: LF, CR, U+2028, or U+2029. */
1782
+ function isLineBreak$1(character) {
1783
+ return [
1784
+ "\n",
1785
+ "\r",
1786
+ "\u2028",
1787
+ "\u2029"
1788
+ ].includes(character);
1789
+ }
1790
+ /**
1791
+ * Pad the text of an `accDescr { ... }` block on one line with one space
1792
+ * inside each brace, `{ a b }`: mermaid.js trims the text, so the whitespace
1793
+ * at its ends carries no meaning, as in the data blocks of
1794
+ * docs/flowchart.md, Data blocks. The block is padded only if it is closed
1795
+ * and the layout holds its text as one atom between the braces, with
1796
+ * nothing but whitespace on one line around it: a comment or a directive in
1797
+ * the block (a `%%{` in the text, whose `}` would be read as the closing
1798
+ * brace), a line break, a line that keeps its `;` (see
1799
+ * `findLinesWithOwnSemicolons`: the line rule of mermaid.js reads its whole
1800
+ * text), or a layout that holds the text
1801
+ * in a longer stretch (a kept line, a hidden form) leaves it as it is.
1802
+ */
1803
+ function padOneLineDescription(source, block, layout) {
1804
+ const closing = findAccDescrBlockClosing(source, block);
1805
+ if (closing === null || closing !== block.range[1] - 1) return layout;
1806
+ const opening = expectToken(findDescriptionOpening(source, expectToken(findTokenStartingAt(source, block.range[0]), "the description keyword"), block.opening), "the description opener");
1807
+ const inside = layout.atoms.filter((atom) => atom.start >= opening.range[1] && atom.end <= closing);
1808
+ if (inside.length !== 1 || !layout.atoms.some((atom) => atom.end === opening.range[1]) || !layout.atoms.some((atom) => atom.start === closing)) return layout;
1809
+ const [text] = inside;
1810
+ const between = source.text.slice(opening.range[1], closing);
1811
+ if (text.doc !== void 0 || [...between].some(isLineBreak$1) || between.includes("%%{") || findSemicolonLines(source).has(lineStartOf(source, closing)) || findTriviaBetween(source, opening.range[1], closing).length > 0) return layout;
1812
+ return {
1813
+ ...layout,
1814
+ rules: new Map([
1815
+ ...layout.rules,
1816
+ [text.start, "space"],
1817
+ [closing, "space"]
1818
+ ])
1819
+ };
1820
+ }
1821
+ /**
1822
+ * Format the text of an `accDescr { ... }` block: align its lines (see
1823
+ * `indentDescriptionLines`) and pad its text on one line (see
1824
+ * `padOneLineDescription`). Callers whose Db also stores the raw description
1825
+ * as a member keep the original body columns instead
1826
+ * (`preservesBodyColumns`; docs/flowchart.md, Multi-line values), and pad the
1827
+ * text on one line all the same: there are no columns to keep in it.
1828
+ */
1829
+ function formatDescriptionBlock(source, block, layout, preservesBodyColumns = false) {
1830
+ return padOneLineDescription(source, block, preservesBodyColumns ? layout : indentDescriptionLines(source, block, layout));
1831
+ }
1640
1832
  /**
1641
1833
  * Align ordinary description text after LF without changing its contents or
1642
1834
  * line breaks. The Db setter drops this indentation. Directives and removed
1643
1835
  * line feeds keep their source, and atoms outside the body stay untouched
1644
1836
  * (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
1837
  */
1648
1838
  function indentDescriptionLines(source, block, layout) {
1649
1839
  const opening = expectToken(findDescriptionOpening(source, expectToken(findTokenStartingAt(source, block.range[0]), "the description keyword"), block.opening), "the description opener");
@@ -1743,7 +1933,7 @@ function protectSemicolonPrefixes(source, start, end, atoms, structuralSemicolon
1743
1933
  const stop = semicolonSegmentEnd(source, position);
1744
1934
  const segment = source.text.slice(position, stop);
1745
1935
  let index = segment.lastIndexOf(";");
1746
- while (index !== -1 && structuralSemicolons.has(position + index)) index = index === 0 ? -1 : segment.lastIndexOf(";", index - 1);
1936
+ while (index !== -1 && (structuralSemicolons.has(position + index) || isDroppedSemicolon(source, position + index))) index = index === 0 ? -1 : segment.lastIndexOf(";", index - 1);
1747
1937
  const semicolon = index === -1 ? -1 : position + index;
1748
1938
  if (semicolon < position) {
1749
1939
  position = stop + 1;
@@ -1773,8 +1963,8 @@ function protectSemicolonPrefixes(source, start, end, atoms, structuralSemicolon
1773
1963
  }
1774
1964
  //#endregion
1775
1965
  //#region src/printers/lines.ts
1776
- const { align, hardline: hardline$1, literalline: literalline$2 } = builders;
1777
- const { mapDoc, replaceEndOfLine } = utils;
1966
+ const { align, hardline: hardline$1, literalline: literalline$3 } = builders;
1967
+ const { mapDoc, replaceEndOfLine: replaceEndOfLine$1 } = utils;
1778
1968
  /**
1779
1969
  * Joins lines with line breaks, with one empty line where a line has
1780
1970
  * `blankBefore`. See `lineBreakBetween`.
@@ -1797,22 +1987,22 @@ function lineBreakBetween(previous, next, indentation) {
1797
1987
  const deeper = next.extraIndentation ?? "";
1798
1988
  if (next.writtenBreakBefore !== void 0) return [next.writtenBreakBefore, next.writtenIndentation ?? indentation + deeper];
1799
1989
  if (next.spaceLineBefore === true) return [
1800
- literalline$2,
1990
+ literalline$3,
1801
1991
  " ",
1802
- literalline$2,
1992
+ literalline$3,
1803
1993
  next.writtenIndentation ?? indentation + deeper
1804
1994
  ];
1805
- if (next.writtenIndentation !== void 0) return [next.blankBefore ? [literalline$2, literalline$2] : literalline$2, next.writtenIndentation];
1995
+ if (next.writtenIndentation !== void 0) return [next.blankBefore ? [literalline$3, literalline$3] : literalline$3, next.writtenIndentation];
1806
1996
  if (!previous.endsWithWhitespace) return next.blankBefore ? [
1807
1997
  hardline$1,
1808
1998
  hardline$1,
1809
1999
  deeper
1810
2000
  ] : [hardline$1, deeper];
1811
2001
  return next.blankBefore ? [
1812
- literalline$2,
2002
+ literalline$3,
1813
2003
  hardline$1,
1814
2004
  deeper
1815
- ] : [literalline$2, indentation + deeper];
2005
+ ] : [literalline$3, indentation + deeper];
1816
2006
  }
1817
2007
  /**
1818
2008
  * Breaks the line after `last` and starts the next line at `indentation`,
@@ -1864,7 +2054,16 @@ function significantIndentationOf(options, depth) {
1864
2054
  * their source columns.
1865
2055
  */
1866
2056
  function printAsWritten(source, start, end) {
1867
- return replaceEndOfLine(source.text.slice(start, end));
2057
+ return replaceEndOfLine$1(source.text.slice(start, end));
2058
+ }
2059
+ /**
2060
+ * Prints the source between two offsets as written, without the whitespace at
2061
+ * its end.
2062
+ */
2063
+ function printAsWrittenTrimmed(source, start, end) {
2064
+ let trimmed = end;
2065
+ while (trimmed > start && isWhitespace(source.text[trimmed - 1])) trimmed--;
2066
+ return printAsWritten(source, start, trimmed);
1868
2067
  }
1869
2068
  /** Prints items that stand after `doc` on its line. */
1870
2069
  function withTrailing(doc, run) {
@@ -2054,6 +2253,7 @@ function literalBreaksBetween(source, start, end) {
2054
2253
  //#endregion
2055
2254
  //#region src/printers/blocks.ts
2056
2255
  const { indent: indent$2 } = builders;
2256
+ const { replaceEndOfLine } = utils;
2057
2257
  /**
2058
2258
  * The indentation of a line with a comment that starts with `%%{`, which has
2059
2259
  * `gaps` gaps of whitespace before the comment after its first item (see
@@ -2200,7 +2400,7 @@ function printBlock(docs, source, bounds, rules) {
2200
2400
  let afterBareMarker = false;
2201
2401
  for (const [index, line] of gap.lines.entries()) {
2202
2402
  const unindented = rules.keepsDirectiveLinesUnindented && afterBareMarker && line.directivesOnly;
2203
- const indentation = percentCommentIndentation(gap, index) ?? keptIndentation(unindented || readsWhitespace && line.directivesOnly, keepsWhitespaceLines && line.directivesOnly, line.indentation);
2403
+ const indentation = percentCommentIndentation(gap, index) ?? (rules.indentsOnlyCommentLines === true && !line.startsWithCommentLine ? "" : void 0) ?? keptIndentation(unindented || readsWhitespace && line.directivesOnly, keepsWhitespaceLines && line.directivesOnly, line.indentation);
2204
2404
  afterBareMarker = line.bareMarker || unindented || afterBareMarker && line.commentLinesOnly;
2205
2405
  pushLine({
2206
2406
  doc: kept.verbatim.has(lineStartOf(source, line.run.range[0])) ? printAsWritten(source, line.run.range[0], line.run.range[1]) : line.run.doc,
@@ -2277,15 +2477,23 @@ function printBlock(docs, source, bounds, rules) {
2277
2477
  /**
2278
2478
  * Prints a stretch: as written when one of its lines is verbatim or it
2279
2479
  * holds a statement that holds statements, and otherwise its statements
2280
- * as formatted, with what lies between them (see `printInlineGap`).
2480
+ * as formatted, with what lies between them (see `printInlineGap`). After
2481
+ * its last statement, the whitespace that the planned indentation of the
2482
+ * next statement supplies (`relocatedWhitespace`) is not printed in either
2483
+ * case.
2281
2484
  */
2282
2485
  function printStretch(stretch) {
2283
2486
  const covered = statements.slice(stretch.first, stretch.after);
2284
- if (holdsVerbatimLine(source, kept, stretch.start, stretch.end) && !isEdgeLinesOfBlock(stretch, covered) || rules.joiningRegionsPrintedAsWritten !== true && holdsJoiningRegion(source, stretch.start, stretch.end)) return {
2285
- doc: printAsWritten(source, stretch.start, stretch.end),
2286
- blankBefore: false,
2287
- endsWithWhitespace: endsWithSpaceOrTab(source.text.slice(stretch.start, stretch.end))
2288
- };
2487
+ if (holdsVerbatimLine(source, kept, stretch.start, stretch.end) && !isEdgeLinesOfBlock(stretch, covered) || rules.joiningRegionsPrintedAsWritten !== true && holdsJoiningRegion(source, stretch.start, stretch.end)) {
2488
+ const last = covered.at(-1);
2489
+ const tailStart = last === void 0 ? stretch.end : rules.printedEnd(last);
2490
+ const written = source.text.slice(stretch.start, tailStart) + withoutRelocatedWhitespace(source, tailStart, stretch.end, rules.relocatedWhitespace ?? []);
2491
+ return {
2492
+ doc: replaceEndOfLine(written),
2493
+ blankBefore: false,
2494
+ endsWithWhitespace: endsWithSpaceOrTab(written)
2495
+ };
2496
+ }
2289
2497
  const parts = [];
2290
2498
  let position = stretch.start;
2291
2499
  for (const [index, statement] of covered.entries()) {
@@ -2300,7 +2508,7 @@ function printBlock(docs, source, bounds, rules) {
2300
2508
  const trailing = written.trim() === "" && (written.includes("\u2028") || written.includes("\u2029")) ? printAsWritten(source, position, stretch.end) : printInlineGap(source, position, stretch.end, {
2301
2509
  atLineStart: false,
2302
2510
  atLineEnd: true
2303
- }, rules.keptInlineGapEnd, void 0, rules.omittedRanges);
2511
+ }, rules.keptInlineGapEnd, void 0, rules.omittedRanges, rules.relocatedWhitespace);
2304
2512
  return {
2305
2513
  doc: [...parts, trailing],
2306
2514
  blankBefore: false,
@@ -2421,7 +2629,7 @@ function printBlock(docs, source, bounds, rules) {
2421
2629
  continuesOpeningLine,
2422
2630
  lines,
2423
2631
  endLeading: gap.leading,
2424
- endLeadingIndentation: rules.oneCharacterIndentation !== void 0 && gap.leadingPercentBraceGaps !== null ? percentBraceIndentation(gap.leadingPercentBraceGaps, rules.oneCharacterIndentation) : keptIndentation(gap.leadingDirectivesOnly && (rules.keepsDirectiveLinesUnindented && endsAfterBareMarker || readsWhitespaceAfter(lastStatement)), endsAfterTakingComment && gap.leadingDirectivesOnly, gap.leadingIndentation),
2632
+ endLeadingIndentation: rules.oneCharacterIndentation !== void 0 && gap.leadingPercentBraceGaps !== null ? percentBraceIndentation(gap.leadingPercentBraceGaps, rules.oneCharacterIndentation) : rules.indentsOnlyCommentLines === true && gap.leading !== null && !gap.leadingStartsWithCommentLine ? "" : keptIndentation(gap.leadingDirectivesOnly && (rules.keepsDirectiveLinesUnindented && endsAfterBareMarker || readsWhitespaceAfter(lastStatement)), endsAfterTakingComment && gap.leadingDirectivesOnly, gap.leadingIndentation),
2425
2633
  endBlank: gap.blankAfter,
2426
2634
  closingJoin,
2427
2635
  endExtraIndentation: extra
@@ -2494,12 +2702,17 @@ function printOpenBlock(header, block, depth, options) {
2494
2702
  /**
2495
2703
  * Prints a gap within a kept line: its `;` and directives, with one space
2496
2704
  * on each side where the source has whitespace, and nothing where it has
2497
- * none, but no space at the start or the end of the line.
2705
+ * none, but no space at the start or the end of the line. Whitespace in
2706
+ * `relocatedWhitespace` is not printed: the planned indentation of the next
2707
+ * statement supplies it.
2498
2708
  */
2499
- function printInlineGap(source, start, end, place, keptEnd, ordinaryRule, omittedRanges = []) {
2709
+ function printInlineGap(source, start, end, place, keptEnd, ordinaryRule, omittedRanges = [], relocatedWhitespace = []) {
2500
2710
  if (keptEnd !== void 0 && keptEnd(start) > start && end <= keptEnd(start)) return printAsWritten(source, start, end);
2501
2711
  if (start >= end) return ordinaryRule === "space" && !place.atLineStart && !place.atLineEnd ? " " : "";
2502
- const gap = readGap(source, start, end, true, { omitted: omittedRanges });
2712
+ const gap = readGap(source, start, end, true, {
2713
+ omitted: omittedRanges,
2714
+ relocatedWhitespace
2715
+ });
2503
2716
  if (gap.breaksLine) throw new Error(`prettier-plugin-mmd: a line break within a kept line at offset ${start}`);
2504
2717
  const run = gap.leading ?? gap.trailing;
2505
2718
  if (run === null) {
@@ -2513,6 +2726,20 @@ function printInlineGap(source, start, end, place, keptEnd, ordinaryRule, omitte
2513
2726
  ];
2514
2727
  }
2515
2728
  /**
2729
+ * The text between two offsets as written, without the whitespace in
2730
+ * `relocatedWhitespace`: a run that the planned indentation of the next
2731
+ * statement supplies, which must not be printed a second time.
2732
+ */
2733
+ function withoutRelocatedWhitespace(source, start, end, relocatedWhitespace) {
2734
+ let text = "";
2735
+ for (let offset = start; offset < end;) {
2736
+ const { element, end: next } = readGapElement(source, offset);
2737
+ if (element.kind !== "whitespace" || findCoveringRange(relocatedWhitespace, offset) === void 0) text += source.text.slice(offset, next);
2738
+ offset = next;
2739
+ }
2740
+ return text;
2741
+ }
2742
+ /**
2516
2743
  * Whether a verbatim line lies in the range. With `exceptClosers`, a line of
2517
2744
  * nothing but a `}` or an `end` does not count: it closes a block of the
2518
2745
  * range, which prints its own closing line as written.
@@ -2820,6 +3047,15 @@ function addStyledStatementRules(source, statement, rules, kept) {
2820
3047
  const start = findStylesStart$1(source, statement);
2821
3048
  if (start >= statement.range[1]) return;
2822
3049
  rules.set(start, "space");
3050
+ const semicolon = statement.range[1] - 1;
3051
+ if (statement.type === "BlockClassDefStatement" && isDroppedSemicolon(source, semicolon)) {
3052
+ kept.push({
3053
+ start,
3054
+ end: statement.range[1],
3055
+ doc: printAsWrittenTrimmed(source, start, semicolon)
3056
+ });
3057
+ return;
3058
+ }
2823
3059
  kept.push({
2824
3060
  start,
2825
3061
  end: statement.range[1]
@@ -3123,6 +3359,114 @@ function isLineEnd(character) {
3123
3359
  return character === "\n" || character === "\u2028" || character === "\u2029";
3124
3360
  }
3125
3361
  //#endregion
3362
+ //#region src/printers/statement-rules.ts
3363
+ /**
3364
+ * The gap rules of the statements that more than one diagram type has in
3365
+ * the same form: the lists of classes and names of the style context, the
3366
+ * direction line, and the accessibility statements. An ER diagram and a
3367
+ * requirement diagram read them with the same units, so they are printed
3368
+ * with the same rules (docs/er.md and docs/requirement.md). A rule is
3369
+ * stated by the start of the atom after the gap (see `GapRule`).
3370
+ */
3371
+ /**
3372
+ * Adds the rules of a list of classes after `:::`: the `:::`, the `,`, and
3373
+ * the names touch what is before them. The list lies after `start`.
3374
+ */
3375
+ function addClassListRules(source, classes, start, rules) {
3376
+ const last = classes.at(-1);
3377
+ if (last === void 0) return;
3378
+ for (const name of classes) rules.set(name.range[0], "none");
3379
+ for (const token of findTokensBetween(source, start, last.range[1])) if (isStructural(source, token) && (token.value === ":::" || token.value === ",")) rules.set(token.range[0], "none");
3380
+ }
3381
+ /**
3382
+ * Adds the rules of a list of names separated by `,`: the first name stands
3383
+ * after one space, and the others touch the `,` before them, which touches
3384
+ * the name before it.
3385
+ */
3386
+ function addNameListRules(source, names, rules) {
3387
+ const first = names.at(0);
3388
+ const last = names.at(-1);
3389
+ if (first === void 0 || last === void 0) return;
3390
+ rules.set(first.range[0], "space");
3391
+ for (const name of names.slice(1)) rules.set(name.range[0], "none");
3392
+ for (const token of findTokensBetween(source, first.range[1], last.range[0])) if (isStructural(source, token) && token.value === ",") rules.set(token.range[0], "none");
3393
+ }
3394
+ /**
3395
+ * The rules of a `classDef` or `style` statement: its names are separated by
3396
+ * `,` without whitespace, and the first style stands after one space. The
3397
+ * default style/comma gaps follow the source. Safe ER and requirement units
3398
+ * instead use no space before a comma and one after it (docs/er.md and
3399
+ * docs/requirement.md, Styles and classes).
3400
+ */
3401
+ function styleStatementRules(source, names, styles, compactStyles = false) {
3402
+ const rules = /* @__PURE__ */ new Map();
3403
+ addNameListRules(source, names, rules);
3404
+ rules.set(styles[0].range[0], "space");
3405
+ if (compactStyles) for (let index = 1; index < styles.length; index++) {
3406
+ const comma = expectToken(findStructuralToken(source, styles[index - 1].range[1]), "the comma between styles");
3407
+ rules.set(comma.range[0], "none");
3408
+ rules.set(styles[index].range[0], "space");
3409
+ }
3410
+ return rules;
3411
+ }
3412
+ /** Keep property and value text, changing only the first colon's padding. */
3413
+ function printStyleUnitSpacing(source, style) {
3414
+ const colon = source.text.indexOf(":", style.range[0]);
3415
+ if (colon <= style.range[0] || colon >= style.range[1]) return printAsWritten(source, ...style.range);
3416
+ let propertyEnd = colon;
3417
+ while (source.text[propertyEnd - 1] === " " || source.text[propertyEnd - 1] === " ") propertyEnd--;
3418
+ if (propertyEnd === style.range[0]) return printAsWritten(source, ...style.range);
3419
+ let valueStart = colon + 1;
3420
+ while (source.text[valueStart] === " " || source.text[valueStart] === " ") valueStart++;
3421
+ return [
3422
+ printAsWritten(source, style.range[0], propertyEnd),
3423
+ ":",
3424
+ valueStart < style.range[1] ? [" ", printAsWritten(source, valueStart, style.range[1])] : ""
3425
+ ];
3426
+ }
3427
+ /**
3428
+ * ER and requirement discard simple same-line style-unit padding. Keep trivia,
3429
+ * physical/Unicode line boundaries and complete semicolon-sensitive lines on
3430
+ * their original path (diagrams/er.md and diagrams/requirement.md, Style context).
3431
+ */
3432
+ function styleUnitsCanCompact(source, start, end, styles) {
3433
+ return styles.every((style) => {
3434
+ const text = source.text.slice(...style.range);
3435
+ return !text.includes("\n") && !text.includes("\u2028") && !text.includes("\u2029");
3436
+ }) && !holdsKeptSemicolon(source, lineStartOf(source, start), lineEndOf(source, end)) && findTriviaBetween(source, start, end).length === 0;
3437
+ }
3438
+ /**
3439
+ * The rules of a `class` statement: the names of the entities and the
3440
+ * classes are lists separated by `,` without whitespace, and the first class
3441
+ * stands after one space.
3442
+ */
3443
+ function classStatementRules(source, names, classes) {
3444
+ const rules = /* @__PURE__ */ new Map();
3445
+ addNameListRules(source, names, rules);
3446
+ addNameListRules(source, classes, rules);
3447
+ return rules;
3448
+ }
3449
+ /**
3450
+ * The rules of a direction line: the text before and after, kept as written,
3451
+ * is separated from `direction` by one space where it was written apart, and
3452
+ * the value stands after one space.
3453
+ */
3454
+ function directionRules(source, statement) {
3455
+ const value = expectToken(findStructuralToken(source, expectToken(findStructuralToken(source, statement.textBefore?.range[1] ?? statement.range[0]), "`direction`").range[1]), "the value of a direction line");
3456
+ return /* @__PURE__ */ new Map([[value.range[0], "space"]]);
3457
+ }
3458
+ /**
3459
+ * The rules of an `accTitle` or `accDescr` line: the `:` touches the keyword
3460
+ * and the text stands after one space.
3461
+ */
3462
+ function accessibilityRules(source, statement) {
3463
+ const colon = expectToken(findStructuralToken(source, expectToken(findStructuralToken(source, statement.range[0]), "`accTitle` or `accDescr`").range[1]), "the `:` after `accTitle` or `accDescr`");
3464
+ expectValue(colon, ":");
3465
+ const rules = /* @__PURE__ */ new Map([[colon.range[0], "none"]]);
3466
+ if (statement.value !== null) rules.set(statement.value.range[0], "space");
3467
+ return rules;
3468
+ }
3469
+ //#endregion
3126
3470
  //#region src/printers/class-layout.ts
3127
3471
  /**
3128
3472
  * The node types of a class diagram whose text is a value, printed as
@@ -3277,7 +3621,7 @@ function layoutClassStatement(source, statement, end) {
3277
3621
  /** Keeps the block's line breaks, including those around empty trivia. */
3278
3622
  function layoutExpandedBlock() {
3279
3623
  const closing = findAccDescrBlockClosing(source, block);
3280
- return indentDescriptionLines(source, block, {
3624
+ return formatDescriptionBlock(source, block, {
3281
3625
  atoms: collectAtoms(source, start, end, collectValueNodes(statement, classValueNodeTypes), findAccDescrBlockStretches(source, block)),
3282
3626
  rules: descriptionOpeningRules(source, start),
3283
3627
  outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing]),
@@ -3477,6 +3821,9 @@ function statementRules$8(source, statement) {
3477
3821
  case "ClassAccDescrStatement":
3478
3822
  addAccessibilityColonRules$1(source, statement, rules);
3479
3823
  break;
3824
+ case "ClassClassDefStatement":
3825
+ addNameListRules(source, statement.cssClasses, rules);
3826
+ break;
3480
3827
  case "ClassDeclaration": if (statement.members !== null) {
3481
3828
  const { opening, closing } = findMemberBraces(source, statement);
3482
3829
  rules.set(opening.range[0], spaceAfterName(source, statement.name, opening.range[0]));
@@ -3759,8 +4106,7 @@ function vennDiagramLineEnd(source, offset) {
3759
4106
  }
3760
4107
  /** The protected semicolon prefix includes inline gaps between statements. */
3761
4108
  function vennKeptPrefixEnd(source, offset) {
3762
- const end = vennDiagramLineEnd(source, offset);
3763
- const last = source.text.lastIndexOf(";", end - 1);
4109
+ const last = lastKeptSemicolonBefore(source, vennDiagramLineEnd(source, offset));
3764
4110
  return last >= offset ? last + 1 : offset;
3765
4111
  }
3766
4112
  /**
@@ -3962,114 +4308,6 @@ function c4KeptGapEnd(source, start, end, beforeStatement) {
3962
4308
  return stop;
3963
4309
  }
3964
4310
  //#endregion
3965
- //#region src/printers/statement-rules.ts
3966
- /**
3967
- * The gap rules of the statements that more than one diagram type has in
3968
- * the same form: the lists of classes and names of the style context, the
3969
- * direction line, and the accessibility statements. An ER diagram and a
3970
- * requirement diagram read them with the same units, so they are printed
3971
- * with the same rules (docs/er.md and docs/requirement.md). A rule is
3972
- * stated by the start of the atom after the gap (see `GapRule`).
3973
- */
3974
- /**
3975
- * Adds the rules of a list of classes after `:::`: the `:::`, the `,`, and
3976
- * the names touch what is before them. The list lies after `start`.
3977
- */
3978
- function addClassListRules(source, classes, start, rules) {
3979
- const last = classes.at(-1);
3980
- if (last === void 0) return;
3981
- for (const name of classes) rules.set(name.range[0], "none");
3982
- for (const token of findTokensBetween(source, start, last.range[1])) if (isStructural(source, token) && (token.value === ":::" || token.value === ",")) rules.set(token.range[0], "none");
3983
- }
3984
- /**
3985
- * Adds the rules of a list of names separated by `,`: the first name stands
3986
- * after one space, and the others touch the `,` before them, which touches
3987
- * the name before it.
3988
- */
3989
- function addNameListRules(source, names, rules) {
3990
- const first = names.at(0);
3991
- const last = names.at(-1);
3992
- if (first === void 0 || last === void 0) return;
3993
- rules.set(first.range[0], "space");
3994
- for (const name of names.slice(1)) rules.set(name.range[0], "none");
3995
- for (const token of findTokensBetween(source, first.range[1], last.range[0])) if (isStructural(source, token) && token.value === ",") rules.set(token.range[0], "none");
3996
- }
3997
- /**
3998
- * The rules of a `classDef` or `style` statement: its names are separated by
3999
- * `,` without whitespace, and the first style stands after one space. The
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).
4003
- */
4004
- function styleStatementRules(source, names, styles, compactStyles = false) {
4005
- const rules = /* @__PURE__ */ new Map();
4006
- addNameListRules(source, names, rules);
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
- }
4013
- return rules;
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
- }
4041
- /**
4042
- * The rules of a `class` statement: the names of the entities and the
4043
- * classes are lists separated by `,` without whitespace, and the first class
4044
- * stands after one space.
4045
- */
4046
- function classStatementRules(source, names, classes) {
4047
- const rules = /* @__PURE__ */ new Map();
4048
- addNameListRules(source, names, rules);
4049
- addNameListRules(source, classes, rules);
4050
- return rules;
4051
- }
4052
- /**
4053
- * The rules of a direction line: the text before and after, kept as written,
4054
- * is separated from `direction` by one space where it was written apart, and
4055
- * the value stands after one space.
4056
- */
4057
- function directionRules(source, statement) {
4058
- const value = expectToken(findStructuralToken(source, expectToken(findStructuralToken(source, statement.textBefore?.range[1] ?? statement.range[0]), "`direction`").range[1]), "the value of a direction line");
4059
- return /* @__PURE__ */ new Map([[value.range[0], "space"]]);
4060
- }
4061
- /**
4062
- * The rules of an `accTitle` or `accDescr` line: the `:` touches the keyword
4063
- * and the text stands after one space.
4064
- */
4065
- function accessibilityRules(source, statement) {
4066
- const colon = expectToken(findStructuralToken(source, expectToken(findStructuralToken(source, statement.range[0]), "`accTitle` or `accDescr`").range[1]), "the `:` after `accTitle` or `accDescr`");
4067
- expectValue(colon, ":");
4068
- const rules = /* @__PURE__ */ new Map([[colon.range[0], "none"]]);
4069
- if (statement.value !== null) rules.set(statement.value.range[0], "space");
4070
- return rules;
4071
- }
4072
- //#endregion
4073
4311
  //#region src/printers/c4-layout.ts
4074
4312
  /** Written leaves, including number-looking text (docs/c4.md, Argument forms). */
4075
4313
  const c4ValueNodeTypes = /* @__PURE__ */ new Set(["C4Literal", "StringLiteral"]);
@@ -4431,6 +4669,223 @@ function blockRules(source, keepsOpeningLine) {
4431
4669
  };
4432
4670
  }
4433
4671
  //#endregion
4672
+ //#region src/printers/data-blocks.ts
4673
+ const { literalline: literalline$2 } = builders;
4674
+ /**
4675
+ * The data blocks that print moved: a `@{` or `{` that a line break follows,
4676
+ * and the lines up to its `}`. The diagram types that write one (flowchart,
4677
+ * agentflow, kanban, sequence, and the JSON tables of a use case diagram) read
4678
+ * its lines as YAML or JSON (docs/flowchart.md, Data blocks).
4679
+ */
4680
+ const movableTypes = /* @__PURE__ */ new Set([
4681
+ "FlowchartDataBlock",
4682
+ "AgentflowDataBlock",
4683
+ "KanbanDataBlock",
4684
+ "SequenceDataBlock",
4685
+ "UsecaseJsonDataBlock"
4686
+ ]);
4687
+ /**
4688
+ * The movable data blocks whose single line is padded: all but the JSON tables
4689
+ * of a use case diagram, whose `{` and `}` are the brackets of the JSON itself
4690
+ * and not the delimiters of a block (docs/usecase.md, JSON tables).
4691
+ */
4692
+ const paddedTypes = /* @__PURE__ */ new Set([
4693
+ "FlowchartDataBlock",
4694
+ "AgentflowDataBlock",
4695
+ "KanbanDataBlock",
4696
+ "SequenceDataBlock"
4697
+ ]);
4698
+ /** The movable data blocks of each source, in source order, found once. */
4699
+ const blocksBySource = /* @__PURE__ */ new WeakMap();
4700
+ /**
4701
+ * The movable data blocks of the source, of one line and of several: a
4702
+ * statement that holds a block of one line next to one of several moves
4703
+ * neither.
4704
+ */
4705
+ function dataBlocksOf(source) {
4706
+ const cached = blocksBySource.get(source);
4707
+ if (cached !== void 0) return cached;
4708
+ const blocks = findNodes(source.root.body, (node) => movableTypes.has(node.type));
4709
+ blocksBySource.set(source, blocks);
4710
+ return blocks;
4711
+ }
4712
+ /**
4713
+ * The layout with the data blocks of the statement in `range` formatted: a
4714
+ * block of one line printed with one space inside each end (see
4715
+ * `padDataBlock`), and, where the statement holds no other block, a block of
4716
+ * several lines printed one level inside the statement, with its closing `}`
4717
+ * on a line of its own at the column of the statement, in spaces (see
4718
+ * `moveDataBlock`).
4719
+ */
4720
+ function formatDataBlocks(source, layout, range, placement) {
4721
+ const all = dataBlocksOf(source);
4722
+ const first = findFirstIndex(all, (block) => block.range[0] >= range[0]);
4723
+ const afterLast = findFirstIndex(all, (block) => block.range[1] > range[1]);
4724
+ const atoms = [...layout.atoms];
4725
+ let changed = false;
4726
+ for (let index = first; index < afterLast; index++) {
4727
+ const block = all[index];
4728
+ const doc = isOneLine(source.text.slice(...block.range)) ? padDataBlock(source, all, index, placement.kept) : afterLast - first === 1 && placement.tabWidth !== 0 ? moveDataBlock(source, block, range, placement) : void 0;
4729
+ if (doc === void 0) continue;
4730
+ const at = findFirstIndex(atoms, (atom) => atom.end >= block.range[1]);
4731
+ const atom = atoms[at];
4732
+ if (atom === void 0 || atom.doc !== void 0 || atom.writtenIndentation !== void 0 || atom.start > block.range[0] || placement.wholeLine !== true && atom.end !== block.range[1]) continue;
4733
+ atoms[at] = {
4734
+ ...atom,
4735
+ doc: [
4736
+ printAsWritten(source, atom.start, block.range[0]),
4737
+ doc,
4738
+ printAsWritten(source, block.range[1], atom.end)
4739
+ ]
4740
+ };
4741
+ changed = true;
4742
+ }
4743
+ return changed ? {
4744
+ ...layout,
4745
+ atoms
4746
+ } : layout;
4747
+ }
4748
+ /** Whether a text holds no line break: LF, CR, U+2028 or U+2029. */
4749
+ function isOneLine(text) {
4750
+ return !text.includes("\n") && !text.includes("\r") && !text.includes("\u2028") && !text.includes("\u2029");
4751
+ }
4752
+ /**
4753
+ * The block of one line printed with one space inside each end, `@{ shape:
4754
+ * circle }`; undefined where it stays as written. These diagram types read the
4755
+ * text inside `@{` and `}` as the lines of a YAML flow mapping
4756
+ * (docs/flowchart.md, Data blocks), so the spaces and tabs at its ends carry no
4757
+ * meaning. A block is padded only if
4758
+ *
4759
+ * - it is one of `paddedTypes`;
4760
+ * - no `%%{` lies in it: a directive in the block is written as it stands;
4761
+ * - it is on no kept line (see `KeptLines`);
4762
+ * - something other than spaces and tabs stands in it: of a block that holds
4763
+ * none, `@{}` is rejected while `@{ }` is accepted;
4764
+ * - its text does not start at the first column with `---`, `...`, or `%`: a
4765
+ * space before `---` or `...` makes a document marker an ordinary string, so
4766
+ * `@{---}` is rejected while `@{ --- }` is accepted; the starts that are no
4767
+ * marker stay as written as well, as in a block of several lines;
4768
+ * - it touches no other block: two blocks with nothing between them, or only
4769
+ * directives, are read as one text.
4770
+ *
4771
+ * Only spaces and tabs are removed at its ends: other whitespace, such as
4772
+ * U+00A0, is part of the text.
4773
+ */
4774
+ function padDataBlock(source, blocks, index, kept) {
4775
+ const block = blocks[index];
4776
+ const text = source.text.slice(...block.range);
4777
+ const before = blocks[index - 1];
4778
+ const after = blocks[index + 1];
4779
+ if (!paddedTypes.has(block.type) || text.includes("%%{") || startsWithYamlMark(text.slice(2)) || holdsKeptLine(source, block.range, kept) || before !== void 0 && holdsOnlyDirectives(source, before.range[1], block.range[0]) || after !== void 0 && holdsOnlyDirectives(source, block.range[1], after.range[0])) return void 0;
4780
+ let start = 2;
4781
+ let end = text.length - 1;
4782
+ while (start < end && (text[start] === " " || text[start] === " ")) start++;
4783
+ while (end > start && (text[end - 1] === " " || text[end - 1] === " ")) end--;
4784
+ if (start === end) return void 0;
4785
+ return [
4786
+ "@{ ",
4787
+ text.slice(start, end),
4788
+ " }"
4789
+ ];
4790
+ }
4791
+ /** Whether nothing but directives lies between two offsets, or nothing. */
4792
+ function holdsOnlyDirectives(source, from, to) {
4793
+ let position = to;
4794
+ while (position > from) {
4795
+ const directive = findDirectiveEndingAt(source, position);
4796
+ if (directive === void 0 || directive.range[0] < from) return false;
4797
+ position = directive.range[0];
4798
+ }
4799
+ return true;
4800
+ }
4801
+ /** Whether a text starts with a YAML document marker or directive mark. */
4802
+ function startsWithYamlMark(text) {
4803
+ return text.startsWith("---") || text.startsWith("...") || text.startsWith("%");
4804
+ }
4805
+ /**
4806
+ * The block printed with every line moved by the same number of spaces, so
4807
+ * that the shallowest line that holds text stands one level inside the
4808
+ * statement, and its closing `}`, where it stands on a line of its own, at
4809
+ * the column of the statement, in spaces; undefined where the block stays as
4810
+ * written. The lines stay literal lines: a literal block scalar reads their
4811
+ * trailing whitespace. A block moves only if
4812
+ *
4813
+ * - a line break follows the `{`: the first line counts its columns from the
4814
+ * `{`, the later lines from the start of the line, so moving the later lines
4815
+ * alone changes the reading of the first;
4816
+ * - the whitespace at the start of each line is spaces: YAML rejects a tab
4817
+ * there, and the lines are moved by a count of spaces;
4818
+ * - no `%%{` lies in it: a directive in the block is written as it stands;
4819
+ * - when a line that holds text starts at the first column, none starts with
4820
+ * `---`, `...`, or `%`: moved, the line would no longer be a document
4821
+ * marker or a comment;
4822
+ * - a diagram that trims the whole block reads one line of text only: the
4823
+ * sequence diagram removes the whitespace at the start of the first line
4824
+ * and counts the columns of the later ones from the first column;
4825
+ * - a `}` that stands on a line of its own has only spaces before it, no more
4826
+ * than the shallowest line that holds text: the whitespace before it is a
4827
+ * line of the text, and a deeper one would be lost when the `}` moves;
4828
+ * - no line of the block, nor the line that the block starts on, is a kept
4829
+ * line (see `KeptLines`);
4830
+ * - the block starts on the first line of its statement, whose indentation is
4831
+ * then the indentation of the line that holds the `{`;
4832
+ * - the statement holds no other block: after the `}` of a block that moved,
4833
+ * the next block would start on a line that is not the first of the
4834
+ * statement, and the text of two blocks that touch is read as one.
4835
+ */
4836
+ function moveDataBlock(source, block, statement, placement) {
4837
+ const text = source.text.slice(...block.range);
4838
+ if (text.includes("%%{") || source.text.slice(statement[0], block.range[0]).includes("\n") || holdsKeptLine(source, block.range, placement.kept)) return void 0;
4839
+ const rows = text.split("\n");
4840
+ const opening = rows[0];
4841
+ const last = rows.at(-1);
4842
+ if (rows.length < 2 || !opening.endsWith("{") || opening.indexOf("{") !== opening.length - 1 || !last.endsWith("}")) return void 0;
4843
+ let closing = 0;
4844
+ while (last[closing] === " ") closing++;
4845
+ const closesAlone = last.slice(closing) === "}";
4846
+ const body = rows.slice(1, closesAlone ? -1 : void 0);
4847
+ const margins = [];
4848
+ for (const row of body) {
4849
+ let margin = 0;
4850
+ while (row[margin] === " ") margin++;
4851
+ if (margin < row.length && isWhitespace(row[margin])) return void 0;
4852
+ margins.push(margin);
4853
+ }
4854
+ /** Whether the line holds text and not spaces only. */
4855
+ function holdsText(index) {
4856
+ return body[index].length > margins[index];
4857
+ }
4858
+ const textLines = body.flatMap((_, index) => holdsText(index) ? [index] : []);
4859
+ if (textLines.length === 0) return void 0;
4860
+ if (block.type === "SequenceDataBlock" && textLines.length > 1) return void 0;
4861
+ const shallowest = minOf(textLines.map((index) => margins[index]));
4862
+ if (shallowest === 0 && textLines.some((index) => margins[index] === 0 && startsWithYamlMark(body[index]))) return void 0;
4863
+ if (closesAlone) {
4864
+ if (closing > shallowest) return void 0;
4865
+ }
4866
+ const shift = columnsOf(placement.statement, placement.tabWidth) + placement.tabWidth - shallowest;
4867
+ const lines = [opening, ...body.map((row, index) => holdsText(index) ? " ".repeat(margins[index] + shift) + row.slice(margins[index]) : " ".repeat(Math.max(0, row.length === 0 ? 0 : row.length + shift)))];
4868
+ const docs = [];
4869
+ for (const [index, line] of lines.entries()) {
4870
+ if (index > 0) docs.push(literalline$2);
4871
+ docs.push(line);
4872
+ }
4873
+ if (closesAlone) docs.push(literalline$2, " ".repeat(columnsOf(placement.statement, placement.tabWidth)), "}");
4874
+ return docs;
4875
+ }
4876
+ /** The columns of an indentation, in which a tab is `tabWidth` columns. */
4877
+ function columnsOf(indentation, tabWidth) {
4878
+ let columns = 0;
4879
+ for (const character of indentation) columns += character === " " ? tabWidth : 1;
4880
+ return columns;
4881
+ }
4882
+ /** Whether the line of a range's start or one of its lines is a kept line. */
4883
+ function holdsKeptLine(source, range, kept) {
4884
+ const starts = [lineStartOf(source, range[0])];
4885
+ for (let lineFeed = source.text.indexOf("\n", range[0]); lineFeed !== -1 && lineFeed < range[1]; lineFeed = source.text.indexOf("\n", lineFeed + 1)) starts.push(lineStartOf(source, lineFeed + 1));
4886
+ return starts.some((start) => kept.joined.has(start) || kept.verbatim.has(start));
4887
+ }
4888
+ //#endregion
4434
4889
  //#region src/printers/usecase-kept-lines.ts
4435
4890
  /**
4436
4891
  * Every semicolon stays; only an open directive needs a whole verbatim line.
@@ -4528,6 +4983,7 @@ function layoutUsecaseStatement(source, statement, end) {
4528
4983
  if (statement.id !== null && statement.title !== null) {
4529
4984
  const opening = expectToken(findStructuralTokenEndingBefore(source, statement.title.range[0]), "the boundary title opener");
4530
4985
  const closing = expectToken(findStructuralToken(source, statement.title.range[1]), "the boundary title closer");
4986
+ rules.set(opening.range[0], "none");
4531
4987
  kept.push({
4532
4988
  start: opening.range[0],
4533
4989
  end: closing.range[1]
@@ -4743,7 +5199,11 @@ function printStatements(source, options, statements, depth, bounds) {
4743
5199
  };
4744
5200
  return printBlock(statements.map((statement) => {
4745
5201
  const classified = classifyUsecaseStatement(statement);
4746
- if (classified.kind === "simple") return printLine$7(source, options, layoutUsecaseStatement(source, statement, statement.range[1]), depth);
5202
+ if (classified.kind === "simple") return printLine$7(source, options, formatDataBlocks(source, layoutUsecaseStatement(source, statement, statement.range[1]), statement.range, {
5203
+ kept: rules.kept,
5204
+ statement: indentationOf(options, depth),
5205
+ tabWidth: options.tabWidth
5206
+ }), depth);
4747
5207
  const boundary = classified.statement;
4748
5208
  const end = usecaseBoundaryHeaderEnd(source, boundary);
4749
5209
  const closing = expectToken(findTokenEndingBefore(source, boundary.range[1]), "the end of a system boundary");
@@ -4967,7 +5427,7 @@ function findAttributeBraces(source, statement) {
4967
5427
  * description blocks that may follow stand on the line as statements of the
4968
5428
  * body (see `findErKeptLines`).
4969
5429
  *
4970
- * The name stands after one space, the title after one space too, with
5430
+ * The name stands after one space, the `[` of the title touches it, with
4971
5431
  * nothing inside its brackets, and its names are separated by one space,
4972
5432
  * written touching or not: mermaid.js joins them with one space
4973
5433
  * (docs/er.md, Subgraphs).
@@ -4978,7 +5438,7 @@ function layoutSubgraphOpening(source, statement, end) {
4978
5438
  if (statement.title !== null) {
4979
5439
  const opening = expectToken(findStructuralToken(source, statement.id.range[1]), "the `[` of a subgraph title");
4980
5440
  expectValue(opening, "[");
4981
- rules.set(opening.range[0], "space");
5441
+ rules.set(opening.range[0], "none");
4982
5442
  for (const [index, name] of statement.title.entries()) rules.set(name.range[0], index === 0 ? "none" : "space");
4983
5443
  const closing = expectToken(findStructuralToken(source, statement.title.at(-1)?.range[1] ?? end), "the `]` of a subgraph title");
4984
5444
  expectValue(closing, "]");
@@ -5078,7 +5538,7 @@ function findKeptStretches$1(source, statement) {
5078
5538
  */
5079
5539
  function findEndingSemicolonStretches(source, statement) {
5080
5540
  const last = findTokenEndingBefore(source, statement.range[1]);
5081
- if (last?.value !== ";") return [];
5541
+ if (last?.value !== ";" || isDroppedSemicolon(source, last.range[0])) return [];
5082
5542
  return [{
5083
5543
  start: statement.styles.at(-1)?.range[1] ?? last.range[0],
5084
5544
  end: statement.range[1]
@@ -5923,16 +6383,17 @@ function layoutContainerHeader(source, node, end) {
5923
6383
  if (node.type === "AgentflowGlobalStatement" || node.name === null) return layoutRange(source, node.range[0], end, [], [], /* @__PURE__ */ new Map());
5924
6384
  const name = node.name;
5925
6385
  let nameEnd = name.range[1];
6386
+ const rules = /* @__PURE__ */ new Map();
5926
6387
  if (node.title !== null && name.parts.length === 1) {
5927
6388
  while (nameEnd > name.range[0] && isWhitespace(source.text[nameEnd - 1])) nameEnd--;
5928
6389
  if (nameEnd === name.range[0]) nameEnd = name.range[1];
6390
+ if (findTriviaBetween(source, name.range[0], nameEnd).at(-1)?.range[1] !== nameEnd) rules.set(expectToken(findStructuralToken(source, name.range[1]), "the heading title opener").range[0], "none");
5929
6391
  } else if (name.parts.length > 1) nameEnd = (node.title === null ? node.data[0]?.range[0] : expectToken(findStructuralToken(source, name.range[1]), "the heading title opener").range[0]) ?? findNamePrintedEnd(source, name);
5930
6392
  const nameAtom = {
5931
6393
  start: name.range[0],
5932
6394
  end: nameEnd
5933
6395
  };
5934
6396
  const values = [...node.data, ...node.title === null ? [] : [node.title]];
5935
- const rules = /* @__PURE__ */ new Map();
5936
6397
  const layout = layoutRange(source, node.range[0], end, values, [nameAtom], rules);
5937
6398
  return {
5938
6399
  ...layout,
@@ -6072,11 +6533,10 @@ function layoutStatement$1(source, statement, end, preservesDescriptionColumns)
6072
6533
  const layout = layoutRange(source, start, end, collectValueNodes(statement, agentflowValueNodeTypes), kept, rules);
6073
6534
  if (statement.type === "AgentflowAccDescrBlockStatement") {
6074
6535
  const closing = findAccDescrBlockClosing(source, statement);
6075
- const descriptionLayout = {
6536
+ return formatDescriptionBlock(source, statement, {
6076
6537
  ...layout,
6077
6538
  outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing])
6078
- };
6079
- return preservesDescriptionColumns ? descriptionLayout : indentDescriptionLines(source, statement, descriptionLayout);
6539
+ }, preservesDescriptionColumns);
6080
6540
  }
6081
6541
  return layout;
6082
6542
  }
@@ -6105,10 +6565,14 @@ function printAgentflow(path, options, print, source) {
6105
6565
  if (node.type === "AgentflowDiagram") return withSignificantIndentation(printDiagram$4(path, bodyOptions, print, source, node), options);
6106
6566
  const classified = classifyAgentflowStatement(node);
6107
6567
  if (classified === null) throw new Error("prettier-plugin-mmd: an unexpected Agentflow node");
6108
- if (classified.kind === "container") return printContainer(path, bodyOptions, print, source, classified.statement);
6568
+ if (classified.kind === "container") return printContainer(path, bodyOptions, print, source, classified.statement, options.tabWidth);
6109
6569
  const statement = classified.statement;
6110
6570
  const depth = depthOf$3(path);
6111
- return printAtoms(source, layoutStatement$1(source, statement, findPrintedEnd$1(source, statement), depth > 1), {
6571
+ return printAtoms(source, formatDataBlocks(source, layoutStatement$1(source, statement, findPrintedEnd$1(source, statement), depth > 1), statement.range, {
6572
+ kept: findAgentflowKeptLines(source),
6573
+ statement: indentationOf(bodyOptions, depth),
6574
+ tabWidth: options.tabWidth
6575
+ }), {
6112
6576
  statement: indentationOf(bodyOptions, depth),
6113
6577
  continuation: indentationOf(bodyOptions, depth + 1)
6114
6578
  }).doc;
@@ -6135,7 +6599,7 @@ function printDiagram$4(path, options, print, source, diagram) {
6135
6599
  * Prints a container: the `flow` or `global` line, the statements one level deeper,
6136
6600
  * and the `end` line.
6137
6601
  */
6138
- function printContainer(path, options, print, source, container) {
6602
+ function printContainer(path, options, print, source, container, tabWidth) {
6139
6603
  const depth = depthOf$3(path);
6140
6604
  const headerEnd = findContainerHeaderEnd(source, container);
6141
6605
  const endKeyword = findGraphEndKeyword(source, container);
@@ -6145,7 +6609,11 @@ function printContainer(path, options, print, source, container) {
6145
6609
  end: endKeyword.range[0],
6146
6610
  isTopLevel: false
6147
6611
  }, agentflowBlockRules(source));
6148
- const headerDoc = printAtoms(source, layoutContainerHeader(source, container, headerEnd), {
6612
+ const headerDoc = printAtoms(source, formatDataBlocks(source, layoutContainerHeader(source, container, headerEnd), [container.range[0], headerEnd], {
6613
+ kept: findAgentflowKeptLines(source),
6614
+ statement: indentationOf(options, depth),
6615
+ tabWidth
6616
+ }), {
6149
6617
  statement: indentationOf(options, depth),
6150
6618
  continuation: indentationOf(options, depth + 1)
6151
6619
  }).doc;
@@ -6378,9 +6846,11 @@ function layoutSubgraphHeader(source, subgraph, headerEnd) {
6378
6846
  end: headerEnd
6379
6847
  }] : [];
6380
6848
  const values = subgraph.title === null ? [] : [subgraph.name, subgraph.title];
6849
+ const rules = /* @__PURE__ */ new Map();
6850
+ if (subgraph.title !== null) rules.set(expectToken(findStructuralToken(source, subgraph.name.range[1]), "the `[` before the title of a subgraph").range[0], "none");
6381
6851
  return {
6382
6852
  atoms: collectAtoms(source, subgraph.range[0], headerEnd, values, kept).filter((atom) => kept.includes(atom) || !startsInside(kept, atom)),
6383
- rules: /* @__PURE__ */ new Map(),
6853
+ rules,
6384
6854
  outdented: /* @__PURE__ */ new Set(),
6385
6855
  lineBreaks: "kept"
6386
6856
  };
@@ -6403,7 +6873,8 @@ function layoutStatement(source, statement, end, preservesDescriptionColumns) {
6403
6873
  outdented: findOutdentedAtoms(source, statement),
6404
6874
  lineBreaks: "kept"
6405
6875
  };
6406
- return statement.type === "FlowchartAccDescrBlockStatement" && !preservesDescriptionColumns ? indentDescriptionLines(source, statement, layout) : layout;
6876
+ if (statement.type !== "FlowchartAccDescrBlockStatement") return layout;
6877
+ return formatDescriptionBlock(source, statement, layout, preservesDescriptionColumns);
6407
6878
  }
6408
6879
  /**
6409
6880
  * The atoms of a statement whose line starts at the statement's
@@ -6541,7 +7012,11 @@ function printFlowchart(path, options, print, source) {
6541
7012
  default: {
6542
7013
  const statement = node;
6543
7014
  const depth = depthOf$2(path);
6544
- return printAtoms(source, layoutStatement(source, statement, findPrintedEnd(source, statement), depth > 1), {
7015
+ return printAtoms(source, formatDataBlocks(source, layoutStatement(source, statement, findPrintedEnd(source, statement), depth > 1), statement.range, {
7016
+ kept: findFlowchartKeptLines(source),
7017
+ statement: indentationOf(bodyOptions, depth),
7018
+ tabWidth: options.tabWidth
7019
+ }), {
6545
7020
  statement: indentationOf(bodyOptions, depth),
6546
7021
  continuation: indentationOf(bodyOptions, depth + 1)
6547
7022
  }).doc;
@@ -7584,7 +8059,12 @@ function printKanban(path, options, _print, source) {
7584
8059
  const keyword = expectToken(findTokenStartingAt(source, diagram.range[0]), "the header keyword");
7585
8060
  const lines = kanbanLines(source);
7586
8061
  const placements = new Map(lines.map((line) => [line, placeLine(source, options, line)]));
7587
- const block = printBlock(lines.map((line) => [placements.get(line)?.head ?? "", printAtoms(source, layoutKanbanLine(line), {
8062
+ const block = printBlock(lines.map((line) => [placements.get(line)?.head ?? "", printAtoms(source, formatDataBlocks(source, layoutKanbanLine(line), line.range, {
8063
+ kept: findKanbanKeptLines(source),
8064
+ statement: (options.useTabs ? " " : " ").repeat(significantIndentationOf(options, 1).length * line.depth),
8065
+ tabWidth: options.tabWidth,
8066
+ wholeLine: true
8067
+ }), {
7588
8068
  statement: "",
7589
8069
  continuation: ""
7590
8070
  }).doc]), source, {
@@ -8737,7 +9217,7 @@ function layoutSequenceStatement(source, statement, end) {
8737
9217
  /** Builds the existing value, trivia and closing-brace layout. */
8738
9218
  function originalLayout() {
8739
9219
  const closing = findAccDescrBlockClosing(source, block);
8740
- return indentDescriptionLines(source, block, {
9220
+ return formatDescriptionBlock(source, block, {
8741
9221
  atoms: collectAtoms(source, start, end, values, findAccDescrBlockStretches(source, block)),
8742
9222
  rules: descriptionOpeningRules(source, start),
8743
9223
  outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing]),
@@ -8809,7 +9289,7 @@ function findTitleText(source, statement) {
8809
9289
  }
8810
9290
  throw new Error(`prettier-plugin-mmd: no whitespace between the keyword of the title at offset ${statement.range[0]} and its text`);
8811
9291
  }
8812
- /** The gap rules of a statement: around its arrow and its `:`. */
9292
+ /** The gap rules of a statement: around its arrow, its `,`, and its `:`. */
8813
9293
  function statementRules$2(source, statement) {
8814
9294
  const rules = /* @__PURE__ */ new Map();
8815
9295
  switch (statement.type) {
@@ -8818,6 +9298,7 @@ function statementRules$2(source, statement) {
8818
9298
  addColonRules(source, statement.to.range[1], statement.text, rules);
8819
9299
  break;
8820
9300
  case "SequenceNoteStatement":
9301
+ addCommaRules$1(source, statement.ids, rules);
8821
9302
  addColonRules(source, (statement.ids.at(-1) ?? statement).range[1], statement.text, rules);
8822
9303
  break;
8823
9304
  case "SequenceLinksStatement":
@@ -8826,6 +9307,9 @@ function statementRules$2(source, statement) {
8826
9307
  case "SequenceDetailsStatement":
8827
9308
  addColonRules(source, statement.id.range[1], statement.text, rules);
8828
9309
  break;
9310
+ case "SequenceParticipantStatement":
9311
+ if (statement.data !== null) rules.set(statement.data.range[0], "none");
9312
+ break;
8829
9313
  case "SequenceAccTitleStatement":
8830
9314
  case "SequenceAccDescrStatement": addColonRules(source, expectToken(findStructuralToken(source, statement.range[0]), "`accTitle` or `accDescr`").range[1], statement.value, rules);
8831
9315
  }
@@ -8836,15 +9320,41 @@ function statementRules$2(source, statement) {
8836
9320
  * after it, before the `+`, `-`, or `()` that may follow it, or before the
8837
9321
  * target; none on either side when the source is an id that a following
8838
9322
  * space would make another unit (see `isReadOtherwiseBeforeWhitespace`).
9323
+ * The `()` of the source touches the source, and the `+`, `-`, or `()`
9324
+ * before the target touches the target (docs/sequence.md, Arrow spacing).
8839
9325
  * The arrow is printed from its token, whose range is the range of the
8840
9326
  * arrow node.
8841
9327
  */
8842
9328
  function addArrowRules(source, statement, rules) {
8843
9329
  const { arrow } = statement;
8844
9330
  const next = expectToken(findStructuralToken(source, arrow.range[1]), "what follows the arrow of a message");
8845
- const rule = isReadOtherwiseBeforeWhitespace$1(statement.from.name) ? "none" : "space";
9331
+ const rule = !statement.fromCentralConnection && isReadOtherwiseBeforeWhitespace$1(statement.from.name) ? "none" : "space";
8846
9332
  rules.set(arrow.range[0], rule);
8847
9333
  rules.set(next.range[0], rule);
9334
+ if (statement.fromCentralConnection) rules.set(expectToken(findStructuralToken(source, statement.from.range[1]), "the `()` after the source of a message").range[0], "none");
9335
+ if (statement.activation !== null || statement.toCentralConnection) rules.set(statement.to.range[0], statement.activation === "-" && isReadAsArrowAfterMinus(statement.to.name) ? "space" : "none");
9336
+ }
9337
+ /**
9338
+ * Whether an id is spelled so that, touching a `-` before it, the lexer reads
9339
+ * the two as an arrow: `-x` and `-X`, since the lexer ignores case, and `-|\`
9340
+ * and `-|/` (diagrams/sequence.md, The statement context). So `A ->> - x: b`
9341
+ * keeps its space: `A ->> -x: b` is rejected.
9342
+ */
9343
+ function isReadAsArrowAfterMinus(id) {
9344
+ return toAsciiLowerCase(id).startsWith("x") || id.startsWith("|\\") || id.startsWith("|/");
9345
+ }
9346
+ /**
9347
+ * Adds the rules of the `,` between the two ids of a note over two
9348
+ * participants: none before it and none after it (docs/sequence.md,
9349
+ * Whitespace between tokens). A note with one id has no `,`.
9350
+ */
9351
+ function addCommaRules$1(source, ids, rules) {
9352
+ if (ids.length < 2) return;
9353
+ const [first, second] = ids;
9354
+ const comma = expectToken(findStructuralToken(source, first.range[1]), "the `,` between the ids of a note");
9355
+ expectValue(comma, ",");
9356
+ rules.set(comma.range[0], "none");
9357
+ rules.set(second.range[0], "none");
8848
9358
  }
8849
9359
  /**
8850
9360
  * Whether an id is spelled so that, followed by whitespace where a unit
@@ -9048,7 +9558,11 @@ function printSequence(path, options, print, source) {
9048
9558
  case "simple": {
9049
9559
  const { statement } = classified;
9050
9560
  const depth = depthOf$1(path);
9051
- return printAtoms(source, layoutSequenceStatement(source, statement, findSequencePrintedEnd(source, statement)), {
9561
+ return printAtoms(source, formatDataBlocks(source, layoutSequenceStatement(source, statement, findSequencePrintedEnd(source, statement)), statement.range, {
9562
+ kept: findSequenceKeptLines(source),
9563
+ statement: indentationOf(options, depth),
9564
+ tabWidth: options.tabWidth
9565
+ }), {
9052
9566
  statement: indentationOf(options, depth),
9053
9567
  continuation: indentationOf(options, depth + 1)
9054
9568
  }).doc;
@@ -9460,7 +9974,7 @@ function layoutStateStatement(source, statement, end, followsStateName, noteInde
9460
9974
  /** Builds the existing value, trivia and closing-brace layout. */
9461
9975
  function originalLayout() {
9462
9976
  const closing = findAccDescrBlockClosing(source, block);
9463
- return indentDescriptionLines(source, block, {
9977
+ return formatDescriptionBlock(source, block, {
9464
9978
  atoms: collectAtoms(source, start, end, collectValueNodes(block, stateValueNodeTypes), findAccDescrBlockStretches(source, block)),
9465
9979
  rules: descriptionOpeningRules(source, start),
9466
9980
  outdented: closing === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([closing]),
@@ -9475,7 +9989,8 @@ function layoutStateStatement(source, statement, end, followsStateName, noteInde
9475
9989
  const kept = [
9476
9990
  ...findNoteStretches(statement, end),
9477
9991
  ...findSecondDescriptionStretches(source, statement, end),
9478
- ...findBlankDescriptionStretches(source, statement, end)
9992
+ ...findBlankDescriptionStretches(source, statement, end),
9993
+ ...findDroppedSemicolonStretches$1(source, statement)
9479
9994
  ];
9480
9995
  const keepsDirectionValue = (statement.type === "StateAccTitleStatement" || statement.type === "StateAccDescrStatement") && statement.value !== null && source.text.slice(start, statement.value.range[0]).includes("\n") && holdsDirection(source, {
9481
9996
  range: statement.range,
@@ -9645,6 +10160,23 @@ function findSecondDescriptionStretches(source, statement, end) {
9645
10160
  }];
9646
10161
  }
9647
10162
  /**
10163
+ * The last style of a `classDef` or `style` statement, printed without the `;`
10164
+ * that ends it, and without the whitespace before it, where the printer drops
10165
+ * that `;` (see `isDroppedSemicolon`): the `;` is a character of the style.
10166
+ */
10167
+ function findDroppedSemicolonStretches$1(source, statement) {
10168
+ if (statement.type !== "StateClassDefStatement" && statement.type !== "StateStyleStatement") return [];
10169
+ const style = statement.styles.findLast((item) => item !== null);
10170
+ if (style === void 0 || style === null) return [];
10171
+ const semicolon = style.range[1] - 1;
10172
+ if (!isDroppedSemicolon(source, semicolon)) return [];
10173
+ return [{
10174
+ start: style.range[0],
10175
+ end: style.range[1],
10176
+ doc: printAsWrittenTrimmed(source, style.range[0], semicolon)
10177
+ }];
10178
+ }
10179
+ /**
9648
10180
  * The `:` that starts the second description of an alias definition
9649
10181
  * without a body, or null: the last token of the structure before the
9650
10182
  * description, which starts after the directives that follow the `:`.
@@ -9855,11 +10387,26 @@ function statementRules$1(source, statement) {
9855
10387
  break;
9856
10388
  }
9857
10389
  case "StateAccTitleStatement":
9858
- case "StateAccDescrStatement": addAccessibilityColonRules(source, statement, rules);
10390
+ case "StateAccDescrStatement":
10391
+ addAccessibilityColonRules(source, statement, rules);
10392
+ break;
10393
+ case "StateClassStatement": addClassIdListRules(source, statement.states, rules);
9859
10394
  }
9860
10395
  return rules;
9861
10396
  }
9862
10397
  /**
10398
+ * Adds the rules of the `,` between the ids of a `class` statement: an id
10399
+ * after a `,` touches it. The ids end at whitespace before a `,`, and mermaid.js
10400
+ * reads the rest as the name of the class, so `class A ,B c` has the one id `A`
10401
+ * and stays as written (docs/state.md, Whitespace between tokens).
10402
+ */
10403
+ function addClassIdListRules(source, states, rules) {
10404
+ for (let index = 1; index < states.length; index++) {
10405
+ expectValue(expectToken(findStructuralToken(source, states[index - 1].range[1]), "the `,` between the ids of a `class` statement"), ",");
10406
+ rules.set(states[index].range[0], "none");
10407
+ }
10408
+ }
10409
+ /**
9863
10410
  * Adds the rules of the `:` of a description or a label after a state
9864
10411
  * reference: one space on each side (docs/state.md, Descriptions and
9865
10412
  * labels), except before the `:` after a reference that a space would make
@@ -10639,6 +11186,8 @@ function printTreeview(path, options, _print, source) {
10639
11186
  omittedRanges: drawing?.omitted,
10640
11187
  blankAfterStatement: (line) => line.item.type === "TreeviewNode" && drawing?.trailingDecorations.get(line.item)?.some((decoration) => drawing.decorations.get(decoration) === "") === true,
10641
11188
  relocatedWhitespace: boxMode ? [] : relocatedWhitespace,
11189
+ indentsOnlyCommentLines: true,
11190
+ extraIndentationOf: (line) => placements.get(line).indentation,
10642
11191
  joiningRegionsPrintedAsWritten: true,
10643
11192
  printedEnd: (line) => layouts.get(line) === void 0 ? line.range[1] : findLayoutEnd(layouts.get(line)),
10644
11193
  holdsStatements: () => false,
@@ -10739,6 +11288,26 @@ function treemapLines(source, diagram, headerEnd) {
10739
11288
  }
10740
11289
  }
10741
11290
  /**
11291
+ * The style of a `classDef` together with what follows it, printed without the
11292
+ * `;` that ends the statement and without the whitespace around that `;`,
11293
+ * where the printer drops that `;` (see `isDroppedSemicolon`); none where it
11294
+ * keeps it. The `;` is a unit at the end of the statement, or one that the
11295
+ * line rule ignores: right after the statement, or inside its style, which then
11296
+ * holds the whitespace that follows the `;`.
11297
+ */
11298
+ function findDroppedSemicolonStretches(source, statement) {
11299
+ if (statement.type !== "TreemapClassDefStatement" || statement.style === null) return [];
11300
+ const [start] = statement.style.range;
11301
+ const end = statement.range[1];
11302
+ const semicolon = endingSemicolonOf(source, statement.range, statement.style);
11303
+ if (semicolon === void 0 || !isDroppedSemicolon(source, semicolon)) return [];
11304
+ return [{
11305
+ start,
11306
+ end,
11307
+ doc: printAsWrittenTrimmed(source, start, semicolon)
11308
+ }];
11309
+ }
11310
+ /**
10742
11311
  * Only a trailing comment keeps whitespace before its mark. Standalone
10743
11312
  * comments lose their leading run, while directive interiors are not gaps
10744
11313
  * (diagrams/treemap.md, Comments and authored boundaries;
@@ -10771,7 +11340,8 @@ function layoutTreemapStatement(source, statement, column, continuationPadding)
10771
11340
  case "TreemapSection":
10772
11341
  case "TreemapLeaf":
10773
11342
  case "TreemapClassDefStatement": {
10774
- const atoms = collectAtoms(source, start, end, statement.type === "TreemapClassDefStatement" ? collectValueNodes(statement, treemapValueNodeTypes) : treemapRowParts(statement).flatMap((part) => treemapValueNodeTypes.has(part.type) ? [part] : collectValueNodes(part, treemapValueNodeTypes)), []);
11343
+ const dropped = findDroppedSemicolonStretches(source, statement);
11344
+ const atoms = collectAtoms(source, start, end, statement.type === "TreemapClassDefStatement" ? collectValueNodes(statement, treemapValueNodeTypes).filter((value) => value !== statement.style || dropped.length === 0) : treemapRowParts(statement).flatMap((part) => treemapValueNodeTypes.has(part.type) ? [part] : collectValueNodes(part, treemapValueNodeTypes)), dropped);
10775
11345
  const rules = /* @__PURE__ */ new Map();
10776
11346
  const joinedBefore = /* @__PURE__ */ new Set();
10777
11347
  for (const [index, atom] of atoms.entries()) {
@@ -10860,6 +11430,8 @@ function printTreemap(path, options, _print, source) {
10860
11430
  ownIndentation: new Set(lines.map((line) => lineStartOf(source, line.range[0])))
10861
11431
  },
10862
11432
  relocatedWhitespace,
11433
+ indentsOnlyCommentLines: true,
11434
+ extraIndentationOf: (line) => placements.get(line).indentation,
10863
11435
  printedEnd: (line) => line.range[1],
10864
11436
  holdsStatements: () => false,
10865
11437
  isDroppedAtTopLevel: () => false,