Skip to content

Instantly share code, notes, and snippets.

@belyaev-mikhail
Created July 29, 2019 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belyaev-mikhail/ae1209fa177c757e23a8915a5c57d760 to your computer and use it in GitHub Desktop.
Save belyaev-mikhail/ae1209fa177c757e23a8915a5c57d760 to your computer and use it in GitHub Desktop.
inline class AppendScope(val appendable: Appendable) {
inline fun indent(indent: Int = 4, body: IndentScope.() -> Unit) {
IndentScope(indent).body()
}
}
inline fun AppendScope.appendln(value: CharSequence) = appendable.appendln(value)
inline class IndentScope(val indent: Int = 4) {
inline fun AppendScope.appendln(value: CharSequence) = appendable.append(" ".repeat(indent)).appendln(value)
inline fun indent(indent: Int = 4, body: IndentScope.() -> Unit) {
IndentScope(this.indent + indent).body()
}
}
inline fun prettyPrintTo(appendable: Appendable, body: AppendScope.() -> Unit) {
AppendScope(appendable).body()
}
fun main() {
val sb = StringBuilder()
prettyPrintTo(sb) {
appendln("fun foo() {")
indent {
appendln("val x = 2")
appendln("val y = 3")
appendln("run {")
indent(4) {
appendln("println(\"x = \$x\")")
}
appendln("}")
appendln("return x * y")
}
appendln("}")
}
println(sb)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment