markdown

package module
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 13 Imported by: 41

README

All Contributors

Go Reference MultiPlatformUnitTest reviewdog Gosec Coverage

日本語 | Русский | 中文 | 한국어 | Español | Français

What is markdown package

The Package markdown is a simple markdown builder in golang. The markdown package assembles Markdown using method chaining, not uses a template engine like html/template. The syntax of Markdown follows GitHub Markdown.

The markdown package was initially developed to save test results in nao1215/spectest. Therefore, the markdown package implements the features required by spectest. For example, the markdown package supports mermaid diagrams (entity relationship diagram, sequence diagram, user journey diagram, git graph diagram, mindmap diagram, requirement diagram, xy chart, packet diagram, block diagram, kanban diagram, flowchart, pie chart, quadrant chart, state diagram, class diagram, Gantt chart, architecture diagram), which was a necessary feature in spectest.

Additionally, complex code that increases the complexity of the library, such as generating nested lists, will not be added. I want to keep this library as simple as possible.

Supported OS and go version

  • OS: Linux, macOS, Windows
  • Go: 1.23 or later

Supported Markdown features

  • Heading; H1, H2, H3, H4, H5, H6
  • Blockquote
  • Bullet list
  • Ordered list
  • Checkbox list
  • Code blocks
  • Horizontal rule
  • Table
  • Text formatting; bold, italic, code, strikethrough, bold italic
  • Text with link
  • Reference link
  • Text with image
  • Plain text
  • Details
  • Footnotes
  • Mathematical expressions
  • Alerts; NOTE, TIP, IMPORTANT, CAUTION, WARNING
  • mermaid sequence diagram
  • mermaid user journey diagram
  • mermaid git graph diagram
  • mermaid mindmap diagram
  • mermaid requirement diagram
  • mermaid xy chart
  • mermaid packet diagram
  • mermaid block diagram
  • mermaid kanban diagram
  • mermaid entity relationship diagram
  • mermaid flowchart
  • mermaid pie chart
  • mermaid quadrant chart
  • mermaid state diagram
  • mermaid class diagram
  • mermaid Gantt chart
  • mermaid architecture diagram (beta feature)
Features not in Markdown syntax
  • Generate badges; RedBadge(), YellowBadge(), GreenBadge().
  • Generate an index for a directory full of markdown files; GenerateIndex()

Example

Basic usage
package main

import (
	"os"

	md "github.com/nao1215/markdown"
)

func main() {
	md.NewMarkdown(os.Stdout).
		H1("This is H1").
		PlainText("This is plain text").
		H2f("This is %s with text format", "H2").
		PlainTextf("Text formatting, such as %s and %s, %s styles.",
			md.Bold("bold"), md.Italic("italic"), md.Code("code")).
		H2("Code Block").
		CodeBlocks(md.SyntaxHighlightGo,
			`package main
import "fmt"

func main() {
	fmt.Println("Hello, World!")
}`).
		H2("List").
		BulletList("Bullet Item 1", "Bullet Item 2", "Bullet Item 3").
		OrderedList("Ordered Item 1", "Ordered Item 2", "Ordered Item 3").
		H2("CheckBox").
		CheckBox([]md.CheckBoxSet{
			{Checked: false, Text: md.Code("sample code")},
			{Checked: true, Text: md.Link("Go", "https://golang.org")},
			{Checked: false, Text: md.Strikethrough("strikethrough")},
		}).
		H2("Blockquote").
		Blockquote("If you can dream it, you can do it.").
		H3("Horizontal Rule").
		HorizontalRule().
		H2("Table").
		Table(md.TableSet{
			Header: []string{"Name", "Age", "Country"},
			Rows: [][]string{
				{"David", "23", "USA"},
				{"John", "30", "UK"},
				{"Bob", "25", "Canada"},
			},
		}).
		H2("Image").
		PlainTextf(md.Image("sample_image", "./sample.png")).
		Build()
}

Output:

# This is H1
This is plain text
  
## This is H2 with text format
Text formatting, such as **bold** and *italic*, `code` styles.
  
## Code Block
```go
package main
import "fmt"

func main() {
        fmt.Println("Hello, World!")
}
```
  
## List
- Bullet Item 1
- Bullet Item 2
- Bullet Item 3
1. Ordered Item 1
2. Ordered Item 2
3. Ordered Item 3
  
## CheckBox
- [ ] `sample code`
- [x] [Go](https://golang.org)
- [ ] ~~strikethrough~~
  
## Blockquote
> If you can dream it, you can do it.
  
### Horizontal Rule
---
  
## Table
| NAME  | AGE | COUNTRY |
|-------|-----|---------|
| David |  23 | USA     |
| John  |  30 | UK      |
| Bob   |  25 | Canada  |

## Image
![sample_image](./sample.png)

If you want to see how it looks in Markdown, please refer to the following link.

Generate Markdown using "go generate ./..."

You can generate Markdown using go generate. Please define code to generate Markdown first. Then, run "go generate ./..." to generate Markdown.

Code example:

package main

import (
	"os"

	md "github.com/nao1215/markdown"
)

//go:generate go run main.go

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

	md.NewMarkdown(f).
		H1("go generate example").
		PlainText("This markdown is generated by `go generate`").
		Build()
}

Run below command:

go generate ./...

Output:

# go generate example
This markdown is generated by `go generate`
Alerts syntax

The markdown package can create alerts. Alerts are useful for displaying important information in Markdown. This syntax is supported by GitHub. Code example:

	md.NewMarkdown(f).
		H1("Alert example").
		Note("This is note").LF().
		Tip("This is tip").LF().
		Important("This is important").LF().
		Warning("This is warning").LF().
		Caution("This is caution").LF().
		Build()

Output:

# Alert example
> [!NOTE]  
> This is note
  
> [!TIP]  
> This is tip
  
> [!IMPORTANT]  
> This is important
  
> [!WARNING]  
> This is warning
  
> [!CAUTION]  
> This is caution

Your alert will look like this;

[!NOTE]
This is note

[!TIP]
This is tip

[!IMPORTANT]
This is important

[!WARNING]
This is warning

[!CAUTION]
This is caution

Status badge syntax

The markdown package can create red, yellow, and green status badges. Code example:

	md.NewMarkdown(os.Stdout).
		H1("badge example").
		RedBadge("red_badge").
		YellowBadge("yellow_badge").
		GreenBadge("green_badge").
		BlueBadge("blue_badge").
		Build()

Output:

# badge example
![Badge](https://img.shields.io/badge/red_badge-red)
![Badge](https://img.shields.io/badge/yellow_badge-yellow)
![Badge](https://img.shields.io/badge/green_badge-green)
![Badge](https://img.shields.io/badge/blue_badge-blue)

Your badge will look like this;
Badge Badge Badge Badge

Mermaid sequence diagram syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := sequence.NewDiagram(io.Discard).
		Participant("Sophia").
		Participant("David").
		Participant("Subaru").
		LF().
		SyncRequest("Sophia", "David", "Please wake up Subaru").
		SyncResponse("David", "Sophia", "OK").
		LF().
		LoopStart("until Subaru wake up").
		SyncRequest("David", "Subaru", "Wake up!").
		SyncResponse("Subaru", "David", "zzz").
		SyncRequest("David", "Subaru", "Hey!!!").
		BreakStart("if Subaru wake up").
		SyncResponse("Subaru", "David", "......").
		BreakEnd().
		LoopEnd().
		LF().
		SyncResponse("David", "Sophia", "wake up, wake up").
		String()

	markdown.NewMarkdown(os.Stdout).
		H2("Sequence Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build()
}

Plain text output: markdown is here

## Sequence Diagram
```mermaid
sequenceDiagram
    participant Sophia
    participant David
    participant Subaru

    Sophia->>David: Please wake up Subaru
    David-->>Sophia: OK

    loop until Subaru wake up
    David->>Subaru: Wake up!
    Subaru-->>David: zzz
    David->>Subaru: Hey!!!
    break if Subaru wake up
    Subaru-->>David: ......
    end
    end

    David-->>Sophia: wake up, wake up
```

Mermaid output:

sequenceDiagram
    participant Sophia
    participant David
    participant Subaru

    Sophia->>David: Please wake up Subaru
    David-->>Sophia: OK

    loop until Subaru wake up
    David->>Subaru: Wake up!
    Subaru-->>David: zzz
    David->>Subaru: Hey!!!
    break if Subaru wake up
    Subaru-->>David: ......
    end
    end

    David-->>Sophia: wake up, wake up
Mermaid user journey diagram syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := userjourney.NewDiagram(
		io.Discard,
		userjourney.WithTitle("Checkout Journey"),
	).
		Section("Discover").
		Task("Browse products", userjourney.ScoreVerySatisfied, "Customer").
		Task("Add item to cart", userjourney.ScoreSatisfied, "Customer").
		LF().
		Section("Checkout").
		Task("Enter shipping details", userjourney.ScoreNeutral, "Customer").
		Task("Complete payment", userjourney.ScoreSatisfied, "Customer", "Payment Service").
		String()

	if err := markdown.NewMarkdown(os.Stdout).
		H2("User Journey Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build(); err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## User Journey Diagram
```mermaid
journey
    title Checkout Journey
    section Discover
        Browse products: 5: Customer
        Add item to cart: 4: Customer

    section Checkout
        Enter shipping details: 3: Customer
        Complete payment: 4: Customer, Payment Service
```

Mermaid output:

journey
    title Checkout Journey
    section Discover
        Browse products: 5: Customer
        Add item to cart: 4: Customer

    section Checkout
        Enter shipping details: 3: Customer
        Complete payment: 4: Customer, Payment Service
Mermaid git graph syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := gitgraph.NewDiagram(
		io.Discard,
		gitgraph.WithTitle("Release Flow"),
	).
		Commit(gitgraph.WithCommitID("init"), gitgraph.WithCommitTag("v0.1.0")).
		Branch("develop", gitgraph.WithBranchOrder(2)).
		Checkout("develop").
		Commit(gitgraph.WithCommitType(gitgraph.CommitTypeHighlight)).
		Checkout("main").
		Merge("develop", gitgraph.WithCommitTag("v1.0.0")).
		String()

	if err := markdown.NewMarkdown(os.Stdout).
		H2("Git Graph").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build(); err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## Git Graph
```mermaid
---
title: Release Flow
---
gitGraph
    commit id: "init" tag: "v0.1.0"
    branch develop order: 2
    checkout develop
    commit type: HIGHLIGHT
    checkout main
    merge develop tag: "v1.0.0"
```

Mermaid output:

---
title: Release Flow
---
gitGraph
    commit id: "init" tag: "v0.1.0"
    branch develop order: 2
    checkout develop
    commit type: HIGHLIGHT
    checkout main
    merge develop tag: "v1.0.0"
Mermaid mindmap syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := mindmap.NewDiagram(
		io.Discard,
		mindmap.WithTitle("Product Strategy Mindmap"),
	).
		Root("Product Strategy").
		Child("Market").
		Child("SMB").
		Sibling("Enterprise").
		Parent().
		Sibling("Execution").
		Child("Q1").
		Sibling("Q2").
		String()

	if err := markdown.NewMarkdown(os.Stdout).
		H2("Mindmap").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build(); err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## Mindmap
```mermaid
---
title: Product Strategy Mindmap
---
mindmap
    Product Strategy
        Market
            SMB
            Enterprise
        Execution
            Q1
            Q2
```

Mermaid output:

---
title: Product Strategy Mindmap
---
mindmap
    Product Strategy
        Market
            SMB
            Enterprise
        Execution
            Q1
            Q2
Mermaid requirement diagram syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := requirement.NewDiagram(
		io.Discard,
		requirement.WithTitle("Checkout Requirements"),
	).
		SetDirection(requirement.DirectionTB).
		Requirement(
			"Login",
			requirement.WithID("REQ-1"),
			requirement.WithText("The system shall support login."),
			requirement.WithRisk(requirement.RiskHigh),
			requirement.WithVerifyMethod(requirement.VerifyMethodTest),
			requirement.WithRequirementClasses("critical"),
		).
		FunctionalRequirement(
			"RememberSession",
			requirement.WithID("REQ-2"),
			requirement.WithText("The system shall remember the user."),
			requirement.WithRisk(requirement.RiskMedium),
			requirement.WithVerifyMethod(requirement.VerifyMethodInspection),
		).
		Element(
			"AuthService",
			requirement.WithElementType("system"),
			requirement.WithDocRef("docs/auth.md"),
			requirement.WithElementClasses("service"),
		).
		From("AuthService").
		Satisfies("Login").
		From("RememberSession").
		Verifies("Login").
		ClassDefs(
			requirement.Def("critical", "fill:#f96,stroke:#333,stroke-width:2px"),
			requirement.Def("service", "fill:#9cf,stroke:#333,stroke-width:1px"),
		).
		String()

	if err := markdown.NewMarkdown(os.Stdout).
		H2("Requirement Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build(); err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## Requirement Diagram
```mermaid
---
title: Checkout Requirements
---
requirementDiagram
    direction TB
    requirement Login:::critical {
        id: "REQ-1"
        text: "The system shall support login."
        risk: High
        verifymethod: Test
    }
    functionalRequirement RememberSession {
        id: "REQ-2"
        text: "The system shall remember the user."
        risk: Medium
        verifymethod: Inspection
    }
    element AuthService:::service {
        type: "system"
        docRef: "docs/auth.md"
    }
    AuthService - satisfies -> Login
    RememberSession - verifies -> Login
    classDef critical fill:#f96,stroke:#333,stroke-width:2px
    classDef service fill:#9cf,stroke:#333,stroke-width:1px
```

Mermaid output:

---
title: Checkout Requirements
---
requirementDiagram
    direction TB
    requirement Login:::critical {
        id: "REQ-1"
        text: "The system shall support login."
        risk: High
        verifymethod: Test
    }
    functionalRequirement RememberSession {
        id: "REQ-2"
        text: "The system shall remember the user."
        risk: Medium
        verifymethod: Inspection
    }
    element AuthService:::service {
        type: "system"
        docRef: "docs/auth.md"
    }
    AuthService - satisfies -> Login
    RememberSession - verifies -> Login
    classDef critical fill:#f96,stroke:#333,stroke-width:2px
    classDef service fill:#9cf,stroke:#333,stroke-width:1px
Mermaid XY chart syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := xychart.NewDiagram(
		io.Discard,
		xychart.WithTitle("Sales Revenue"),
	).
		XAxisLabels("Jan", "Feb", "Mar", "Apr", "May", "Jun").
		YAxisRangeWithTitle("Revenue (k$)", 0, 100).
		Bar(25, 40, 60, 80, 70, 90).
		Line(30, 50, 70, 85, 75, 95).
		String()

	if err := markdown.NewMarkdown(os.Stdout).
		H2("XY Chart").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build(); err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## XY Chart
```mermaid
xychart
    title "Sales Revenue"
    x-axis [Jan, Feb, Mar, Apr, May, Jun]
    y-axis "Revenue (k$)" 0 --> 100
    bar [25, 40, 60, 80, 70, 90]
    line [30, 50, 70, 85, 75, 95]
```

Mermaid output:

xychart
    title "Sales Revenue"
    x-axis [Jan, Feb, Mar, Apr, May, Jun]
    y-axis "Revenue (k$)" 0 --> 100
    bar [25, 40, 60, 80, 70, 90]
    line [30, 50, 70, 85, 75, 95]
Mermaid packet syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := packet.NewDiagram(
		io.Discard,
		packet.WithTitle("UDP Packet"),
	).
		Next(16, "Source Port").
		Next(16, "Destination Port").
		Field(32, 47, "Length").
		Field(48, 63, "Checksum").
		Field(64, 95, "Data (variable length)").
		String()

	if err := markdown.NewMarkdown(os.Stdout).
		H2("Packet").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build(); err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## Packet
```mermaid
packet
    title UDP Packet
    +16: "Source Port"
    +16: "Destination Port"
    32-47: "Length"
    48-63: "Checksum"
    64-95: "Data (variable length)"
```

Mermaid output:

packet
    title UDP Packet
    +16: "Source Port"
    +16: "Destination Port"
    32-47: "Length"
    48-63: "Checksum"
    64-95: "Data (variable length)"
Mermaid block syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := block.NewDiagram(
		io.Discard,
		block.WithTitle("Checkout Architecture"),
	).
		Columns(3).
		Row(
			block.Node("Frontend"),
			block.ArrowRight("toBackend", block.WithArrowLabel("calls")),
			block.Node("Backend"),
		).
		Row(
			block.Space(2),
			block.ArrowDown("toDB"),
		).
		Row(
			block.Node("Database", block.WithNodeLabel("Primary DB"), block.WithNodeShape(block.ShapeCylinder)),
			block.Space(),
			block.Node("Cache", block.WithNodeLabel("Cache"), block.WithNodeShape(block.ShapeRound)),
		).
		Link("Backend", "Database").
		LinkWithLabel("Backend", "reads from", "Cache").
		String()

	if err := markdown.NewMarkdown(os.Stdout).
		H2("Block Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build(); err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## Block Diagram
```mermaid
block
    title Checkout Architecture
    columns 3
    Frontend toBackend<["calls"]>(right) Backend
    space:2 toDB<["&nbsp;"]>(down)
    Database[("Primary DB")] space Cache("Cache")
    Backend --> Database
    Backend -- "reads from" --> Cache
```

Mermaid output:

block
    title Checkout Architecture
    columns 3
    Frontend toBackend<["calls"]>(right) Backend
    space:2 toDB<["&nbsp;"]>(down)
    Database[("Primary DB")] space Cache("Cache")
    Backend --> Database
    Backend -- "reads from" --> Cache
Mermaid kanban syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

func main() {
	diagram := kanban.NewDiagram(
		io.Discard,
		kanban.WithTitle("Sprint Board"),
		kanban.WithTicketBaseURL("https://example.com/tickets/"),
	).
		Column("Todo").
		Task("Define scope").
		Task(
			"Create login page",
			kanban.WithTaskTicket("MB-101"),
			kanban.WithTaskAssigned("Alice"),
			kanban.WithTaskPriority(kanban.PriorityHigh),
		).
		Column("In Progress").
		Task("Review API", kanban.WithTaskPriority(kanban.PriorityVeryHigh)).
		String()

	if err := markdown.NewMarkdown(os.Stdout).
		H2("Kanban Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build(); err != nil {
		panic(err)
	}
}

Plain text output: markdown is here

## Kanban Diagram
```mermaid
---
title: Sprint Board
config:
  kanban:
    ticketBaseUrl: 'https://example.com/tickets/'
---
kanban
    [Todo]
        [Define scope]
        [Create login page]@{ ticket: 'MB-101', assigned: 'Alice', priority: 'High' }
    [In Progress]
        [Review API]@{ priority: 'Very High' }
```

Mermaid output:

---
title: Sprint Board
config:
  kanban:
    ticketBaseUrl: 'https://example.com/tickets/'
---
kanban
    [Todo]
        [Define scope]
        [Create login page]@{ ticket: 'MB-101', assigned: 'Alice', priority: 'High' }
    [In Progress]
        [Review API]@{ priority: 'Very High' }
Entity Relationship Diagram syntax
package main

import (
	"os"

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

//go:generate go run main.go

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

	teachers := er.NewEntity(
		"teachers",
		[]*er.Attribute{
			{
				Type:         "int",
				Name:         "id",
				IsPrimaryKey: true,
				IsForeignKey: false,
				IsUniqueKey:  true,
				Comment:      "Teacher ID",
			},
			{
				Type:         "string",
				Name:         "name",
				IsPrimaryKey: false,
				IsForeignKey: false,
				IsUniqueKey:  false,
				Comment:      "Teacher Name",
			},
		},
	)
	students := er.NewEntity(
		"students",
		[]*er.Attribute{
			{
				Type:         "int",
				Name:         "id",
				IsPrimaryKey: true,
				IsForeignKey: false,
				IsUniqueKey:  true,
				Comment:      "Student ID",
			},
			{
				Type:         "string",
				Name:         "name",
				IsPrimaryKey: false,
				IsForeignKey: false,
				IsUniqueKey:  false,
				Comment:      "Student Name",
			},
			{
				Type:         "int",
				Name:         "teacher_id",
				IsPrimaryKey: false,
				IsForeignKey: true,
				IsUniqueKey:  true,
				Comment:      "Teacher ID",
			},
		},
	)
	schools := er.NewEntity(
		"schools",
		[]*er.Attribute{
			{
				Type:         "int",
				Name:         "id",
				IsPrimaryKey: true,
				IsForeignKey: false,
				IsUniqueKey:  true,
				Comment:      "School ID",
			},
			{
				Type:         "string",
				Name:         "name",
				IsPrimaryKey: false,
				IsForeignKey: false,
				IsUniqueKey:  false,
				Comment:      "School Name",
			},
			{
				Type:         "int",
				Name:         "teacher_id",
				IsPrimaryKey: false,
				IsForeignKey: true,
				IsUniqueKey:  true,
				Comment:      "Teacher ID",
			},
		},
	)

	erString := er.NewDiagram(f).
		Relationship(
			teachers,
			students,
			er.ExactlyOneRelationship, // "||"
			er.ZeroToMoreRelationship, // "}o"
			er.Identifying,            // "--"
			"Teacher has many students",
		).
		Relationship(
			teachers,
			schools,
			er.OneToMoreRelationship,  // "|}"
			er.ExactlyOneRelationship, // "||"
			er.NonIdentifying,         // ".."
			"School has many teachers",
		).
		String()

	err = markdown.NewMarkdown(f).
		H2("Entity Relationship Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, erString).
		Build()

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

Plain text output: markdown is here

## Entity Relationship Diagram
```mermaid
erDiagram
	teachers ||--o{ students : "Teacher has many students"
	teachers }|..|| schools : "School has many teachers"
	schools {
		int id PK,UK "School ID"
		string name  "School Name"
		int teacher_id FK,UK "Teacher ID"
	}
	students {
		int id PK,UK "Student ID"
		string name  "Student Name"
		int teacher_id FK,UK "Teacher ID"
	}
	teachers {
		int id PK,UK "Teacher ID"
		string name  "Teacher Name"
	}

```

Mermaid output:

erDiagram
	teachers ||--o{ students : "Teacher has many students"
	teachers }|..|| schools : "School has many teachers"
	schools {
		int id PK,UK "School ID"
		string name  "School Name"
		int teacher_id FK,UK "Teacher ID"
	}
	students {
		int id PK,UK "Student ID"
		string name  "Student Name"
		int teacher_id FK,UK "Teacher ID"
	}
	teachers {
		int id PK,UK "Teacher ID"
		string name  "Teacher Name"
	}
Flowchart syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

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

	fc := flowchart.NewFlowchart(
		io.Discard,
		flowchart.WithTitle("mermaid flowchart builder"),
		flowchart.WithOrientalTopToBottom(),
	).
		NodeWithText("A", "Node A").
		StadiumNode("B", "Node B").
		SubroutineNode("C", "Node C").
		DatabaseNode("D", "Database").
		LinkWithArrowHead("A", "B").
		LinkWithArrowHeadAndText("B", "D", "send original data").
		LinkWithArrowHead("B", "C").
		DottedLinkWithText("C", "D", "send filtered data").
		String()

	err = markdown.NewMarkdown(f).
		H2("Flowchart").
		CodeBlocks(markdown.SyntaxHighlightMermaid, fc).
		Build()

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

Plain text output: markdown is here

## Flowchart
```mermaid
---
title: mermaid flowchart builder
---
flowchart TB
	A["Node A"]
	B(["Node B"])
	C[["Node C"]]
	D[("Database")]
	A-->B
	B-->|"send original data"|D
	B-->C
	C-. "send filtered data" .-> D
```

Mermaid output:

flowchart TB
	A["Node A"]
	B(["Node B"])
	C[["Node C"]]
	D[("Database")]
	A-->B
	B-->|"send original data"|D
	B-->C
	C-. "send filtered data" .-> D
Pie chart syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

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

	chart := piechart.NewPieChart(
		io.Discard,
		piechart.WithTitle("mermaid pie chart builder"),
		piechart.WithShowData(true),
	).
		LabelAndIntValue("A", 10).
		LabelAndFloatValue("B", 20.1).
		LabelAndIntValue("C", 30).
		String()

	err = markdown.NewMarkdown(f).
		H2("Pie Chart").
		CodeBlocks(markdown.SyntaxHighlightMermaid, chart).
		Build()

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

Plain text output: markdown is here

## Pie Chart
```mermaid
%%{init: {"pie": {"textPosition": 0.75}, "themeVariables": {"pieOuterStrokeWidth": "5px"}} }%%
pie showData
    title mermaid pie chart builder
    "A" : 10
    "B" : 20.100000
    "C" : 30
```

Mermaid output:

%%{init: {"pie": {"textPosition": 0.75}, "themeVariables": {"pieOuterStrokeWidth": "5px"}} }%%
pie showData
    title mermaid pie chart builder
    "A" : 10
    "B" : 20.100000
    "C" : 30
Architecture Diagrams (beta feature)

The mermaid provides a feature to visualize infrastructure architecture as a beta version, and that feature has been introduced.

package main

import (
	"io"
	"os"

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

//go:generate go run main.go

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

	diagram := arch.NewArchitecture(io.Discard).
		Service("left_disk", arch.IconDisk, "Disk").
		Service("top_disk", arch.IconDisk, "Disk").
		Service("bottom_disk", arch.IconDisk, "Disk").
		Service("top_gateway", arch.IconInternet, "Gateway").
		Service("bottom_gateway", arch.IconInternet, "Gateway").
		Junction("junctionCenter").
		Junction("junctionRight").
		LF().
		Edges(
			arch.Edge{
				ServiceID: "left_disk",
				Position:  arch.PositionRight,
				Arrow:     arch.ArrowNone,
			},
			arch.Edge{
				ServiceID: "junctionCenter",
				Position:  arch.PositionLeft,
				Arrow:     arch.ArrowNone,
			}).
		Edges(
			arch.Edge{
				ServiceID: "top_disk",
				Position:  arch.PositionBottom,
				Arrow:     arch.ArrowNone,
			},
			arch.Edge{
				ServiceID: "junctionCenter",
				Position:  arch.PositionTop,
				Arrow:     arch.ArrowNone,
			}).
		Edges(
			arch.Edge{
				ServiceID: "bottom_disk",
				Position:  arch.PositionTop,
				Arrow:     arch.ArrowNone,
			},
			arch.Edge{
				ServiceID: "junctionCenter",
				Position:  arch.PositionBottom,
				Arrow:     arch.ArrowNone,
			}).
		Edges(
			arch.Edge{
				ServiceID: "junctionCenter",
				Position:  arch.PositionRight,
				Arrow:     arch.ArrowNone,
			},
			arch.Edge{
				ServiceID: "junctionRight",
				Position:  arch.PositionLeft,
				Arrow:     arch.ArrowNone,
			}).
		Edges(
			arch.Edge{
				ServiceID: "top_gateway",
				Position:  arch.PositionBottom,
				Arrow:     arch.ArrowNone,
			},
			arch.Edge{
				ServiceID: "junctionRight",
				Position:  arch.PositionTop,
				Arrow:     arch.ArrowNone,
			}).
		Edges(
			arch.Edge{
				ServiceID: "bottom_gateway",
				Position:  arch.PositionTop,
				Arrow:     arch.ArrowNone,
			},
			arch.Edge{
				ServiceID: "junctionRight",
				Position:  arch.PositionBottom,
				Arrow:     arch.ArrowNone,
			}).String() //nolint

	err = markdown.NewMarkdown(f).
		H2("Architecture Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build()

	if err != nil {
		panic(err)
	}

Plain text output: markdown is here

## Architecture Diagram
```mermaid
architecture-beta
    service left_disk(disk)[Disk]
    service top_disk(disk)[Disk]
    service bottom_disk(disk)[Disk]
    service top_gateway(internet)[Gateway]
    service bottom_gateway(internet)[Gateway]
    junction junctionCenter
    junction junctionRight

    left_disk:R -- L:junctionCenter
    top_disk:B -- T:junctionCenter
    bottom_disk:T -- B:junctionCenter
    junctionCenter:R -- L:junctionRight
    top_gateway:B -- T:junctionRight
    bottom_gateway:T -- B:junctionRight
```

Architecture Diagram

State Diagram syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

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

	diagram := state.NewDiagram(io.Discard, state.WithTitle("Order State Machine")).
		StartTransition("Pending").
		State("Pending", "Order received").
		State("Processing", "Preparing order").
		State("Shipped", "Order in transit").
		State("Delivered", "Order completed").
		LF().
		TransitionWithNote("Pending", "Processing", "payment confirmed").
		TransitionWithNote("Processing", "Shipped", "items packed").
		TransitionWithNote("Shipped", "Delivered", "customer received").
		LF().
		NoteRight("Pending", "Waiting for payment").
		NoteRight("Processing", "Preparing items").
		LF().
		EndTransition("Delivered").
		String()

	err = markdown.NewMarkdown(f).
		H2("State Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagram).
		Build()

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

Plain text output: markdown is here

## State Diagram
```mermaid
---
title: Order State Machine
---
stateDiagram-v2
    [*] --> Pending
    Pending : Order received
    Processing : Preparing order
    Shipped : Order in transit
    Delivered : Order completed

    Pending --> Processing : payment confirmed
    Processing --> Shipped : items packed
    Shipped --> Delivered : customer received

    note right of Pending : Waiting for payment
    note right of Processing : Preparing items

    Delivered --> [*]
```

Mermaid output:

---
title: Order State Machine
---
stateDiagram-v2
    [*] --> Pending
    Pending : Order received
    Processing : Preparing order
    Shipped : Order in transit
    Delivered : Order completed

    Pending --> Processing : payment confirmed
    Processing --> Shipped : items packed
    Shipped --> Delivered : customer received

    note right of Pending : Waiting for payment
    note right of Processing : Preparing items

    Delivered --> [*]
Class Diagram syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

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

	diagram := class.NewDiagram(
		io.Discard,
		class.WithTitle("Checkout Domain"),
	).
		SetDirection(class.DirectionLR).
		Class(
			"Order",
			class.WithPublicField("string", "id"),
			class.WithPublicMethod("Create", "error", "items []LineItem"),
			class.WithPublicMethod("Pay", "error"),
		).
		Class(
			"LineItem",
			class.WithPublicField("string", "sku"),
			class.WithPublicField("int", "quantity"),
			class.WithPublicMethod("Subtotal", "int"),
		).
		Interface("PaymentGateway")

	diagram.From("Order").
		Composition("LineItem", class.WithOneToMany(), class.WithRelationLabel("contains")).
		Association("PaymentGateway", class.WithRelationLabel("uses"))

	diagramString := diagram.
		NoteFor("Order", "Aggregate Root").
		String()

	err = markdown.NewMarkdown(f).
		H2("Class Diagram").
		CodeBlocks(markdown.SyntaxHighlightMermaid, diagramString).
		Build()

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

Plain text output: markdown is here

## Class Diagram
```mermaid
---
title: Checkout Domain
---
classDiagram
    direction LR
    class Order {
        +string id
        +Create(items []LineItem) error
        +Pay() error
    }
    class LineItem {
        +string sku
        +int quantity
        +Subtotal() int
    }
    class PaymentGateway
    <<Interface>> PaymentGateway
    Order "1" *-- "many" LineItem : contains
    Order --> PaymentGateway : uses
    note for Order "Aggregate Root"
```

Mermaid output:

---
title: Checkout Domain
---
classDiagram
    direction LR
    class Order {
        +string id
        +Create(items []LineItem) error
        +Pay() error
    }
    class LineItem {
        +string sku
        +int quantity
        +Subtotal() int
    }
    class PaymentGateway
    <<Interface>> PaymentGateway
    Order "1" *-- "many" LineItem : contains
    Order --> PaymentGateway : uses
    note for Order "Aggregate Root"
Quadrant Chart syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

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

	chart := quadrant.NewChart(io.Discard, quadrant.WithTitle("Product Prioritization")).
		XAxis("Low Effort", "High Effort").
		YAxis("Low Value", "High Value").
		LF().
		Quadrant1("Quick Wins").
		Quadrant2("Major Projects").
		Quadrant3("Fill Ins").
		Quadrant4("Thankless Tasks").
		LF().
		Point("Feature A", 0.9, 0.85).
		Point("Feature B", 0.25, 0.75).
		Point("Feature C", 0.15, 0.20).
		Point("Feature D", 0.80, 0.15).
		String()

	err = markdown.NewMarkdown(f).
		H2("Quadrant Chart").
		CodeBlocks(markdown.SyntaxHighlightMermaid, chart).
		Build()

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

Plain text output: markdown is here

## Quadrant Chart
```mermaid
quadrantChart
    title Product Prioritization
    x-axis Low Effort --> High Effort
    y-axis Low Value --> High Value

    quadrant-1 Quick Wins
    quadrant-2 Major Projects
    quadrant-3 Fill Ins
    quadrant-4 Thankless Tasks

    Feature A: [0.90, 0.85]
    Feature B: [0.25, 0.75]
    Feature C: [0.15, 0.20]
    Feature D: [0.80, 0.15]
```

Mermaid output:

quadrantChart
    title Product Prioritization
    x-axis Low Effort --> High Effort
    y-axis Low Value --> High Value

    quadrant-1 Quick Wins
    quadrant-2 Major Projects
    quadrant-3 Fill Ins
    quadrant-4 Thankless Tasks

    Feature A: [0.90, 0.85]
    Feature B: [0.25, 0.75]
    Feature C: [0.15, 0.20]
    Feature D: [0.80, 0.15]
Gantt Chart syntax
package main

import (
	"io"
	"os"

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

//go:generate go run main.go

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

	chart := gantt.NewChart(
		io.Discard,
		gantt.WithTitle("Project Schedule"),
		gantt.WithDateFormat("YYYY-MM-DD"),
	).
		Section("Planning").
		DoneTaskWithID("Requirements", "req", "2024-01-01", "5d").
		DoneTaskWithID("Design", "design", "2024-01-08", "3d").
		Section("Development").
		CriticalActiveTaskWithID("Coding", "code", "2024-01-12", "10d").
		TaskAfterWithID("Review", "review", "code", "2d").
		Section("Release").
		MilestoneWithID("Launch", "launch", "2024-01-26").
		String()

	err = markdown.NewMarkdown(f).
		H2("Gantt Chart").
		CodeBlocks(markdown.SyntaxHighlightMermaid, chart).
		Build()

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

Plain text output: markdown is here

## Gantt Chart
```mermaid
gantt
    title Project Schedule
    dateFormat YYYY-MM-DD
    section Planning
    Requirements :done, req, 2024-01-01, 5d
    Design :done, design, 2024-01-08, 3d
    section Development
    Coding :crit, active, code, 2024-01-12, 10d
    Review :review, after code, 2d
    section Release
    Launch :milestone, launch, 2024-01-26, 0d
```

Mermaid output:

gantt
    title Project Schedule
    dateFormat YYYY-MM-DD
    section Planning
    Requirements :done, req, 2024-01-01, 5d
    Design :done, design, 2024-01-08, 3d
    section Development
    Coding :crit, active, code, 2024-01-12, 10d
    Review :review, after code, 2d
    section Release
    Launch :milestone, launch, 2024-01-26, 0d

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.

For example, consider the following directory structure:

testdata
├── abc
│   ├── dummy.txt
│   ├── jkl
│   │   └── text.md
│   └── test.md
├── def
│   ├── test.md
│   └── test2.md
├── expected
│   └── index.md
├── ghi
└── test.md

In the following implementation, it creates an index markdown file containing links to all markdown files located within the testdata directory.

		if err := GenerateIndex(
			"testdata", // target directory that contains markdown files
			WithTitle("Test Title"), // title of index markdown
			WithDescription([]string{"Test Description", "Next Description"}), // description of index markdown
		); err != nil {
			panic(err)
		}

The index Markdown file is created under "target directory/index.md" by default. If you want to change this path, please use the WithWriter() option. The link names in the file will be the first occurrence of H1 or H2 in the target Markdown. If neither H1 nor H2 is present, the link name will be the file name of the destination.

Output:

## Test Title
Test Description
  
Next Description
  
### testdata
- [test.md](test.md)
  
### abc
- [h2 is here](abc/test.md)
  
### jkl
- [text.md](abc/jkl/text.md)
  
### def
- [h2 is first, not h1](def/test.md)
- [h1 is here](def/test2.md)
  
### expected
- [Test Title](expected/index.md)

License

MIT License

Contribution

First off, thanks for taking the time to contribute! See CONTRIBUTING.md for more information. Contributions are not only related to development. For example, GitHub Star motivates me to develop! Please feel free to contribute to this project.

Star History Chart

Contributors ✨

Thanks goes to these wonderful people (emoji key):

CHIKAMATSU Naohiro
CHIKAMATSU Naohiro

💻
Karthik Sundari
Karthik Sundari

💻
Avihuc
Avihuc

💻
Clarance Liberiste Ntwari
Clarance Liberiste Ntwari

💻
Amitai Frey
Amitai Frey

💻
Add your contributions

This project follows the all-contributors specification. Contributions of any kind welcome!

Documentation

Overview

Package markdown is markdown builder that includes to convert Markdown to HTML.

Index

Examples

Constants

View Source
const (
	// TableOfContentsMarkerBegin is the marker for the beginning of the table of contents.
	TableOfContentsMarkerBegin = "<!-- BEGIN_TOC -->"
	// TableOfContentsMarkerEnd is the marker for the end of the table of contents.
	TableOfContentsMarkerEnd = "<!-- END_TOC -->"
)

Variables

View Source
var (
	// ErrMismatchColumn is returned when the number of columns in the record doesn't match the header.
	ErrMismatchColumn = errors.New("number of columns in the record doesn't match the header")
	// ErrInitMarkdownIndex is returned when the index can't be initialized.
	ErrInitMarkdownIndex = errors.New("markdown index can't be initialized")
	// ErrCreateMarkdownIndex is returned when the index can't be created.
	ErrCreateMarkdownIndex = errors.New("markdown index can't be created")
	// ErrWriteMarkdownIndex is returned when the index can't be written.
	ErrWriteMarkdownIndex = errors.New("markdown index can't be written")
)

Functions

func BlockMath added in v0.11.0

func BlockMath(expression string) string

BlockMath returns text with block mathematical expression format. BlockMath does not escape expression; it writes the raw expression between '$$' delimiters. If you set expression "x^2 + y^2 = z^2", it will be converted to:

$$
x^2 + y^2 = z^2
$$

func Bold

func Bold(text string) string

Bold return text with bold format. If you set text "Hello", it will be converted to "**Hello**".

func BoldItalic

func BoldItalic(text string) string

BoldItalic return text with bold and italic format. If you set text "Hello", it will be converted to "***Hello***".

func Code

func Code(text string) string

Code return text with code format. If you set text "Hello", it will be converted to "`Hello`".

func FootnoteDefinition added in v0.11.0

func FootnoteDefinition(id, text string) string

FootnoteDefinition returns text with footnote definition format. If you set id "1" and text "Hello", it will be converted to "[^1]: Hello".

func FootnoteReference added in v0.11.0

func FootnoteReference(id string) string

FootnoteReference returns text with footnote reference format. If you set id "1", it will be converted to "[^1]".

func GenerateIndex

func GenerateIndex(targetDir string, opts ...IndexOption) error

GenerateIndex generates an index of all markdown files in the target directory. The index is written to the provided io.Writer.

func Highlight added in v0.6.0

func Highlight(text string) string

Highlight return text with highlight format. If you set text "Hello", it will be converted to "==Hello==".

func Image

func Image(text, url string) string

Image return text with image format. If you set text "Hello" and url "https://example.com/image.png", it will be converted to "![Hello](https://example.com/image.png)".

func InlineMath added in v0.11.0

func InlineMath(expression string) string

InlineMath returns text with inline mathematical expression format. It calls escapeMathExpression, so '$' in expression is escaped as '\$'. If you set expression "E=mc^2", it will be converted to "$E=mc^2$".

func Italic

func Italic(text string) string

Italic return text with italic format. If you set text "Hello", it will be converted to "*Hello*".

func Link(text, url string) string

Link return text with link format. If you set text "Hello" and url "https://example.com", it will be converted to "[Hello](https://example.com)".

func ReferenceLink(text, id string) string

ReferenceLink returns text with reference link format. If you set text "Go" and id "go-site", it will be converted to "[Go][go-site]".

func ReferenceLinkDefinition added in v0.11.0

func ReferenceLinkDefinition(id, url string, title ...string) string

ReferenceLinkDefinition returns text with reference link definition format. If you set id "go-site" and url "https://golang.org", it will be converted to "[go-site]: https://golang.org". If title is set, it will be converted to "[go-site]: https://golang.org \"The Go Programming Language\"".

func Strikethrough

func Strikethrough(text string) string

Strikethrough return text with strikethrough format. If you set text "Hello", it will be converted to "~~Hello~~".

Types

type CheckBoxSet

type CheckBoxSet struct {
	// Checked is whether checked or not.
	Checked bool
	// Text is checkbox text.
	Text string
}

CheckBoxSet is markdown checkbox list.

type Index

type Index struct {
	// contains filtered or unexported fields
}

Index represents an Index of all markdown files in a directory.

type IndexOption

type IndexOption func(*Index) error

IndexOption are options for generating an index.

func WithDescription

func WithDescription(description []string) IndexOption

WithDescription sets the description of the index.

func WithTitle

func WithTitle(title string) IndexOption

WithTitle sets the title of the index.

func WithWriter

func WithWriter(w io.Writer) IndexOption

WithWriter sets the writer to write the index to.

type Markdown

type Markdown struct {
	// contains filtered or unexported fields
}

Markdown is markdown text.

Example

ExampleMarkdown skips this test on Windows. The newline codes in the comment section where the expected values are written are represented as '\n', causing failures when testing on Windows.

package main

import (
	"os"

	md "github.com/nao1215/markdown"
)

func main() {
	_ = md.NewMarkdown(os.Stdout).
		H1("This is H1").
		PlainText("This is plain text").
		H2f("This is %s with text format", "H2").
		PlainTextf("Text formatting, such as %s and %s, %s styles.",
			md.Bold("bold"), md.Italic("italic"), md.Code("code")).
		H2("Code Block").
		CodeBlocks(md.SyntaxHighlightGo,
			`package main
import "fmt"

func main() {
	fmt.Println("Hello, World!")
}`).
		H2("List").
		BulletList("Bullet Item 1", "Bullet Item 2", "Bullet Item 3").
		OrderedList("Ordered Item 1", "Ordered Item 2", "Ordered Item 3").
		H2("CheckBox").
		CheckBox([]md.CheckBoxSet{
			{Checked: false, Text: md.Code("sample code")},
			{Checked: true, Text: md.Link("Go", "https://golang.org")},
			{Checked: false, Text: md.Strikethrough("strikethrough")},
		}).
		H2("Blockquote").
		Blockquote("If you can dream it, you can do it.").
		H3("Horizontal Rule").
		HorizontalRule().
		H2("Table").
		Table(md.TableSet{
			Header: []string{"Name", "Age", "Country"},
			Rows: [][]string{
				{"David", "23", "USA"},
				{"John", "30", "UK"},
				{"Bob", "25", "Canada"},
			},
		}).
		H2("Image").
		PlainTextf(md.Image("sample_image", "./sample.png")).
		Build()

}
Output:
# This is H1
This is plain text
## This is H2 with text format
Text formatting, such as **bold** and *italic*, `code` styles.
## Code Block
```go
package main
import "fmt"

func main() {
	fmt.Println("Hello, World!")
}
```
## List
- Bullet Item 1
- Bullet Item 2
- Bullet Item 3
1. Ordered Item 1
2. Ordered Item 2
3. Ordered Item 3
## CheckBox
- [ ] `sample code`
- [x] [Go](https://golang.org)
- [ ] ~~strikethrough~~
## Blockquote
> If you can dream it, you can do it.
### Horizontal Rule
---
## Table
| Name | Age | Country |
|---------|---------|---------|
| David | 23 | USA |
| John | 30 | UK |
| Bob | 25 | Canada |

## Image
![sample_image](./sample.png)

func NewMarkdown

func NewMarkdown(w io.Writer) *Markdown

NewMarkdown returns new Markdown.

func (*Markdown) Blockquote

func (m *Markdown) Blockquote(text string) *Markdown

Blockquote is markdown blockquote. If you set text "Hello", it will be converted to "> Hello".

func (*Markdown) BlueBadge added in v0.5.0

func (m *Markdown) BlueBadge(text string) *Markdown

BlueBadge set text with blue badge format.

func (*Markdown) BlueBadgef added in v0.5.0

func (m *Markdown) BlueBadgef(format string, args ...interface{}) *Markdown

BlueBadgef set text with blue badge format. It is similar to fmt.Sprintf.

func (*Markdown) Build

func (m *Markdown) Build() error

Build writes markdown text to output destination.

func (*Markdown) BulletList

func (m *Markdown) BulletList(text ...string) *Markdown

BulletList is markdown bullet list. If you set text "Hello", it will be converted to "- Hello".

func (*Markdown) Caution

func (m *Markdown) Caution(text string) *Markdown

Caution set text with caution format.

func (*Markdown) Cautionf

func (m *Markdown) Cautionf(format string, args ...interface{}) *Markdown

Cautionf set text with caution format. It is similar to fmt.Sprintf.

func (*Markdown) CheckBox

func (m *Markdown) CheckBox(set []CheckBoxSet) *Markdown

CheckBox is markdown CheckBox.

func (*Markdown) CodeBlocks

func (m *Markdown) CodeBlocks(lang SyntaxHighlight, text string) *Markdown

CodeBlocks is code blocks. If you set text "Hello" and lang "go", it will be converted to "```go Hello ```".

func (*Markdown) CustomTable

func (m *Markdown) CustomTable(t TableSet, options TableOptions) *Markdown

CustomTable is markdown table. This is so not break the original Table function. with Possible breaking changes.

func (*Markdown) Details

func (m *Markdown) Details(summary, text string) *Markdown

Details is markdown details.

func (*Markdown) Detailsf

func (m *Markdown) Detailsf(summary, format string, args ...interface{}) *Markdown

Detailsf is markdown details with format.

func (*Markdown) Error

func (m *Markdown) Error() error

Error returns error.

func (*Markdown) GreenBadge

func (m *Markdown) GreenBadge(text string) *Markdown

GreenBadge set text with green badge format.

func (*Markdown) GreenBadgef

func (m *Markdown) GreenBadgef(format string, args ...interface{}) *Markdown

GreenBadgef set text with green badge format. It is similar to fmt.Sprintf.

func (*Markdown) H1

func (m *Markdown) H1(text string) *Markdown

H1 is markdown header. If you set text "Hello", it will be converted to "# Hello".

func (*Markdown) H1f

func (m *Markdown) H1f(format string, args ...interface{}) *Markdown

H1f is markdown header with format. If you set format "%s", text "Hello", it will be converted to "# Hello".

func (*Markdown) H2

func (m *Markdown) H2(text string) *Markdown

H2 is markdown header. If you set text "Hello", it will be converted to "## Hello".

func (*Markdown) H2f

func (m *Markdown) H2f(format string, args ...interface{}) *Markdown

H2f is markdown header with format. If you set format "%s", text "Hello", it will be converted to "## Hello".

func (*Markdown) H3

func (m *Markdown) H3(text string) *Markdown

H3 is markdown header. If you set text "Hello", it will be converted to "### Hello".

func (*Markdown) H3f

func (m *Markdown) H3f(format string, args ...interface{}) *Markdown

H3f is markdown header with format. If you set format "%s", text "Hello", it will be converted to "### Hello".

func (*Markdown) H4

func (m *Markdown) H4(text string) *Markdown

H4 is markdown header. If you set text "Hello", it will be converted to "#### Hello".

func (*Markdown) H4f

func (m *Markdown) H4f(format string, args ...interface{}) *Markdown

H4f is markdown header with format. If you set format "%s", text "Hello", it will be converted to "#### Hello".

func (*Markdown) H5

func (m *Markdown) H5(text string) *Markdown

H5 is markdown header. If you set text "Hello", it will be converted to "##### Hello".

func (*Markdown) H5f

func (m *Markdown) H5f(format string, args ...interface{}) *Markdown

H5f is markdown header with format. If you set format "%s", text "Hello", it will be converted to "##### Hello".

func (*Markdown) H6

func (m *Markdown) H6(text string) *Markdown

H6 is markdown header. If you set text "Hello", it will be converted to "###### Hello".

func (*Markdown) H6f

func (m *Markdown) H6f(format string, args ...interface{}) *Markdown

H6f is markdown header with format. If you set format "%s", text "Hello", it will be converted to "###### Hello".

func (*Markdown) HorizontalRule

func (m *Markdown) HorizontalRule() *Markdown

HorizontalRule is markdown horizontal rule. It will be converted to "---".

func (*Markdown) Important

func (m *Markdown) Important(text string) *Markdown

Important set text with important format.

func (*Markdown) Importantf

func (m *Markdown) Importantf(format string, args ...interface{}) *Markdown

Importantf set text with important format. It is similar to fmt.Sprintf.

func (*Markdown) LF

func (m *Markdown) LF() *Markdown

LF is line feed.

func (*Markdown) Note

func (m *Markdown) Note(text string) *Markdown

Note set text with note format.

func (*Markdown) Notef

func (m *Markdown) Notef(format string, args ...interface{}) *Markdown

Notef set text with note format. It is similar to fmt.Sprintf.

func (*Markdown) OrderedList

func (m *Markdown) OrderedList(text ...string) *Markdown

OrderedList is markdown number list. If you set text "Hello", it will be converted to "1. Hello".

func (*Markdown) PlainText

func (m *Markdown) PlainText(text string) *Markdown

PlainText set plain text

func (*Markdown) PlainTextf

func (m *Markdown) PlainTextf(format string, args ...interface{}) *Markdown

PlainTextf set plain text with format

func (*Markdown) RedBadge

func (m *Markdown) RedBadge(text string) *Markdown

RedBadge set text with red badge format.

func (*Markdown) RedBadgef

func (m *Markdown) RedBadgef(format string, args ...interface{}) *Markdown

RedBadgef set text with red badge format. It is similar to fmt.Sprintf.

func (*Markdown) String

func (m *Markdown) String() string

String returns markdown text.

func (*Markdown) Table

func (m *Markdown) Table(t TableSet) *Markdown

Table is markdown table with alignment support.

func (*Markdown) TableOfContents added in v0.8.2

func (m *Markdown) TableOfContents(maxDepth TableOfContentsDepth) *Markdown

TableOfContents generates a table of contents placeholder that will be replaced when Build() is called. The table of contents will include all headers from H1 to the specified maxDepth. Only one table of contents can be generated per document.

Example:

markdown.NewMarkdown(os.Stdout).
   H1("Title").
   TableOfContents(markdown.TableOfContentsDepthH3).  // Table of contents will be placed here
   H2("Section 1").
   H3("Subsection 1.1").
   Build()

func (*Markdown) TableOfContentsWithRange added in v0.8.3

func (m *Markdown) TableOfContentsWithRange(minDepth, maxDepth TableOfContentsDepth) *Markdown

TableOfContentsWithRange generates a table of contents placeholder with custom depth range. The table of contents will include headers from minDepth to maxDepth inclusive. Only one table of contents can be generated per document.

Example:

markdown.NewMarkdown(os.Stdout).
   H1("Title").  // This H1 will not appear in table of contents
   H2("Table of Contents").
   TableOfContentsWithRange(markdown.TableOfContentsDepthH2, markdown.TableOfContentsDepthH4).  // Only include H2-H4 in table of contents
   H2("Section 1").
   H3("Subsection 1.1").
   H4("Detail").
   H5("Deep Detail").  // This H5 will not appear in table of contents
   Build()

func (*Markdown) Tip

func (m *Markdown) Tip(text string) *Markdown

Tip set text with tip format.

func (*Markdown) Tipf

func (m *Markdown) Tipf(format string, args ...interface{}) *Markdown

Tipf set text with tip format. It is similar to fmt.Sprintf.

func (*Markdown) Warning

func (m *Markdown) Warning(text string) *Markdown

Warning set text with warning format.

func (*Markdown) Warningf

func (m *Markdown) Warningf(format string, args ...interface{}) *Markdown

Warningf set text with warning format. It is similar to fmt.Sprintf.

func (*Markdown) YellowBadge

func (m *Markdown) YellowBadge(text string) *Markdown

YellowBadge set text with yellow badge format.

func (*Markdown) YellowBadgef

func (m *Markdown) YellowBadgef(format string, args ...interface{}) *Markdown

YellowBadgef set text with yellow badge format. It is similar to fmt.Sprintf.

type SyntaxHighlight

type SyntaxHighlight string

SyntaxHighlight is syntax highlight language.

const (
	// SyntaxHighlightNone is no syntax highlight.
	SyntaxHighlightNone SyntaxHighlight = ""
	// SyntaxHighlightText is syntax highlight for text.
	SyntaxHighlightText SyntaxHighlight = "text"
	// SyntaxHighlightAPIBlueprint is syntax highlight for API Blueprint.
	SyntaxHighlightAPIBlueprint SyntaxHighlight = "markdown"
	// SyntaxHighlightShell is syntax highlight for Shell.
	SyntaxHighlightShell SyntaxHighlight = "shell"
	// SyntaxHighlightGo is syntax highlight for Go.
	SyntaxHighlightGo SyntaxHighlight = "go"
	// SyntaxHighlightJSON is syntax highlight for JSON.
	SyntaxHighlightJSON SyntaxHighlight = "json"
	// SyntaxHighlightYAML is syntax highlight for YAML.
	SyntaxHighlightYAML SyntaxHighlight = "yaml"
	// SyntaxHighlightXML is syntax highlight for XML.
	SyntaxHighlightXML SyntaxHighlight = "xml"
	// SyntaxHighlightHTML is syntax highlight for HTML.
	SyntaxHighlightHTML SyntaxHighlight = "html"
	// SyntaxHighlightCSS is syntax highlight for CSS.
	SyntaxHighlightCSS SyntaxHighlight = "css"
	// SyntaxHighlightJavaScript is syntax highlight for JavaScript.
	SyntaxHighlightJavaScript SyntaxHighlight = "javascript"
	// SyntaxHighlightTypeScript is syntax highlight for TypeScript.
	SyntaxHighlightTypeScript SyntaxHighlight = "typescript"
	// SyntaxHighlightSQL is syntax highlight for SQL.
	SyntaxHighlightSQL SyntaxHighlight = "sql"
	// SyntaxHighlightC is syntax highlight for C.
	SyntaxHighlightC SyntaxHighlight = "c"
	// SyntaxHighlightCSharp is syntax highlight for C#.
	SyntaxHighlightCSharp SyntaxHighlight = "csharp"
	// SyntaxHighlightCPlusPlus is syntax highlight for C++.
	SyntaxHighlightCPlusPlus SyntaxHighlight = "cpp"
	// SyntaxHighlightJava is syntax highlight for Java.
	SyntaxHighlightJava SyntaxHighlight = "java"
	// SyntaxHighlightKotlin is syntax highlight for Kotlin.
	SyntaxHighlightKotlin SyntaxHighlight = "kotlin"
	// SyntaxHighlightPHP is syntax highlight for PHP.
	SyntaxHighlightPHP SyntaxHighlight = "php"
	// SyntaxHighlightPython is syntax highlight for Python.
	SyntaxHighlightPython SyntaxHighlight = "python"
	// SyntaxHighlightRuby is syntax highlight for Ruby.
	SyntaxHighlightRuby SyntaxHighlight = "ruby"
	// SyntaxHighlightSwift is syntax highlight for Swift.
	SyntaxHighlightSwift SyntaxHighlight = "swift"
	// SyntaxHighlightScala is syntax highlight for Scala.
	SyntaxHighlightScala SyntaxHighlight = "scala"
	// SyntaxHighlightRust is syntax highlight for Rust.
	SyntaxHighlightRust SyntaxHighlight = "rust"
	// SyntaxHighlightObjectiveC is syntax highlight for Objective-C.
	SyntaxHighlightObjectiveC SyntaxHighlight = "objectivec"
	// SyntaxHighlightPerl is syntax highlight for Perl.
	SyntaxHighlightPerl SyntaxHighlight = "perl"
	// SyntaxHighlightLua is syntax highlight for Lua.
	SyntaxHighlightLua SyntaxHighlight = "lua"
	// SyntaxHighlightDart is syntax highlight for Dart.
	SyntaxHighlightDart SyntaxHighlight = "dart"
	// SyntaxHighlightClojure is syntax highlight for Clojure.
	SyntaxHighlightClojure SyntaxHighlight = "clojure"
	// SyntaxHighlightGroovy is syntax highlight for Groovy.
	SyntaxHighlightGroovy SyntaxHighlight = "groovy"
	// SyntaxHighlightR is syntax highlight for R.
	SyntaxHighlightR SyntaxHighlight = "r"
	// SyntaxHighlightHaskell is syntax highlight for Haskell.
	SyntaxHighlightHaskell SyntaxHighlight = "haskell"
	// SyntaxHighlightErlang is syntax highlight for Erlang.
	SyntaxHighlightErlang SyntaxHighlight = "erlang"
	// SyntaxHighlightElixir is syntax highlight for Elixir.
	SyntaxHighlightElixir SyntaxHighlight = "elixir"
	// SyntaxHighlightOCaml is syntax highlight for OCaml.
	SyntaxHighlightOCaml SyntaxHighlight = "ocaml"
	// SyntaxHighlightJulia is syntax highlight for Julia.
	SyntaxHighlightJulia SyntaxHighlight = "julia"
	// SyntaxHighlightScheme is syntax highlight for Scheme.
	SyntaxHighlightScheme SyntaxHighlight = "scheme"
	// SyntaxHighlightFSharp is syntax highlight for F#.
	SyntaxHighlightFSharp SyntaxHighlight = "fsharp"
	// SyntaxHighlightCoffeeScript is syntax highlight for CoffeeScript.
	SyntaxHighlightCoffeeScript SyntaxHighlight = "coffeescript"
	// SyntaxHighlightVBNet is syntax highlight for VB.NET.
	SyntaxHighlightVBNet SyntaxHighlight = "vbnet"
	// SyntaxHighlightTeX is syntax highlight for TeX.
	SyntaxHighlightTeX SyntaxHighlight = "tex"
	// SyntaxHighlightDiff is syntax highlight for Diff.
	SyntaxHighlightDiff SyntaxHighlight = "diff"
	// SyntaxHighlightApache is syntax highlight for Apache.
	SyntaxHighlightApache SyntaxHighlight = "apache"
	// SyntaxHighlightDockerfile is syntax highlight for Dockerfile.
	SyntaxHighlightDockerfile SyntaxHighlight = "dockerfile"
	// SyntaxHighlightMermaid is syntax highlight for Mermaid.
	SyntaxHighlightMermaid SyntaxHighlight = "mermaid"
)

type TableAlignment added in v0.8.1

type TableAlignment int

TableAlignment represents column alignment in markdown tables.

Example

ExampleTableAlignment demonstrates table alignment features.

package main

import (
	"os"

	md "github.com/nao1215/markdown"
)

func main() {
	_ = md.NewMarkdown(os.Stdout).
		H2("Table with Alignments").
		Table(md.TableSet{
			Header: []string{"Left Align", "Center Align", "Right Align"},
			Rows: [][]string{
				{"Content1", "Content2", "Content3"},
				{"Content4", "Content5", "Content6"},
			},
			Alignment: []md.TableAlignment{md.AlignLeft, md.AlignCenter, md.AlignRight},
		}).
		Build()

}
Output:
## Table with Alignments
| Left Align | Center Align | Right Align |
|:--------|:-------:|--------:|
| Content1 | Content2 | Content3 |
| Content4 | Content5 | Content6 |
const (
	// AlignDefault represents no specific alignment (left by default).
	AlignDefault TableAlignment = iota
	// AlignLeft represents left alignment (:------).
	AlignLeft
	// AlignCenter represents center alignment (:-----:).
	AlignCenter
	// AlignRight represents right alignment (------:).
	AlignRight
)

type TableOfContentsDepth added in v0.8.2

type TableOfContentsDepth int

TableOfContentsDepth represents the depth level for table of contents.

const (
	// TableOfContentsDepthH1 includes only H1 headers in the table of contents.
	TableOfContentsDepthH1 TableOfContentsDepth = 1
	// TableOfContentsDepthH2 includes H1 and H2 headers in the table of contents.
	TableOfContentsDepthH2 TableOfContentsDepth = 2
	// TableOfContentsDepthH3 includes H1, H2, and H3 headers in the table of contents.
	TableOfContentsDepthH3 TableOfContentsDepth = 3
	// TableOfContentsDepthH4 includes H1, H2, H3, and H4 headers in the table of contents.
	TableOfContentsDepthH4 TableOfContentsDepth = 4
	// TableOfContentsDepthH5 includes H1, H2, H3, H4, and H5 headers in the table of contents.
	TableOfContentsDepthH5 TableOfContentsDepth = 5
	// TableOfContentsDepthH6 includes all headers (H1 through H6) in the table of contents.
	TableOfContentsDepthH6 TableOfContentsDepth = 6
)

type TableOfContentsOptions added in v0.8.3

type TableOfContentsOptions struct {
	// MinDepth is the minimum header level to include (e.g., 2 for H2 and deeper).
	MinDepth TableOfContentsDepth
	// MaxDepth is the maximum header level to include (e.g., 4 for H4 and shallower).
	MaxDepth TableOfContentsDepth
}

TableOfContentsOptions contains options for generating the table of contents.

type TableOptions

type TableOptions struct {
	// AutoWrapText is whether to wrap the text automatically.
	AutoWrapText bool
	// AutoFormatHeaders is whether to format the header automatically.
	AutoFormatHeaders bool
}

TableOptions is markdown table options.

type TableSet

type TableSet struct {
	// Header is table header.
	Header []string
	// Rows is table record.
	Rows [][]string
	// Alignment is column alignment for each column.
	// If nil or shorter than header length, remaining columns use AlignDefault.
	Alignment []TableAlignment
}

TableSet is markdown table.

func (*TableSet) ValidateColumns

func (t *TableSet) ValidateColumns() error

ValidateColumns checks if the number of columns in the header and records match.

Directories

Path Synopsis
doc
alert command
Package main is generating markdown.
Package main is generating markdown.
architecture command
Package main is generating mermaid sequence diagram.
Package main is generating mermaid sequence diagram.
badge command
Package main is generating markdown.
Package main is generating markdown.
block command
Package main is generating mermaid block diagram.
Package main is generating mermaid block diagram.
class command
Package main is generating mermaid class diagram.
Package main is generating mermaid class diagram.
er command
Package main is generating entity relationship diagram.
Package main is generating entity relationship diagram.
flowchart command
Package main is generating flowchart.
Package main is generating flowchart.
gantt command
Package main is generating mermaid Gantt chart.
Package main is generating mermaid Gantt chart.
generate command
Package main is generating markdown.
Package main is generating markdown.
gitgraph command
Package main is generating mermaid git graph diagram.
Package main is generating mermaid git graph diagram.
kanban command
Package main is generating mermaid kanban diagram.
Package main is generating mermaid kanban diagram.
mindmap command
Package main is generating mermaid mindmap diagram.
Package main is generating mermaid mindmap diagram.
packet command
Package main is generating mermaid packet diagram.
Package main is generating mermaid packet diagram.
piechart command
Package main is generating pie chart.
Package main is generating pie chart.
quadrant command
Package main is generating mermaid quadrant chart.
Package main is generating mermaid quadrant chart.
requirement command
Package main is generating mermaid requirement diagram.
Package main is generating mermaid requirement diagram.
sequence command
Package main is generating mermaid sequence diagram.
Package main is generating mermaid sequence diagram.
state command
Package main is generating mermaid state diagram.
Package main is generating mermaid state diagram.
toc command
Package main is generating markdown with table of contents.
Package main is generating markdown with table of contents.
userjourney command
Package main is generating mermaid user journey diagram.
Package main is generating mermaid user journey diagram.
xychart command
Package main is generating mermaid XY chart.
Package main is generating mermaid XY chart.
Package internal package is used to store the internal implementation of the mermaid package.
Package internal package is used to store the internal implementation of the mermaid package.
mermaid
arch
Package arch is mermaid architecture diagram builder.
Package arch is mermaid architecture diagram builder.
block
Package block is mermaid block diagram builder.
Package block is mermaid block diagram builder.
class
Package class is mermaid class diagram builder.
Package class is mermaid class diagram builder.
er
Package er is mermaid entity relationship diagram builder.
Package er is mermaid entity relationship diagram builder.
flowchart
Package flowchart provides a simple way to create flowcharts in mermaid syntax.
Package flowchart provides a simple way to create flowcharts in mermaid syntax.
gantt
Package gantt is a mermaid Gantt chart builder.
Package gantt is a mermaid Gantt chart builder.
gitgraph
Package gitgraph is mermaid git graph diagram builder.
Package gitgraph is mermaid git graph diagram builder.
kanban
Package kanban is mermaid kanban diagram builder.
Package kanban is mermaid kanban diagram builder.
mindmap
Package mindmap is mermaid mindmap diagram builder.
Package mindmap is mermaid mindmap diagram builder.
packet
Package packet is mermaid packet diagram builder.
Package packet is mermaid packet diagram builder.
piechart
Package piechart is mermaid pie chart builder.
Package piechart is mermaid pie chart builder.
quadrant
Package quadrant is mermaid quadrant chart builder.
Package quadrant is mermaid quadrant chart builder.
requirement
Package requirement is mermaid requirement diagram builder.
Package requirement is mermaid requirement diagram builder.
sequence
Package sequence is mermaid sequence diagram builder.
Package sequence is mermaid sequence diagram builder.
state
Package state is mermaid state diagram builder.
Package state is mermaid state diagram builder.
userjourney
Package userjourney is mermaid user journey diagram builder.
Package userjourney is mermaid user journey diagram builder.
xychart
Package xychart is mermaid XY chart builder.
Package xychart is mermaid XY chart builder.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL