Skip to content

Build your personal knowledge base with Trilium Notes

fix(codemirror): parse Mermaid front matter as YAML

Elian Doranca914ba513ac
diff --git a/.claude/skills/developing-mermaid-highlighting/SKILL.md b/.claude/skills/developing-mermaid-highlighting/SKILL.md
index e9c025f627..a6e5d82a48 100644
--- a/.claude/skills/developing-mermaid-highlighting/SKILL.md
+++ b/.claude/skills/developing-mermaid-highlighting/SKILL.md
@@ -12,9 +12,11 @@ Markdown, `buildMarkdown()` there mounts it on ` ```mermaid ` code blocks throug
Mermaid; `foldByIndent()` stays off there, since it folds by indentation across the whole document.
The language was vendored from
-[Edge-Tools/codemirror-lang-mermaid](https://github.com/Edge-Tools/codemirror-lang-mermaid) at `03bcd7d`, itself a fork of inspirnathan's `codemirror-lang-mermaid`. Both upstreams are dormant:
-**the code is ours now**. Never re-vendor over it; `git log -- packages/codemirror/src/languages/mermaid`
-shows what changed after the verbatim copy and why.
+[Edge-Tools/codemirror-lang-mermaid](https://github.com/Edge-Tools/codemirror-lang-mermaid) at
+`03bcd7d`, itself a fork of inspirnathan's `codemirror-lang-mermaid`. Both upstreams are dormant:
+**the code is ours now**. Never re-vendor over it;
+`git log -- packages/codemirror/src/languages/mermaid` shows what changed after the verbatim copy
+and why.
## Layout
@@ -31,12 +33,17 @@ languages/mermaid/
LICENSE upstream MIT licence — keep it
```
-How a document parses: `mermaid.grammar` skips the preamble (front matter, `%%{init}%%`, blank
-lines) as `preDiagramLine`s, then its `diagramText` tokenizer (`parsers/mermaid/tokens.ts`) matches
-the first other line against `diagramMap` and emits one node for the rest of the document, such as
-`FlowchartDiagram`. `parseMixed()` in `index.ts` looks that node's name up in `DIAGRAM_PARSERS` and
-mounts the diagram's own parser over it. A diagram with no entry there, or a keyword missing from
-`diagramMap`, gets no highlighting at all.
+How a document parses: `mermaid.grammar` first takes the front matter, the way Mermaid does: a
+`---` line at the very start of the document, opening only when a closing `---` line follows. Its
+`frontMatter` tokenizer (`parsers/mermaid/tokens.ts`) emits a `FrontMatter` node, and `parseMixed()`
+in `index.ts` mounts the YAML parser of `@codemirror/lang-yaml` on its content, so the tree shows
+YAML's `Stream` there. The front matter must be its own token, not lines for diagram detection:
+Mermaid's config keys (`flowchart:`, `gantt:`, `block:`, …) start with diagram keywords. The rest of
+the preamble (`%%{init}%%`, blank lines) parses as `preDiagramLine`s, then the `diagramText`
+tokenizer matches the first other line against `diagramMap` and emits one node for the rest of the
+document, such as `FlowchartDiagram`. `parseMixed()` looks that node's name up in `DIAGRAM_PARSERS`
+and mounts the diagram's own parser over it. A diagram with no entry there, or a keyword missing
+from `diagramMap`, gets no highlighting at all.
## Rules
@@ -95,6 +102,10 @@ grammar for radar; the rest have none anywhere, so write them from Mermaid's syn
- **External tokenizers run in declaration order; the first that accepts wins.** Kanban's
`columnTitleTokens` claims every line without a `[`, so `nodeIdTokens` only ever sees card lines.
Check what an earlier tokenizer swallows before deciding a later one's branch is reachable.
+- **An external tokenizer runs only in parse states that accept one of its tokens**, and
+ `stack.canShift(term)` says which. For context (am I at the start, inside front matter?) ask the
+ stack, not `input.pos`: `frontMatter` has a separate `frontMatterStart` token, valid only at the
+ start of the document, and both its `---` tokens keep one node name with `[@name=DashLine]`.
- **`acceptToken(term, offset)`** with a negative offset ends the token before what was read —
kanban uses it to keep the spaces in `id1 [Task]` out of the id. Fixture trees do not show token
ranges; assert those in the spec, or look with `tree.mts --spans`.
@@ -106,7 +117,8 @@ grammar for radar; the rest have none anywhere, so write them from Mermaid's syn
`languageData` on `mermaidLanguage` alone reaches only the preamble, so `index.ts` configures every
diagram parser with `languageDataProp` pointing at `mermaidLanguage.data` (that is how `%%`
comment toggling, `commentTokens`, reaches the diagram body). Add new data (autocompletion
- sources, indentation hints) to `languageData`, never to one diagram parser.
+ sources, indentation hints) to `languageData`, never to one diagram parser. The YAML parser keeps
+ its own data, which is why Ctrl+/ comments front matter with `#`.
- **Error recovery is behaviour too.** A fixture whose tree has `⚠` pins how the grammar recovers.
That is fine for input Mermaid rejects; for input Mermaid accepts it records a limitation, and the
fixture name must say so (`… (unsupported, parses as empty lines)`).
@@ -172,5 +184,7 @@ root; `\n`, `\r` and `\t` in an input are unescaped.
- `mindmap root` (root on the `mindmap` line, valid Mermaid) parses as empty lines.
- A bare word under a kanban column parses as another column, not a card.
- Dotted edge labels (`A -. text .-> B`) parse as two links.
+- `flowchart` or `graph` without a direction (valid Mermaid, top to bottom) parses with errors.
+- `%%{init: …}%%` directives highlight as one comment, not as the JSON they hold.
- No autocompletion exists for Mermaid in any editor library; it would be an
`@codemirror/autocomplete` source written here.
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index 33851c9813..1cf25cd6cf 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -160,7 +160,7 @@
"_help_iRwzGnHPzonm": "<p>Relation map is a type of&nbsp;note&nbsp;which visualizes notes and their <a href=\"#root/_help_zEY4DaJG4YT5\">relations</a>.</p><h2>Interaction</h2><ul><li>To create a new note and add it to the map, press the <span class=\"tn-icon bx bx-note\"></span> <em>Add note</em> button at the bottom of the map, then click anywhere on the map to place it there.<ul><li>While the map waits for the click, a translucent box follows the mouse to show where the note will go. To cancel, press the button again (now labeled <em>Cancel</em>) or press <kbd>Esc</kbd>.</li><li>The note is created as a child of the map, with the default title of a new note. It opens in the note panel (see below) with its title selected, so you can type its name straight away.</li></ul></li><li>An existing note can also be dragged from the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>. It will be placed at the position it's dragged on.<ul><li>Multiple notes can also be dragged via&nbsp;<a class=\"reference-link\" href=\"#root/_help_yTjUdsOi4CIE\">Multiple selection</a>. The notes will be positioned near the dragged position without overlapping.</li><li>The dragged note can be a sub-child of the map, or it can be at any arbitrary position.</li></ul></li><li>Notes can also be pasted onto the map. Copy or cut them in the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, then click the map and press <kbd>Ctrl</kbd>+<kbd>V</kbd>, or right click an empty part of the map and select <em>Paste note(s)</em>.<ul><li>With <kbd>Ctrl</kbd>+<kbd>V</kbd>, the notes are placed under the mouse, or in the middle of the map if the mouse is not over it. From the right click menu, they are placed where the menu was opened.</li><li>Copied notes stay where they are in the tree. Cut notes are moved under the map, as if they had been pasted into it in the tree.</li><li>Links to notes, such as an <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> copied from a text note, can be pasted the same way. If the clipboard holds no link to a note, the notes last copied or cut in the tree are pasted.</li><li>The right click menu of an empty part of the map also has <em>Add note</em>, which creates a new note where the menu was opened.</li></ul></li><li>To create a relationship, hold the mouse on the dot on the right of a note and then:<ul><li>Drag it over another note to create a relationship pointing from the first note to the second one.</li><li>Drag over the same note to create a self-referencing relationship (represented as a loop).</li><li>Once dragged, a popover next to the relationship asks for its name. Type a new name and press <kbd>Enter</kbd>, or pick a relation name already in use from the suggestions. To cancel, press <kbd>Esc</kbd>, close the popover or click elsewhere on the map.</li></ul></li><li>Each note is shown as a card with its icon and title, colored in the note's color the same way as the cards of a <a class=\"reference-link\" href=\"#root/_help_CtBQqbwXDx1w\">Kanban Board</a>.</li><li>Hovering a note highlights its relationships, in the note's color if it has one, and fades the other relationships.</li><li>To view or edit a note, click it on the map. This opens the note panel (see below).<ul><li>To open the note in a new tab instead, <kbd>Ctrl</kbd>+click it or click it with the middle mouse button. <kbd>Shift</kbd>+click opens it in a new window. The right click menu offers the same options.</li></ul></li><li>To edit the title of a note, change its color or delete it (either from the map, or delete it completely), right click the note.</li><li>To rename or delete a relationship, right click it and select the corresponding option.</li><li>On a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only</a> map, notes cannot be moved and relationships cannot be drawn, renamed or deleted. The right click menu of a note only offers to open it, and a relationship has no right click menu.</li><li>To move around the map, drag an empty part of it, and zoom with the mouse wheel or the <span class=\"tn-icon bx bx-minus-circle\"></span> and <span class=\"tn-icon bx bx-plus-circle\"></span> buttons at the bottom-right corner. Clicking the zoom percentage goes back to 100%, and <span class=\"tn-icon bx bx-scan\"></span> <em>Fit to view</em> zooms and pans so that all the notes are visible.<ul><li>Once the map has been clicked, the arrow keys or <kbd>W</kbd> <kbd>A</kbd> <kbd>S</kbd> <kbd>D</kbd> pan it, and <kbd>+</kbd> and <kbd>-</kbd> zoom it. The <kbd>?</kbd> button at the top-right corner of the map lists all its keyboard shortcuts.</li></ul></li></ul><h2>Note panel</h2><p>When a note on the map is clicked, a panel opens to the right of the map and the note is highlighted. If the panel would cover the note, or the note is partly off-screen, the map pans to bring it into view. The panel contains:</p><ul><li>The title and icon of the note, both editable.</li><li>A <span class=\"tn-icon bx bx-expand-alt\"></span> button to expand the panel over the whole map, and to restore it afterwards.</li><li>Buttons to interact with the note:<ul><li><span class=\"tn-icon bx bx-log-in\"></span> Open the note in the current tab, or, through the <span class=\"tn-icon bx bx-dots-horizontal-rounded\"></span> menu, in a new tab, split, window or the quick edit popup.</li><li>A <span class=\"tn-icon bx bx-palette\"></span> color picker to change the color of the note.</li><li>A <span class=\"tn-icon bx bx-trash\"></span> button to remove the note from the map, which can optionally delete the note as well.</li></ul></li><li>The <a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a> of the note, if any.</li><li>The note's content, which can be edited directly from the panel.</li></ul><p>The color picker and the remove button are not shown if the map is read-only.</p><p>Clicking another note on the map switches the panel to it. Similarly, clicking an <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> inside the panel switches the panel to that note, as long as it is on the map.</p><p>To close the panel, press the <span class=\"tn-icon bx bx-x\"></span> button at its top-right, click an empty part of the map, or press <kbd>Esc</kbd>.</p><p>On mobile, the note opens as a dialog over the whole screen instead of a panel.</p><h2>Development process demo</h2><p>This is a basic example how you can create simple diagram using relation maps:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Relation%20Map_relation-map-dev-process.png\" width=\"934\" height=\"667\"><p>And this is how you can create it:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Relation%20Map_relation-map-dev-process-demo.gif\" width=\"812\" height=\"585\"><p>We start completely from scratch by first creating new note called \"Development process\" and changing its type to \"Relation map\". After that we create new notes one by one and place them by clicking into the map. We also drag <a href=\"#root/_help_zEY4DaJG4YT5\">relations</a>between notes and name them. That's all!</p><p>Items on the map - \"Specification\", \"Development\", \"Testing\" and \"Demo\" are actually notes which have been created under \"Development process\" note - you can click on them and write some content. Connections between notes are called \"<a href=\"#root/_help_zEY4DaJG4YT5\">relations</a>\".</p><h2>Family demo</h2><p>This is more complicated demo using some advanced concepts. Resulting diagram is here:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Relation%20Map_relation-map-family.png\" width=\"941\" height=\"758\"><p>This is how you get to it:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Relation%20Map_relation-map-family-demo.gif\" width=\"812\" height=\"585\"><p>There are several steps here:</p><ul><li>we start with empty relation map and two existing notes representing Prince Philip and Queen Elizabeth II. These two notes already have <code>isPartnerOf</code> <a href=\"#root/_help_zEY4DaJG4YT5\">relations</a>defined.<ul><li>There are actually two \"inverse\" relations (one from Philip to Elizabeth and one from Elizabeth to Philip)</li></ul></li><li>we drag both notes to relation map and place to suitable position. Notice how the existing <code>isPartnerOf</code> relations are displayed.</li><li>now we create new note - we name it \"Prince Charles\" and place it on the relation map by clicking on the desired position. The note is by default created under the relation map note (visible in the note tree on the left).</li><li>we create two new relations <code>isChildOf</code> targeting both Philip and Elizabeth<ul><li>now there's something unexpected - we can also see the relation to display another <code>hasChild</code> relation. This is because there's a <a href=\"#root/_help_OFXdgB2nNk1F\">relation definition</a> which puts <code>isChildOf</code> as an \"<a href=\"#root/_help_OFXdgB2nNk1F\">inverse</a>\" relation of <code>hasChildOf</code> (and vice versa) and thus it is created automatically.</li></ul></li><li>we create another note for Princess Diana and create <code>isPartnerOf</code> relation from Charles. Again notice how the relation has arrows both ways - this is because <code>isPartnerOf</code> definition specifies its inverse relation as again \"isPartnerOf\" so the opposite relation is created automatically.</li><li>as the last step we pan &amp; zoom the map to fit better to window dimensions.</li></ul><p>Relation definitions mentioned above come from \"Person template\" note which is assigned to any child of \"My Family Tree\" relation note. You can play with the whole thing in the <a href=\"#root/_help_wX4HbRucYSDD\">demo notes</a>.</p><h2>Details</h2><p>You can specify which relations should be displayed with comma delimited names of relations in <code>displayRelations</code> label.</p><p>Alternatively, you can specify comma delimited list of relation names in <code>hideRelations</code> which will display all relations, except for the ones defined in the label.</p><h2>See also</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a>&nbsp;is a similar concept.</li></ul>",
"_help_bdUJEHsAPYQR": "<figure class=\"image image_resized\" style=\"width:72.68%;\"><img style=\"aspect-ratio:1311/1271;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Note%20Map_image.png\" width=\"1311\" height=\"1271\"></figure><p>A Note map is a note type which displays a standalone version of the feature of the same name:&nbsp;<a class=\"reference-link\" href=\"#root/_help_BCkXAVs63Ttv\">Note Map (Link map, Tree map)</a>. Consult that page for more information on how the note map works and what it displays.</p><p>Once created, the note map will display the relations between notes. Only the notes that are part of the parent of the note map will be displayed (including their children).</p><h2>Root note</h2><p>The root note defines the starting point of the graph, from which the relations and the hierarchy are derived from.</p><p>There are three possible root notes:</p><ul><li>The default root note is the parent note of the note map.</li><li>To use the currently <a href=\"#root/_help_OR8WJ7Iz9K4U\">hoisted note</a> instead, set the <code>mapRootNoteId</code> label to <code>hoisted</code>.</li><li>To use a specific note instead, set <code>mapRootNoteId</code> to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_m1lbrzyKDaRB\">Note ID</a>&nbsp;of the desired note.</li></ul><h2>Customization</h2><p>The note map can be customized using the following&nbsp;<a class=\"reference-link\" href=\"#root/_help_HI6GBBIduIgv\">Labels</a>:</p><figure class=\"table\"><table><thead><tr><th>Label</th><th>Description</th></tr></thead><tbody><tr><td><code>#mapIncludeRelation</code></td><td>Comma-delimited relation names to include from the note map.</td></tr><tr><td><code>#mapExcludeRelation</code></td><td>Comma-delimited relation names to exclude from the note map.</td></tr><tr><td><code>#mapRootNoteId</code></td><td>The ID of the note the map roots from, or <code>hoisted</code>. See the root note section above for more information.</td></tr></tbody></table></figure>",
"_help_HcABDtFCkbFN": "<figure class=\"image\"><img style=\"aspect-ratio:601/216;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Render%20Note_image.png\" width=\"601\" height=\"216\"></figure><p>Render Note is a special case of <a href=\"#root/_help_yIhgI5H7A2Sm\">front-end scripting</a> which allows rendering custom content inside a note. This makes it possible to create custom dashboards, or to use a custom note editor.</p><p>The content can either be a vanilla HTML, or Preact JSX.</p><h2>Creating a render note</h2><ol><li>Create a&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note with the:<ol><li>HTML language for the legacy/vanilla method, with what needs to be displayed (for example <code>&lt;p&gt;Hello world.&lt;/p&gt;</code>).</li><li>JSX for the Preact-based approach (see below).</li></ol></li><li>Create a&nbsp;<a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a>.</li><li>Assign the <code>renderNote</code> <a href=\"#root/_help_zEY4DaJG4YT5\">relation</a> to point at the previously created code note.</li></ol><h2>Legacy scripting using jQuery</h2><p>A static HTML is generally not enough for&nbsp;<a class=\"reference-link\" href=\"#root/_help_CdNpE2pqjmI6\">Scripting</a>. The next step is to automatically change parts of the note using JavaScript.</p><p>For a simple example, we are going to create a render note that displays the current date in a field.</p><p>To do so, first create an HTML code note with the following content:</p><pre><code class=\"language-text-html\">&lt;h1&gt;Current date &amp; time&lt;/h1&gt;\nThe current date &amp; time is &lt;span class=\"date\"&gt;&lt;/span&gt;</code></pre><p>Now we need to add the script. Create another&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>, but this time of JavaScript (frontend) language. Make sure the newly created note is a direct child of the HTML note created previously; with the following content:</p><pre><code class=\"language-text-javascript\">const $dateEl = api.$container.find(\".date\");\n$dateEl.text(new Date());</code></pre><p>Now create a render note at any place and set its <code>~renderNote</code> relation to point to the HTML note. When the render note is accessed it will display:</p><blockquote><p><strong>Current date &amp; time</strong><br>The current date &amp; time is Sun Apr 06 2025 15:26:29 GMT+0300 (Eastern European Summer Time)</p></blockquote><h2>Dynamic content using Preact &amp; JSX</h2><p>As a more modern alternative to jQuery, it's possible to use Preact &amp; JSX to render pages. Since JSX is a superset of JavaScript, there's no need to provide a HTML anymore.</p><p>Here are the steps to creating a simple render note:</p><ol><li><p>Create a note of type&nbsp;<a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a>.</p></li><li><p>Create a child&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note with JSX as the language.<br>As an example, use the following content:</p><pre><code class=\"language-text-x-trilium-auto\">export default function() {\n return (\n &lt;&gt;\n &lt;p&gt;Hello world.&lt;/p&gt;\n &lt;/&gt;\n );\n}</code></pre></li><li><p>In the parent render note, define a <code>~renderNote</code> relation pointing to the newly created child.</p></li><li><p>Refresh the render note and it should display a “Hello world” message.</p></li></ol><h2>Refreshing the note</h2><p>It's possible to refresh the note via:</p><ul><li>The&nbsp;<span class=\"tn-icon bx bx-refresh\"></span> button in&nbsp;the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>&nbsp;area.</li><li>The “Render active note” <a href=\"#root/_help_A9Oc6YKKc65v\">keyboard shortcut</a> (not assigned by default).</li></ul><h2>Printing</h2><p>A render note can be printed or exported as PDF from the <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> once its <code>~renderNote</code> relation is set (see <a class=\"reference-link\" href=\"#root/_help_NRnIZmSMc5sj\">Printing &amp; Exporting as PDF</a>). Unlike other notes, it is printed exactly as it is displayed: the script does not run again, so what was typed, selected or loaded in the note is kept.</p><ul><li>The content is laid out again at the width of the page, so elements sized by the script for the screen (such as charts) might not fit.</li><li>Scrolling areas, such as a table in a scrolling container, are printed at their full height, without a scrollbar.</li><li>To adjust the layout for printing, use a <code>~printCss</code> relation.</li><li>The light colors are used for printing, whatever the current theme.</li></ul><p>When a render note is printed as part of a <a class=\"reference-link\" href=\"#root/_help_mULW0Q3VojwY\">List View</a> collection, or from another view such as its attachments, it is not on screen, so its script runs again for the print. In a collection, the output is printed without the note's own styles.</p><h2>Examples</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_R7abl2fc6Mxi\">Weight Tracker</a>&nbsp;which is present in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_6tZeKvSHEUiB\">Demo Notes</a>.</li></ul>",
- "_help_s1aBHPd79XYj": "<aside class=\"admonition tip\"><p>For a quick understanding of the Mermaid syntax, see&nbsp;<a class=\"reference-link\" href=\"{{helpAssets}}/User%20Guide/Note%20Types/Mermaid%20Diagrams/Syntax%20reference.dat\">Syntax reference</a>&nbsp;(official documentation).</p></aside><figure class=\"image\"><img style=\"aspect-ratio:1464/915;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Mermaid%20Diagrams_image.png\" width=\"1464\" height=\"915\"></figure><p>Trilium supports Mermaid, which adds support for various diagrams such as flowchart, sequence diagram, class diagram, state diagram, pie charts, etc., all using a text description of the chart instead of manually drawing the diagram.</p><p>This note type is a split view, meaning that both the source code and a preview of the document are displayed side-by-side. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>&nbsp;for more information.</p><h2>Sample diagrams</h2><p>Starting with v0.103.0, Mermaid diagrams no longer start with a sample flowchart, but instead a pane at the bottom will show all the supported diagrams with sample code for each:</p><ul><li>Simply click on any of the samples to apply it.</li><li>The pane will disappear as soon as something is typed in the code editor or a sample is selected. To make it appear again, simply remove the content of the note.</li></ul><h2>Layouts</h2><p>Depending on the chart being edited and user preference, there are two layouts supported by the Mermaid note type:</p><ul><li>Horizontal, where the source code (editable part) is on the left side of the screen and the preview is to the right.</li><li>Vertical, where the source code is at the bottom of the screen and the preview is at the top.</li></ul><p>It's possible to switch between the two layouts at any time by pressing the&nbsp;<span class=\"tn-icon bx bxs-dock-left\"></span> icon in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>.</p><h2>Interaction</h2><ul><li>The source code of the diagram (in Mermaid format) is displayed on the left or bottom side of the note (depending on the layout).<ul><li>Changing the diagram code will refresh automatically the diagram.</li><li><kbd>Ctrl</kbd>+<kbd>/</kbd> (Mac: <kbd>⌘</kbd>+<kbd>/</kbd>) comments out the current or selected lines with <code>%%</code>. Pressing it again on commented lines removes the <code>%%</code>.</li></ul></li><li>The preview of the diagram is displayed at the right or top side of the note (depending on the layout):<ul><li>There are dedicated buttons at the bottom-right of the preview to control the zoom in, zoom out or fit the diagram.</li><li>The preview can be moved around by holding the left mouse button and dragging.</li><li>Zooming can also be done by using the scroll wheel.</li><li>The zoom and position on the preview will remain fixed as the diagram changes, to be able to work more easily with large diagrams.</li><li>Double-clicking the preview resets the zoom/position.</li><li>The preview can also be focused by clicking on it, case in which keyboard shortcuts can be used:<ul><li><kbd>+</kbd> or <kbd>E</kbd> to zoom in, <kbd>-</kbd> or <kbd>Q</kbd> to zoom out.</li><li><kbd>/</kbd> to reset the zoom/position.</li><li>Arrow keys or <kbd>W</kbd> <kbd>A</kbd> <kbd>S</kbd> <kbd>D</kbd> to pan. Holding <kbd>Shift</kbd> pans faster.</li></ul></li></ul></li><li>The size of the source/preview panes can be adjusted by hovering over the border between them and dragging it with the mouse.</li><li>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>:<ul><li>The source/preview can be laid out left-right (via <span class=\"tn-icon bx bxs-dock-left\"></span>) or bottom-top (via <span class=\"tn-icon bx bxs-dock-bottom\"></span>).</li><li>Press the&nbsp;<span class=\"tn-icon bx bx-copy\"></span> (<em>Copy image reference to the clipboard</em>) to be able to insert the image representation of the diagram into a text note. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_0Ofbk1aSuVRu\">Image references</a>&nbsp;for more information.</li></ul></li><li>To export the diagram as either SVG or PNG, go to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>&nbsp;and select <em>Export as image</em>:<ul><li>Select <em>SVG (vector)</em> to download a scalable/vector rendering of the diagram. Can be used to present the diagram without degrading when zooming.</li><li>Select <em>PNG (raster)</em> to download a normal image (at 1x scale, raster) of the diagram. Can be used to send the diagram in more traditional channels such as e-mail.</li></ul></li><li>The note can be marked as <a href=\"#root/_help_CoFPLs3dRlXc\">read-only</a>, case in which it switches by default to the preview (although it can be switched back using the source/preview buttons) and the source is no longer editable.</li></ul><h2>Errors in the diagram</h2><p>If there is an error in the source code, the error will be displayed in an information pane.</p><p>During the state of an error, the diagram will no longer be rendered and the previously working diagram will remain in the preview section.</p>",
+ "_help_s1aBHPd79XYj": "<aside class=\"admonition tip\"><p>For a quick understanding of the Mermaid syntax, see&nbsp;<a class=\"reference-link\" href=\"{{helpAssets}}/User%20Guide/Note%20Types/Mermaid%20Diagrams/Syntax%20reference.dat\">Syntax reference</a>&nbsp;(official documentation).</p></aside><figure class=\"image\"><img style=\"aspect-ratio:1464/915;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Mermaid%20Diagrams_image.png\" width=\"1464\" height=\"915\"></figure><p>Trilium supports Mermaid, which adds support for various diagrams such as flowchart, sequence diagram, class diagram, state diagram, pie charts, etc., all using a text description of the chart instead of manually drawing the diagram.</p><p>This note type is a split view, meaning that both the source code and a preview of the document are displayed side-by-side. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>&nbsp;for more information.</p><h2>Sample diagrams</h2><p>Starting with v0.103.0, Mermaid diagrams no longer start with a sample flowchart, but instead a pane at the bottom will show all the supported diagrams with sample code for each:</p><ul><li>Simply click on any of the samples to apply it.</li><li>The pane will disappear as soon as something is typed in the code editor or a sample is selected. To make it appear again, simply remove the content of the note.</li></ul><h2>Layouts</h2><p>Depending on the chart being edited and user preference, there are two layouts supported by the Mermaid note type:</p><ul><li>Horizontal, where the source code (editable part) is on the left side of the screen and the preview is to the right.</li><li>Vertical, where the source code is at the bottom of the screen and the preview is at the top.</li></ul><p>It's possible to switch between the two layouts at any time by pressing the&nbsp;<span class=\"tn-icon bx bxs-dock-left\"></span> icon in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>.</p><h2>Interaction</h2><ul><li>The source code of the diagram (in Mermaid format) is displayed on the left or bottom side of the note (depending on the layout).<ul><li>Changing the diagram code will refresh automatically the diagram.</li><li>The front matter (the block between <code>---</code> lines at the start of the diagram, which holds its title and configuration) is highlighted as YAML.</li><li><kbd>Ctrl</kbd>+<kbd>/</kbd> (Mac: <kbd>⌘</kbd>+<kbd>/</kbd>) comments out the current or selected lines with <code>%%</code>, or with <code>#</code> in the front matter. Pressing it again on commented lines removes the comment marker.</li></ul></li><li>The preview of the diagram is displayed at the right or top side of the note (depending on the layout):<ul><li>There are dedicated buttons at the bottom-right of the preview to control the zoom in, zoom out or fit the diagram.</li><li>The preview can be moved around by holding the left mouse button and dragging.</li><li>Zooming can also be done by using the scroll wheel.</li><li>The zoom and position on the preview will remain fixed as the diagram changes, to be able to work more easily with large diagrams.</li><li>Double-clicking the preview resets the zoom/position.</li><li>The preview can also be focused by clicking on it, case in which keyboard shortcuts can be used:<ul><li><kbd>+</kbd> or <kbd>E</kbd> to zoom in, <kbd>-</kbd> or <kbd>Q</kbd> to zoom out.</li><li><kbd>/</kbd> to reset the zoom/position.</li><li>Arrow keys or <kbd>W</kbd> <kbd>A</kbd> <kbd>S</kbd> <kbd>D</kbd> to pan. Holding <kbd>Shift</kbd> pans faster.</li></ul></li></ul></li><li>The size of the source/preview panes can be adjusted by hovering over the border between them and dragging it with the mouse.</li><li>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>:<ul><li>The source/preview can be laid out left-right (via <span class=\"tn-icon bx bxs-dock-left\"></span>) or bottom-top (via <span class=\"tn-icon bx bxs-dock-bottom\"></span>).</li><li>Press the&nbsp;<span class=\"tn-icon bx bx-copy\"></span> (<em>Copy image reference to the clipboard</em>) to be able to insert the image representation of the diagram into a text note. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_0Ofbk1aSuVRu\">Image references</a>&nbsp;for more information.</li></ul></li><li>To export the diagram as either SVG or PNG, go to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>&nbsp;and select <em>Export as image</em>:<ul><li>Select <em>SVG (vector)</em> to download a scalable/vector rendering of the diagram. Can be used to present the diagram without degrading when zooming.</li><li>Select <em>PNG (raster)</em> to download a normal image (at 1x scale, raster) of the diagram. Can be used to send the diagram in more traditional channels such as e-mail.</li></ul></li><li>The note can be marked as <a href=\"#root/_help_CoFPLs3dRlXc\">read-only</a>, case in which it switches by default to the preview (although it can be switched back using the source/preview buttons) and the source is no longer editable.</li></ul><h2>Errors in the diagram</h2><p>If there is an error in the source code, the error will be displayed in an information pane.</p><p>During the state of an error, the diagram will no longer be rendered and the previously working diagram will remain in the preview section.</p>",
"_help_RH6yLjjWJHof": "<p>Mermaid supports a different layout engine which supports slightly more complex diagrams, called the <a href=\"https://eclipse.dev/elk/\">Eclipse Layout Kernel (ELK)</a>. Trilium has support for these as well, but it's not enabled by default.</p><p>In order to activate ELK for any diagram, insert the following YAML frontmatter right at the beginning of the diagram:</p><pre><code class=\"language-text-x-yaml\">---\nconfig:\n layout: elk\n---</code></pre><figure class=\"table\"><table><thead><tr><th>With ELK off</th><th>With ELK on</th></tr></thead><tbody><tr><td><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Mermaid%20Diagrams/ELK%20layout_ELK%20off.svg\"></td><td><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Mermaid%20Diagrams/ELK%20layout_ELK%20on.svg\"></td></tr></tbody></table></figure>",
"_help_grjYqerjn243": "<figure class=\"image\"><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Canvas_image.png\" alt=\"grafik\"></figure><p>Canvas notes use the Excalidraw library to allow handwritten notes with mouse, pen or touch on an infinite canvas. It also supports basic diagramming, text and graphics input.</p><h2>Interaction</h2><ul><li>The note can be togged <a href=\"#root/_help_CoFPLs3dRlXc\">read-only</a> from the&nbsp;<a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a>.</li></ul><h2>Embedding notes</h2><p>Since v0.104.0, Canvas supports embedding notes in a similar fashion to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>&nbsp;functionality for&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes.</p><p>To embed a note:</p><ul><li>From the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, drag the item onto the canvas.</li><li>Manually, by choosing <em>More tools</em> → <em>Web Embed</em> and pasting the link to the note (e.g. <code>root/MujWAc9fQ1nj</code>).</li></ul><p>Embedding notes in the canvas follows the same rules as&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>: some notes are rendered as images (e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_gBbsAeiuUxI5\">Mind Map</a>), whereas some render fully interactive such as&nbsp;<a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>.</p><h2>Linking to a note</h2><ol><li>From the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>&nbsp;right click the note to be linked and selected <em>Advanced → Copy note path to the clipboard</em>.</li><li>In the canvas note, right click an element and select <em>Add link</em> (or press <kbd>Ctrl</kbd>+<kbd>K</kbd>). Paste the link and press <kbd>Enter</kbd>.</li><li>A&nbsp;<span class=\"tn-icon bx bx-link-external\"></span> icon will appear at the top-right of the element which will navigate to the linked note when clicked.</li></ol><h2>Drawing in a text note</h2><p>To draw inside a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note instead of in a note of its own, insert a drawing canvas with <span class=\"tn-icon bx bx-pen\"></span><em>Drawing canvas</em> in the <span class=\"tn-icon cke cke-plus\"></span><em>Insert</em> menu. See <em>Drawing canvases</em> in&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p>",
"_help_1vHRoWCEjj0L": "<h2>Configuration</h2><p>A webview needs to know which URL to render, and it can be provided by setting the <code>webViewSrc</code> <a href=\"#root/_help_zEY4DaJG4YT5\">label</a>, such as:</p><pre><code class=\"language-text-x-trilium-auto\">#webViewSrc=\"https://www.wikipedia.org\"</code></pre><p>The URL needs to contain the full scheme.</p><h2>Web view on the server vs. Electron</h2><p>When accessing Trilium via a browser instead of the desktop application, the web view will still try to render the content of the desired webpage. However, since it's running in a browser there are quite a few limitations as opposed to the desktop one.</p><p>More specifically, quite a few websites oppose being embedded in another website (technically they have a non-permisive <code>X-Frame-Options</code> header). This is not bypassable by Trilium so the page will simply fail to render.</p><p>You can diagnose this by right clicking the Trilium web page → Inspect (element) and looking in the “Console” tab for errors such as:</p><ul><li><code>Refused to display 'https://www.google.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.</code></li><li><code>Refused to frame 'https://duckduckgo.com/' because an ancestor violates the following Content Security Policy directive: \"frame-ancestors 'self' https://html.duckduckgo.com\".</code></li></ul><p>There are a few websites that do render such as <code>wikipedia.org</code>.</p><p>Do note that we are also applying some sandboxing constraints on the server side, so if you have any issues other than the unresolvable <code>X-Frame-Options</code> described above, feel free to report them.</p><p>On the desktop side, a different technology is used which bypasses the constraints of an <code>iframe</code> (<code>webview</code>).</p><h2>Embedding in other note types</h2><p>Starting with v0.104.0, web views can be embedded into other note types:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_IF7Q6I9x7zuw\">Dashboard</a></li><li><a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a></li><li><a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes via&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</li></ul>",
diff --git a/docs/User Guide/User Guide/Note Types/Mermaid Diagrams.md b/docs/User Guide/User Guide/Note Types/Mermaid Diagrams.md
index 686b7445a2..9933dc43ad 100644
--- a/docs/User Guide/User Guide/Note Types/Mermaid Diagrams.md
+++ b/docs/User Guide/User Guide/Note Types/Mermaid Diagrams.md
@@ -28,7 +28,8 @@ It's possible to switch between the two layouts at any time by pressing the <sp
* The source code of the diagram (in Mermaid format) is displayed on the left or bottom side of the note (depending on the layout).
* Changing the diagram code will refresh automatically the diagram.
- * <kbd>Ctrl</kbd>+<kbd>/</kbd> (Mac: <kbd>⌘</kbd>+<kbd>/</kbd>) comments out the current or selected lines with `%%`. Pressing it again on commented lines removes the `%%`.
+ * The front matter (the block between `---` lines at the start of the diagram, which holds its title and configuration) is highlighted as YAML.
+ * <kbd>Ctrl</kbd>+<kbd>/</kbd> (Mac: <kbd>⌘</kbd>+<kbd>/</kbd>) comments out the current or selected lines with `%%`, or with `#` in the front matter. Pressing it again on commented lines removes the comment marker.
* The preview of the diagram is displayed at the right or top side of the note (depending on the layout):
* There are dedicated buttons at the bottom-right of the preview to control the zoom in, zoom out or fit the diagram.
* The preview can be moved around by holding the left mouse button and dragging.
diff --git a/packages/codemirror/package.json b/packages/codemirror/package.json
index 6e1a22b42c..c108551846 100644
--- a/packages/codemirror/package.json
+++ b/packages/codemirror/package.json
@@ -20,6 +20,7 @@
"@codemirror/lang-php": "6.0.2",
"@codemirror/lang-vue": "0.1.3",
"@codemirror/lang-xml": "6.1.0",
+ "@codemirror/lang-yaml": "6.1.3",
"@codemirror/legacy-modes": "6.5.5",
"@codemirror/lint": "6.9.7",
"@codemirror/autocomplete": "6.20.3",
diff --git a/packages/codemirror/src/languages/mermaid/index.ts b/packages/codemirror/src/languages/mermaid/index.ts
index 55f1f3fc9f..37ef073dc3 100644
--- a/packages/codemirror/src/languages/mermaid/index.ts
+++ b/packages/codemirror/src/languages/mermaid/index.ts
@@ -2,6 +2,7 @@
// (itself a fork of https://github.com/inspirnathan/codemirror-lang-mermaid); MIT, see LICENSE.
// After editing a `.grammar` file, regenerate its parser with
// `pnpm --filter @triliumnext/codemirror build:mermaid-grammars`.
+import { yamlLanguage } from "@codemirror/lang-yaml";
import { languageDataProp, LanguageSupport, LRLanguage } from "@codemirror/language";
import { parseMixed } from "@lezer/common";
import type { LRParser } from "@lezer/lr";
@@ -62,6 +63,7 @@ export const mermaidLanguage = LRLanguage.define({
name: "mermaid",
parser: mermaidParser.configure({
wrap: parseMixed((node) => {
+ if (node.name === "FrontMatterContent") return { parser: yamlLanguage.parser };
const parser = nestedParsers[node.name];
return parser ? { parser } : null;
})
diff --git a/packages/codemirror/src/languages/mermaid/mermaid.spec.ts b/packages/codemirror/src/languages/mermaid/mermaid.spec.ts
index c36990d9e6..84afc14d3d 100644
--- a/packages/codemirror/src/languages/mermaid/mermaid.spec.ts
+++ b/packages/codemirror/src/languages/mermaid/mermaid.spec.ts
@@ -58,17 +58,25 @@ describe("mermaid", () => {
expect(support).toBeInstanceOf(LanguageSupport);
expect(support.language).toBe(mermaidLanguage);
- const tree = mermaidLanguage.parser.parse("---\ntitle: x\n---\npie\n \"A\": 1\n");
+ const tree = mermaidLanguage.parser.parse("%%{init: {}}%%\n\npie\n \"A\": 1\n");
expect(tree.toString()).toBe("MermaidDiagram(PieDiagram(DiagramName,String,Number))");
expect(mermaidLanguage.parser.parse("not a diagram\n").toString())
.toBe("MermaidDiagram(⚠)");
});
- it("toggles %% line comments in the preamble and in the diagram", () => {
+ it("accepts whitespace after the dashes of front matter", () => {
+ // Kept out of the `.txt` fixtures, where an editor can strip trailing whitespace.
+ const tree = (doc: string) => mermaidLanguage.parser.parse(doc).toString();
+ const doc = "---\nconfig:\n gantt: {}\n---\nsequenceDiagram\n A->>B: hi";
+ expect(tree(doc)).toContain("FrontMatter");
+ expect(tree(doc.replace("---\n", "--- \t\n").replace("\n---", "\n--- "))).toBe(tree(doc));
+ });
+
+ it("toggles # comments in the front matter and %% comments in the diagram", () => {
const doc = "---\ntitle: x\n---\nflowchart\n A --> B";
const state = EditorState.create({ doc, extensions: [ mermaid() ] });
const view = new EditorView({ state });
- const cases = [ [ 2, "%% title: x" ], [ 5, " %% A --> B" ] ] as const;
+ const cases = [ [ 2, "# title: x" ], [ 5, " %% A --> B" ] ] as const;
for (const [ lineNumber, commented ] of cases) {
view.dispatch({ selection: { anchor: view.state.doc.line(lineNumber).from } });
expect(toggleComment(view), commented).toBe(true);
@@ -82,7 +90,10 @@ describe("mermaid", () => {
it("parses Windows line endings like Unix ones", () => {
// Kept out of the `.txt` fixtures, where Git normalizes CRLF to LF.
const tree = (doc: string) => mermaidLanguage.parser.parse(doc).toString();
- for (const unix of [ "mindmap\n root\n \n child\n", "mindmap\n#x\n \n" ]) {
+ const docs = [
+ "mindmap\n root\n \n child\n", "mindmap\n#x\n \n", "---\na: 1\n---\npie"
+ ];
+ for (const unix of docs) {
expect(tree(unix.replaceAll("\n", "\r\n")), JSON.stringify(unix)).toBe(tree(unix));
}
});
diff --git a/packages/codemirror/src/languages/mermaid/parsers/mermaid/highlight.ts b/packages/codemirror/src/languages/mermaid/parsers/mermaid/highlight.ts
new file mode 100644
index 0000000000..0b659e5ccf
--- /dev/null
+++ b/packages/codemirror/src/languages/mermaid/parsers/mermaid/highlight.ts
@@ -0,0 +1,7 @@
+import { styleTags } from "@lezer/highlight";
+
+import { mermaidTags } from "../../tags/index.js";
+
+export const mermaidHighlighting = styleTags({
+ DashLine: mermaidTags.frontMatterDelimiter
+});
diff --git a/packages/codemirror/src/languages/mermaid/parsers/mermaid/mermaid.grammar b/packages/codemirror/src/languages/mermaid/parsers/mermaid/mermaid.grammar
index 5975d9f16f..77b4b66cac 100644
--- a/packages/codemirror/src/languages/mermaid/parsers/mermaid/mermaid.grammar
+++ b/packages/codemirror/src/languages/mermaid/parsers/mermaid/mermaid.grammar
@@ -2,7 +2,7 @@
// meaningful line and emits a single node for it. The main mermaidLanguage then
// uses parseMixed to hand that node's range to the matching sub-diagram parser.
@top MermaidDiagram {
- preDiagramLine* (
+ FrontMatter? preDiagramLine* (
PieDiagram |
MindmapDiagram |
FlowchartDiagram |
@@ -26,12 +26,24 @@
)
}
+// Mermaid reads front matter only at the very start of the document. index.ts parses
+// FrontMatterContent with the YAML parser.
+@skip {} {
+ FrontMatter { frontMatterStart FrontMatterContent? frontMatterEnd }
+}
+
@skip { space }
@tokens {
space { $[ \t\r]+ }
}
+@external tokens frontMatter from "./tokens.js" {
+ frontMatterStart[@name=DashLine],
+ FrontMatterContent,
+ frontMatterEnd[@name=DashLine]
+}
+
@external tokens diagramText from "./tokens.js" {
preDiagramLine,
PieDiagram,
@@ -55,3 +67,5 @@
GitDiagram,
C4Diagram
}
+
+@external propSource mermaidHighlighting from "./highlight.js"
diff --git a/packages/codemirror/src/languages/mermaid/parsers/mermaid/parser.terms.ts b/packages/codemirror/src/languages/mermaid/parsers/mermaid/parser.terms.ts
index 142c531ba4..423b4d9623 100644
--- a/packages/codemirror/src/languages/mermaid/parsers/mermaid/parser.terms.ts
+++ b/packages/codemirror/src/languages/mermaid/parsers/mermaid/parser.terms.ts
@@ -1,25 +1,29 @@
// AUTO-GENERATED by scripts/build_mermaid_grammars.mts from the grammar in this directory.
// This file was generated by lezer-generator. You probably shouldn't edit it.
export const
- preDiagramLine = 24,
- PieDiagram = 1,
- MindmapDiagram = 2,
- FlowchartDiagram = 3,
- SequenceDiagram = 4,
- JourneyDiagram = 5,
- RequirementDiagram = 6,
- GanttDiagram = 7,
- TimelineDiagram = 8,
- QuadrantDiagram = 9,
- SankeyDiagram = 10,
- XYChartDiagram = 11,
- PacketDiagram = 12,
- KanbanDiagram = 13,
- BlockDiagram = 14,
- ArchitectureDiagram = 15,
- ClassDiagram = 16,
- StateDiagram = 17,
- ERDiagram = 18,
- GitDiagram = 19,
- C4Diagram = 20,
- MermaidDiagram = 21
+ frontMatterStart = 1,
+ FrontMatterContent = 2,
+ frontMatterEnd = 3,
+ preDiagramLine = 28,
+ PieDiagram = 4,
+ MindmapDiagram = 5,
+ FlowchartDiagram = 6,
+ SequenceDiagram = 7,
+ JourneyDiagram = 8,
+ RequirementDiagram = 9,
+ GanttDiagram = 10,
+ TimelineDiagram = 11,
+ QuadrantDiagram = 12,
+ SankeyDiagram = 13,
+ XYChartDiagram = 14,
+ PacketDiagram = 15,
+ KanbanDiagram = 16,
+ BlockDiagram = 17,
+ ArchitectureDiagram = 18,
+ ClassDiagram = 19,
+ StateDiagram = 20,
+ ERDiagram = 21,
+ GitDiagram = 22,
+ C4Diagram = 23,
+ MermaidDiagram = 24,
+ FrontMatter = 25
diff --git a/packages/codemirror/src/languages/mermaid/parsers/mermaid/parser.ts b/packages/codemirror/src/languages/mermaid/parsers/mermaid/parser.ts
index e6705adcd3..0b50ff202c 100644
--- a/packages/codemirror/src/languages/mermaid/parsers/mermaid/parser.ts
+++ b/packages/codemirror/src/languages/mermaid/parsers/mermaid/parser.ts
@@ -1,18 +1,20 @@
// AUTO-GENERATED by scripts/build_mermaid_grammars.mts from the grammar in this directory.
// This file was generated by lezer-generator. You probably shouldn't edit it.
import {LRParser} from "@lezer/lr"
-import {diagramText} from "./tokens.js"
+import {frontMatter, diagramText} from "./tokens.js"
+import {mermaidHighlighting} from "./highlight.js"
export const parser = LRParser.deserialize({
version: 14,
- states: "nOVQROOOOQQ'#Cr'#CrOVQROOQOQPOOOOQQ-E6p-E6p",
- stateData: "!j~OjOS~OPROQRORROSROTROUROVROWROXROYROZRO[RO]RO^RO_RO`ROaRObROcROdROhPO~O",
- goto: "ngPPPPPPPPPPPPPPPPPPPPPPhQQORSQ",
- nodeNames: "⚠ PieDiagram MindmapDiagram FlowchartDiagram SequenceDiagram JourneyDiagram RequirementDiagram GanttDiagram TimelineDiagram QuadrantDiagram SankeyDiagram XYChartDiagram PacketDiagram KanbanDiagram BlockDiagram ArchitectureDiagram ClassDiagram StateDiagram ERDiagram GitDiagram C4Diagram MermaidDiagram",
- maxTerm: 26,
+ states: "!^O!jQVOOO!qOQO'#CuOOQS'#Cv'#CvOVQTOOQOQPOOOVQTOOOOQS,59a,59aO!yOQO,59aOOQS-E6t-E6tOOQS1G.{1G.{",
+ stateData: "#O~OnOS~OSSOTSOUSOVSOWSOXSOYSOZSO[SO]SO^SO_SO`SOaSObSOcSOdSOeSOfSOgSOlQO~OPPO~PVOQVORUO~ORXO~O",
+ goto: "vkPPPPPPPPPPPPPPPPPPPPPPPPPloRTOSROTRWR",
+ nodeNames: "⚠ DashLine FrontMatterContent DashLine PieDiagram MindmapDiagram FlowchartDiagram SequenceDiagram JourneyDiagram RequirementDiagram GanttDiagram TimelineDiagram QuadrantDiagram SankeyDiagram XYChartDiagram PacketDiagram KanbanDiagram BlockDiagram ArchitectureDiagram ClassDiagram StateDiagram ERDiagram GitDiagram C4Diagram MermaidDiagram FrontMatter",
+ maxTerm: 30,
+ propSources: [mermaidHighlighting],
skippedNodes: [0],
repeatNodeCount: 1,
- tokenData: "j~RRXY[]^[pq[~aRj~XY[]^[pq[",
- tokenizers: [0, diagramText],
- topRules: {"MermaidDiagram":[0,21]},
+ tokenData: "j~RRXY[]^[pq[~aRn~XY[]^[pq[",
+ tokenizers: [0, frontMatter, diagramText],
+ topRules: {"MermaidDiagram":[0,24]},
tokenPrec: 0
})
diff --git a/packages/codemirror/src/languages/mermaid/parsers/mermaid/tokens.ts b/packages/codemirror/src/languages/mermaid/parsers/mermaid/tokens.ts
index 9f22ecb2a5..d50e818487 100644
--- a/packages/codemirror/src/languages/mermaid/parsers/mermaid/tokens.ts
+++ b/packages/codemirror/src/languages/mermaid/parsers/mermaid/tokens.ts
@@ -1,5 +1,8 @@
-import { ExternalTokenizer } from "@lezer/lr";
+import { ExternalTokenizer, type InputStream } from "@lezer/lr";
import {
+ FrontMatterContent,
+ frontMatterEnd,
+ frontMatterStart,
preDiagramLine,
MindmapDiagram,
PieDiagram,
@@ -65,6 +68,28 @@ const diagramMap: Record<string, number> = {
const diagrams = Object.keys(diagramMap);
+/**
+ * Splits front matter into its `---` lines and the YAML between them. Like Mermaid, it takes a
+ * `---` line as the opening only at the start of the document (the only place the grammar can
+ * shift `frontMatterStart`) and only when a closing `---` line follows; otherwise the lines go
+ * to `diagramText`.
+ */
+export const frontMatter = new ExternalTokenizer((input, stack) => {
+ if (stack.canShift(frontMatterStart)) {
+ const opening = dashLineLength(input, 0);
+ if (opening > 0 && findClosingLine(input, opening) >= 0) {
+ input.acceptToken(frontMatterStart, opening);
+ }
+ } else {
+ const closing = findClosingLine(input, 0);
+ if (closing > 0) {
+ input.acceptToken(FrontMatterContent, closing);
+ } else {
+ input.acceptToken(frontMatterEnd, dashLineLength(input, 0));
+ }
+ }
+});
+
export const diagramText = new ExternalTokenizer((input) => {
if (skipCodePoints.includes(input.next)) return;
@@ -90,3 +115,29 @@ export const diagramText = new ExternalTokenizer((input) => {
input.acceptToken(preDiagramLine);
}
});
+
+/** The offset of the first `---` line at or after `offset`, or -1 when there is none. */
+function findClosingLine(input: InputStream, offset: number) {
+ while (input.peek(offset) !== -1) {
+ if (dashLineLength(input, offset) > 0) return offset;
+ while (input.peek(offset) !== 10 && input.peek(offset) !== -1) offset++;
+ offset++;
+ }
+ return -1;
+}
+
+/**
+ * The length of the line at `offset`, newline included, when it is `---` followed by nothing but
+ * whitespace; otherwise 0.
+ */
+function dashLineLength(input: InputStream, offset: number) {
+ let length = 0;
+ while (length < 3) {
+ if (input.peek(offset + length) !== 45) return 0;
+ length++;
+ }
+ while ([ 9, 13, 32 ].includes(input.peek(offset + length))) length++;
+ const next = input.peek(offset + length);
+ if (next === 10) return length + 1;
+ return next === -1 ? length : 0;
+}
diff --git a/packages/codemirror/src/languages/mermaid/tags/index.ts b/packages/codemirror/src/languages/mermaid/tags/index.ts
index 0aa444df8a..76e9a0c3a3 100644
--- a/packages/codemirror/src/languages/mermaid/tags/index.ts
+++ b/packages/codemirror/src/languages/mermaid/tags/index.ts
@@ -1,7 +1,8 @@
import { Tag, tags as t } from "@lezer/highlight";
export const mermaidTags = {
- diagramName: Tag.define(t.typeName)
+ diagramName: Tag.define(t.typeName),
+ frontMatterDelimiter: Tag.define(t.meta)
};
export const mindmapTags = {
diff --git a/packages/codemirror/src/languages/mermaid/test/mermaid.txt b/packages/codemirror/src/languages/mermaid/test/mermaid.txt
index 5581f64406..d6d407b29a 100644
--- a/packages/codemirror/src/languages/mermaid/test/mermaid.txt
+++ b/packages/codemirror/src/languages/mermaid/test/mermaid.txt
@@ -165,3 +165,74 @@ C4Context
==>
MermaidDiagram(C4Diagram(DiagramName))
+
+# Front matter whose config names another diagram
+
+---
+config:
+ gantt:
+ barHeight: 30
+---
+sequenceDiagram
+ A->>B: hi
+
+==>
+
+MermaidDiagram(FrontMatter(DashLine,Stream(Document(BlockMapping(Pair(Key(Literal),":",BlockMapping(Pair(Key(Literal),":",BlockMapping(Pair(Key(Literal),":",Literal)))))))),DashLine),SequenceDiagram(DiagramName,NodeText,Arrow,NodeText,MessageText1))
+
+# Empty front matter
+
+---
+---
+pie
+ "A": 1
+
+==>
+
+MermaidDiagram(FrontMatter(DashLine,DashLine),PieDiagram(DiagramName,String,Number))
+
+# Unclosed front matter is not front matter
+
+---
+title: x
+pie
+ "A": 1
+
+==>
+
+MermaidDiagram(PieDiagram(DiagramName,String,Number))
+
+# Front matter after a directive is not front matter
+
+%%{init: {}}%%
+---
+title: x
+---
+pie
+ "A": 1
+
+==>
+
+MermaidDiagram(PieDiagram(DiagramName,String,Number))
+
+# Front matter with no diagram after it
+
+---
+title: x
+---
+
+==>
+
+MermaidDiagram(FrontMatter(DashLine,Stream(Document(BlockMapping(Pair(Key(Literal),":",Literal)))),DashLine),⚠)
+
+# A dash line followed by other text is not a delimiter
+
+---x
+title: x
+---
+pie
+ "A": 1
+
+==>
+
+MermaidDiagram(PieDiagram(DiagramName,String,Number))
diff --git a/packages/codemirror/src/syntax_highlighting.spec.ts b/packages/codemirror/src/syntax_highlighting.spec.ts
index dd064373b0..dffdbaba34 100644
--- a/packages/codemirror/src/syntax_highlighting.spec.ts
+++ b/packages/codemirror/src/syntax_highlighting.spec.ts
@@ -57,16 +57,20 @@ describe("byMimeType", () => {
if (!syntax) return;
// The Mermaid grammar loads on first use, so a code block parses as plain text until then.
- const doc = "```mermaid\nflowchart\n A --> B\n```\n";
+ const doc = "```mermaid\n---\nconfig:\n gantt: {}\n---\nflowchart\n A --> B\n```\n";
await vi.waitFor(() => {
const tree = ensureSyntaxTree(stateFor(syntax, doc), doc.length, 1000);
- const names: string[] = [];
- let node = tree?.resolveInner(doc.indexOf("A"), 1) ?? null;
- while (node) {
- names.push(node.name);
- node = node.parent;
- }
- expect(names).toContain("FlowchartDiagram");
+ const nodeAt = (text: string) => {
+ const names: string[] = [];
+ let node = tree?.resolveInner(doc.indexOf(text), 1) ?? null;
+ while (node) {
+ names.push(node.name);
+ node = node.parent;
+ }
+ return names;
+ };
+ expect(nodeAt("A -->")).toContain("FlowchartDiagram");
+ expect(nodeAt("gantt")).toContain("Key");
});
});
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7602475fe0..ac10ff5df6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1156,6 +1156,9 @@ importers:
'@codemirror/lang-xml':
specifier: 6.1.0
version: 6.1.0
+ '@codemirror/lang-yaml':
+ specifier: 6.1.3
+ version: 6.1.3
'@codemirror/language-data':
specifier: 6.5.2
version: 6.5.2