prettier-plugin-mmd 0.6.0 → 0.7.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,7 +1,7 @@
1
1
  import { parse, traverseNodes, visitorKeys } from "@mmd-toolkit/parser";
2
2
  import { builders, printer, utils } from "prettier/doc";
3
- import { Marked } from "marked";
4
3
  import { util } from "prettier";
4
+ import { Marked } from "marked";
5
5
  //#region src/printers/collections.ts
6
6
  /**
7
7
  * Append the items in order to the existing array, as `target.push(...items)`
@@ -684,6 +684,14 @@ function isNextToSemicolon(source, offset) {
684
684
  return false;
685
685
  }
686
686
  /**
687
+ * Whether nothing but whitespace precedes `offset` on its line: no token,
688
+ * comment, or directive starts between the start of the line and `offset`.
689
+ */
690
+ function isFirstOnItsLine(source, offset) {
691
+ const lineStart = lineStartOf(source, offset);
692
+ return findTokensBetween(source, lineStart, offset).length === 0 && findTriviaBetween(source, lineStart, offset).length === 0;
693
+ }
694
+ /**
687
695
  * Whether nothing but whitespace follows the `;` at `offset` on its line: no
688
696
  * token that holds more than whitespace, comment, or directive starts after it
689
697
  * before the line ends (a style holds the whitespace after an ignored `;`). A
@@ -1817,15 +1825,12 @@ function childrenOf(node) {
1817
1825
  * order of the parser's `visitorKeys`. Value nodes have no child fields.
1818
1826
  */
1819
1827
  function walk(node, visit) {
1820
- for (const key of visitorKeys[node.type]) {
1821
- const value = node[key];
1822
- const children = Array.isArray(value) ? value : [value];
1823
- for (const child of children) {
1824
- if (child === null) continue;
1825
- visit(child);
1826
- walk(child, visit);
1827
- }
1828
- }
1828
+ traverseNodes(node, {
1829
+ enterNode(child, parent) {
1830
+ if (parent !== null) visit(child);
1831
+ },
1832
+ leaveNode() {}
1833
+ });
1829
1834
  }
1830
1835
  /**
1831
1836
  * The atoms in `[start, end)`: the kept stretches, the value nodes outside
@@ -2183,7 +2188,51 @@ function padOneLineDescription(source, block, layout) {
2183
2188
  * text on one line all the same: there are no columns to keep in it.
2184
2189
  */
2185
2190
  function formatDescriptionBlock(source, block, layout, preservesBodyColumns = false) {
2186
- return padOneLineDescription(source, block, preservesBodyColumns ? layout : indentDescriptionLines(source, block, layout));
2191
+ return padOneLineDescription(source, block, dropOpeningLineWhitespace(source, block, preservesBodyColumns ? layout : indentDescriptionLines(source, block, layout)));
2192
+ }
2193
+ /**
2194
+ * Sets the whitespace on the line of the `{` of an `accDescr` block whose text
2195
+ * starts on a later line. The whitespace at the end of the line is left out,
2196
+ * after the `{` or after a directive that follows it: mermaid.js reads the
2197
+ * whitespace after the `{`, line feeds included, with the `{`, so the text
2198
+ * starts after it and the Db is the same. The whitespace before a comment or a
2199
+ * directive on the line is one space where it is a run or a tab, as a gap
2200
+ * before a directive at the end of a printed line is (docs/compatibility.md,
2201
+ * Description block indentation and Directives between tokens). The whitespace
2202
+ * after a comment is part of the comment and stays, as does a removed line
2203
+ * feed.
2204
+ */
2205
+ function dropOpeningLineWhitespace(source, block, layout) {
2206
+ const opening = expectToken(findDescriptionOpening(source, expectToken(findTokenStartingAt(source, block.range[0]), "the description keyword"), block.opening), "the description opener");
2207
+ const edits = [];
2208
+ let lineEnd = opening.range[1];
2209
+ let itemEnd = opening.range[1];
2210
+ for (;;) {
2211
+ const runStart = lineEnd;
2212
+ while (isSpaceOrTab(source.text[lineEnd])) lineEnd++;
2213
+ const item = findTriviaAt(source, lineEnd);
2214
+ if (item === void 0) break;
2215
+ if (lineEnd > runStart && source.text.slice(runStart, lineEnd) !== " ") edits.push({
2216
+ range: [runStart, lineEnd],
2217
+ replacement: " "
2218
+ });
2219
+ lineEnd = itemEnd = item.range[1];
2220
+ }
2221
+ let dropFrom = lineEnd;
2222
+ while (dropFrom > itemEnd && isSpaceOrTab(source.text[dropFrom - 1])) dropFrom--;
2223
+ if (dropFrom < lineEnd) edits.push({
2224
+ range: [dropFrom, lineEnd],
2225
+ replacement: ""
2226
+ });
2227
+ if (source.text[lineEnd] !== "\n" || source.removedLineFeeds.has(lineEnd)) return layout;
2228
+ const inAtoms = edits.filter((edit) => layout.atoms.some((atom) => atom.start <= edit.range[0] && edit.range[1] <= atom.end));
2229
+ if (inAtoms.length === 0) return layout;
2230
+ const atoms = [...layout.atoms];
2231
+ replaceInAtoms(source, atoms, inAtoms);
2232
+ return {
2233
+ ...layout,
2234
+ atoms
2235
+ };
2187
2236
  }
2188
2237
  /**
2189
2238
  * Align ordinary description text after LF without changing its contents or
@@ -2915,7 +2964,7 @@ function respellingsOf(source) {
2915
2964
  const map = /* @__PURE__ */ new Map();
2916
2965
  findTokenRespellings(source, map);
2917
2966
  if (source.root.diagramType === "er") findRelationshipRespellings(source, map);
2918
- if (source.root.diagramType === "packet") findEqualRangeRespellings(source, source.root, map);
2967
+ if (source.root.diagramType === "packet") findEqualRangeRespellings(source, map);
2919
2968
  findLinkLabelRespellings(source, map);
2920
2969
  collectNumbers(source, source.root, map);
