This project implements literate programming in Kotlin. Literate programming is useful for documenting projects. Having working code in your documentation, ensures that the examples you include are correct and always up to date. And making it easy to include examples with your code lowers the barrier for writing good documentation.
This library is intended for anyone that publishes some kind of Kotlin library or code and wants to document their code using Markdown files that contain working examples.
Write your documentation using a kotlin markdown DSL. Use simple example { // code goes here } blocks to provide examples. Kotlin4example will generate nice markdown with the code inside that block added as code blocks. See below for a detailed introduction.
This README is of course generated with kotlin4example.
Add the dependency to your project and start writing some documentation. See below for some examples. I tend to put my documentation code in my tests so running the tests produces the documentation as a side effect.
implementation("com.github.jillesvangurp:kotlin4example:<version>")You will also need to add the Jitpack repository:
repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
}After adding this library to your (test) dependencies, you can start adding code to generate markdown.
The first thing you need is a SourceRepository definition. This is needed to tell
kotlin4example about your repository, where to link, and where your code is.
Some of the functions in kotlin4example construct links to files in your github repository, or lookup code from files in your source code.
val k4ERepo = SourceRepository(
// used to construct markdown links to files in your repository
repoUrl = "https://github.com/jillesvangurp/kotlin4example",
// default is main
branch = "master",
// this is the default
sourcePaths = setOf(
"src/main/kotlin",
"src/test/kotlin"
)
)val myMarkdown = k4ERepo.md {
section("Introduction")
+"""
Hello world!
""".trimIndent()
}
println(myMarkdown)This will generate some markdown that looks as follows.
## Introduction
Hello world!
Kotlin4example has a simple page abstraction that you can use to organize your markdown content into pages and files
val page = Page(title = "Hello!", fileName = "hello.md")
// creates hello.md
page.write(myMarkdown)This README.md is of course created from kotlin code that runs as part of the test suite. You can look at the kotlin source code that generates this markdown here.
The code that writes the README.md file is as follows:
/**
* The readme is generated when the tests run.
*/
class DocGenTest {
@Test
fun `generate readme for this project`() {
val readmePage = Page(
title = "Kotlin4Example",
fileName = "README.md"
)
// readmeMarkdown is a lazy of the markdown content
readmePage.write(markdown = readmeMarkdown)
}
}Here's a link to the source code on Github: DocGenTest.
The code that constructs the markdown is a bit longer, you can find it here.
With Kotlin4Example you can mix examples and markdown easily. An example is a Kotlin code block. Because it is a code block, you are forced to ensure it is syntactically correct and that it compiles.
By executing the block (you can disable this), you can further guarantee it does what it is supposed to and you can intercept output and integrate that into your documentation as well
For example:
// out is an ExampleOutput instance
// with both stdout and the return
// value as a Result<T>. Any exceptions
// are captured as well.
val out = example {
print("Hello World")
}
// this is how you can append arbitrary markdown
+"""
This example prints **${out.stdOut}** when it executes.
""".trimIndent()The block you pass to example can be a suspending block; so you can create examples for
your co-routine libraries too. Kotlin4example uses runBlocking to run your examples.
When you include the above in your Markdown it will render as follows:
print("Hello World")This example prints Hello World when it executes.
Sometimes you just want to show but not run the code. You can control this with the
runExample parameter.
//
example(
runExample = false,
) {
// your code goes here
// but it won't run
}The library imposes a default line length of 80 characters on your examples. The reason is that code blocks with long lines look ugly on web pages. E.g. Github will give you a horizontal scrollbar.
You can of course turn this off or turn on the built in wrapping (wraps at the 80th character)
// making sure the example fits in a web page
// long lines tend to look ugly in documentation
example(
// use longer line length
// default is 80
lineLength = 120,
// wrap lines that are too long
// default is false
wrap = true,
// don't fail on lines that are too long
// default is false
allowLongLines = true,
) {
// your code goes here
}While it is nice to have executable blocks as examples, sometimes you just want to grab code directly from some Kotlin file. You can do that with snippets.
// BEGIN_MY_CODE_SNIPPET
println("Example code that shows in a snippet")
// END_MY_CODE_SNIPPETprintln("Example code that shows in a snippet")The BEGIN_ and END_ prefix are optional but it helps readability.
You include the code in your markdown as follows:
exampleFromSnippet(
// relative path to your source file
// setup your source modules in the repository
sourceFileName = "com/jillesvangurp/kotlin4example/docs/readme.kt",
snippetId = "MY_CODE_SNIPPET"
)This is how you can use the markdown dsl to generate markdown.
You can use string literals, templates 2, and links or other markdown formatting.
There's more
- bullets
- bold
- *italic
- one
- two
- three
The difference between code and poetry ...
... poetry doesn’t need to compile.
section("Section") {
subSection("Sub Section") {
+"""
You can use string literals, templates ${1 + 1},
and [links](https://github.com/jillesvangurp/kotlin4example)
or other **markdown** formatting.
""".trimIndent()
subSubSection("Sub sub section") {
+"""
There's more
""".trimIndent()
unorderedList("bullets","**bold**","*italic")
orderedList("one","two","three")
blockquote("""
The difference between code and poetry ...
... poetry doesn’t need to compile.
""".trimIndent()
)
}
}
}Linking to different things in your repository.
// you can also just include markdown files
// useful if you have a lot of markdown
// content without code examples
includeMdFile("intro.md")
// link to things in your git repository
mdLink(DocGenTest::class)
// link to things in one of your source directories
// you can customize where it looks in SourceRepository
mdLinkToRepoResource(
title = "A file",
relativeUrl = "com/jillesvangurp/kotlin4example/Kotlin4Example.kt"
)
val anotherPage = Page("Page 2", "page2.md")
// link to another page in your manual
mdPageLink(anotherPage)
// and of course you can link to your self
mdLinkToSelf("This class")Including tables is easy if you don't want to manually format them.
| Function | Explanation |
|---|---|
| mdLink | Add a link to a class or file in your repository |
| mdLinkToRepoResource | Add a file in your repository |
| includeMdFile | include a markdown file |
| example | Example code block |
table(listOf("Function","Explanation"),listOf(
listOf("mdLink","Add a link to a class or file in your repository"),
listOf("mdLinkToRepoResource","Add a file in your repository"),
listOf("includeMdFile","include a markdown file"),
listOf("example","Example code block"),
))You can add your own source code blocks as well.
mdCodeBlock(
code = """
Useful if you have some **non kotlin code** that you want to show
""".trimIndent(),
type = "markdown"
)For more elaborate examples of using this library, checkout my kt-search project. That project is where this project emerged from and all markdown in that project is generated by kotlin4example. Give it a try on one of your own projects and let me know what you think.
When I started writing documentation for my Kotlin Client for Elasticsearch, I quickly discovered that keeping the examples in the documentation working was a challenge. I'd refactor or rename something which then would invalidate all my examples. Staying on top of that is a lot of work.
Instead of just using one of the many documentation tools out there that can grab chunks of source code based on
some string marker, I instead came up with a better solution: Kotlin4example implements a Markdown Kotlin DSL that includes a few nifty features, including an example function that takes an arbitrary block of Kotlin code and turns it into a markdown code block.
So, to write documentation, you simply use the DSL to write your documentation in Kotlin. You don't have to write all of it in Kotlin of course; it can include regular markdown files as well. But when writing examples, you just write them in Kotlin and the library turns them into markdown code blocks.
There is of course more to this library. For more on that, check out the examples below. Which are of course generated with this library.
Create a pull request against outro.md if you want to add your project here.