prettier-plugin-mmd 0.1.0 → 0.2.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/README.ja.md CHANGED
@@ -184,8 +184,10 @@ flowchart LR
184
184
  - `useTabs` と `tabWidth` で字下げを決めます。
185
185
  既定は空白 2 つです。
186
186
  - `endOfLine` で改行コードを決めます。
187
- - `printWidth` は効きません。
188
- 行を折り返すことはありません。
187
+ - `printWidth` は図の改行位置を決めません。
188
+ `railroad-beta` の呼び出しは文法の構造に従います。
189
+ 詳細は[長い行](./docs/railroad.ja.md#長い行)を参照してください。
190
+ Markdown と YAML frontmatter には、Prettier が使う場合があります。
189
191
 
190
192
  ## 整形しない場合
191
193
 
@@ -209,16 +211,18 @@ flowchart LR
209
211
 
210
212
  ## 保証と制限
211
213
 
212
- - 整形で図は変わりません。
213
- mermaid.js は、整形の前と後で同じ図を読みます。
214
- - 例外が 1 つあります。
215
- `style`、`classDef`、`linkStyle` の行の末尾の空白を取り除きます。
214
+ - 次に記す空白の変更を除き、mermaid.js の読み取りを保ちます。
215
+ - `style`、`classDef`、`linkStyle` の行の末尾の空白を取り除きます。
216
216
  mermaid.js は、その空白を最後のスタイルの末尾に残します。
217
+ - `eventmodeling` の block data と note は、
218
+ [Data blocks](./docs/eventmodeling.ja.md#data-blocks) の規則で、
219
+ ASCII 空白の margin を限定的に変更します。
220
+ 描画を保ちながら、raw Db 値が変わる場合があります。
217
221
  - 整形した図をもう一度整形しても、何も変わりません。
218
222
  - ディレクティブ、不透明な `@{ ... }` のデータブロック、
219
223
  フロントマターの中身は検査しません。
220
224
  その中身のために mermaid.js が拒否する図も整形します。
221
- ディレクティブとデータブロックは書かれたまま残し、
225
+ ディレクティブと不透明な `@{ ... }` データブロックは書かれたまま残し、
222
226
  フロントマターは Prettier が YAML として読めるときだけ整形します。
223
227
  usecase の native metadata は構文として解析し、プロパティを検証します。
224
228
  - mermaid.js が許すより多くの辺を持つ flowchart は、mermaid.js は拒否しますが、
package/README.md CHANGED
@@ -145,7 +145,10 @@ flowchart LR
145
145
 
146
146
  - `useTabs` and `tabWidth` set the indentation. The default is two spaces.
147
147
  - `endOfLine` sets the line endings.
148
- - `printWidth` has no effect: lines are never wrapped.
148
+ - `printWidth` does not control diagram line breaks. `railroad-beta` calls
149
+ follow their grammar structure; see
150
+ [Long lines](./docs/railroad.md#long-lines). Prettier can still use it for
151
+ Markdown and YAML frontmatter.
149
152
 
150
153
  ## When a diagram is not formatted
151
154
 
@@ -164,16 +167,21 @@ flowchart LR
164
167
 
165
168
  ## Guarantees and limitations
166
169
 
167
- - Formatting does not change the diagram: mermaid.js reads the same diagram
168
- before and after.
169
- - One exception: whitespace at the end of a `style`, `classDef`, or `linkStyle`
170
- line is removed. mermaid.js keeps it at the end of the last style.
170
+ - Formatting preserves what mermaid.js reads, apart from the documented
171
+ whitespace changes below.
172
+ - Whitespace at the end of a `style`, `classDef`, or `linkStyle` line is
173
+ removed. mermaid.js keeps it at the end of the last style.
174
+ - For `eventmodeling` block data and notes, the
175
+ [Data blocks](./docs/eventmodeling.md#data-blocks) rule permits a restricted
176
+ ASCII space margin adjustment. This can change raw Db values while preserving
177
+ the rendered diagram.
171
178
  - Formatting a formatted diagram again changes nothing.
172
179
  - The content of directives, of opaque `@{ ... }` data blocks, and of the
173
180
  frontmatter is not checked. A diagram that mermaid.js rejects because of that
174
- content is still formatted. Directives and data blocks are kept as written;
175
- the frontmatter is formatted only when Prettier can read it as YAML. Native
176
- usecase metadata properties are parsed and validated as syntax.
181
+ content is still formatted. Directives and opaque `@{ ... }` data blocks are
182
+ kept as written; the frontmatter is formatted only when Prettier can read it
183
+ as YAML. Native usecase metadata properties are parsed and validated as
184
+ syntax.
177
185
  - A flowchart with more edges than mermaid.js allows, 500 by default (its
178
186
  `maxEdges` site setting), is rejected by mermaid.js but still formatted: the
179
187
  plugin does not know the site settings.
package/lib/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { parse, visitorKeys } from "@mmd-toolkit/parser";
2
2
  import { builders, printer, utils } from "prettier/doc";
3
+ import { util } from "prettier";
3
4
  //#region src/printers/collections.ts
4
5
  /**
5
6
  * Append the items in order to the existing array, as `target.push(...items)`
@@ -951,13 +952,13 @@ const { replaceEndOfLine: replaceEndOfLine$1 } = utils;
951
952
  * real comments, while still keeping them before directives.
952
953
  *
953
954
  * Throws when the gap holds any other text than whitespace, line
954
- * terminators, comments, directives, and `;` tokens: the tree places every
955
- * other token in a node, so such text means that the printer was given
956
- * wrong bounds.
955
+ * terminators, comments, directives, `;` tokens, and supplied opaque nodes:
956
+ * the tree places every other token in a node, so such text means that the
957
+ * printer was given wrong bounds.
957
958
  */
958
959
  function readGap(source, start, end, keepsSeparators, options = {}) {
959
960
  const { endsText = false, keepsInlineDirectivesWithPrevious = false, dropsSeparatorsBeforeComments = false } = options;
960
- const lines = scanLines(source, start, end, keepsSeparators, options.relocatedWhitespace ?? [], options.omitted ?? []);
961
+ const lines = scanLines(source, start, end, keepsSeparators, options.relocatedWhitespace ?? [], options.omitted ?? [], options.opaqueNodes ?? []);
961
962
  if (lines.length === 1) return readSingleLine(source, lines[0], endsText, keepsInlineDirectivesWithPrevious, dropsSeparatorsBeforeComments);
962
963
  const [first, ...rest] = lines;
963
964
  const last = rest.pop();
@@ -1040,8 +1041,20 @@ function readSingleLine(source, line, endsText, keepsInlineDirectivesWithPreviou
1040
1041
  whitespaceLineAfter: false
1041
1042
  };
1042
1043
  }
1043
- /** Reads the element that starts at `offset`, and where it ends. */
1044
- function readGapElement(source, offset) {
1044
+ /**
1045
+ * Reads the element that starts at `offset`, and where it ends. Opaque nodes
1046
+ * are complete, disjoint and source-ordered; their internal trivia belongs
1047
+ * to their retained source instead of becoming separate gap items.
1048
+ */
1049
+ function readGapElement(source, offset, opaqueNodes = []) {
1050
+ const opaque = opaqueNodes[findFirstIndex(opaqueNodes, (node) => node.range[0] >= offset)];
1051
+ if (opaque?.range[0] === offset) return {
1052
+ element: {
1053
+ kind: "item",
1054
+ item: opaque
1055
+ },
1056
+ end: opaque.range[1]
1057
+ };
1045
1058
  const trivia = findTriviaBetween(source, offset, offset + 1).at(0);
1046
1059
  if (trivia !== void 0) return {
1047
1060
  element: {
@@ -1117,7 +1130,7 @@ function isLineSeparator(character) {
1117
1130
  /**
1118
1131
  * Splits the gap into lines, keeping the items of each line.
1119
1132
  */
1120
- function scanLines(source, start, end, keepsSeparators, relocatedWhitespace, omittedRanges) {
1133
+ function scanLines(source, start, end, keepsSeparators, relocatedWhitespace, omittedRanges, opaqueNodes) {
1121
1134
  const lines = [newLine()];
1122
1135
  let current = lines[0];
1123
1136
  let spacePending = false;
@@ -1147,7 +1160,7 @@ function scanLines(source, start, end, keepsSeparators, relocatedWhitespace, omi
1147
1160
  offset = Math.min(end, omitted[1]);
1148
1161
  continue;
1149
1162
  }
1150
- const { element, end: elementEnd } = readGapElement(source, offset);
1163
+ const { element, end: elementEnd } = readGapElement(source, offset, opaqueNodes);
1151
1164
  switch (element.kind) {
1152
1165
  case "item":
1153
1166
  if (!keepsSeparators && isDroppedSemicolon(source, element.item.range[0])) {
@@ -1625,7 +1638,7 @@ function protectSemicolonPrefixes(source, start, end, atoms, structuralSemicolon
1625
1638
  }
1626
1639
  //#endregion
1627
1640
  //#region src/printers/lines.ts
1628
- const { align, hardline, literalline: literalline$1 } = builders;
1641
+ const { align, hardline: hardline$1, literalline: literalline$2 } = builders;
1629
1642
  const { mapDoc, replaceEndOfLine } = utils;
1630
1643
  /**
1631
1644
  * Joins lines with line breaks, with one empty line where a line has
@@ -1649,22 +1662,22 @@ function lineBreakBetween(previous, next, indentation) {
1649
1662
  const deeper = next.extraIndentation ?? "";
1650
1663
  if (next.writtenBreakBefore !== void 0) return [next.writtenBreakBefore, next.writtenIndentation ?? indentation + deeper];
1651
1664
  if (next.spaceLineBefore === true) return [
1652
- literalline$1,
1665
+ literalline$2,
1653
1666
  " ",
1654
- literalline$1,
1667
+ literalline$2,
1655
1668
  next.writtenIndentation ?? indentation + deeper
1656
1669
  ];
1657
- if (next.writtenIndentation !== void 0) return [next.blankBefore ? [literalline$1, literalline$1] : literalline$1, next.writtenIndentation];
1670
+ if (next.writtenIndentation !== void 0) return [next.blankBefore ? [literalline$2, literalline$2] : literalline$2, next.writtenIndentation];
1658
1671
  if (!previous.endsWithWhitespace) return next.blankBefore ? [
1659
- hardline,
1660
- hardline,
1672
+ hardline$1,
1673
+ hardline$1,
1661
1674
  deeper
1662
- ] : [hardline, deeper];
1675
+ ] : [hardline$1, deeper];
1663
1676
  return next.blankBefore ? [
1664
- literalline$1,
1665
- hardline,
1677
+ literalline$2,
1678
+ hardline$1,
1666
1679
  deeper
1667
- ] : [literalline$1, indentation + deeper];
1680
+ ] : [literalline$2, indentation + deeper];
1668
1681
  }
1669
1682
  /**
1670
1683
  * Breaks the line after `last` and starts the next line at `indentation`,
@@ -1784,7 +1797,7 @@ function endsInsideOpenDirective(source) {
1784
1797
  }
1785
1798
  //#endregion
1786
1799
  //#region src/printers/atoms.ts
1787
- const { indent: indent$2 } = builders;
1800
+ const { indent: indent$3 } = builders;
1788
1801
  /**
1789
1802
  * Prints atoms with the gaps between them.
1790
1803
  *
@@ -1794,7 +1807,8 @@ const { indent: indent$2 } = builders;
1794
1807
  * inside the statement, the line stays broken, and every later line of the
1795
1808
  * statement starts one level deeper, except the lines of the layout's
1796
1809
  * outdented atoms; runs of empty lines become one. An atom's written
1797
- * indentation overrides that level. When the layout joins line breaks, or joins
1810
+ * indentation or statement-relative padding overrides that level. When the
1811
+ * layout joins line breaks, or joins
1798
1812
  * the one before an atom (`joinedBefore`), such a line break is printed as
1799
1813
  * whitespace on one line is.
1800
1814
  */
@@ -1824,12 +1838,13 @@ function printAtoms(source, layout, indentation) {
1824
1838
  }
1825
1839
  for (const atom of layout.atoms) {
1826
1840
  const text = source.text.slice(atom.start, atom.end);
1841
+ const alignedIndentation = atom.statementPadding === void 0 ? void 0 : indentation.statement + atom.statementPadding;
1827
1842
  if (previous !== void 0) {
1828
1843
  if (layout.writtenGapsBefore?.has(atom.start) === true) {
1829
1844
  const lastBreak = source.text.lastIndexOf("\n", atom.start - 1);
1830
1845
  if (layout.alignedGapsBefore?.has(atom.start) === true && lastBreak >= previous.end && [...source.text.slice(lastBreak + 1, atom.start)].every((character) => character === " " || character === " ")) current.push(printAsWritten(source, previous.end, lastBreak + 1), indentation.statement);
1831
1846
  else current.push(printAsWritten(source, previous.end, atom.start));
1832
- current.push(printAsWritten(source, atom.start, atom.end));
1847
+ current.push(atom.doc ?? printAsWritten(source, atom.start, atom.end));
1833
1848
  currentEndsWithWhitespace = endsWithSpaceOrTab(text);
1834
1849
  previous = atom;
1835
1850
  continue;
@@ -1847,13 +1862,13 @@ function printAtoms(source, layout, indentation) {
1847
1862
  gapOffset = gap.trailing.range[1];
1848
1863
  }
1849
1864
  for (const line of gap.lines) {
1850
- breakCurrentLine(line.blankBefore, false, indentation.trivia);
1865
+ breakCurrentLine(line.blankBefore, false, indentation.trivia ?? alignedIndentation);
1851
1866
  currentWrittenBreak = keepsBreaks ? literalBreaksBetween(source, gapOffset, line.run.range[0]) : void 0;
1852
1867
  current = [line.run.doc];
1853
1868
  currentEndsWithWhitespace = line.run.endsWithWhitespace;
1854
1869
  gapOffset = line.run.range[1];
1855
1870
  }
1856
- breakCurrentLine(gap.blankAfter, layout.outdented.has(atom.start), atom.writtenIndentation);
1871
+ breakCurrentLine(gap.blankAfter, layout.outdented.has(atom.start), atom.writtenIndentation ?? alignedIndentation);
1857
1872
  currentWrittenBreak = keepsBreaks ? literalBreaksBetween(source, gapOffset, gap.leading?.range[0] ?? atom.start) : void 0;
1858
1873
  if (gap.leading !== null) current = [withLeading(gap.leading, "")];
1859
1874
  } else if (gap.trailing !== null || gap.leading !== null) {
@@ -1872,7 +1887,7 @@ function printAtoms(source, layout, indentation) {
1872
1887
  current.push((written.includes("\u2028") || written.includes("\u2029")) && layout.joinedBefore?.has(atom.start) !== true ? written : inStyleRuleStretch ? written === "" ? "" : " " : spaceFor(layout.rules.get(atom.start), previous, atom));
1873
1888
  }
1874
1889
  }
1875
- current.push(printAsWritten(source, atom.start, atom.end));
1890
+ current.push(atom.doc ?? printAsWritten(source, atom.start, atom.end));
1876
1891
  currentEndsWithWhitespace = endsWithSpaceOrTab(text);
1877
1892
  previous = atom;
1878
1893
  }
@@ -1882,7 +1897,7 @@ function printAtoms(source, layout, indentation) {
1882
1897
  if (index === 0) return line.doc;
1883
1898
  const previousLine = lines[index - 1];
1884
1899
  if (line.outdented) return [lineBreakBetween(previousLine, line, indentation.statement), line.doc];
1885
- return indent$2([lineBreakBetween(previousLine, line, indentation.continuation), line.doc]);
1900
+ return indent$3([lineBreakBetween(previousLine, line, indentation.continuation), line.doc]);
1886
1901
  }),
1887
1902
  endsWithWhitespace: lines[lines.length - 1].endsWithWhitespace
1888
1903
  };
@@ -1903,7 +1918,7 @@ function literalBreaksBetween(source, start, end) {
1903
1918
  }
1904
1919
  //#endregion
1905
1920
  //#region src/printers/blocks.ts
1906
- const { indent: indent$1 } = builders;
1921
+ const { indent: indent$2 } = builders;
1907
1922
  /**
1908
1923
  * The indentation of a line with a comment that starts with `%%{`, which has
1909
1924
  * `gaps` gaps of whitespace before the comment after its first item (see
@@ -2291,10 +2306,10 @@ function openingLine(doc, block, endsWithWhitespace) {
2291
2306
  }
2292
2307
  /**
2293
2308
  * Prints a diagram from its header line: its statements one level deeper,
2294
- * or at the level of the header with `bodyDepth` 0 (a sankey diagram, whose
2295
- * lines cannot be indented), and the end of the text. The statements run to
2296
- * the end of the text, so comments and directives after the last one stand
2297
- * at its level, and what stands on the last line is a line of its own.
2309
+ * or at the level of the header with `bodyDepth` 0 (eventmodeling and sankey).
2310
+ * The statements run to the end of the text, so comments and directives after
2311
+ * the last one stand at its level, and what stands on the last line is a line
2312
+ * of its own.
2298
2313
  */
2299
2314
  function printDiagramBlock(source, header, block, options, bodyDepth = 1) {
2300
2315
  const indentation = indentationOf(options, bodyDepth);
@@ -2310,7 +2325,7 @@ function printDiagramBlock(source, header, block, options, bodyDepth = 1) {
2310
2325
  const body = [block.continuesOpeningLine ? "" : lineBreakBetween(header, lines[0], indentation), joinLines(lines, indentation)];
2311
2326
  return [
2312
2327
  header.doc,
2313
- bodyDepth === 0 ? body : indent$1(body),
2328
+ bodyDepth === 0 ? body : indent$2(body),
2314
2329
  endOfText
2315
2330
  ];
2316
2331
  }
@@ -2324,7 +2339,7 @@ function printClosedBlock(header, block, closing, depth, options) {
2324
2339
  const bodyIndentation = indentationOf(options, depth + 1);
2325
2340
  const last = block.lines.at(-1) ?? header;
2326
2341
  const [first] = block.lines;
2327
- const body = first === void 0 ? "" : indent$1([block.continuesOpeningLine ? "" : lineBreakBetween(header, first, bodyIndentation), joinLines(block.lines, bodyIndentation)]);
2342
+ const body = first === void 0 ? "" : indent$2([block.continuesOpeningLine ? "" : lineBreakBetween(header, first, bodyIndentation), joinLines(block.lines, bodyIndentation)]);
2328
2343
  return [
2329
2344
  header.doc,
2330
2345
  body,
@@ -2337,7 +2352,7 @@ function printOpenBlock(header, block, depth, options) {
2337
2352
  const first = block.lines.at(0);
2338
2353
  return [
2339
2354
  header.doc,
2340
- first === void 0 ? "" : indent$1([block.continuesOpeningLine ? "" : lineBreakBetween(header, first, indentationOf(options, depth + 1)), joinLines(block.lines, indentationOf(options, depth + 1))]),
2355
+ first === void 0 ? "" : indent$2([block.continuesOpeningLine ? "" : lineBreakBetween(header, first, indentationOf(options, depth + 1)), joinLines(block.lines, indentationOf(options, depth + 1))]),
2341
2356
  block.writtenEnd ?? ""
2342
2357
  ];
2343
2358
  }
@@ -6578,7 +6593,7 @@ function findLinesReadByTheirWhitespace$1(source) {
6578
6593
  }
6579
6594
  //#endregion
6580
6595
  //#region src/printers/sectioned.ts
6581
- const { indent } = builders;
6596
+ const { indent: indent$1 } = builders;
6582
6597
  /**
6583
6598
  * Prints the body of a diagram whose statements a `section` groups, and the
6584
6599
  * nodes below it, to the end of the text (docs/gantt.md and docs/journey.md).
@@ -6623,7 +6638,7 @@ function findStatementsAfterSection(statements, isSection) {
6623
6638
  /** Prints a statement on its lines, at the level that the section decides. */
6624
6639
  function printStatement(diagram, source, options, statement, isDeeper) {
6625
6640
  const printed = printLine$5(source, options, diagram.layoutStatement(source, statement, statement.range[1]), isDeeper ? 2 : 1);
6626
- return isDeeper ? indent(printed) : printed;
6641
+ return isDeeper ? indent$1(printed) : printed;
6627
6642
  }
6628
6643
  /** Prints a statement laid out on its lines at `depth`. */
6629
6644
  function printLine$5(source, options, layout, depth) {
@@ -10516,9 +10531,10 @@ function layoutTimelineHeader(source, keyword) {
10516
10531
  * - A period with its events, and the events after another statement, keep
10517
10532
  * the line breaks between the units: a period and an event keep their
10518
10533
  * whitespace as their text, so no event moves from line to line. The later
10519
- * lines of such a statement stand one level deeper (docs/timeline.md,
10520
- * Periods and events). The line break that is the one whitespace character
10521
- * after the `:` of an event is not one of them (see `layoutEvents`).
10534
+ * event colons align under the period's colon when it immediately follows
10535
+ * the period on its line (docs/timeline.md, Periods and events). The line
10536
+ * break that is the one whitespace character after the `:` of an event is
10537
+ * not one of them (see `layoutEvents`).
10522
10538
  * - A title, a section, and an accessibility statement written over several
10523
10539
  * lines stand on one line where the lexer reads the line break as
10524
10540
  * whitespace, which it does only right after a keyword; one with a comment
@@ -10529,7 +10545,7 @@ function layoutTimelineHeader(source, keyword) {
10529
10545
  function layoutTimelineStatement(source, statement, end) {
10530
10546
  const start = statement.range[0];
10531
10547
  switch (statement.type) {
10532
- case "TimelineAccDescrBlockStatement": return layoutDescriptionBlock(source, statement, end, timelineValueNodeTypes);
10548
+ case "TimelineAccDescrBlockStatement": return layoutTimelineDescriptionBlock(source, statement, end);
10533
10549
  case "TimelinePeriodStatement":
10534
10550
  case "TimelineEventStatement": return layoutEvents(source, statement, end);
10535
10551
  }
@@ -10541,6 +10557,51 @@ function layoutTimelineStatement(source, statement, end) {
10541
10557
  lineBreaks: "joined"
10542
10558
  };
10543
10559
  }
10560
+ /**
10561
+ * Align description lines one level inside their statement. Indentation after
10562
+ * LF is absent from the Db, so normalize those columns while preserving written
10563
+ * line breaks and trailing whitespace (docs/timeline.md, Multi-line values).
10564
+ * Reuse the shared block layout, splitting its retained atoms only at those safe
10565
+ * LFs; directives keep their complete written contents.
10566
+ */
10567
+ function layoutTimelineDescriptionBlock(source, statement, end) {
10568
+ const layout = layoutDescriptionBlock(source, statement, end, timelineValueNodeTypes);
10569
+ const atoms = [];
10570
+ const keptBreaksBefore = /* @__PURE__ */ new Set();
10571
+ const outdented = new Set(layout.outdented);
10572
+ const closing = findAccDescrBlockClosing(source, {
10573
+ range: statement.range,
10574
+ value: statement.value,
10575
+ closed: true
10576
+ });
10577
+ if (closing !== null) outdented.add(closing);
10578
+ for (const atom of layout.atoms) {
10579
+ const trivia = findTriviaBetween(source, atom.start, atom.end);
10580
+ let start = atom.start;
10581
+ for (let offset = atom.start; offset < atom.end; offset++) {
10582
+ if (source.text[offset] !== "\n") continue;
10583
+ if (trivia.some((item) => item.range[0] <= offset && offset < item.range[1]) || source.removedLineFeeds.has(offset)) continue;
10584
+ if (start < offset) atoms.push({
10585
+ start,
10586
+ end: offset
10587
+ });
10588
+ start = offset + 1;
10589
+ while (start < atom.end && (source.text[start] === " " || source.text[start] === " ")) start++;
10590
+ if (start < atom.end && source.text[start] !== "\n") keptBreaksBefore.add(start);
10591
+ offset = start - 1;
10592
+ }
10593
+ if (start < atom.end) atoms.push({
10594
+ ...atom,
10595
+ start
10596
+ });
10597
+ }
10598
+ return {
10599
+ ...layout,
10600
+ atoms,
10601
+ keptBreaksBefore,
10602
+ outdented
10603
+ };
10604
+ }
10544
10605
  /** The gap rules of a title, a section, or an accessibility statement. */
10545
10606
  function textStatementRules(source, statement) {
10546
10607
  switch (statement.type) {
@@ -10569,16 +10630,25 @@ function layoutEvents(source, statement, end) {
10569
10630
  const atoms = collectAtoms(source, start, end, collectValueNodes(statement, timelineValueNodeTypes), []);
10570
10631
  const rules = /* @__PURE__ */ new Map();
10571
10632
  const joinedBefore = /* @__PURE__ */ new Set();
10633
+ const alignedColons = /* @__PURE__ */ new Set();
10634
+ let statementPadding = statement.type === "TimelineEventStatement" ? "" : void 0;
10572
10635
  for (const event of statement.events) {
10573
10636
  const eventIndex = atoms.findIndex((atom) => atom.start === event.range[0]);
10574
10637
  const colon = eventIndex < 1 ? void 0 : atoms[eventIndex - 1];
10575
10638
  if (colon === void 0) throw new Error(`prettier-plugin-mmd: no colon before the event at offset ${event.range[0]}`);
10639
+ if (event === statement.events[0] && statement.type === "TimelinePeriodStatement") {
10640
+ const writtenPeriod = source.text.slice(...statement.period.range);
10641
+ if (colon.start === statement.period.range[1] && !writtenPeriod.includes("\n") && !writtenPeriod.includes("\u2028") && !writtenPeriod.includes("\u2029")) statementPadding = writtenPeriod.split(" ").map((part) => " ".repeat(util.getStringWidth(part))).join(" ");
10642
+ } else if (statementPadding !== void 0) alignedColons.add(colon.start);
10576
10643
  if (readGap(source, colon.end, event.range[0], true).breaksLine) joinedBefore.add(event.range[0]);
10577
10644
  rules.set(event.range[0], "space");
10578
10645
  }
10579
10646
  if (joinedBefore.size > 0 && spansLinesThatCannotJoin(source, start, end)) return keptAsWritten(start, end);
10580
10647
  return {
10581
- atoms,
10648
+ atoms: atoms.map((atom) => alignedColons.has(atom.start) ? {
10649
+ ...atom,
10650
+ statementPadding
10651
+ } : atom),
10582
10652
  rules,
10583
10653
  outdented: /* @__PURE__ */ new Set(),
10584
10654
  lineBreaks: "kept",
@@ -10870,7 +10940,7 @@ function statementBlockRules(source) {
10870
10940
  }
10871
10941
  //#endregion
10872
10942
  //#region src/printers/hidden-forms.ts
10873
- const { literalline } = builders;
10943
+ const { literalline: literalline$1 } = builders;
10874
10944
  /**
10875
10945
  * Hidden body openers and closers share a line with their written neighbors
10876
10946
  * (docs/pie.md and docs/gitgraph.md, Hidden yaml and Hidden directives).
@@ -10932,7 +11002,7 @@ function hiddenBlockRules(source, hiddenEnds, kept, printedEnd, headerHiddenEnds
10932
11002
  if (!hasOrdinaryHiddenBreak(start, stop)) return printAsWritten(source, start, stop);
10933
11003
  const gap = readGap(source, start, stop, false);
10934
11004
  const firstBreak = source.text.indexOf("\n", start);
10935
- const breaks = !terminal && !headerHiddenEnds.has(start) && gap.blankAfter ? [literalline, literalline] : [literalline];
11005
+ const breaks = !terminal && !headerHiddenEnds.has(start) && gap.blankAfter ? [literalline$1, literalline$1] : [literalline$1];
10936
11006
  if (terminal && !source.text.endsWith("\n")) breaks.pop();
10937
11007
  return [printAsWritten(source, start, firstBreak), ...breaks];
10938
11008
  }
@@ -10992,19 +11062,20 @@ function createFlatHiddenDiagramPrinter(layouts) {
10992
11062
  headerHiddenEnds.add(item.range[1]);
10993
11063
  headerEnd = item.range[1];
10994
11064
  }
10995
- const block = printBody(diagram.body, findLayoutEnd(headerLayout), source.text.length, 1, true, headerHiddenEnds);
11065
+ const bodyDepth = layouts.bodyDepth ?? 1;
11066
+ const block = printBody(diagram.body, findLayoutEnd(headerLayout), source.text.length, bodyDepth, true, headerHiddenEnds);
10996
11067
  const header = openingLine(printAtoms(source, headerLayout, {
10997
11068
  statement: "",
10998
11069
  continuation: ""
10999
11070
  }).doc, block, false);
11000
- return [printAsWritten(source, diagram.range[0], first.start), printDiagramBlock(source, header, block, options)];
11071
+ return [printAsWritten(source, diagram.range[0], first.start), printDiagramBlock(source, header, block, options, bodyDepth)];
11001
11072
  /** Only authored body boundaries join lines; inner component gaps do not. */
11002
11073
  function collectBodyHidden(body) {
11003
11074
  for (const item of body) {
11004
11075
  appendItems(allHidden, layouts.prefixes?.(item) ?? []);
11005
11076
  if (item.type === layouts.ignoredType) allHidden.push(item);
11006
11077
  appendItems(allHidden, layouts.suffixes?.(item) ?? item.textAfter ?? []);
11007
- const selected = layouts.statement(source, item);
11078
+ const selected = layouts.statement(source, item, options);
11008
11079
  if ("body" in selected) collectBodyHidden(selected.body);
11009
11080
  }
11010
11081
  }
@@ -11019,7 +11090,7 @@ function createFlatHiddenDiagramPrinter(layouts) {
11019
11090
  const bodyStatements = new Map(body.map((item) => [item, item]));
11020
11091
  const nested = /* @__PURE__ */ new Map();
11021
11092
  for (const item of body) {
11022
- let selected = layouts.statement(source, item);
11093
+ let selected = layouts.statement(source, item, options);
11023
11094
  const prefixes = layouts.prefixes?.(item) ?? [];
11024
11095
  const prefixEnd = prefixes.at(-1)?.range[1];
11025
11096
  const ownedHeader = "body" in selected ? selected.header : selected;
@@ -11650,7 +11721,7 @@ function layoutEventmodelingHeader(source, diagram) {
11650
11721
  * (diagrams/eventmodeling.md, Common statements; docs/eventmodeling.md,
11651
11722
  * Common boundaries and Description blocks). Other components use one layout.
11652
11723
  */
11653
- function layoutEventmodelingStatement(source, statement) {
11724
+ function layoutEventmodelingStatement(source, statement, options) {
11654
11725
  const [start, end] = statement.range;
11655
11726
  const selected = classifyEventmodelingStatement(statement);
11656
11727
  switch (selected.kind) {
@@ -11659,7 +11730,7 @@ function layoutEventmodelingStatement(source, statement) {
11659
11730
  case "gwt": {
11660
11731
  const gwt = selected.statement;
11661
11732
  return {
11662
- header: layoutComponents$1(source, gwt, start, gwt.sourceFrame.range[1]),
11733
+ header: layoutComponents$1(source, gwt, start, gwt.sourceFrame.range[1], options.tabWidth),
11663
11734
  body: [
11664
11735
  gwt.given,
11665
11736
  ...gwt.when === null ? [] : [gwt.when],
@@ -11671,13 +11742,13 @@ function layoutEventmodelingStatement(source, statement) {
11671
11742
  case "clause": {
11672
11743
  const clause = selected.statement;
11673
11744
  return {
11674
- header: layoutComponents$1(source, clause, start, expectToken(findStructuralToken(source, clause.textBefore.at(-1)?.range[1] ?? start), "a GWT clause").range[1]),
11745
+ header: layoutComponents$1(source, clause, start, expectToken(findStructuralToken(source, clause.textBefore.at(-1)?.range[1] ?? start), "a GWT clause").range[1], options.tabWidth),
11675
11746
  body: clause.body,
11676
11747
  end
11677
11748
  };
11678
11749
  }
11679
11750
  case "ordinary":
11680
- case "data": return layoutComponents$1(source, statement, start, end);
11751
+ case "data": return layoutComponents$1(source, statement, start, end, options.tabWidth);
11681
11752
  default: throw new Error(`prettier-plugin-mmd: unknown eventmodeling kind ${JSON.stringify(selected)}`);
11682
11753
  }
11683
11754
  }
@@ -11687,15 +11758,17 @@ function layoutEventmodelingStatement(source, statement) {
11687
11758
  * title would become EM_TITLE (diagrams/eventmodeling.md, Data and Common
11688
11759
  * statements; docs/eventmodeling.md, Frame components and Qualified names).
11689
11760
  */
11690
- function layoutComponents$1(source, statement, start, end) {
11761
+ function layoutComponents$1(source, statement, start, end, tabWidth) {
11691
11762
  const values = collectValueNodes(statement, eventmodelingValueNodeTypes).filter((node) => start <= node.range[0] && node.range[1] <= end);
11692
11763
  const kept = [];
11693
11764
  walk(statement, (node) => {
11694
11765
  if ((node.type === "EventmodelingInlineData" || node.type === "EventmodelingDataBlock") && node.range[1] <= end) {
11695
11766
  const opening = expectToken(node.value?.type === "StringLiteral" ? findTokenStartingAt(source, node.value.range[0]) : findTokensBetween(source, node.range[0], node.range[1]).find((token) => token.type === "Punctuator" && token.value === "{"), "a data body");
11767
+ const doc = node.type === "EventmodelingDataBlock" ? indentedDataBlock(source.text.slice(opening.range[0], node.range[1]), tabWidth) : void 0;
11696
11768
  kept.push({
11697
11769
  start: opening.range[0],
11698
- end: node.range[1]
11770
+ end: node.range[1],
11771
+ doc
11699
11772
  });
11700
11773
  }
11701
11774
  });
@@ -11734,7 +11807,8 @@ function layoutComponents$1(source, statement, start, end) {
11734
11807
  ...layout,
11735
11808
  atoms: [...layout.atoms.slice(0, -1), {
11736
11809
  ...last,
11737
- end: paddedEnd
11810
+ end: paddedEnd,
11811
+ doc: last.doc === void 0 ? void 0 : [last.doc, printAsWritten(source, last.end, paddedEnd)]
11738
11812
  }]
11739
11813
  };
11740
11814
  }
@@ -11743,12 +11817,42 @@ function layoutComponents$1(source, statement, start, end) {
11743
11817
  writtenGapsBefore: /* @__PURE__ */ new Set([...layout.writtenGapsBefore ?? [], ...writtenGapsBefore])
11744
11818
  };
11745
11819
  }
11820
+ /**
11821
+ * Only change a common ASCII-space margin whose space-separated words stay
11822
+ * the same in Mermaid's data label. A new space on a later physical line
11823
+ * adds a visible nonbreaking space; tabs, markup and padded openers also
11824
+ * need their authored text (docs/eventmodeling.md, Data blocks).
11825
+ */
11826
+ function indentedDataBlock(text, tabWidth) {
11827
+ if (tabWidth === 0 || !text.startsWith("{\n") || !text.endsWith("\n}") || text.includes("<") || text.includes("&") || text.includes("%%{")) return void 0;
11828
+ const rows = text.slice(2, -2).split("\n");
11829
+ const margins = rows.map((row) => {
11830
+ let margin = 0;
11831
+ while (row[margin] === " ") margin++;
11832
+ return margin;
11833
+ });
11834
+ let commonMargin = Infinity;
11835
+ for (const [index, row] of rows.entries()) {
11836
+ if (row.trim() === "") continue;
11837
+ const margin = margins[index];
11838
+ if (isWhitespace(row[margin]) || index > 0 && margin === 0) return void 0;
11839
+ commonMargin = Math.min(commonMargin, margin);
11840
+ }
11841
+ if (commonMargin === Infinity || commonMargin === tabWidth) return void 0;
11842
+ const delta = tabWidth - commonMargin;
11843
+ const indented = rows.map((row, index) => {
11844
+ if (row.trim() === "") return row;
11845
+ return " ".repeat(margins[index] + delta) + row.slice(margins[index]);
11846
+ });
11847
+ return utils.replaceEndOfLine(`{\n${indented.join("\n")}\n}`);
11848
+ }
11746
11849
  //#endregion
11747
11850
  //#region src/printers/eventmodeling.ts
11748
11851
  /** Common terminals retain their source boundary; GWT uses two open bodies. */
11749
11852
  const eventmodelingPrinter = createFlatHiddenDiagramPrinter({
11750
11853
  type: "EventmodelingDiagram",
11751
11854
  ignoredType: "EventmodelingIgnoredText",
11855
+ bodyDepth: 0,
11752
11856
  header: layoutEventmodelingHeader,
11753
11857
  statement: layoutEventmodelingStatement,
11754
11858
  writtenGapBefore: (source, item) => classifyEventmodelingStatement(item).kind === "common" || source.joiningRegions.some((region) => region.end <= item.range[0] && source.text.slice(region.end, item.range[0]).trim() === ""),
@@ -11966,6 +12070,7 @@ const wardleyPrinter = createFlatHiddenDiagramPrinter({
11966
12070
  });
11967
12071
  //#endregion
11968
12072
  //#region src/printers/railroad-layout.ts
12073
+ const { group, hardline, ifBreak, indent, line, literalline, markAsRoot, softline } = builders;
11969
12074
  /** Written text leaves retain spelling, quotes and physical value columns. */
11970
12075
  const railroadValueNodeTypes = /* @__PURE__ */ new Set([
11971
12076
  "Identifier",
@@ -11990,8 +12095,9 @@ function layoutRailroadStatement(source, statement) {
11990
12095
  const verbatim = layoutOnVerbatimStyleLine(source, start, end);
11991
12096
  if (verbatim !== null) return verbatim;
11992
12097
  const values = collectValueNodes(statement, railroadValueNodeTypes);
11993
- const hidden = values.filter((value) => value.type === "RailroadIgnoredText");
12098
+ const hidden = values.filter((value) => value.type === "RailroadIgnoredText").sort((a, b) => a.range[0] - b.range[0]);
11994
12099
  const grammaticalSemicolons = grammaticalSemicolonsOf(source);
12100
+ const wrapsCalls = statement.type === "RailroadRule" && source.root.diagramType === "railroad" && !findTokensBetween(source, start, end).some((token) => source.ignoredSemicolons.has(token.range[0]));
11995
12101
  let layout;
11996
12102
  switch (statement.type) {
11997
12103
  case "RailroadIgnoredText":
@@ -12014,14 +12120,14 @@ function layoutRailroadStatement(source, statement) {
12014
12120
  layout = layoutCommonDescription(source, statement, railroadValueNodeTypes);
12015
12121
  break;
12016
12122
  case "RailroadRule":
12017
- layout = layoutRule(source, statement, values, hidden, grammaticalSemicolons);
12123
+ layout = layoutRule(source, statement, values, hidden, grammaticalSemicolons, wrapsCalls);
12018
12124
  break;
12019
12125
  default: throw new Error(`prettier-plugin-mmd: unknown railroad item ${JSON.stringify(statement)}`);
12020
12126
  }
12021
12127
  return protectHiddenGaps({
12022
12128
  ...layout,
12023
- atoms: protectSemicolonPrefixes(source, start, end, layout.atoms, grammaticalSemicolons)
12024
- }, hidden);
12129
+ atoms: wrapsCalls ? layout.atoms : protectSemicolonPrefixes(source, start, end, layout.atoms, grammaticalSemicolons)
12130
+ }, statement.type === "RailroadRule" && wrapsCalls ? hidden.filter((item) => item.range[0] < statement.definition.range[0] || item.range[1] > statement.definition.range[1]) : hidden);
12025
12131
  }
12026
12132
  /**
12027
12133
  * Calls, groups, postfixes, predicates and repeats attach; binary separators
@@ -12029,10 +12135,15 @@ function layoutRailroadStatement(source, statement) {
12029
12135
  * marks in a special sequence never become postfixes (docs/railroad.md,
12030
12136
  * Groups, Postfixes, Predicates, Repeats, Calls and Special sequences).
12031
12137
  */
12032
- function layoutRule(source, statement, values, hidden, grammaticalSemicolons) {
12138
+ function layoutRule(source, statement, values, hidden, grammaticalSemicolons, wrapsCalls) {
12033
12139
  const [start, end] = statement.range;
12034
- if (source.text.slice(start, end).includes("\n") && (source.text.slice(start, end).split("").some((character, index) => character === ";" && !grammaticalSemicolons.has(start + index)) || findSemicolonLines(source).has(lineStartOf(source, end - 1)))) return keptAsWritten(start, end);
12035
- const atoms = collectAtoms(source, start, end, values, [{
12140
+ const hasTextualSemicolon = source.text.slice(start, end).split("").some((character, index) => character === ";" && !grammaticalSemicolons.has(start + index));
12141
+ if (!wrapsCalls && source.text.slice(start, end).includes("\n") && (hasTextualSemicolon || findSemicolonLines(source).has(lineStartOf(source, end - 1)))) return keptAsWritten(start, end);
12142
+ const atoms = collectAtoms(source, start, end, values, [...wrapsCalls ? [{
12143
+ start: statement.definition.range[0],
12144
+ end: statement.definition.range[1],
12145
+ doc: printCall(source, statement.definition, hidden)
12146
+ }] : [], {
12036
12147
  start: end - 1,
12037
12148
  end
12038
12149
  }]);
@@ -12068,6 +12179,109 @@ function layoutRule(source, statement, values, hidden, grammaticalSemicolons) {
12068
12179
  lineBreaks: "kept"
12069
12180
  };
12070
12181
  }
12182
+ /** IR calls expose argument structure; simple quoted leaves stay together. */
12183
+ function printCall(source, expression, hidden) {
12184
+ if (expression.type === "StringLiteral") return printAsWritten(source, ...expression.range);
12185
+ let arguments_, members;
12186
+ let valueCall = false;
12187
+ switch (expression.type) {
12188
+ case "RailroadSequenceCall":
12189
+ case "RailroadChoiceCall":
12190
+ members = expression.arguments;
12191
+ arguments_ = members.map((member) => member.expression);
12192
+ break;
12193
+ case "RailroadOptionalCall":
12194
+ case "RailroadOneOrMoreCall":
12195
+ case "RailroadZeroOrMoreCall":
12196
+ arguments_ = [expression.element];
12197
+ break;
12198
+ case "RailroadTerminalCall":
12199
+ arguments_ = [expression.value];
12200
+ valueCall = true;
12201
+ break;
12202
+ case "RailroadNonterminalCall":
12203
+ arguments_ = [expression.name];
12204
+ valueCall = true;
12205
+ break;
12206
+ case "RailroadSpecialCall":
12207
+ arguments_ = [expression.text];
12208
+ valueCall = true;
12209
+ break;
12210
+ default: throw new Error(`prettier-plugin-mmd: ${expression.type} is not an IR call`);
12211
+ }
12212
+ const keyword = expectToken(findTokenStartingAt(source, expression.range[0]), "an IR constructor");
12213
+ const opening = expectToken(findStructuralToken(source, expression.textBeforeOpen.at(-1)?.range[1] ?? keyword.range[1]), "an IR call opening parenthesis");
12214
+ expectValue(opening, "(");
12215
+ const closing = expectToken(findTokenEndingBefore(source, expression.range[1]), "an IR call closing parenthesis");
12216
+ expectValue(closing, ")");
12217
+ const gapOptions = { opaqueNodes: hidden };
12218
+ const constructorGap = readGap(source, keyword.range[1], opening.range[0], true, gapOptions);
12219
+ const firstGap = readGap(source, opening.range[1], arguments_[0].range[0], true, gapOptions);
12220
+ const closingGap = readGap(source, arguments_.at(-1).range[1], closing.range[0], true, gapOptions);
12221
+ const breaksArguments = !valueCall || hasCallTrivia(constructorGap) || hasCallTrivia(firstGap) || hasCallTrivia(closingGap);
12222
+ const contents = [];
12223
+ let previousEnd = opening.range[1];
12224
+ for (const [index, argument] of arguments_.entries()) {
12225
+ if (index > 0) {
12226
+ const comma = expectToken(findStructuralToken(source, members?.[index - 1].range[1] ?? previousEnd), "an IR argument comma");
12227
+ expectValue(comma, ",");
12228
+ contents.push(printCallGap(readGap(source, previousEnd, comma.range[0], true, gapOptions), "", "comma"), ",");
12229
+ previousEnd = comma.range[1];
12230
+ }
12231
+ contents.push(printCallGap(index === 0 ? firstGap : readGap(source, previousEnd, argument.range[0], true, gapOptions), breaksArguments ? index === 0 ? softline : line : "", "leading"), printCall(source, argument, hidden));
12232
+ previousEnd = argument.range[1];
12233
+ }
12234
+ const call = [
12235
+ printCallGap(constructorGap, "", "constructor"),
12236
+ "(",
12237
+ indent(contents),
12238
+ printCallGap(closingGap, breaksArguments ? softline : "", "closing"),
12239
+ ")"
12240
+ ];
12241
+ return group([printAsWritten(source, ...keyword.range), constructorGap.breaksLine && hasCallTrivia(constructorGap) ? indent(call) : call], { shouldBreak: breaksArguments });
12242
+ }
12243
+ /**
12244
+ * IR call padding is ordinary whitespace, so trivia uses readable outside
12245
+ * spacing at each syntactic boundary (diagrams/railroad.md, IR grammar;
12246
+ * docs/railroad.md, Comments and Global directives).
12247
+ */
12248
+ function printCallGap(gap, ordinary, placement) {
12249
+ if (!hasCallTrivia(gap)) return ordinary;
12250
+ if (!gap.breaksLine) {
12251
+ const run = gap.leading ?? gap.trailing;
12252
+ if (placement === "leading") return [
12253
+ ordinary,
12254
+ run.doc,
12255
+ " "
12256
+ ];
12257
+ return [
12258
+ " ",
12259
+ run.doc,
12260
+ placement === "closing" ? ifBreak(ordinary, "") : placement === "constructor" ? " " : ""
12261
+ ];
12262
+ }
12263
+ const trivia = gap.trailing === null ? [] : [" ", gap.trailing.doc];
12264
+ let previous = gap.trailing;
12265
+ for (const item of gap.lines) {
12266
+ trivia.push(triviaBreak(previous, item.blankBefore), item.run.doc);
12267
+ previous = item.run;
12268
+ }
12269
+ if (gap.leading !== null) {
12270
+ trivia.push(triviaBreak(previous, gap.blankAfter), gap.leading.doc);
12271
+ previous = gap.leading;
12272
+ }
12273
+ const after = gap.leading !== null ? placement === "leading" || placement === "constructor" ? " " : "" : triviaBreak(previous, gap.leading === null && gap.blankAfter);
12274
+ return placement === "closing" ? [indent(trivia), after] : [trivia, after];
12275
+ }
12276
+ /** Whitespace-only gaps collapse to their ordinary call separator. */
12277
+ function hasCallTrivia(gap) {
12278
+ return gap.trailing !== null || gap.lines.length > 0 || gap.leading !== null;
12279
+ }
12280
+ /** A literal break keeps comment tails while adopting this call's indentation. */
12281
+ function triviaBreak(previous, blank = false) {
12282
+ const boundary = previous?.endsWithWhitespace === true ? markAsRoot(literalline) : hardline;
12283
+ return blank ? [boundary, hardline] : boundary;
12284
+ }
12071
12285
  //#endregion
12072
12286
  //#region src/printers/railroad.ts
12073
12287
  /** The four dialects share one flat body and its hidden-form boundaries. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prettier-plugin-mmd",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Prettier plugin for the Mermaid diagram syntax (.mmd files and mermaid code blocks in Markdown)",
5
5
  "license": "MIT",
6
6
  "repository": {