2921
2970
  found = {
@@ -2960,18 +3009,12 @@ function findTokenRespellings(source, found) {
2960
3009
  function isTouchedAfter(source, offset) {
2961
3010
  return source.text[offset] === ";" || source.text[offset] === "-";
2962
3011
  }
2963
- /** The relationships of an ER diagram under a node, in source order. */
2964
- function collectRelationships(node, relationships) {
2965
- for (const child of childrenOf(node)) if (child.type === "ErRelationship") relationships.push(child);
2966
- else collectRelationships(child, relationships);
2967
- }
2968
3012
  /**
2969
3013
  * Records the respelling of the three units of each relationship of an ER
2970
3014
  * diagram as symbols: `only one to zero or more` is `||--o{`.
2971
3015
  */
2972
3016
  function findRelationshipRespellings(source, found) {
2973
- const relationships = [];
2974
- collectRelationships(source.root, relationships);
3017
+ const relationships = findNodes(source.root, (node) => node.type === "ErRelationship");
2975
3018
  for (const relationship of relationships) {
2976
3019
  if (relationship.type !== "ErRelationship") continue;
2977
3020
  const units = source.root.tokens.filter((token) => token.range[0] >= relationship.range[0] && token.range[1] <= relationship.range[1]);
@@ -2993,12 +3036,10 @@ function findRelationshipRespellings(source, found) {
2993
3036
  * Records the respelling of a range of a packet diagram that starts and ends
2994
3037
  * at the same position as the position alone: `4-4` is `4`.
2995
3038
  */
2996
- function findEqualRangeRespellings(source, node, found) {
2997
- for (const child of childrenOf(node)) {
2998
- if (child.type !== "PacketRangeBlockStatement") {
2999
- findEqualRangeRespellings(source, child, found);
3000
- continue;
3001
- }
3039
+ function findEqualRangeRespellings(source, found) {
3040
+ const ranges = findNodes(source.root, (node) => node.type === "PacketRangeBlockStatement");
3041
+ for (const child of ranges) {
3042
+ if (child.type !== "PacketRangeBlockStatement") continue;
3002
3043
  const { start, end } = child;
3003
3044
  const between = source.text.slice(start.range[1], end.range[0]);
3004
3045
  if (source.text.slice(...start.range) !== source.text.slice(...end.range) || between.trim() !== "-") continue;
@@ -3529,7 +3570,14 @@ function collapseRunEdits(source, start, end) {
3529
3570
  }
3530
3571
  return edits;
3531
3572
  }
3532
- /** The doc with the runs of spaces and tabs in its strings printed as one. */
3573
+ /**
3574
+ * The doc with the runs of spaces and tabs in its strings printed as one. It
3575
+ * reaches the strings and the arrays of the doc only, and not the contents of
3576
+ * its commands, which `utils.mapDoc` of `prettier/doc` would also reach: a
3577
+ * layout puts text that stays as written inside a command, such as the text
3578
+ * that a railroad-beta call ignores: `r = terminal(%%{! }%% "a");` keeps both
3579
+ * spaces of `%%{! }%%`, which `mapDoc` would print as one.
3580
+ */
3533
3581
  function collapseDoc(doc) {
3534
3582
  if (typeof doc === "string") {
3535
3583
  const collapsed = collapseRuns(doc);
@@ -3619,14 +3667,15 @@ function isGeneratedSubgraphId(id) {
3619
3667
  }
3620
3668
  /** Records the ids of the vertices that carry a data block. */
3621
3669
  function collectDataIds(source, node, ids) {
3622
- if (node.type === "FlowchartVertex" || node.type === "AgentflowVertex") {
3623
- const data = node.data;
3624
- if (Array.isArray(data) ? data.length > 0 : data != null) ids.add(source.text.slice(...node.id.range));
3625
- }
3626
- for (const key of visitorKeys[node.type]) {
3627
- const value = node[key];
3628
- for (const child of Array.isArray(value) ? value : [value]) if (child !== null && child !== void 0) collectDataIds(source, child, ids);
3629
- }
3670
+ traverseNodes(node, {
3671
+ enterNode(item) {
3672
+ if (item.type === "FlowchartVertex" || item.type === "AgentflowVertex") {
3673
+ const data = item.data;
3674
+ if (Array.isArray(data) ? data.length > 0 : data != null) ids.add(source.text.slice(...item.id.range));
3675
+ }
3676
+ },
3677
+ leaveNode() {}
3678
+ });
3630
3679
  }
3631
3680
  /**
3632
3681
  * Records the range of the title of a subgraph, or of a flow of an agentflow
@@ -4446,22 +4495,126 @@ function styleStatementRules(source, names, styles, compactStyles = false) {
4446
4495
  }
4447
4496
  return rules;
4448
4497
  }
4449
- /** Keep property and value text, changing only the first colon's padding. */
4498
+ /**
4499
+ * Keep property and value text, changing only the first colon's padding and
4500
+ * the runs of spaces and tabs between the words of a style, which are printed
4501
+ * as one space (docs/er.md and docs/requirement.md, Styles and classes). A
4502
+ * style with a `:` at its start has no padding to set before it.
4503
+ */
4450
4504
  function printStyleUnitSpacing(source, style) {
4451
- const colon = source.text.indexOf(":", style.range[0]);
4452
- if (colon <= style.range[0] || colon >= style.range[1]) return printAsWritten(source, ...style.range);
4453
- let propertyEnd = colon;
4454
- while (source.text[propertyEnd - 1] === " " || source.text[propertyEnd - 1] === " ") propertyEnd--;
4455
- if (propertyEnd === style.range[0]) return printAsWritten(source, ...style.range);
4456
- let valueStart = colon + 1;
4457
- while (source.text[valueStart] === " " || source.text[valueStart] === " ") valueStart++;
4505
+ const [start, end] = style.range;
4506
+ const gap = findColonGap(source.text, start, end);
4507
+ if (gap === void 0) return printWordGaps(source, start, end);
4458
4508
  return [
4459
- printAsWritten(source, style.range[0], propertyEnd),
4509
+ printWordGaps(source, start, gap.nameEnd),
4460
4510
  ":",
4461
- valueStart < style.range[1] ? [" ", printAsWritten(source, valueStart, style.range[1])] : ""
4511
+ gap.valueStart < end ? [" ", printWordGaps(source, gap.valueStart, end)] : ""
4462
4512
  ];
4463
4513
  }
4464
4514
  /**
4515
+ * The text at `[start, end)`, with each run of spaces and tabs that
4516
+ * `styleRunEdits` lists printed as one space.
4517
+ */
4518
+ function printWordGaps(source, start, end) {
4519
+ const parts = [];
4520
+ let position = start;
4521
+ for (const { range } of styleRunEdits(source, start, end)) {
4522
+ parts.push(printAsWritten(source, position, range[0]), " ");
4523
+ position = range[1];
4524
+ }
4525
+ parts.push(printAsWritten(source, position, end));
4526
+ return parts;
4527
+ }
4528
+ /**
4529
+ * The edits that print each run of spaces and tabs inside the text of a style,
4530
+ * at `[start, end)`, as one space. CSS reads a run as one whitespace, so the
4531
+ * figure is the same, except where the run is a character of the value: inside
4532
+ * a string (`"…"` or `'…'`), inside a comment, inside the parentheses of
4533
+ * `url(`, and the escape after a backslash (see `endOfEscape`). A string, a
4534
+ * comment, or `url(` that is not closed runs to the end of the text.
4535
+ * The runs at the ends of the text are the business of the caller.
4536
+ */
4537
+ function styleRunEdits(source, start, end) {
4538
+ const { text } = source;
4539
+ const edits = [];
4540
+ let position = start;
4541
+ while (position < end) {
4542
+ const character = text[position];
4543
+ if (character === "\\") position = endOfEscape(text, position, end);
4544
+ else if (character === "\"" || character === "'") position = endOfQuoted(text, position, end);
4545
+ else if (text.startsWith("/*", position)) {
4546
+ const close = text.indexOf("*/", position + 2);
4547
+ position = close === -1 || close + 2 > end ? end : close + 2;
4548
+ } else if (text.slice(position, position + 4).toLowerCase() === "url(") position = endOfUrl(text, position + 4, end);
4549
+ else if (isSpaceOrTab(character)) {
4550
+ let runEnd = position;
4551
+ while (runEnd < end && isSpaceOrTab(text[runEnd])) runEnd++;
4552
+ if (position > start && runEnd < end && !(runEnd - position === 1 && character === " ")) edits.push({
4553
+ range: [position, runEnd],
4554
+ replacement: " "
4555
+ });
4556
+ position = runEnd;
4557
+ } else position++;
4558
+ }
4559
+ return edits;
4560
+ }
4561
+ /**
4562
+ * The offset after the escape that starts with the backslash at `backslashAt`.
4563
+ * CSS reads one to six hexadecimal digits after a backslash, and one space or
4564
+ * tab after them, as the escape; any other character after a backslash, a
4565
+ * space or a tab included, is the escaped character. The whitespace after the
4566
+ * escape is a run like any other (`Arial\20 Black` is `Arial`, the escape
4567
+ * `\20 `, one space, and `Black`).
4568
+ */
4569
+ function endOfEscape(text, backslashAt, end) {
4570
+ let digits = 0;
4571
+ while (digits < 6 && backslashAt + 1 + digits < end && isHexDigit(text[backslashAt + 1 + digits])) digits++;
4572
+ if (digits === 0) return backslashAt + 2;
4573
+ const after = backslashAt + 1 + digits;
4574
+ return after < end && isSpaceOrTab(text[after]) ? after + 1 : after;
4575
+ }
4576
+ /** Whether a character is a hexadecimal digit. */
4577
+ function isHexDigit(character) {
4578
+ return character !== void 0 && "0123456789abcdefABCDEF".includes(character);
4579
+ }
4580
+ /** The offset after the string that starts with the quote at `quoteAt`. */
4581
+ function endOfQuoted(text, quoteAt, end) {
4582
+ for (let index = quoteAt + 1; index < end; index++) if (text[index] === "\\") index++;
4583
+ else if (text[index] === text[quoteAt]) return index + 1;
4584
+ return end;
4585
+ }
4586
+ /** The offset after the `)` that closes the `url(` whose text starts at `from`. */
4587
+ function endOfUrl(text, from, end) {
4588
+ for (let index = from; index < end; index++) {
4589
+ const character = text[index];
4590
+ if (character === "\\") index++;
4591
+ else if (character === "\"" || character === "'") index = endOfQuoted(text, index, end) - 1;
4592
+ else if (character === ")") return index + 1;
4593
+ }
4594
+ return end;
4595
+ }
4596
+ /**
4597
+ * Adds the edits that print each run of spaces and tabs between the words of a
4598
+ * style as one space, where the Db of mermaid.js either does not hold the
4599
+ * whitespace (it joins the words of a style that has no `:`) or holds it and
4600
+ * draws the figure without it (docs/compatibility.md, Styles that are drawn
4601
+ * the same). The whitespace next to the first `:` is the business of
4602
+ * `addColonEdit`, called before this, and stays as that edit leaves it. The
4603
+ * other runs that `styleRunEdits` lists change, also in a style where that edit
4604
+ * leaves the colon as written, as in one that starts with the `:`. Not the
4605
+ * whitespace at the ends of `range`, which is the business of the caller, which
4606
+ * keeps the whitespace after a backslash that ends a style.
4607
+ */
4608
+ function addWordGapEdits(source, [start, end], edits) {
4609
+ const colon = source.text.indexOf(":", start);
4610
+ const hasColon = colon !== -1 && colon < end;
4611
+ for (const edit of styleRunEdits(source, start, end)) {
4612
+ const [from, to] = edit.range;
4613
+ if (hasColon && (to === colon || from === colon + 1)) continue;
4614
+ if (!edits.some((other) => other.range[0] < to && from < other.range[1])) edits.push(edit);
4615
+ }
4616
+ }
4617
+ /**
4465
4618
  * ER and requirement discard simple same-line style-unit padding. Keep trivia,
4466
4619
  * physical/Unicode line boundaries and complete semicolon-sensitive lines (a
4467
4620
  * line that holds a `;` of its own, not one that separates statements and is
@@ -4537,6 +4690,11 @@ function styleUnitsCanCompact(source, start, end, styles) {
4537
4690
  * `style` of a node of the other diagram types and their `classDef` are not
4538
4691
  * joined so: mermaid.js takes the whitespace at their ends away first.
4539
4692
  *
4693
+ * Where `collapsesWordGaps` is set, a run of spaces and tabs between the words
4694
+ * of a style is printed as one space, whether the style has a `:` or not
4695
+ * (`addWordGapEdits`). Where `trimsEnd` is set, the whitespace after the last
4696
+ * style is left out.
4697
+ *
4540
4698
  * Where `escapesComma` is set, a `,` after a backslash is part of a style, and
4541
4699
  * so is a space after a backslash at the end of one: taking that space away
4542
4700
  * would make the `,` part of the style. A space after a backslash before the
@@ -4545,7 +4703,7 @@ function styleUnitsCanCompact(source, start, end, styles) {
4545
4703
  * or a directive, or on a line with a kept `;` stays as written, as in ER (see
4546
4704
  * `styleUnitsCanCompact`).
4547
4705
  */
4548
- function normalizeStyleList(source, atoms, statement, { keepsSpaceBeforeFill = false, isLinkStyle = false, joinsStyles = false, splitsLabelStyles = false, keepsGapAfterStroke = false, escapesComma = false } = {}) {
4706
+ function normalizeStyleList(source, atoms, statement, { keepsSpaceBeforeFill = false, isLinkStyle = false, joinsStyles = false, splitsLabelStyles = false, keepsGapAfterStroke = false, escapesComma = false, collapsesWordGaps = false, trimsEnd = false } = {}) {
4549
4707
  const styles = statement.styles.filter((style) => style !== null);
4550
4708
  const first = styles.at(0);
4551
4709
  const last = styles.at(-1);
@@ -4560,10 +4718,20 @@ function normalizeStyleList(source, atoms, statement, { keepsSpaceBeforeFill = f
4560
4718
  let core = keepsValue ? [skipSpacesAndTabs(source, start, comma), comma] : trimStyle(source, [start, comma], { keepsEscapedSpace: escapesComma });
4561
4719
  if (core[0] === core[1]) return;
4562
4720
  if (joinsStyles && !keepsValue && core[1] < comma && endsWithEscape(source.text.slice(core[0], core[1]))) core = [core[0], core[1] + 1];
4563
- if (!keepsValue) addColonEdit(source, core, edits, {
4564
- keepsGapAfterStroke,
4565
- keepsGapAfterLabelName: splitsLabelStyles
4566
- });
4721
+ if (!keepsValue) {
4722
+ addColonEdit(source, core, edits, {
4723
+ keepsGapAfterStroke,
4724
+ keepsGapAfterLabelName: splitsLabelStyles
4725
+ });
4726
+ if (collapsesWordGaps) addWordGapEdits(source, core, edits);
4727
+ }
4728
+ if (trimsEnd && comma === to && core[1] < comma) {
4729
+ const beforeDirective = findTriviaBetween(source, comma, comma + 1).length > 0;
4730
+ edits.push({
4731
+ range: [core[1], comma],
4732
+ replacement: beforeDirective ? " " : ""
4733
+ });
4734
+ }
4567
4735
  if (previousEnd !== -1) {
4568
4736
  const touchesWord = core[0] === start && (keepsSpaceBeforeFill && source.text.startsWith("fill", core[0]) || isLinkStyle && source.text.startsWith("stroke:", core[0]) || splitsLabelStyles && (source.text.startsWith("color:", core[0]) || source.text.startsWith("text-align:", core[0])));
4569
4737
  edits.push({
@@ -4855,19 +5023,16 @@ function trimStyle(source, range, { keepsEscapedSpace = false } = {}) {
4855
5023
  /**
4856
5024
  * Adds the edit that takes the whitespace before the first `:` of a style away
4857
5025
  * and puts one space after it, where the value is not empty. A style without
4858
- * a name before the `:`, or with an escaped space before it, stays. Where
5026
+ * a name before the `:` has no whitespace before it to take away. The space
5027
+ * that a backslash before the `:` escapes stays, and the whitespace after it
5028
+ * goes: CSS reads the escaped space as part of the name. Where
4859
5029
  * `keepsGapAfterStroke` is set and the name ends with `stroke`, one space
4860
5030
  * stays before the `:` if whitespace stood there.
4861
5031
  */
4862
5032
  function addColonEdit(source, [start, end], edits, { keepsGapAfterStroke = false, keepsGapAfterLabelName = false } = {}) {
4863
- const colon = source.text.indexOf(":", start);
4864
- if (colon <= start || colon >= end) return;
4865
- let nameEnd = colon;
4866
- while (nameEnd > start && isSpaceOrTab(source.text[nameEnd - 1])) nameEnd--;
4867
- if (nameEnd === start) return;
4868
- if (nameEnd < colon && source.text[nameEnd - 1] === "\\") return;
4869
- let valueStart = colon + 1;
4870
- while (valueStart < end && isSpaceOrTab(source.text[valueStart])) valueStart++;
5033
+ const gap = findColonGap(source.text, start, end);
5034
+ if (gap === void 0) return;
5035
+ const { nameEnd, colon, valueStart } = gap;
4871
5036
  const name = source.text.slice(start, nameEnd);
4872
5037
  const spaceBeforeColon = nameEnd < colon && (keepsGapAfterStroke && name.endsWith("stroke") || keepsGapAfterLabelName && (name === "color" || name === "text-align"));
4873
5038
  edits.push({
@@ -4876,6 +5041,27 @@ function addColonEdit(source, [start, end], edits, { keepsGapAfterStroke = false
4876
5041
  });
4877
5042
  }
4878
5043
  /**
5044
+ * The first `:` of the style at `[start, end)` and the whitespace around it,
5045
+ * or undefined where the style has no `:`. A style that starts with the `:`
5046
+ * has no name before it. A backslash directly before the whitespace before the
5047
+ * `:` escapes its first space, which CSS reads as a character of the name, so
5048
+ * that space stays and the whitespace after it goes.
5049
+ */
5050
+ function findColonGap(text, start, end) {
5051
+ const colon = text.indexOf(":", start);
5052
+ if (colon === -1 || colon >= end) return void 0;
5053
+ let valueStart = colon + 1;
5054
+ while (valueStart < end && isSpaceOrTab(text[valueStart])) valueStart++;
5055
+ let nameEnd = colon;
5056
+ while (nameEnd > start && isSpaceOrTab(text[nameEnd - 1])) nameEnd--;
5057
+ if (nameEnd === start && colon > start) return void 0;
5058
+ return {
5059
+ nameEnd: nameEnd < colon && endsWithEscape(text.slice(start, nameEnd)) ? nameEnd + 1 : nameEnd,
5060
+ colon,
5061
+ valueStart
5062
+ };
5063
+ }
5064
+ /**
4879
5065
  * The rules of a `class` statement: the names of the entities and the
4880
5066
  * classes are lists separated by `,` without whitespace, and the first class
4881
5067
  * stands after one space.
@@ -5185,7 +5371,8 @@ function addStyledStatementRules(source, statement, rules, kept, printsStyles) {
5185
5371
  }];
5186
5372
  if (printsStyles) normalizeStyleList(source, atoms, statement, {
5187
5373
  joinsStyles,
5188
- splitsLabelStyles: statement.type === "BlockStyleStatement"
5374
+ splitsLabelStyles: statement.type === "BlockStyleStatement",
5375
+ collapsesWordGaps: true
5189
5376
  });
5190
5377
  const doc = atoms[0].doc ?? (dropsSemicolon ? printAsWrittenTrimmed(source, start, semicolon) : void 0);
5191
5378
  kept.push({
@@ -5706,7 +5893,10 @@ function layoutClassStatement(source, statement, end) {
5706
5893
  ...lastAtom,
5707
5894
  end
5708
5895
  };
5709
- normalizeStyleList(source, atoms, statement, { joinsStyles });
5896
+ normalizeStyleList(source, atoms, statement, {
5897
+ joinsStyles,
5898
+ collapsesWordGaps: true
5899
+ });
5710
5900
  }
5711
5901
  return {
5712
5902
  atoms: keepFirstGapLineTails(source, atoms, (from, to) => gapKeepsLineBreak(source, keptBreaks, from, to)),
@@ -5932,7 +6122,10 @@ function statementRules$8(source, statement) {
5932
6122
  addAccessibilityColonRules$1(source, statement, rules);
5933
6123
  break;
5934
6124
  case "ClassClassDefStatement":
5935
- addNameListRules(source, statement.cssClasses, rules);
6125
+ for (const [offset, rule] of styleStatementRules(source, statement.cssClasses, statement.styles, true)) rules.set(offset, rule);
6126
+ break;
6127
+ case "ClassStyleStatement":
6128
+ for (const [offset, rule] of styleStatementRules(source, [], statement.styles, true)) rules.set(offset, rule);
5936
6129
  break;
5937
6130
  case "ClassAnnotationStatement":
5938
6131
  addAnnotationRules(source, statement.annotation, statement.class.range[0], rules);
@@ -6324,6 +6517,32 @@ function groupVennUnits(source, statements) {
6324
6517
  }
6325
6518
  return units;
6326
6519
  }
6520
+ /**
6521
+ * The edits that print each run of spaces and tabs between the words of an
6522
+ * unquoted value as one space. A run inside parentheses stays: mermaid.js keeps
6523
+ * it in the Db (`rgb(1, 2,3)`), where it joins the words outside them.
6524
+ */
6525
+ function findWordRunEdits(source, [start, end]) {
6526
+ const edits = [];
6527
+ let depth = 0;
6528
+ for (let position = start; position < end;) {
6529
+ const character = source.text[position];
6530
+ if (character === "(") depth++;
6531
+ else if (character === ")" && depth > 0) depth--;
6532
+ if (depth > 0 || !isSpaceOrTab(character)) {
6533
+ position++;
6534
+ continue;
6535
+ }
6536
+ let runEnd = position;
6537
+ while (runEnd < end && isSpaceOrTab(source.text[runEnd])) runEnd++;
6538
+ if (position > start && runEnd < end && !(runEnd - position === 1 && character === " ")) edits.push({
6539
+ range: [position, runEnd],
6540
+ replacement: " "
6541
+ });
6542
+ position = runEnd;
6543
+ }
6544
+ return edits;
6545
+ }
6327
6546
  /** Only targetless text uses positive indentation; it is a marker, not nesting. */
6328
6547
  function isImplicitVennUnit(unit) {
6329
6548
  const first = unit.statements[0];
@@ -6341,6 +6560,7 @@ function layoutVennStatement(source, statement) {
6341
6560
  atoms = protectSemicolonPrefixes(source, start, end, atoms);
6342
6561
  if ("label" in statement && statement.label !== null) trimBracketedText(source, atoms, statement.label.range);
6343
6562
  if (statement.type === "VennTitleStatement") trimTextAfterKeyword(source, atoms, statement.value.range, true);
6563
+ if (statement.type === "VennStyleStatement") replaceInAtoms(source, atoms, statement.properties.flatMap((property) => property.value.type === "VennLiteral" ? findWordRunEdits(source, property.value.range) : []));
6344
6564
  const rules = /* @__PURE__ */ new Map();
6345
6565
  for (let index = 1; index < atoms.length; index++) {
6346
6566
  const previous = atoms[index - 1];
@@ -6808,7 +7028,7 @@ function blockRules(source, keepsOpeningLine) {
6808
7028
  }
6809
7029
  //#endregion
6810
7030
  //#region src/printers/data-blocks.ts
6811
- const { literalline: literalline$2 } = builders;
7031
+ const { conditionalGroup, literalline: literalline$2, literallineWithoutBreakParent } = builders;
6812
7032
  /**
6813
7033
  * The data blocks that print moved: a `@{` or `{` that a line break follows,
6814
7034
  * and the lines up to its `}`. The diagram types that write one (flowchart,
@@ -6833,6 +7053,17 @@ const paddedTypes = /* @__PURE__ */ new Set([
6833
7053
  "KanbanDataBlock",
6834
7054
  "SequenceDataBlock"
6835
7055
  ]);
7056
+ /**
7057
+ * The blocks of one line that print on several lines when the line is too long:
7058
+ * the diagram types that read the text of a block as YAML and accept the lines
7059
+ * of a block mapping in place of a flow mapping. A sequence diagram rejects the
7060
+ * lines, and a JSON table is JSON.
7061
+ */
7062
+ const splitTypes = /* @__PURE__ */ new Set([
7063
+ "FlowchartDataBlock",
7064
+ "AgentflowDataBlock",
7065
+ "KanbanDataBlock"
7066
+ ]);
6836
7067
  /** The movable data blocks of each source, in source order, found once. */
6837
7068
  const blocksBySource = /* @__PURE__ */ new WeakMap();
6838
7069
  /**
@@ -6847,25 +7078,119 @@ function dataBlocksOf(source) {
6847
7078
  blocksBySource.set(source, blocks);
6848
7079
  return blocks;
6849
7080
  }
7081
+ /** The stretches of the statements of each source, found once. */
7082
+ const stretchesBySource = /* @__PURE__ */ new WeakMap();
7083
+ /**
7084
+ * The stretches of the lists of statements that the nodes of the source hold,
7085
+ * and the offsets where things start (see {@link StatementStretches}). One
7086
+ * diagram type has one `statementListsOf`.
7087
+ */
7088
+ function statementStretchesOf(source, statementListsOf) {
7089
+ const cached = stretchesBySource.get(source);
7090
+ if (cached !== void 0) return cached;
7091
+ const holders = findNodes(source.root.body, (node) => statementListsOf(node).length > 0);
7092
+ const lists = holders.flatMap(statementListsOf);
7093
+ const starts = /* @__PURE__ */ new Set();
7094
+ for (const list of lists) {
7095
+ starts.add(list.head);
7096
+ for (const statement of list.statements) starts.add(statement.range[0]);
7097
+ }
7098
+ for (const holder of holders) {
7099
+ const end = findTokenEndingBefore(source, holder.range[1]);
7100
+ if (holder !== source.root.body && end !== void 0) starts.add(end.range[0]);
7101
+ }
7102
+ const stretches = {
7103
+ lists: lists.flatMap(({ statements }) => {
7104
+ const first = statements.at(0);
7105
+ const last = statements.at(-1);
7106
+ return first === void 0 || last === void 0 ? [] : [{
7107
+ start: first.range[0],
7108
+ end: last.range[1]
7109
+ }];
7110
+ }),
7111
+ starts
7112
+ };
7113
+ stretchesBySource.set(source, stretches);
7114
+ return stretches;
7115
+ }
7116
+ /**
7117
+ * Whether the whitespace at the start of the line of the statement in `range`
7118
+ * was written for the depth of the statement. It is the indentation of the
7119
+ * first thing on the line, after the directives that start on it, so it fits the
7120
+ * statement only if the statement is at the depth of that thing. Only these
7121
+ * things have a depth that the whitespace is written for: a statement that
7122
+ * starts on the line, the header of a container, a section keyword, an `end`,
7123
+ * and the `}` that closes a data block of a statement from an earlier line.
7124
+ * The printer prints a header, a section keyword, and an `end` at the depth of
7125
+ * their container, and the `}` of a data block at the column of its statement,
7126
+ * where it moves the block; an author puts it there in a statement that stays
7127
+ * as written. Anything else that a line can start with, the rest of a
7128
+ * statement from an earlier line, of a directive, or of a comment, or a kind
7129
+ * that is not listed, is a thing the whitespace was not written for, and the
7130
+ * statement is moved. The line is the physical line, since a directive that
7131
+ * runs over lines holds the rest of it. The statement is deeper than the first
7132
+ * thing in `subgraph s; A@{`, where the header comes first, and shallower in
7133
+ * `B; end; A@{`, where the statement `B` inside the container comes first; the
7134
+ * printer then puts the statement on a line of its own at its own depth. The
7135
+ * statement is at the depth of the line in `C; A@{` and in `end; A@{`, where
7136
+ * the printer prints the `end` at the depth of its container and the statement
7137
+ * after the container is at that depth too.
7138
+ */
7139
+ function standsAtDepthOfItsLine(source, range, statementListsOf) {
7140
+ const lineStart = source.text.lastIndexOf("\n", range[0] - 1) + 1;
7141
+ let first = lineStart;
7142
+ for (;;) {
7143
+ while (first < range[0] && isSpaceOrTab(source.text[first])) first++;
7144
+ const directive = findTriviaBetween(source, first, first + 1).find((item) => item.type === "Directive");
7145
+ if (directive === void 0 || directive.range[1] > range[0]) break;
7146
+ first = directive.range[1];
7147
+ }
7148
+ if (first === range[0]) return true;
7149
+ const { lists, starts } = statementStretchesOf(source, statementListsOf);
7150
+ const closed = closedBlockStartingBefore(source, first, lineStart);
7151
+ if (closed === void 0 && !starts.has(first)) return false;
7152
+ return depthAt(lists, closed ?? first) === depthAt(lists, range[0]);
7153
+ }
7154
+ /** The number of lists of statements whose text holds `offset`. */
7155
+ function depthAt(lists, offset) {
7156
+ return lists.filter((list) => list.start <= offset && offset < list.end).length;
7157
+ }
7158
+ /**
7159
+ * The start of the data block that the `}` at `offset` closes, if that block
7160
+ * starts before `lineStart`. The printer puts the `}` of a block that it moves
7161
+ * at the column of the statement that holds it, and an author writes it there
7162
+ * too, so the whitespace before it, where it starts a line, is taken as written
7163
+ * for the depth of that statement.
7164
+ */
7165
+ function closedBlockStartingBefore(source, offset, lineStart) {
7166
+ if (source.text[offset] !== "}") return void 0;
7167
+ return dataBlocksOf(source).find((block) => block.range[1] === offset + 1 && block.range[0] < lineStart)?.range[0];
7168
+ }
6850
7169
  /**
6851
7170
  * The layout with the data blocks of the statement in `range` formatted: a
6852
7171
  * block of one line printed with one space inside each end (see
6853
- * `padDataBlock`), and, where the statement holds no other block, a block of
6854
- * several lines printed one level inside the statement, with its closing `}`
6855
- * on a line of its own at the column of the statement, in spaces (see
6856
- * `moveDataBlock`). The `{` of a JSON table of a use case diagram is printed
6857
- * right after its `@` (see `findJsonTableBrace`).
7172
+ * `padDataBlock`), and, where the statement holds no other block and the lines
7173
+ * can move (see `movesLines`), a block of several lines printed one level
7174
+ * inside the statement, with its closing `}` on a line of its own at the column
7175
+ * of the statement, in spaces (see `moveDataBlock`). The `{` of a JSON table
7176
+ * of a use case diagram is printed right after its `@` (see
7177
+ * `findJsonTableBrace`). Where the printer indents with tabs, a statement that
7178
+ * holds a block of several lines is printed as written (see
7179
+ * `printStatementAsWritten`).
6858
7180
  */
6859
7181
  function formatDataBlocks(source, layout, range, placement) {
6860
7182
  const all = dataBlocksOf(source);
6861
7183
  const first = findFirstIndex(all, (block) => block.range[0] >= range[0]);
6862
7184
  const afterLast = findFirstIndex(all, (block) => block.range[1] > range[1]);
7185
+ const asWritten = printStatementAsWritten(source, layout, range, placement);
7186
+ if (asWritten !== void 0) return asWritten;
6863
7187
  const atoms = [...layout.atoms];
6864
7188
  let changed = false;
6865
7189
  for (let index = first; index < afterLast; index++) {
6866
7190
  const block = all[index];
6867
7191
  const brace = findJsonTableBrace(source, block, placement.kept);
6868
- 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, brace) : void 0) ?? (brace === null ? void 0 : ["@", printAsWritten(source, brace, block.range[1])]);
7192
+ const padded = isOneLine(source.text.slice(...block.range)) ? padDataBlock(source, all, index, placement.kept) : void 0;
7193
+ const doc = (padded !== void 0 ? splitDataBlock(source, block, range, placement, padded, afterLast - first === 1) ?? padded : isOneLine(source.text.slice(...block.range)) ? void 0 : afterLast - first === 1 && movesLines(placement) ? moveDataBlock(source, block, range, placement, brace) : void 0) ?? (brace === null ? void 0 : ["@", printAsWritten(source, brace, block.range[1])]);
6869
7194
  if (doc === void 0) continue;
6870
7195
  const at = findFirstIndex(atoms, (atom) => atom.end >= block.range[1]);
6871
7196
  const atom = atoms[at];
@@ -6956,6 +7281,238 @@ function startsWithYamlMark(text) {
6956
7281
  return text.startsWith("---") || text.startsWith("...") || text.startsWith("%");
6957
7282
  }
6958
7283
  /**
7284
+ * Whether the printer may set the indentation of the lines of a block of
7285
+ * several lines: it indents them with spaces, since mermaid.js rejects a tab
7286
+ * before them, and only if `tabWidth` is not 0, which supplies no step. Under a
7287
+ * node indented with tabs the spaces stand right where a tab is as wide as
7288
+ * `tabWidth`, and a statement that can be printed as written never gets here
7289
+ * (see `printStatementAsWritten`; docs/flowchart.md, Data blocks).
7290
+ */
7291
+ function movesLines(placement) {
7292
+ return placement.tabWidth !== 0;
7293
+ }
7294
+ /**
7295
+ * Whether the printer may print a block of one line on several lines: its
7296
+ * lines can move (see `movesLines`), and it does not indent with tabs, since
7297
+ * under a node indented with tabs the lines would stand right for one width of
7298
+ * a tab only, while the block on its line is read the same at every width.
7299
+ */
7300
+ function splitsBlocks(placement) {
7301
+ return movesLines(placement) && placement.useTabs !== true;
7302
+ }
7303
+ /**
7304
+ * Whether the statement in `range` is printed as written: the printer indents
7305
+ * with tabs and the statement holds a block of several lines. The lines of the
7306
+ * block are indented with spaces, which stand right for one width of a tab
7307
+ * only, and the node line alone, indented to the depth of the statement, would
7308
+ * stand right of the content and the closing `}` wherever they were written no
7309
+ * deeper than the node line (docs/flowchart.md, Data blocks). A statement whose
7310
+ * indentation the printer decides (see `DataBlockPlacement.decidesIndentation`),
7311
+ * or that is not at the depth of the first thing on its line (see
7312
+ * `standsAtDepthOfItsLine`), prints as usual, and the lines of its block move
7313
+ * with the node line, as without tabs (see `movesLines`).
7314
+ */
7315
+ function keepsStatementAsWritten(source, range, useTabs, statementListsOf) {
7316
+ if (useTabs !== true || !standsAtDepthOfItsLine(source, range, statementListsOf)) return false;
7317
+ const all = dataBlocksOf(source);
7318
+ const first = findFirstIndex(all, (block) => block.range[0] >= range[0]);
7319
+ const afterLast = findFirstIndex(all, (block) => block.range[1] > range[1]);
7320
+ return all.slice(first, afterLast).some((block) => !isOneLine(source.text.slice(...block.range)));
7321
+ }
7322
+ /**
7323
+ * The indentation that a statement printed as written (see
7324
+ * `keepsStatementAsWritten`) starts its line with: the whitespace written at
7325
+ * the start of the line where the statement starts, also where a directive
7326
+ * stands before it on the line, which goes with it, or a statement that the
7327
+ * printer puts on a line of its own, as after `C;` in `C; A@{`. The caller
7328
+ * puts it in `BlockRules.writtenIndentationOf`; undefined where the statement
7329
+ * prints as usual. A statement that holds statements is not one.
7330
+ */
7331
+ function writtenIndentationOfBlockStatement(source, range, useTabs, statementListsOf) {
7332
+ if (!keepsStatementAsWritten(source, range, useTabs, statementListsOf)) return void 0;
7333
+ const start = lineStartOf(source, range[0]);
7334
+ let end = start;
7335
+ while (end < range[0] && isSpaceOrTab(source.text[end])) end++;
7336
+ return source.text.slice(start, end);
7337
+ }
7338
+ /**
7339
+ * The `BlockRules.writtenIndentationOf` of a diagram type with data blocks: a
7340
+ * statement printed as written (see `keepsStatementAsWritten`) stands at the
7341
+ * indentation written at the start of its line. A statement that holds
7342
+ * statements, such as a subgraph, is no such statement: its range holds the
7343
+ * blocks of the statements inside it.
7344
+ */
7345
+ function writtenIndentationRule(source, useTabs, statementListsOf) {
7346
+ return (statement) => statementListsOf(statement).length > 0 ? void 0 : writtenIndentationOfBlockStatement(source, statement.range, useTabs, statementListsOf);
7347
+ }
7348
+ /**
7349
+ * The layout with the statement printed as written, or undefined where it
7350
+ * prints as usual (see `keepsStatementAsWritten`). The indentation of its line
7351
+ * is set by `writtenIndentationOfBlockStatement`.
7352
+ */
7353
+ function printStatementAsWritten(source, layout, range, placement) {
7354
+ const first = layout.atoms.at(0);
7355
+ const last = layout.atoms.at(-1);
7356
+ if (first === void 0 || last === void 0 || placement.decidesIndentation === true || !keepsStatementAsWritten(source, range, placement.useTabs, placement.statementListsOf)) return void 0;
7357
+ return keptAsWritten(first.start, last.end);
7358
+ }
7359
+ /**
7360
+ * The block of one line, `@{ a: 1, b: 2 }`, printed as the lines of a block
7361
+ * mapping where its line is too long, one entry on each line, one level inside
7362
+ * the statement, with the `}` alone on a line at the column of the statement
7363
+ * (see `moveDataBlock`); `padded` where it fits or does not split. Prettier
7364
+ * chooses: the block stays on its line if the line fits; otherwise it prints
7365
+ * on lines if the line of the `{` fits then, and as `padded` if it does not,
7366
+ * since the lines would not shorten the line that is too long. mermaid.js
7367
+ * reads the text of a block on one line as a YAML flow mapping, and the text of
7368
+ * a block of several lines as the lines of a block mapping, which reads the
7369
+ * same where each entry is a key and a value that read the same in both (see
7370
+ * `splitEntries`) (docs/flowchart.md, Data blocks). A block splits only if
7371
+ *
7372
+ * - it is one of `splitTypes` and the printer may split a block (see
7373
+ * `splitsBlocks`), as the lines of a block mapping are what the split prints;
7374
+ * - it is the only block of its statement, and the last thing in it, on the
7375
+ * first line of the statement: the text after its `}` would stand after the
7376
+ * `}` on a line of its own, and the statement level is the level of that
7377
+ * first line;
7378
+ * - it has at least two entries: with one, the lines would not shorten the
7379
+ * line, and add lines.
7380
+ */
7381
+ function splitDataBlock(source, block, statement, placement, padded, alone) {
7382
+ if (!splitTypes.has(block.type) || !alone || !splitsBlocks(placement) || block.range[1] !== statement[1] || source.text.slice(statement[0], block.range[0]).includes("\n")) return void 0;
7383
+ const entries = splitEntries(source.text.slice(block.range[0] + 2, -1 + block.range[1]));
7384
+ if (entries === null) return void 0;
7385
+ const column = util.getAlignmentSize(placement.statement, placement.tabWidth);
7386
+ const lines = [];
7387
+ for (const entry of entries) lines.push(literallineWithoutBreakParent, " ".repeat(column + placement.tabWidth), entry);
7388
+ return conditionalGroup([
7389
+ padded,
7390
+ [
7391
+ "@{",
7392
+ ...lines,
7393
+ literallineWithoutBreakParent,
7394
+ " ".repeat(column),
7395
+ "}"
7396
+ ],
7397
+ padded
7398
+ ]);
7399
+ }
7400
+ /**
7401
+ * The entries of the text inside a block of one line, or null where the block
7402
+ * does not split. An entry is a key and a value separated by a colon and
7403
+ * whitespace, which read the same in a flow mapping, where a `,` ends an entry,
7404
+ * and in a block mapping, where a line break does:
7405
+ *
7406
+ * - the key is a plain or a quoted scalar, and the value a quoted scalar that
7407
+ * ends the entry, or a plain scalar that starts with no indicator of YAML
7408
+ * (`&`, `*`, `!`, `|`, `>`, `%`, `@`, a backquote, `-`, `?` or `:` before
7409
+ * whitespace) and holds no colon before whitespace or at its end;
7410
+ * - the text holds no nested `{}` or `[]` and no comment (a `#` after
7411
+ * whitespace or at the start), outside the quotes: a flow collection in a
7412
+ * value, and a comment, read differently over lines, and a value that holds
7413
+ * a nested collection is not a line to read one entry at a time;
7414
+ * - an entry without a value, as the `a` of `{a, b}`, or an empty entry,
7415
+ * as after a trailing `,`, is a key without a value in a flow mapping and
7416
+ * no mapping in a block;
7417
+ * - at least two entries.
7418
+ *
7419
+ * An entry is printed as it is written, without the spaces and tabs at its
7420
+ * ends; the characters of its key and value stay.
7421
+ */
7422
+ function splitEntries(inside) {
7423
+ const text = trimSpacesAndTabs(inside);
7424
+ if (text.includes("%%")) return null;
7425
+ const entries = [];
7426
+ let start = 0;
7427
+ let quote = "";
7428
+ let startsScalar = true;
7429
+ for (let index = 0; index < text.length; index++) {
7430
+ const character = text[index];
7431
+ if (quote !== "") {
7432
+ if (quote === "\"" && character === "\\") index++;
7433
+ else if (character === quote) {
7434
+ if (quote === "'" && text[index + 1] === "'") index++;
7435
+ else {
7436
+ quote = "";
7437
+ startsScalar = false;
7438
+ }
7439
+ }
7440
+ continue;
7441
+ }
7442
+ if (character === "{" || character === "}" || character === "[" || character === "]" || character === "#" && (index === 0 || isSpaceOrTab(text[index - 1]))) return null;
7443
+ if (character === ",") {
7444
+ entries.push(text.slice(start, index));
7445
+ start = index + 1;
7446
+ startsScalar = true;
7447
+ } else if (startsScalar && (character === "\"" || character === "'")) quote = character;
7448
+ else if (character === ":") startsScalar = text[index + 1] === void 0 || isSpaceOrTab(text[index + 1]);
7449
+ else if (!isSpaceOrTab(character)) startsScalar = false;
7450
+ }
7451
+ if (quote !== "") return null;
7452
+ entries.push(text.slice(start));
7453
+ const trimmed = entries.map(trimSpacesAndTabs);
7454
+ return trimmed.length >= 2 && trimmed.every(readsAsEntry) ? trimmed : null;
7455
+ }
7456
+ /** Whether an entry is a key and a value as `splitEntries` describes. */
7457
+ function readsAsEntry(entry) {
7458
+ const key = entry.startsWith("\"") || entry.startsWith("'") ? quotedScalarEnd(entry, 0) : plainKeyEnd(entry);
7459
+ if (key === -1) return false;
7460
+ let colon = key;
7461
+ while (isSpaceOrTab(entry[colon])) colon++;
7462
+ if (entry[colon] !== ":" || !isSpaceOrTab(entry[colon + 1])) return false;
7463
+ const value = trimSpacesAndTabs(entry.slice(colon + 1));
7464
+ if (value === "") return false;
7465
+ if (value.startsWith("\"") || value.startsWith("'")) return quotedScalarEnd(value, 0) === value.length;
7466
+ return isPlainScalar(value);
7467
+ }
7468
+ /**
7469
+ * The offset after a quoted scalar that starts at `start`, or -1 where it is
7470
+ * not closed. A double-quoted scalar escapes with a backslash, a single-quoted
7471
+ * one doubles its quote.
7472
+ */
7473
+ function quotedScalarEnd(text, start) {
7474
+ const quote = text[start];
7475
+ for (let index = start + 1; index < text.length; index++) if (quote === "\"" && text[index] === "\\") index++;
7476
+ else if (text[index] === quote) {
7477
+ if (quote === "'" && text[index + 1] === "'") index++;
7478
+ else return index + 1;
7479
+ }
7480
+ return -1;
7481
+ }
7482
+ /**
7483
+ * The offset of the end of a plain key, before the whitespace and the colon
7484
+ * that follow it, or -1 where the entry starts with an indicator or has no
7485
+ * colon before whitespace.
7486
+ */
7487
+ function plainKeyEnd(entry) {
7488
+ if (startsWithIndicator(entry)) return -1;
7489
+ for (let index = 0; index < entry.length; index++) if (entry[index] === ":" && (entry[index + 1] === void 0 || isSpaceOrTab(entry[index + 1]))) {
7490
+ let end = index;
7491
+ while (end > 0 && isSpaceOrTab(entry[end - 1])) end--;
7492
+ return end === 0 ? -1 : end;
7493
+ }
7494
+ return -1;
7495
+ }
7496
+ /** Whether a plain scalar value reads the same in a flow mapping and a block. */
7497
+ function isPlainScalar(value) {
7498
+ if (startsWithIndicator(value) || value.endsWith(":")) return false;
7499
+ for (let index = 0; index < value.length; index++) if (value[index] === ":" && isSpaceOrTab(value[index + 1])) return false;
7500
+ return true;
7501
+ }
7502
+ /** Whether a text starts with a character that YAML gives a meaning. */
7503
+ function startsWithIndicator(text) {
7504
+ const [first, second] = [text[0], text[1]];
7505
+ return "&*!|>%@`\"'".includes(first) || "-?:".includes(first) && (second === void 0 || isSpaceOrTab(second));
7506
+ }
7507
+ /** The text without the spaces and tabs at its ends. */
7508
+ function trimSpacesAndTabs(text) {
7509
+ let start = 0;
7510
+ let end = text.length;
7511
+ while (start < end && isSpaceOrTab(text[start])) start++;
7512
+ while (end > start && isSpaceOrTab(text[end - 1])) end--;
7513
+ return text.slice(start, end);
7514
+ }
7515
+ /**
6959
7516
  * The block printed with every line moved by the same number of spaces, so
6960
7517
  * that the shallowest line that holds text stands one level inside the
6961
7518
  * statement, and its closing `}`, where it stands on a line of its own, at
@@ -7016,22 +7573,16 @@ function moveDataBlock(source, block, statement, placement, brace) {
7016
7573
  if (closesAlone) {
7017
7574
  if (closing > shallowest) return void 0;
7018
7575
  }
7019
- const shift = columnsOf(placement.statement, placement.tabWidth) + placement.tabWidth - shallowest;
7576
+ const shift = util.getAlignmentSize(placement.statement, placement.tabWidth) + placement.tabWidth - shallowest;
7020
7577
  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)))];
7021
7578
  const docs = [];
7022
7579
  for (const [index, line] of lines.entries()) {
7023
7580
  if (index > 0) docs.push(literalline$2);
7024
7581
  docs.push(line);
7025
7582
  }
7026
- if (closesAlone) docs.push(literalline$2, " ".repeat(columnsOf(placement.statement, placement.tabWidth)), "}");
7583
+ if (closesAlone) docs.push(literalline$2, " ".repeat(util.getAlignmentSize(placement.statement, placement.tabWidth)), "}");
7027
7584
  return docs;
7028
7585
  }
7029
- /** The columns of an indentation, in which a tab is `tabWidth` columns. */
7030
- function columnsOf(indentation, tabWidth) {
7031
- let columns = 0;
7032
- for (const character of indentation) columns += character === " " ? tabWidth : 1;
7033
- return columns;
7034
- }
7035
7586
  /** Whether the line of a range's start or one of its lines is a kept line. */
7036
7587
  function holdsKeptLine(source, range, kept) {
7037
7588
  const starts = [lineStartOf(source, range[0])];
@@ -7063,7 +7614,6 @@ const usecaseValueNodeTypes = /* @__PURE__ */ new Set([
7063
7614
  "UsecaseLabel",
7064
7615
  "UsecaseJsonDataBlock"
7065
7616
  ]);
7066
- /** Exhaustively separates the one body-bearing statement from ordinary lines. */
7067
7617
  function classifyUsecaseStatement(statement) {
7068
7618
  switch (statement.type) {
7069
7619
  case "UsecaseSystemBoundaryStatement": return {
@@ -7086,7 +7636,7 @@ function classifyUsecaseStatement(statement) {
7086
7636
  kind: "simple",
7087
7637
  statement
7088
7638
  };
7089
- default: throw new Error(`prettier-plugin-mmd: unknown usecase statement ${JSON.stringify(statement)}`);
7639
+ default: return null;
7090
7640
  }
7091
7641
  }
7092
7642
  /** The last authored heading component, before the required physical newline. */
@@ -7200,6 +7750,7 @@ function layoutUsecaseStatement(source, statement, end) {
7200
7750
  }
7201
7751
  const atoms = protectSemicolonPrefixes(source, start, end, collectAtoms(source, start, end, collectValueNodes(statement, usecaseValueNodeTypes).filter((value) => value.range[1] <= end), kept));
7202
7752
  dropPaddings(source, atoms, titlePads);
7753
+ if (statement.type === "UsecaseClassDefStatement" || statement.type === "UsecaseStyleStatement") replaceInAtoms(source, atoms, styleColonEdits(source, statement, end));
7203
7754
  for (const stereotype of stereotypes) {
7204
7755
  const index = atoms.findIndex((atom) => atom.start === stereotype.value.range[0] && atom.end === stereotype.value.range[1]);
7205
7756
  if (index === -1) continue;
@@ -7218,6 +7769,30 @@ function layoutUsecaseStatement(source, statement, end) {
7218
7769
  };
7219
7770
  }
7220
7771
  /**
7772
+ * The edits that print the styles of a `classDef` or a `style` in the form of
7773
+ * the other diagram types: no whitespace before the first `:` of a style and
7774
+ * one space after it, where the value is not empty. The Db keeps the
7775
+ * whitespace, so it changes, but mermaid.js draws the same figure: it trims
7776
+ * each style before it reads its name, and the whitespace around `:` is not
7777
+ * read in the CSS of the figure (docs/compatibility.md, Styles that are drawn
7778
+ * the same). A style can reach a link, as an explicit relationship id can be
7779
+ * the target of a `classDef` or a `style`, so a name that ends with `stroke`
7780
+ * keeps whether whitespace stands between it and the `:` (see
7781
+ * `addColonEdit`). A statement with a comment or a directive, a line break in
7782
+ * a style, or on a line with a `;` of its own stays as written (see
7783
+ * `styleUnitsCanCompact`).
7784
+ */
7785
+ function styleColonEdits(source, statement, end) {
7786
+ const styles = statement.styles.filter((style) => style.range[1] <= end);
7787
+ if (!styleUnitsCanCompact(source, statement.range[0], end, styles)) return [];
7788
+ const edits = [];
7789
+ for (const style of styles) {
7790
+ addColonEdit(source, style.range, edits, { keepsGapAfterStroke: true });
7791
+ addWordGapEdits(source, style.range, edits);
7792
+ }
7793
+ return edits;
7794
+ }
7795
+ /**
7221
7796
  * Where a statement is printed to: its range, except for a one-line
7222
7797
  * accessibility statement, which leaves out the whitespace at the end of its
7223
7798
  * value. That whitespace is then the gap before a directive that follows the
@@ -7361,12 +7936,29 @@ function printLine$7(source, options, layout, depth) {
7361
7936
  continuation: indentationOf(options, depth + 1)
7362
7937
  }).doc;
7363
7938
  }
7939
+ /** The lists of statements that the node holds, the diagram included. */
7940
+ function statementListsOf$3(node) {
7941
+ if (node.type === "UsecaseDiagram") return [{
7942
+ head: node.range[0],
7943
+ statements: node.body
7944
+ }];
7945
+ const classified = classifyUsecaseStatement(node);
7946
+ return classified?.kind === "boundary" ? [{
7947
+ head: node.range[0],
7948
+ statements: classified.statement.body
7949
+ }] : [];
7950
+ }
7951
+ /** Whether the node holds statements of its own. */
7952
+ function holdsStatements$4(node) {
7953
+ return statementListsOf$3(node).length > 0;
7954
+ }
7364
7955
  /** Only system boundaries contain declaration bodies (docs/usecase.md). */
7365
7956
  function printStatements(source, options, statements, depth, bounds) {
7366
7957
  const rules = {
7367
7958
  kept: findUsecaseKeptLines(source),
7368
7959
  printedEnd: (statement) => findUsecasePrintedEnd(source, statement),
7369
- holdsStatements: (statement) => classifyUsecaseStatement(statement).kind === "boundary",
7960
+ holdsStatements: holdsStatements$4,
7961
+ writtenIndentationOf: writtenIndentationRule(source, options.useTabs, statementListsOf$3),
7370
7962
  isDroppedAtTopLevel: () => false,
7371
7963
  keepsWhitespaceLineAfterComment: false,
7372
7964
  keepsDirectiveLinesUnindented: false,
@@ -7378,7 +7970,9 @@ function printStatements(source, options, statements, depth, bounds) {
7378
7970
  if (classified.kind === "simple") return printLine$7(source, options, formatDataBlocks(source, layoutUsecaseStatement(source, statement, statement.range[1]), statement.range, {
7379
7971
  kept: rules.kept,
7380
7972
  statement: indentationOf(options, depth),
7381
- tabWidth: options.tabWidth
7973
+ tabWidth: options.tabWidth,
7974
+ useTabs: options.useTabs,
7975
+ statementListsOf: statementListsOf$3
7382
7976
  }), depth);
7383
7977
  const boundary = classified.statement;
7384
7978
  const end = usecaseBoundaryHeaderEnd(source, boundary);
@@ -8054,7 +8648,7 @@ const DIRECTION_VALUES = [
8054
8648
  "TD"
8055
8649
  ];
8056
8650
  /** The graph containers whose body is visited by the shared line rules. */
8057
- function holdsStatements(statement) {
8651
+ function holdsStatements$3(statement) {
8058
8652
  return statement.type === "FlowchartSubgraphStatement" || statement.type === "AgentflowFlowStatement" || statement.type === "AgentflowGlobalStatement";
8059
8653
  }
8060
8654
  /**
@@ -8073,7 +8667,7 @@ function holdsStatements(statement) {
8073
8667
  function findStyleLinesWithLineSeparators(source, statements) {
8074
8668
  const lines = [];
8075
8669
  for (const statement of statements) {
8076
- if (holdsStatements(statement)) {
8670
+ if (holdsStatements$3(statement)) {
8077
8671
  appendItems(lines, findStyleLinesWithLineSeparators(source, statement.body));
8078
8672
  continue;
8079
8673
  }
@@ -8178,7 +8772,7 @@ function findLinesAfterWords(source, statements, words) {
8178
8772
  */
8179
8773
  function collectLineRanges(statements) {
8180
8774
  const ranges = [];
8181
- for (const statement of statements) if (holdsStatements(statement)) {
8775
+ for (const statement of statements) if (holdsStatements$3(statement)) {
8182
8776
  if (statement.type !== "AgentflowGlobalStatement" && statement.title === null && statement.name !== null) ranges.push(statement.name.range);
8183
8777
  appendItems(ranges, collectLineRanges(statement.body));
8184
8778
  } else if (statement.type !== "FlowchartEmptyStatement" && statement.type !== "AgentflowEmptyStatement") ranges.push(statement.range);
@@ -8202,7 +8796,7 @@ function collectLineRanges(statements) {
8202
8796
  function findLinesAfterEmptyStyle(source, statements) {
8203
8797
  const lines = [];
8204
8798
  for (const [index, statement] of statements.entries()) {
8205
- if (holdsStatements(statement)) {
8799
+ if (holdsStatements$3(statement)) {
8206
8800
  appendItems(lines, findLinesAfterEmptyStyle(source, statement.body));
8207
8801
  continue;
8208
8802
  }
@@ -8268,7 +8862,7 @@ function findDirectionValueStart(text, offset) {
8268
8862
  /** The ranges of the direction statements, at every depth. */
8269
8863
  function collectDirectionStatementRanges(statements) {
8270
8864
  const ranges = [];
8271
- for (const statement of statements) if (holdsStatements(statement)) appendItems(ranges, collectDirectionStatementRanges(statement.body));
8865
+ for (const statement of statements) if (holdsStatements$3(statement)) appendItems(ranges, collectDirectionStatementRanges(statement.body));
8272
8866
  else if (statement.type === "FlowchartDirectionStatement" || statement.type === "AgentflowDirectionStatement") ranges.push(statement.range);
8273
8867
  return ranges;
8274
8868
  }
@@ -8832,7 +9426,8 @@ function layoutStatement$1(source, statement, end, preservesDescriptionColumns)
8832
9426
  isLinkStyle,
8833
9427
  joinsStyles: isLinkStyle,
8834
9428
  keepsGapAfterStroke: statement.type !== "AgentflowStyleStatement",
8835
- escapesComma: statement.type === "AgentflowClassDefStatement"
9429
+ escapesComma: statement.type === "AgentflowClassDefStatement",
9430
+ collapsesWordGaps: true
8836
9431
  });
8837
9432
  return {
8838
9433
  ...keptAsWritten(start, end),
@@ -8913,7 +9508,9 @@ function printAgentflow(path, options, print, source) {
8913
9508
  return printAtoms(source, formatDataBlocks(source, layoutStatement$1(source, statement, findPrintedEnd$1(source, statement), depth > 1), statement.range, {
8914
9509
  kept: findAgentflowKeptLines(source),
8915
9510
  statement: indentationOf(bodyOptions, depth),
8916
- tabWidth: options.tabWidth
9511
+ tabWidth: options.tabWidth,
9512
+ useTabs: options.useTabs,
9513
+ statementListsOf: statementListsOf$2
8917
9514
  }), {
8918
9515
  statement: indentationOf(bodyOptions, depth),
8919
9516
  continuation: indentationOf(bodyOptions, depth + 1)
@@ -8931,12 +9528,28 @@ function printDiagram$4(path, options, print, source, diagram) {
8931
9528
  start: headerEnd,
8932
9529
  end: source.text.length,
8933
9530
  isTopLevel: true
8934
- }, agentflowBlockRules(source));
9531
+ }, agentflowBlockRules(source, options));
8935
9532
  return printDiagramBlock(source, openingLine(printAtoms(source, layoutGraphHeader(source, diagram, headerEnd), {
8936
9533
  statement: "",
8937
9534
  continuation: indentationOf(options, 1)
8938
9535
  }).doc, block, false), block, options);
8939
9536
  }
9537
+ /** The lists of statements that the node holds, the diagram included. */
9538
+ function statementListsOf$2(node) {
9539
+ if (node.type === "AgentflowDiagram") return [{
9540
+ head: node.range[0],
9541
+ statements: node.body
9542
+ }];
9543
+ const classified = classifyAgentflowStatement(node);
9544
+ return classified?.kind === "container" ? [{
9545
+ head: node.range[0],
9546
+ statements: classified.statement.body
9547
+ }] : [];
9548
+ }
9549
+ /** Whether the node holds statements of its own. */
9550
+ function holdsStatements$2(node) {
9551
+ return statementListsOf$2(node).length > 0;
9552
+ }
8940
9553
  /**
8941
9554
  * Prints a container: the `flow` or `global` line, the statements one level deeper,
8942
9555
  * and the `end` line.
@@ -8950,11 +9563,14 @@ function printContainer(path, options, print, source, container, tabWidth) {
8950
9563
  start: headerEnd,
8951
9564
  end: endKeyword.range[0],
8952
9565
  isTopLevel: false
8953
- }, agentflowBlockRules(source));
9566
+ }, agentflowBlockRules(source, options));
8954
9567
  const headerDoc = printAtoms(source, formatDataBlocks(source, layoutContainerHeader(source, container, headerEnd), [container.range[0], headerEnd], {
8955
9568
  kept: findAgentflowKeptLines(source),
8956
9569
  statement: indentationOf(options, depth),
8957
- tabWidth
9570
+ tabWidth,
9571
+ useTabs: options.useTabs,
9572
+ decidesIndentation: true,
9573
+ statementListsOf: statementListsOf$2
8958
9574
  }), {
8959
9575
  statement: indentationOf(options, depth),
8960
9576
  continuation: indentationOf(options, depth + 1)
@@ -8966,11 +9582,12 @@ function printContainer(path, options, print, source, container, tabWidth) {
8966
9582
  * statements, and a `;` of its own is dropped at the top level, where the
8967
9583
  * Db does not list it.
8968
9584
  */
8969
- function agentflowBlockRules(source) {
9585
+ function agentflowBlockRules(source, options) {
8970
9586
  return {
8971
9587
  kept: findAgentflowKeptLines(source),
8972
9588
  printedEnd: (statement) => findPrintedEnd$1(source, statement),
8973
- holdsStatements: (statement) => classifyAgentflowStatement(statement).kind === "container",
9589
+ holdsStatements: holdsStatements$2,
9590
+ writtenIndentationOf: writtenIndentationRule(source, options.useTabs, statementListsOf$2),
8974
9591
  isDroppedAtTopLevel: (statement) => statement.type === "AgentflowEmptyStatement",
8975
9592
  keepsWhitespaceLineAfterComment: false,
8976
9593
  dropsSeparatorsBeforeComments: true,
@@ -9178,14 +9795,74 @@ function startsInside(kept, atom) {
9178
9795
  return kept.some((stretch) => stretch.start <= atom.start && atom.start < stretch.end);
9179
9796
  }
9180
9797
  /**
9181
- * The layout of the `subgraph` line. A name without a title is printed
9182
- * with the whitespace after it, which mermaid.js reads as part of the name.
9798
+ * Whether the name of a subgraph without a title is one word: mermaid.js makes
9799
+ * the name the id of the subgraph, unless the text of the name holds
9800
+ * whitespace, which it reads with the trailing whitespace of the name. So the
9801
+ * whitespace after a name of one word decides whether the subgraph has the
9802
+ * name as its id or a generated id, while a name of several words has a
9803
+ * generated id either way (docs/flowchart.md, Subgraph header).
9804
+ */
9805
+ function isOneWord(name) {
9806
+ return ![...name.value.trimEnd()].some((character) => character.trim() === "");
9807
+ }
9808
+ /**
9809
+ * The end of the header of a subgraph without a title whose name has several
9810
+ * words, when its line ends at `end`: the start of the directives that end the
9811
+ * line, if there are any, and `end` otherwise. Whitespace after a directive
9812
+ * makes mermaid.js read the directive as part of the name, so the token of the
9813
+ * name reaches over `S1 S2 %%{x}%% `, while without that whitespace the name
9814
+ * ends before the directive. The whitespace at the end of the name of several
9815
+ * words decides nothing, so both are laid out as a name that ends before the
9816
+ * directives, and a second formatting finds the text it has printed (docs/
9817
+ * flowchart.md, Subgraph header). A name of one word keeps its whitespace.
9818
+ */
9819
+ function findSeveralWordsHeaderEnd(source, subgraph, end) {
9820
+ if (subgraph.title !== null || isOneWord(subgraph.name)) return end;
9821
+ let position = end;
9822
+ let directivesStart = end;
9823
+ while (position > subgraph.name.range[0]) {
9824
+ while (position > subgraph.name.range[0] && isSpaceOrTab(source.text[position - 1])) position--;
9825
+ const directive = findDirectiveEndingAt(source, position);
9826
+ if (directive === void 0) break;
9827
+ position = directive.range[0];
9828
+ directivesStart = position;
9829
+ }
9830
+ return directivesStart;
9831
+ }
9832
+ /**
9833
+ * Whether the line of the header of `subgraph` ends at `offset`, apart from a
9834
+ * `;` that is dropped: an ignored one, or the one that ends the header, on a
9835
+ * line that is not kept with its `;` (see `findFlowchartKeptLines`).
9836
+ */
9837
+ function endsLine(source, subgraph, offset) {
9838
+ let next = offset;
9839
+ while (isSpaceOrTab(source.text[next])) next++;
9840
+ const character = source.text[next];
9841
+ if (character === void 0 || character === "\n" || character === "\r") return true;
9842
+ if (character !== ";") return false;
9843
+ const kept = findFlowchartKeptLines(source);
9844
+ const line = lineStartOf(source, next);
9845
+ return !kept.joined.has(line) && !kept.verbatim.has(line) && (isDroppedSemicolon(source, next) || subgraph.body[0] === void 0 || next < subgraph.body[0].range[0]);
9846
+ }
9847
+ /**
9848
+ * The layout of the `subgraph` line. A name of one word without a title is
9849
+ * printed with the whitespace after it, which mermaid.js reads as part of the
9850
+ * name; the whitespace at the end of the line of a name of several words
9851
+ * decides nothing and is left out.
9183
9852
  */
9184
9853
  function layoutSubgraphHeader(source, subgraph, headerEnd) {
9185
9854
  if (holdsJoiningRegion(source, subgraph.range[0], headerEnd)) return keptAsWritten(subgraph.range[0], headerEnd);
9855
+ let keptEnd = headerEnd;
9856
+ let runStart;
9857
+ if (subgraph.title === null && !isOneWord(subgraph.name)) {
9858
+ let position = headerEnd;
9859
+ while (position > subgraph.name.range[0] && isSpaceOrTab(source.text[position - 1])) position--;
9860
+ if (endsLine(source, subgraph, headerEnd)) keptEnd = position;
9861
+ else if (position < headerEnd && !isWhitespace(source.text[position - 1])) runStart = position;
9862
+ }
9186
9863
  const kept = subgraph.title === null ? [{
9187
9864
  start: subgraph.name.range[0],
9188
- end: headerEnd
9865
+ end: keptEnd
9189
9866
  }] : [];
9190
9867
  const values = subgraph.title === null ? [] : [subgraph.name, subgraph.title];
9191
9868
  const rules = /* @__PURE__ */ new Map();
@@ -9193,8 +9870,13 @@ function layoutSubgraphHeader(source, subgraph, headerEnd) {
9193
9870
  rules.set(expectToken(findStructuralToken(source, subgraph.name.range[1]), "the `[` before the title of a subgraph").range[0], "none");
9194
9871
  addHeadingTitleRules(source, subgraph.title, rules);
9195
9872
  }
9873
+ const atoms = collectAtoms(source, subgraph.range[0], keptEnd, values, kept).filter((atom) => kept.includes(atom) || !startsInside(kept, atom));
9874
+ if (runStart !== void 0) replaceInAtoms(source, atoms, [{
9875
+ range: [runStart, keptEnd],
9876
+ replacement: " "
9877
+ }]);
9196
9878
  return {
9197
- atoms: collectAtoms(source, subgraph.range[0], headerEnd, values, kept).filter((atom) => kept.includes(atom) || !startsInside(kept, atom)),
9879
+ atoms,
9198
9880
  rules,
9199
9881
  outdented: /* @__PURE__ */ new Set(),
9200
9882
  lineBreaks: "kept"
@@ -9229,7 +9911,8 @@ function layoutStatement(source, statement, end, preservesDescriptionColumns) {
9229
9911
  isLinkStyle,
9230
9912
  joinsStyles: isLinkStyle,
9231
9913
  keepsGapAfterStroke: statement.type !== "FlowchartStyleStatement",
9232
- escapesComma: statement.type === "FlowchartClassDefStatement"
9914
+ escapesComma: statement.type === "FlowchartClassDefStatement",
9915
+ collapsesWordGaps: true
9233
9916
  });
9234
9917
  }
9235
9918
  if (statement.type !== "FlowchartAccDescrBlockStatement") return layout;
@@ -9365,7 +10048,9 @@ function printFlowchart(path, options, print, source) {
9365
10048
  return printAtoms(source, formatDataBlocks(source, layoutStatement(source, statement, findPrintedEnd(source, statement), depth > 1), statement.range, {
9366
10049
  kept: findFlowchartKeptLines(source),
9367
10050
  statement: indentationOf(bodyOptions, depth),
9368
- tabWidth: options.tabWidth
10051
+ tabWidth: options.tabWidth,
10052
+ useTabs: options.useTabs,
10053
+ statementListsOf: statementListsOf$1
9369
10054
  }), {
9370
10055
  statement: indentationOf(bodyOptions, depth),
9371
10056
  continuation: indentationOf(bodyOptions, depth + 1)
@@ -9385,7 +10070,7 @@ function printDiagram$3(path, options, print, source, diagram) {
9385
10070
  start: headerEnd,
9386
10071
  end: source.text.length,
9387
10072
  isTopLevel: true
9388
- }, flowchartBlockRules(source));
10073
+ }, flowchartBlockRules(source, options));
9389
10074
  return printDiagramBlock(source, openingLine(printAtoms(source, layoutGraphHeader(source, diagram, headerEnd), {
9390
10075
  statement: "",
9391
10076
  continuation: indentationOf(options, 1)
@@ -9404,23 +10089,35 @@ function printSubgraph(path, options, print, source, subgraph) {
9404
10089
  start: headerEnd,
9405
10090
  end: endKeyword.range[0],
9406
10091
  isTopLevel: false
9407
- }, flowchartBlockRules(source));
10092
+ }, flowchartBlockRules(source, options));
9408
10093
  const headerDoc = printAtoms(source, layoutSubgraphHeader(source, subgraph, headerEnd), {
9409
10094
  statement: indentationOf(options, depth),
9410
10095
  continuation: indentationOf(options, depth + 1)
9411
10096
  }).doc;
9412
10097
  return printClosedBlock(openingLine(headerDoc, block, endsWithSpaceOrTab(source.text.slice(subgraph.range[0], headerEnd))), block, endKeyword.value, depth, options);
9413
10098
  }
10099
+ /** The lists of statements that the node holds, the diagram included. */
10100
+ function statementListsOf$1(node) {
10101
+ return node.type === "FlowchartDiagram" || node.type === "FlowchartSubgraphStatement" ? [{
10102
+ head: node.range[0],
10103
+ statements: node.body
10104
+ }] : [];
10105
+ }
10106
+ /** Whether the node holds statements of its own. */
10107
+ function holdsStatements$1(node) {
10108
+ return statementListsOf$1(node).length > 0;
10109
+ }
9414
10110
  /**
9415
10111
  * The block rules of a flowchart (see `BlockRules`): a subgraph holds
9416
10112
  * statements, and a `;` of its own is dropped at the top level, where the
9417
10113
  * Db does not list it.
9418
10114
  */
9419
- function flowchartBlockRules(source) {
10115
+ function flowchartBlockRules(source, options) {
9420
10116
  return {
9421
10117
  kept: findFlowchartKeptLines(source),
9422
10118
  printedEnd: (statement) => findPrintedEnd(source, statement),
9423
- holdsStatements: (statement) => statement.type === "FlowchartSubgraphStatement",
10119
+ holdsStatements: holdsStatements$1,
10120
+ writtenIndentationOf: writtenIndentationRule(source, options.useTabs, statementListsOf$1),
9424
10121
  isDroppedAtTopLevel: (statement) => statement.type === "FlowchartEmptyStatement",
9425
10122
  keepsWhitespaceLineAfterComment: false,
9426
10123
  keepsDirectiveLinesUnindented: false
@@ -9468,7 +10165,7 @@ function findSubgraphHeaderEnd(source, subgraph) {
9468
10165
  const semicolon = findSemicolonOnLaterLine(source, subgraph);
9469
10166
  if (semicolon !== void 0) return semicolon.range[1];
9470
10167
  const { range } = subgraph.name;
9471
- return Math.min(range[1], lineEndOf(source, range[1] - 1));
10168
+ return findSeveralWordsHeaderEnd(source, subgraph, Math.min(range[1], lineEndOf(source, range[1] - 1)));
9472
10169
  }
9473
10170
  /**
9474
10171
  * The level of the lines of the statement at `path`: 1 at the top level, one
@@ -9478,6 +10175,128 @@ function depthOf$2(path) {
9478
10175
  return 1 + path.ancestors.filter((ancestor) => ancestor.type === "FlowchartSubgraphStatement").length;
9479
10176
  }
9480
10177
  //#endregion
10178
+ //#region src/printers/gantt-alignment.ts
10179
+ const alignmentBySource = /* @__PURE__ */ new WeakMap();
10180
+ /**
10181
+ * The column, counted from the start of the name, at which the printer puts the
10182
+ * colon of a task, for the tasks whose colons it moves: the tasks of a section
10183
+ * where a name has padding before its colon (more than one whitespace
10184
+ * character, or a tab), whether the colons are in one column or not
10185
+ * (docs/gantt.md, Task data). Mermaid keeps the whitespace before the colon in
10186
+ * the name of the task, and draws the same figure (docs/compatibility.md,
10187
+ * Texts after a keyword that are drawn the same).
10188
+ *
10189
+ * The column of such a section is one space after its longest name. The
10190
+ * sections with padding whose colons are all in one and the same column go
10191
+ * together: they share the column of one space after the longest of their
10192
+ * longest names, and a section whose colons are not all in one column is alone.
10193
+ * A section whose names are all followed by one space, with its colons in the
10194
+ * column of a group, is part of the group's longest name too, since it is what
10195
+ * a section with padding becomes when its padding goes, but its lines are not
10196
+ * changed. The tasks before the first `section` are a section of their own and
10197
+ * share nothing, as they stand one level less deep. A section is left as it is
10198
+ * where the aligned lines would be longer than `printWidth` and longer than
10199
+ * they are, which only a section whose colons are not all in one column can
10200
+ * come to: the colons of a group stand at least one space after its longest
10201
+ * name, so its lines only get shorter. A chart that holds `white-space` is left
10202
+ * as it is, since its CSS may draw the whitespace.
10203
+ *
10204
+ * A task is no part of a section's tasks where the printer prints its line as
10205
+ * written, where it runs over lines, where something stands before it on its
10206
+ * line, or where its name ends with a directive. A section where a name holds a
10207
+ * tab is left as it is: a tab reaches the next tab stop of the editor, so no
10208
+ * width that Prettier counts lines the colons up. The width of a name, and of
10209
+ * the rest of the line, is the width as written, so a directive in the name
10210
+ * counts, as the colons are lined up in the text.
10211
+ */
10212
+ function findColonColumns(source, statements, kept, options) {
10213
+ const cached = alignmentBySource.get(source);
10214
+ if (cached !== void 0 && cached.printWidth === options.printWidth && cached.tabWidth === options.tabWidth) return cached.columns;
10215
+ const columns = /* @__PURE__ */ new Map();
10216
+ alignmentBySource.set(source, {
10217
+ printWidth: options.printWidth,
10218
+ tabWidth: options.tabWidth,
10219
+ columns
10220
+ });
10221
+ if (holdsWhiteSpaceProperty(source)) return columns;
10222
+ /** Sets the column of the tasks of the sections, where every line fits. */
10223
+ function align(sections, column, depth) {
10224
+ const indentWidth = depth * options.tabWidth;
10225
+ if (!sections.every((section) => section.every((row) => {
10226
+ const longer = indentWidth + column + row.widthFromColon;
10227
+ return longer <= options.printWidth || longer <= indentWidth + row.column + row.widthFromColon;
10228
+ }))) return;
10229
+ for (const section of sections) for (const row of section) columns.set(row.task, column);
10230
+ }
10231
+ const [before, ...after] = findSections(source, statements, kept);
10232
+ if (isPadded(before)) align([before], longestName(before) + 1, 1);
10233
+ const padded = after.filter(isPadded);
10234
+ const grouped = /* @__PURE__ */ new Set();
10235
+ for (const section of padded) {
10236
+ if (grouped.has(section)) continue;
10237
+ const column = commonColumn(section);
10238
+ const group = column === null ? [section] : padded.filter((other) => commonColumn(other) === column);
10239
+ for (const member of group) grouped.add(member);
10240
+ const unchanged = column === null ? [] : after.filter((other) => !isPadded(other) && isSingleSpaced(other) && commonColumn(other) === column);
10241
+ align(group, maxOf([...group, ...unchanged].map(longestName)) + 1, 2);
10242
+ }
10243
+ return columns;
10244
+ }
10245
+ /** Whether a name of a section has padding before its colon. */
10246
+ function isPadded(section) {
10247
+ return section.some((row) => row.padded);
10248
+ }
10249
+ /** Whether every name of a section is followed by one space. */
10250
+ function isSingleSpaced(section) {
10251
+ return section.every((row) => row.column - row.nameWidth === 1);
10252
+ }
10253
+ /** The width of the longest name of a section. */
10254
+ function longestName(section) {
10255
+ return maxOf(section.map((row) => row.nameWidth));
10256
+ }
10257
+ /** The column that every row has for its colon, or null. */
10258
+ function commonColumn(rows) {
10259
+ const first = rows.at(0);
10260
+ return first !== void 0 && rows.every((row) => row.column === first.column) ? first.column : null;
10261
+ }
10262
+ /**
10263
+ * The task lines of the chart that the printer may align, in groups: the tasks
10264
+ * before the first `section`, and the tasks of each `section` (a group with no
10265
+ * such task, or where a name holds a tab, is left out, but the first group is
10266
+ * kept in its place, empty).
10267
+ */
10268
+ function findSections(source, statements, kept) {
10269
+ const sections = [[]];
10270
+ for (const statement of statements) if (statement.type === "GanttSectionStatement") sections.push([]);
10271
+ else if (statement.type === "GanttTaskStatement") {
10272
+ const row = toRow(source, statement, kept.verbatim);
10273
+ if (row !== null) sections.at(-1).push(row);
10274
+ }
10275
+ return sections.map((rows) => rows.some((row) => row.holdsTab) ? [] : rows).filter((rows, index) => index === 0 || rows.length > 0);
10276
+ }
10277
+ /** The row of a task whose line the printer may align, or null. */
10278
+ function toRow(source, task, verbatimLines) {
10279
+ const lineStart = lineStartOf(source, task.range[0]);
10280
+ if (verbatimLines.has(lineStart) || source.text.slice(task.range[0], task.range[1]).includes("\n") || !isFirstOnItsLine(source, task.range[0])) return null;
10281
+ const [from, colon] = task.description.range;
10282
+ if (source.text[colon] !== ":") return null;
10283
+ let nameEnd = colon;
10284
+ while (nameEnd > from && isSpaceOrTab(source.text[nameEnd - 1])) nameEnd--;
10285
+ if (nameEnd === from || findTriviaBetween(source, from, nameEnd).some((item) => item.range[1] === nameEnd)) return null;
10286
+ const padding = source.text.slice(nameEnd, colon);
10287
+ const nameWidth = util.getStringWidth(source.text.slice(from, nameEnd));
10288
+ let dataEnd = lineEndOf(source, colon);
10289
+ while (dataEnd > colon && isSpaceOrTab(source.text[dataEnd - 1])) dataEnd--;
10290
+ return {
10291
+ task,
10292
+ nameWidth,
10293
+ column: nameWidth + padding.length,
10294
+ padded: padding !== "" && padding !== " ",
10295
+ holdsTab: source.text.slice(from, nameEnd).includes(" "),
10296
+ widthFromColon: util.getStringWidth(source.text.slice(colon, dataEnd))
10297
+ };
10298
+ }
10299
+ //#endregion
9481
10300
  //#region src/printers/gantt-layout.ts
9482
10301
  /**
9483
10302
  * The node types of a Gantt chart whose text is a value, printed as written:
@@ -9560,8 +10379,10 @@ function isAtLineEnd$1(source, offset) {
9560
10379
  * (docs/gantt.md, Multi-line statements).
9561
10380
  * - The rules of the gaps are those of docs/gantt.md: Task data, Settings,
9562
10381
  * Lists, Click statements, and Accessibility statements.
10382
+ * - The whitespace after the name of a task is printed so that its colon
10383
+ * stands in the column that `colonColumns` gives (see `findColonColumns`).
9563
10384
  */
9564
- function layoutGanttStatement(source, statement, end) {
10385
+ function layoutGanttStatement(source, statement, end, colonColumns) {
9565
10386
  const start = statement.range[0];
9566
10387
  if (statement.type === "GanttAccDescrBlockStatement") return layoutDescriptionBlock(source, statement, end, ganttValueNodeTypes);
9567
10388
  const keptBreaks = findKeptBreaks(source, start, end);
@@ -9571,6 +10392,7 @@ function layoutGanttStatement(source, statement, end) {
9571
10392
  const atoms = collectAtoms(source, start, end, collectValueNodes(statement, ganttValueNodeTypes), findCallArgumentsStretches(source, statement));
9572
10393
  trimTextAfterKeyword(source, atoms, textAfterKeyword(source, statement)?.range ?? null, statement.type === "GanttTitleStatement");
9573
10394
  if (statement.type === "GanttClickStatement") normalizeCallArguments(source, atoms, statement.call?.args?.range ?? null);
10395
+ if (statement.type === "GanttTaskStatement") alignColon(source, statement, atoms, colonColumns);
9574
10396
  const remainder = findBlankRemainder$1(source, statement);
9575
10397
  if (remainder !== null) atoms.push(remainder);
9576
10398
  return {
@@ -9581,6 +10403,23 @@ function layoutGanttStatement(source, statement, end) {
9581
10403
  };
9582
10404
  }
9583
10405
  /**
10406
+ * Prints the whitespace between the name of a task and its colon as the spaces
10407
+ * that put the colon in its column, where `colonColumns` has one for the task
10408
+ * (docs/gantt.md, Task data).
10409
+ */
10410
+ function alignColon(source, task, atoms, colonColumns) {
10411
+ const column = colonColumns.get(task);
10412
+ if (column === void 0) return;
10413
+ const [from, colon] = task.description.range;
10414
+ let nameEnd = colon;
10415
+ while (nameEnd > from && isSpaceOrTab(source.text[nameEnd - 1])) nameEnd--;
10416
+ const nameWidth = util.getStringWidth(source.text.slice(from, nameEnd));
10417
+ replaceInAtoms(source, atoms, [{
10418
+ range: [nameEnd, colon],
10419
+ replacement: " ".repeat(column - nameWidth)
10420
+ }]);
10421
+ }
10422
+ /**
9584
10423
  * The text after the keyword of a statement whose whitespace at the start
9585
10424
  * mermaid.js leaves out of the figure (docs/compatibility.md, Texts after a
9586
10425
  * keyword that are drawn the same): a title, a date format, an axis format.
@@ -9800,7 +10639,7 @@ function findStatementsAfterSection(statements, isSection) {
9800
10639
  }
9801
10640
  /** Prints a statement on its lines, at the level that the section decides. */
9802
10641
  function printStatement(diagram, source, options, statement, isDeeper) {
9803
- const printed = printLine$5(source, options, diagram.layoutStatement(source, statement, statement.range[1]), isDeeper ? 2 : 1);
10642
+ const printed = printLine$5(source, options, diagram.layoutStatement(source, statement, statement.range[1], options), isDeeper ? 2 : 1);
9804
10643
  return isDeeper ? indent$1(printed) : printed;
9805
10644
  }
9806
10645
  /** Prints a statement laid out on its lines at `depth`. */
@@ -9843,7 +10682,7 @@ const ganttDiagram = {
9843
10682
  keptLines: findGanttKeptLines,
9844
10683
  printedEnd: findGanttPrintedEnd,
9845
10684
  layoutHeader: layoutKeywordHeader,
9846
- layoutStatement: layoutGanttStatement,
10685
+ layoutStatement: (source, statement, end, options) => layoutGanttStatement(source, statement, end, findColonColumns(source, source.root.body.type === "GanttDiagram" ? source.root.body.body : [], findGanttKeptLines(source), options)),
9847
10686
  readsCommentsByWhitespaceBefore: true
9848
10687
  };
9849
10688
  /**
@@ -10603,6 +11442,9 @@ function printKanban(path, options, _print, source) {
10603
11442
  kept: findKanbanKeptLines(source),
10604
11443
  statement: (options.useTabs ? " " : " ").repeat(significantIndentationOf(options, 1).length * line.depth),
10605
11444
  tabWidth: options.tabWidth,
11445
+ useTabs: options.useTabs,
11446
+ decidesIndentation: true,
11447
+ statementListsOf: () => [],
10606
11448
  wholeLine: true
10607
11449
  }), {
10608
11450
  statement: "",
@@ -12159,7 +13001,9 @@ function printSequence(path, options, print, source) {
12159
13001
  return printAtoms(source, formatDataBlocks(source, layoutSequenceStatement(source, statement, findSequencePrintedEnd(source, statement)), statement.range, {
12160
13002
  kept: findSequenceKeptLines(source),
12161
13003
  statement: indentationOf(options, depth),
12162
- tabWidth: options.tabWidth
13004
+ tabWidth: options.tabWidth,
13005
+ useTabs: options.useTabs,
13006
+ statementListsOf
12163
13007
  }), {
12164
13008
  statement: indentationOf(options, depth),
12165
13009
  continuation: indentationOf(options, depth + 1)
@@ -12180,7 +13024,7 @@ function printDiagram$1(path, options, print, source, diagram) {
12180
13024
  start: headerEnd,
12181
13025
  end: source.text.length,
12182
13026
  isTopLevel: true
12183
- }, sequenceBlockRules(source));
13027
+ }, sequenceBlockRules(source, options));
12184
13028
  return printDiagramBlock(source, openingLine(printAtoms(source, layoutSequenceHeader(source, keyword), {
12185
13029
  statement: "",
12186
13030
  continuation: indentationOf(options, 1)
@@ -12236,7 +13080,7 @@ function openBlock(source, options, docs, statements, opening, depth) {
12236
13080
  start: headerEnd,
12237
13081
  end: opening.end,
12238
13082
  isTopLevel: false
12239
- }, sequenceBlockRules(source));
13083
+ }, sequenceBlockRules(source, options));
12240
13084
  return {
12241
13085
  header: openingLine(printAtoms(source, layoutBlockHeader(source, opening.start, headerEnd, opening.text), {
12242
13086
  statement: indentationOf(options, depth),
@@ -12245,15 +13089,39 @@ function openBlock(source, options, docs, statements, opening, depth) {
12245
13089
  block
12246
13090
  };
12247
13091
  }
13092
+ /** The lists of statements that the node holds, the diagram included. */
13093
+ function statementListsOf(node) {
13094
+ if (node.type === "SequenceDiagram") return [{
13095
+ head: node.range[0],
13096
+ statements: node.body
13097
+ }];
13098
+ const classified = classifySequenceStatement(node);
13099
+ switch (classified?.kind) {
13100
+ case "body": return [{
13101
+ head: node.range[0],
13102
+ statements: classified.statement.body
13103
+ }];
13104
+ case "sections": return classified.statement.sections.map((section) => ({
13105
+ head: section.range[0],
13106
+ statements: section.body
13107
+ }));
13108
+ default: return [];
13109
+ }
13110
+ }
13111
+ /** Whether the node holds statements of its own. */
13112
+ function holdsStatements(node) {
13113
+ return statementListsOf(node).length > 0;
13114
+ }
12248
13115
  /**
12249
13116
  * The block rules of a sequence diagram (see `BlockRules`): the blocks and
12250
13117
  * boxes hold statements, and no statement is dropped.
12251
13118
  */
12252
- function sequenceBlockRules(source) {
13119
+ function sequenceBlockRules(source, options) {
12253
13120
  return {
12254
13121
  kept: findSequenceKeptLines(source),
12255
13122
  printedEnd: (statement) => findSequencePrintedEnd(source, statement),
12256
- holdsStatements: (statement) => classifySequenceStatement(statement).kind !== "simple",
13123
+ holdsStatements,
13124
+ writtenIndentationOf: writtenIndentationRule(source, options.useTabs, statementListsOf),
12257
13125
  isDroppedAtTopLevel: () => false,
12258
13126
  keepsWhitespaceLineAfterComment: false,
12259
13127
  keepsDirectiveLinesUnindented: false
@@ -12596,7 +13464,7 @@ function layoutStateStatement(source, statement, end, followsStateName, noteInde
12596
13464
  });
12597
13465
  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);
12598
13466
  replaceInAtoms(source, atoms, secondDescriptionEndEdits(source, statement, end));
12599
- if ((statement.type === "StateClassDefStatement" || statement.type === "StateStyleStatement") && !spansKeptBreaks(source, keptBreaks, start, end)) normalizeStyleList(source, atoms, statement);
13467
+ if ((statement.type === "StateClassDefStatement" || statement.type === "StateStyleStatement") && !spansKeptBreaks(source, keptBreaks, start, end)) normalizeStyleList(source, atoms, statement, { collapsesWordGaps: true });
12600
13468
  return {
12601
13469
  atoms: keepFirstGapLineTails(source, atoms, (from, to) => gapKeepsLineBreak(source, keptBreaks, from, to)),
12602
13470
  rules: statementRules$1(source, statement),
@@ -14054,10 +14922,17 @@ function findDroppedSemicolonStretches(source, statement) {
14054
14922
  const end = statement.range[1];
14055
14923
  const semicolon = endingSemicolonOf(source, statement.range, statement.style);
14056
14924
  if (semicolon === void 0 || !isDroppedSemicolon(source, semicolon)) return [];
14925
+ let styleEnd = semicolon;
14926
+ while (styleEnd > start && isWhitespace(source.text[styleEnd - 1])) styleEnd--;
14927
+ const style = [{
14928
+ start,
14929
+ end: styleEnd
14930
+ }];
14931
+ normalizeTreemapStyle(source, style, statement, styleEnd);
14057
14932
  return [{
14058
14933
  start,
14059
14934
  end,
14060
- doc: printAsWrittenTrimmed(source, start, semicolon)
14935
+ doc: style[0].doc ?? printAsWrittenTrimmed(source, start, semicolon)
14061
14936
  }];
14062
14937
  }
14063
14938
  /**
@@ -14144,14 +15019,48 @@ function layoutTreemapStatement(source, statement, column, continuationPadding)
14144
15019
  }
14145
15020
  default: throw new Error(`prettier-plugin-mmd: unknown treemap item ${JSON.stringify(statement)}`);
14146
15021
  }
15022
+ const atoms = protectSemicolonPrefixes(source, start, end, layout.atoms.map((atom) => layout.outdented.has(atom.start) ? {
15023
+ ...atom,
15024
+ writtenIndentation: column
15025
+ } : atom));
15026
+ if (statement.type === "TreemapClassDefStatement") normalizeTreemapStyle(source, atoms, statement);
14147
15027
  return {
14148
15028
  ...layout,
14149
- atoms: protectSemicolonPrefixes(source, start, end, layout.atoms.map((atom) => layout.outdented.has(atom.start) ? {
14150
- ...atom,
14151
- writtenIndentation: column
14152
- } : atom))
15029
+ atoms
14153
15030
  };
14154
15031
  }
15032
+ /**
15033
+ * Prints the style of a `classDef` in the atoms as the styles of the other
15034
+ * diagram types are printed: the whitespace around the first `:` and the `,` of
15035
+ * each style, between the words of a style, and at the end of the style are
15036
+ * set. mermaid.js splits the style at the commas that no backslash escapes, and
15037
+ * takes the whitespace around the name and the value of each style away before
15038
+ * it draws (docs/treemap.md, Styles; docs/compatibility.md, Styles that are
15039
+ * drawn the same). An empty style between two commas, or after the last one,
15040
+ * stays as written (see `normalizeStyleList`), and so does a style that holds a
15041
+ * `;`, or that has a comment or a directive on its line: they may take part in
15042
+ * the line rule, and a second formatting must find the same. `styleEnd` is
15043
+ * where the style ends when a `;` that the printer drops ends it (see
15044
+ * `findDroppedSemicolonStretches`), so that the whitespace before that `;` and
15045
+ * what is dropped with it decide nothing.
15046
+ */
15047
+ function normalizeTreemapStyle(source, atoms, statement, styleEnd = statement.style?.range[1]) {
15048
+ const { style } = statement;
15049
+ if (style === null || styleEnd === void 0) return;
15050
+ const range = [style.range[0], styleEnd];
15051
+ if (source.text.slice(...range).includes(";") || findTriviaBetween(source, range[0], lineEndOf(source, range[0])).length > 0) return;
15052
+ normalizeStyleList(source, atoms, {
15053
+ range: [statement.range[0], styleEnd],
15054
+ styles: [{
15055
+ ...style,
15056
+ range
15057
+ }]
15058
+ }, {
15059
+ escapesComma: true,
15060
+ collapsesWordGaps: true,
15061
+ trimsEnd: true
15062
+ });
15063
+ }
14155
15064
  //#endregion
14156
15065
  //#region src/printers/treemap.ts
14157
15066
  /** Prints the nested section forest and named gaps in source order. */