Skip to content

Commit

Permalink
Dont escape text inside gfm code blocks (#2541)
Browse files Browse the repository at this point in the history
  • Loading branch information
IgnatBeresnev committed Jun 19, 2022
1 parent 9f67dcf commit a11a8dd
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 5 deletions.
Expand Up @@ -382,7 +382,7 @@ open class PageContentBuilder(
}

fun codeInline(
language: String,
language: String = "",
kind: Kind = ContentKind.Main,
sourceSets: Set<DokkaSourceSet> = mainSourcesetData,
styles: Set<Style> = mainStyles,
Expand Down
Expand Up @@ -315,15 +315,25 @@ open class CommonmarkRenderer(
append("```")
append(code.language.ifEmpty { "kotlin" })
buildNewLine()
code.children.forEach { it.build(this, pageContext) }
code.children.forEach {
if (it is ContentText) {
// since this is a code block where text will be rendered as is,
// no need to escape text, apply styles, etc. Just need the plain value
append(it.text)
} else if (it is ContentBreakLine) {
// since this is a code block where text will be rendered as is,
// there's no need to add tailing slash for line breaks
buildNewLine()
}
}
buildNewLine()
append("```")
buildNewLine()
}

override fun StringBuilder.buildCodeInline(code: ContentCodeInline, pageContext: ContentPage) {
append("`")
code.children.forEach { it.build(this, pageContext) }
code.children.filterIsInstance<ContentText>().forEach { append(it.text) }
append("`")
}

Expand Down
39 changes: 37 additions & 2 deletions plugins/gfm/src/test/kotlin/renderers/gfm/CodeWrappingTest.kt
Expand Up @@ -24,15 +24,33 @@ class CodeWrappingTest : GfmRenderingOnlyTestBase() {
assertEquals(expect, renderedContent)
}

@Test
fun `should preserve original text without escaping`() {
val page = testPage {
codeBlock {
text("<----> **text** & ~~this~~ and \"that\"")
}
}
val expect = """|//[testPage](test-page.md)
|
|```kotlin
|<----> **text** & ~~this~~ and "that"
|```""".trimMargin()

CommonmarkRenderer(context).render(page)
assertEquals(expect, renderedContent)
}


@Test
fun wrappedInlineCode() {
val page = testPage {
text("This function adds the values of ")
codeInline("") {
codeInline {
text("left")
}
text(" and ")
codeInline("") {
codeInline {
text("right")
}
text(".\nBoth numbers must be finite, or an exception occurs.\n")
Expand All @@ -45,4 +63,21 @@ class CodeWrappingTest : GfmRenderingOnlyTestBase() {
CommonmarkRenderer(context).render(page)
assertEquals(expect, renderedContent)
}

@Test
fun `should not add trailing backslash to newline elements for code inline code`() {
val page = testPage {
text("This adds some symbols (")
codeInline {
text("<----> **text** & ~~this~~ and \"that\"")
}
text(") to the test")
}
val expect = """|//[testPage](test-page.md)
|
|This adds some symbols (`<----> **text** & ~~this~~ and "that"`) to the test""".trimMargin()

CommonmarkRenderer(context).render(page)
assertEquals(expect, renderedContent)
}
}

0 comments on commit a11a8dd

Please sign in to comment.