Skip to content

Commit

Permalink
fix: support 4 backticks
Browse files Browse the repository at this point in the history
Make it possible to use more than 3 backticks (or ~)
for code markers. This change also ensure it is possible
to use a codeblock with 4 markers, which itself contains
code blocks with 3 markers.

Basically, remember what the start was, and consider the
code block end only when the same marker is found.
  • Loading branch information
derlin committed Jan 18, 2025
1 parent 5b28d6c commit 4b0eef0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/commonMain/kotlin/ch/derlin/bitdowntoc/BitGenerator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,12 @@ object BitGenerator {

while (iter.hasNext()) {
val line = iter.next()
when {
line.isCodeStart("```") -> iter.consumeCode("```")
line.isCodeStart("~~~") -> iter.consumeCode("~~~")
commenter.isAnchor(line) -> iter.remove()
else -> line.parseHeader(toc)?.let {
val codeMarker = listOf('`', '~').firstNotNullOfOrNull { line.getCodeStart(it) }

if (!codeMarker.isNullOrBlank()) iter.consumeCode(codeMarker)
else if (commenter.isAnchor(line)) iter.remove()
else {
line.parseHeader(toc)?.let {
if (params.generateAnchors) {
iter.set(commenter.toAnchor(it.link))
iter.add(line)
Expand Down Expand Up @@ -104,14 +105,17 @@ object BitGenerator {
throw MissingTocEndException()
}

private fun String.isCodeStart(codeMarker: String) =
codeStartTrimmer.replace(this, "").startsWith(codeMarker)
private fun String.getCodeStart(char: Char): String? =
codeStartTrimmer.replace(this, "")
// We expect at least 3 for code start (```), but 4 is also supported.
// See https://github.com/derlin/bitdowntoc/issues/65
.takeIf { it.startsWith("$char".repeat(3)) }
?.let { trimmedLine -> trimmedLine.takeWhile { it == char } }


private fun Iterator<String>.consumeCode(codeMarker: String) {
while (this.hasNext() && !this.next().trim().startsWith(codeMarker));
}

private fun Iterable<String>.asText() = this.joinToString(NL)

}
25 changes: 25 additions & 0 deletions src/commonTest/kotlin/ch.derlin.bitdowntoc/GenerateTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,31 @@ class GenerateTest {
```
""".trimIndent()
)

assertDoesNotChangeToc(
"""
````
# Markdown
- ```
code
```
~~~
code
~~~
````
""".trimIndent()
)

assertFailsWith<AssertionError> {
assertDoesNotChangeToc(
"""
````
code
```
""".trimIndent()
)
}
}

@Test
Expand Down

0 comments on commit 4b0eef0

Please sign in to comment.