Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Anything that would make the library complicated, such as generating nested list
- [x] mermaid treemap diagram
- [x] mermaid radar chart
- [x] mermaid sankey diagram
- [x] mermaid C4 context diagram (experimental feature)

### Features not in Markdown syntax
- Generate badges; RedBadge(), YellowBadge(), GreenBadge().
Expand Down Expand Up @@ -2137,6 +2138,96 @@ treemap-beta
"Ads": 800
```

### C4 context syntax

mermaid marks its C4 support experimental and says the syntax may change, so this package stays on the C4Context diagram: the people and the software systems around the one being described.

```go
package main

import (
"io"
"os"

"github.com/nao1215/markdown"
"github.com/nao1215/markdown/mermaid/c4"
)

//go:generate go run main.go

func main() {
f, err := os.Create("generated.md")
if err != nil {
panic(err)
}
defer f.Close()

diagram := c4.NewDiagram(io.Discard, c4.WithTitle("System Context: Internet Banking")).
EnterpriseBoundary("bank", "Big Bank plc").
Person("customer", "Personal Banking Customer", c4.WithDescription("A customer of the bank.")).
SystemBoundary("banking", "Internet Banking").
System("web", "Internet Banking System", c4.WithDescription("Shows account information.")).
SystemDb("accounts", "Accounts Database").
BoundaryEnd().
BoundaryEnd().
SystemExt("mail", "E-mail System", c4.WithDescription("The internal Microsoft Exchange system.")).
Rel("customer", "web", "Views balances", c4.WithTechnology("HTTPS")).
BiRel("web", "accounts", "Reads from and writes to", c4.WithTechnology("SQL/TCP")).
Rel("web", "mail", "Sends e-mail using", c4.WithTechnology("SMTP")).
String()

err = markdown.NewMarkdown(f).
H2("C4 Context").
CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
Build()
Comment on lines +2179 to +2182

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Make the README example reproduce the linked generated file.

Line 2179 uses default spacing, but doc/c4/main.go Line 43 uses markdown.WithBlockSpacing(). The committed doc/c4/generated.md also contains a blank line after ## C4 Context, while both README output blocks omit it.

Add markdown.WithBlockSpacing() to the README example and regenerate the displayed output.

Suggested fix
-	err = markdown.NewMarkdown(f).
+	err = markdown.NewMarkdown(f, markdown.WithBlockSpacing()).

Also applies to: 2194-2229

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 2179 - 2182, Update the README markdown builder
example around the C4 Context section to include markdown.WithBlockSpacing(),
matching doc/c4/main.go. Regenerate the displayed output blocks so they include
the blank line after “## C4 Context” and exactly match doc/c4/generated.md.


if err != nil {
panic(err)
}
}
```

A boundary is a pair of calls rather than a nested builder: `Boundary`, `EnterpriseBoundary` and `SystemBoundary` open one, everything after belongs to it, and `BoundaryEnd` closes it. Leaving one open is reported from `Build`, because mermaid refuses a diagram whose brace never closes.

Labels are escaped with the entity form mermaid decodes, so a quotation mark or a `#` in one cannot break the macro syntax. The title is the exception: mermaid reads the rest of the line, quotes and all, so the package does not quote it.

Plain text output: [markdown is here](./doc/c4/generated.md)
````
## C4 Context
```mermaid
C4Context
title System Context: Internet Banking
Enterprise_Boundary(bank, "Big Bank plc") {
Person(customer, "Personal Banking Customer", "A customer of the bank.")
System_Boundary(banking, "Internet Banking") {
System(web, "Internet Banking System", "Shows account information.")
SystemDb(accounts, "Accounts Database")
}
}
System_Ext(mail, "E-mail System", "The internal Microsoft Exchange system.")
Rel(customer, web, "Views balances", "HTTPS")
BiRel(web, accounts, "Reads from and writes to", "SQL/TCP")
Rel(web, mail, "Sends e-mail using", "SMTP")
```
````

