Skip to content

Commit

Permalink
fix: handle empty newlines before diagrams in md
Browse files Browse the repository at this point in the history
Handles empty newlines before and after diagrams in Markdown.

For example, the following Markdown:

````markdown
My text.

```mermaid
  my diagram
```
````

Should get converted to:

```markdown
My text.

![diagram](./my-diagram)
```

However, currently, the empty newline is removed.
We can fix this by making sure that our Regex ignores newlines outside
of the Mermaid diagram code.

Fixes: 9d7b4b2
Fixes: #413
  • Loading branch information
aloisklink authored and MindaugasLaganeckas committed Jan 2, 2023
1 parent 3a5c983 commit a0888a4
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src-test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,9 @@ describe("NodeJS API (import ... from '@mermaid-js/mermaid-cli')", () => {
'(./mermaid-run-output-test-png-8.png "State diagram example with \\\\\\"double-quotes\\"")')
expect(markdownFile).toContain(markdownImageWithCustomTitle)

// check whether newlines before/after mermaid diagram are kept
expect(markdownFile).toContain('There should be an empty newline after this line, but before the Mermaid diagram:\n\n')

// files should exist, and they should be PNGs
await Promise.all(expectedOutputPngs.map(async (expectedOutputPng) => {
// markdown file should point to png relative to md file
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,8 @@ async function run (input, output, { puppeteerConfig = {}, quiet = false, output
}
}

const mermaidChartsInMarkdown = /^\s*```(?:mermaid)(\r?\n([\s\S]*?))```\s*$/
// TODO: should we use a Markdown parser like remark instead of rolling our own parser?
const mermaidChartsInMarkdown = /^[^\S\n]*```(?:mermaid)(\r?\n([\s\S]*?))```[^\S\n]*$/
const mermaidChartsInMarkdownRegexGlobal = new RegExp(mermaidChartsInMarkdown, 'gm')
const browser = await puppeteer.launch(puppeteerConfig)
try {
Expand Down
4 changes: 4 additions & 0 deletions test-positive/mermaid.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ graph LR
A -->|こんにちは| B
```
7. sequence.mmd

There should be an empty newline after this line, but before the Mermaid diagram:

```mermaid
sequenceDiagram
%% See https://mermaidjs.github.io/sequenceDiagram.html
Expand All @@ -103,6 +106,7 @@ loop D-1 before deadline at 7:45
Note over HII,FGG: D-1 before deadline
end
```

8. Should still find mermaid code even when code-block is indented.

```mermaid
Expand Down

0 comments on commit a0888a4

Please sign in to comment.