/mdgen

A Kotlin DSL to generate basic Markdown files

Primary LanguageKotlinMIT LicenseMIT

About

This is a tiny Kotlin DSL for creating Markdown files.

Features

The DSL currently supports

  • Headings
  • Lists
  • Code Blocks

Headings

Headings can be created like by using the section() method

val md = Md(FileOutputStream(File("README.md")))

md.start {
    section {
        +"This is a heading with one #"
    }
}

Nesting section() methods automatically increases the number of # used for the heading The following results in a # Heading and a ## Sub-Heading

val md = Md(FileOutputStream(File("README.md")))

md.start {
    section {
        +"Heading"
        section {
            +"Sub-Heading"
        }
    }
}

Headings will be put on the same level if their section() methods are called after one-another.

val md = Md(FileOutputStream(File("README.md")))

md.start {
    section {
        +"Heading"
    }
    section {
        +"Another Heading"
    }
}

Lists

Lists can be created using the list() method. By default, ordered lists start at index 1 and their elements are added with the unary plus operator. Unordered list elements are added using the unaryMinus operator and use the asterisk (*).

val md = Md(FileOutputStream(File("README.md")))

md.start {
    list {
         +"First element"
         +"Second element"
         +"Third element"
    }
    list {
        -"Foo"
        -"Bar"
        -"Baz"
    }
}

Running the code above results in the following Markdown.

  1. First element
  2. Second element
  3. Third element
  • Foo
  • Bar
  • Baz

Code Blocks

At the moment this DSL only supports code fenced code blocks using three backticks. An optional parameter can be used to specify the language of the code block.

println("Hello World")

The listing above is created by this code.

code("kotlin") {
    """
    println("Hello World")
    """.trimIndent()
}

Other languages can be specified by passing them in the first parameter.

fn main() {
    println!("Hello World!");
}

The listing above is created by this code.

code("rust") {
    """
    fn main() {
        println!("Hello World!");
    }
    """.trimIndent()
}

Tables

Tables can be created using the table() methods, which takes a variable amount of Strings for the headers of the table and as last parameter a lambda describing the table contents. Alternatively the table headers can be provided as Pairs of String to MdTableHeader.Alignment to configure the alignment of the content of a column.

This README.md is generated by the DSL as well. Take a look at ReadmeTest.kt for details.

Hello Beautiful World
Foo Bar Baz

The table above is created by the following code.

val md = Md(FileOutputStream(File("README.md")))
md.start {
    table("Hello" to LEFT, "Beautiful" to CENTER, "World" to RIGHT) {
        row {
            +"Foo" + "Bar" + "Baz"
        }
    }
}