Skip to content

Commit ccbbb65

Browse files
committed
fix: support 4 backticks
Make it possible to use more than 3 backticks (or ~) for code markers. This change also ensures it is possible to use a code block with 4 markers, which itself contains code blocks with 3 markers. Basically, it remembers what the start was, and considers the code block end only when the same marker is found.
1 parent 5b28d6c commit ccbbb65

File tree

2 files changed

+37
-8
lines changed

2 files changed

+37
-8
lines changed

src/commonMain/kotlin/ch/derlin/bitdowntoc/BitGenerator.kt

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,12 @@ object BitGenerator {
6464

6565
while (iter.hasNext()) {
6666
val line = iter.next()
67-
when {
68-
line.isCodeStart("```") -> iter.consumeCode("```")
69-
line.isCodeStart("~~~") -> iter.consumeCode("~~~")
70-
commenter.isAnchor(line) -> iter.remove()
71-
else -> line.parseHeader(toc)?.let {
67+
val codeMarker = listOf('`', '~').firstNotNullOfOrNull { line.getCodeStart(it) }
68+
69+
if (!codeMarker.isNullOrBlank()) iter.consumeCode(codeMarker)
70+
else if (commenter.isAnchor(line)) iter.remove()
71+
else {
72+
line.parseHeader(toc)?.let {
7273
if (params.generateAnchors) {
7374
iter.set(commenter.toAnchor(it.link))
7475
iter.add(line)
@@ -104,14 +105,17 @@ object BitGenerator {
104105
throw MissingTocEndException()
105106
}
106107

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

110115

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

115120
private fun Iterable<String>.asText() = this.joinToString(NL)
116-
117121
}

src/commonTest/kotlin/ch.derlin.bitdowntoc/GenerateTest.kt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,31 @@ class GenerateTest {
137137
```
138138
""".trimIndent()
139139
)
140+
141+
assertDoesNotChangeToc(
142+
"""
143+
````
144+
# Markdown
145+
- ```
146+
code
147+
```
148+
149+
~~~
150+
code
151+
~~~
152+
````
153+
""".trimIndent()
154+
)
155+
156+
assertFailsWith<AssertionError> {
157+
assertDoesNotChangeToc(
158+
"""
159+
````
160+
code
161+
```
162+
""".trimIndent()
163+
)
164+
}
140165
}
141166

142167
@Test

0 commit comments

Comments
 (0)