Mermaid output:
```mermaid
C4Context
title System Context: Internet Banking
Enterprise_Boundary(bank, "Big Bank plc") {
Person(customer, "Personal Banking Customer", "A customer of the bank.")
System_Boundary(banking, "Internet Banking") {
System(web, "Internet Banking System", "Shows account information.")
SystemDb(accounts, "Accounts Database")
}
}
System_Ext(mail, "E-mail System", "The internal Microsoft Exchange system.")
Rel(customer, web, "Views balances", "HTTPS")
BiRel(web, accounts, "Reads from and writes to", "SQL/TCP")
Rel(web, mail, "Sends e-mail using", "SMTP")
```

## Creating an index for a directory full of markdown files
The markdown package can create an index for Markdown files within the specified directory. This feature was added to generate indexes for Markdown documents produced by [nao1215/spectest](https://github.com/nao1215/spectest).

Expand Down
2 changes: 1 addition & 1 deletion SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Two helpers fall outside GFM and are documented here so their behavior is not mi
- `Highlight` emits `==text==`. GitHub does not render this; Obsidian, Bear, and several static site generators do. It is kept because it has always been part of the API and it costs nothing, but it is not part of the GFM target.
- The badge helpers (`RedBadge` and friends) emit an image link pointing at `img.shields.io`. The markdown is plain GFM; what the image looks like is up to that external service.

Mermaid diagram bodies follow [the mermaid syntax](https://mermaid.js.org/intro/syntax-reference.html) rather than GFM, since a markdown parser treats them as opaque code block content. Diagram titles are emitted as a YAML front matter block inside the diagram, which is how mermaid itself expects them.
Mermaid diagram bodies follow [the mermaid syntax](https://mermaid.js.org/intro/syntax-reference.html) rather than GFM, since a markdown parser treats them as opaque code block content. Diagram titles are emitted as a YAML front matter block inside the diagram, which is how mermaid itself expects them; the exception is the C4 diagram, which draws a `title` statement and ignores the front matter.

## Out of scope

Expand Down
11 changes: 11 additions & 0 deletions contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/nao1215/markdown/internal/golden"
"github.com/nao1215/markdown/mermaid/arch"
"github.com/nao1215/markdown/mermaid/block"
"github.com/nao1215/markdown/mermaid/c4"
"github.com/nao1215/markdown/mermaid/class"
"github.com/nao1215/markdown/mermaid/er"
"github.com/nao1215/markdown/mermaid/flowchart"
Expand Down Expand Up @@ -1380,6 +1381,16 @@ func mermaidBuilders() []mermaidBuilder {
String()
},
},
{
name: "c4",
build: func() string {
return c4.NewDiagram(io.Discard).
Person("customer", "Customer").
System("ledger", "Ledger").
Rel("customer", "ledger", "Uses").
String()
},
},
{
name: "class",
build: func() string {
Expand Down
17 changes: 17 additions & 0 deletions doc/c4/generated.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
## C4 Context

```mermaid
C4Context
title System Context: Internet Banking
Enterprise_Boundary(bank, "Big Bank plc") {
Person(customer, "Personal Banking Customer", "A customer of the bank.")
System_Boundary(banking, "Internet Banking") {
System(web, "Internet Banking System", "Shows account information.")
SystemDb(accounts, "Accounts Database")
}
}
System_Ext(mail, "E-mail System", "The internal Microsoft Exchange system.")
Rel(customer, web, "Views balances", "HTTPS")
BiRel(web, accounts, "Reads from and writes to", "SQL/TCP")
Rel(web, mail, "Sends e-mail using", "SMTP")
```
50 changes: 50 additions & 0 deletions doc/c4/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//go:build linux || darwin

// Package main is generating mermaid C4 context diagram.
package main

import (
"io"
"os"

"github.com/nao1215/markdown"
"github.com/nao1215/markdown/mermaid/c4"
)

// This file is gated by //go:build linux || darwin, so //go:generate is skipped
// on Windows. To regenerate generated.md on Windows, run under WSL or via CI.
//go:generate go run main.go
Comment on lines +1 to +16

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- tracked files ---'
git ls-files 'doc/c4' 'go.mod' 'go.work' | sed -n '1,120p'

printf '%s\n' '--- generator source ---'
cat -n doc/c4/main.go

printf '%s\n' '--- C4 directory ---'
find doc/c4 -maxdepth 1 -type f -print -exec wc -l {} \;

printf '%s\n' '--- generation directives and related constraints ---'
rg -n --glob '!generated.md' 'go:generate|go:build|mermaid/c4|package main' doc/c4 .

Repository: nao1215/markdown

Length of output: 11896


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- module metadata ---'
cat -n go.mod | sed -n '1,80p'

printf '%s\n' '--- Windows package selection ---'
GOOS=windows GOARCH=amd64 go list -e -json ./doc/c4 | jq '{Dir,Name,GoFiles,IgnoredGoFiles,Imports,Error}'

printf '%s\n' '--- generation commands discovered for Windows ---'
GOOS=windows GOARCH=amd64 go generate -n ./doc/c4 2>&1 || true

printf '%s\n' '--- native package selection ---'
GOOS=linux GOARCH=amd64 go list -e -json ./doc/c4 | jq '{Dir,Name,GoFiles,IgnoredGoFiles,Imports,Error}'

printf '%s\n' '--- build constraints in imported C4 package ---'
rg -n --glob '*.go' '^//go:build|^// \+build|^package |^import ' mermaid/c4

Repository: nao1215/markdown

Length of output: 2944


🏁 Script executed:

#!/bin/bash
set -eu

for pkg in . ./mermaid/c4 ./doc/c4; do
  printf '%s\n' "--- Windows package: $pkg ---"
  GOOS=windows GOARCH=amd64 go list -e -json "$pkg" |
    jq '{ImportPath,Name,GoFiles,IgnoredGoFiles,Imports,Error}'
done

printf '%s\n' '--- platform-specific files in generator dependencies ---'
rg -n --glob '*.go' '^//go:build|^// \+build' markdown.go mermaid/c4 2>/dev/null || true

Repository: nao1215/markdown

Length of output: 1619


Remove the Windows build constraint from doc/c4/main.go.

On Windows, Go ignores main.go, so go generate ./doc/c4 finds no directive. The generator and its dependencies use Windows-compatible files and portable APIs.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@doc/c4/main.go` around lines 1 - 16, Remove the //go:build linux || darwin
constraint from doc/c4/main.go so the main package and its //go:generate
directive are included on Windows. Leave the generator implementation and
existing directive unchanged.


func main() {
f, err := os.Create("generated.md")
if err != nil {
panic(err)
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()

diagram := c4.NewDiagram(io.Discard, c4.WithTitle("System Context: Internet Banking")).
EnterpriseBoundary("bank", "Big Bank plc").
Person("customer", "Personal Banking Customer", c4.WithDescription("A customer of the bank.")).
SystemBoundary("banking", "Internet Banking").
System("web", "Internet Banking System", c4.WithDescription("Shows account information.")).
SystemDb("accounts", "Accounts Database").
BoundaryEnd().
BoundaryEnd().
SystemExt("mail", "E-mail System", c4.WithDescription("The internal Microsoft Exchange system.")).
Rel("customer", "web", "Views balances", c4.WithTechnology("HTTPS")).
BiRel("web", "accounts", "Reads from and writes to", c4.WithTechnology("SQL/TCP")).
Rel("web", "mail", "Sends e-mail using", c4.WithTechnology("SMTP")).
String()

err = markdown.NewMarkdown(f, markdown.WithBlockSpacing()).
H2("C4 Context").
CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
Build()
if err != nil {
panic(err)
}
}
22 changes: 22 additions & 0 deletions doc/edgecase/c4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# C4 context rendering edge cases

Every label below holds the punctuation this diagram type can carry. Generated by doc/edgecase/main.go and rendered in continuous integration, so a quoting defect fails the build rather than reaching a diagram.

```mermaid
C4Context
title title "'#35;#59;[](){}🎉日本語:,*-|%%\
Enterprise_Boundary(enterprise, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x") {
Person(person, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x", "before #quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\ after")
System_Boundary(systems, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x nested") {
System(system, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x", "before #quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\ after")
}
}
Boundary(outside, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x", "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x") {
System_Ext(external, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x")
}
Person_Ext(auditor, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x")
SystemDb(db, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x")
SystemQueue(queue, "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x")
Rel(person, system, "before #quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\ after", "x#quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\x")
BiRel(system, db, "before #quot;'#35;;[](){}<br/>🎉日本語:,*-|%%\ after")
```
27 changes: 27 additions & 0 deletions doc/edgecase/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/nao1215/markdown"
"github.com/nao1215/markdown/mermaid/arch"
"github.com/nao1215/markdown/mermaid/block"
"github.com/nao1215/markdown/mermaid/c4"
"github.com/nao1215/markdown/mermaid/class"
"github.com/nao1215/markdown/mermaid/er"
"github.com/nao1215/markdown/mermaid/flowchart"
Expand Down Expand Up @@ -70,6 +71,11 @@ func supported(diagram string) string {
// plain emoji and Japanese text.
"architecture": "",
"block": `"'#;[](){}<br/>` + emoji + japanese + `:,*-|%%`,
// c4 escapes a quote and a "#" in a label as the entity form mermaid
// decodes, and a "#" and a ";" in the unquoted title the same way, so
// every character below survives both. Only a line break is left out:
// one macro is one line, and "<br/>" is how a label breaks one.
"c4": `"'#;[](){}<br/>` + emoji + japanese + `:,*-|%%\`,
// class: ";" and ":" end a relation label.
"class": `"'#[](){}` + emoji + japanese + `,*-|%%`,
// er: a double quote ends the comment it is written in.
Expand Down Expand Up @@ -212,6 +218,7 @@ func diagrams() []diagram {
return []diagram{
{name: "Architecture", file: "architecture", build: architecture},
{name: "Block", file: "block", build: blockDiagram},
{name: "C4 context", file: "c4", build: c4Context},
{name: "Class", file: "class", build: classDiagram},
{name: "Entity relationship", file: "er", build: entityRelationship},
{name: "Flowchart", file: "flowchart", build: flowchartDiagram},
Expand Down Expand Up @@ -256,6 +263,26 @@ func blockDiagram(diagram string) string {
String()
}

// c4Context is the C4 context diagram's edge case document.
func c4Context(diagram string) string {
return c4.NewDiagram(io.Discard, c4.WithTitle(title(diagram))).
EnterpriseBoundary("enterprise", shortLabel(diagram)).
Person("person", shortLabel(diagram), c4.WithDescription(label(diagram))).
SystemBoundary("systems", shortLabel(diagram)+" nested").
System("system", shortLabel(diagram), c4.WithDescription(label(diagram))).
BoundaryEnd().
BoundaryEnd().
Boundary("outside", shortLabel(diagram), c4.WithBoundaryType(shortLabel(diagram))).
SystemExt("external", shortLabel(diagram)).
BoundaryEnd().
PersonExt("auditor", shortLabel(diagram)).
SystemDb("db", shortLabel(diagram)).
SystemQueue("queue", shortLabel(diagram)).
Rel("person", "system", label(diagram), c4.WithTechnology(shortLabel(diagram))).
BiRel("system", "db", label(diagram)).
String()
}

func classDiagram(diagram string) string {
return class.NewDiagram(io.Discard, class.WithTitle(title(diagram))).
Class("Account", class.WithPublicField("string", "id")).
Expand Down
Loading