Skip to content

Commit

Permalink
generate: don't alter # line inside fenced code block
Browse files Browse the repository at this point in the history
Previously, `configlet generate` assumed that every line beginning
with a '#' character inside a concept `introduction.md` is a header.
For our purposes, the most common exception to that idea is probably
a comment inside a fenced code block. With this commit, we no longer
add a '#' to such a line.

The markdown handling here is rudimentary, but it may be good enough to
avoid a full markdown parser for `configlet generate`.

But this doesn't support other blocks, like HTML blocks.
  • Loading branch information
ee7 committed Jun 19, 2022
1 parent 600e1f9 commit e3111b5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
11 changes: 9 additions & 2 deletions src/generate/generate.nim
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,17 @@ func alterHeaders(s: string): string =
if i < s.len and s[i] == '#' and i+1 < s.len and s[i+1] == ' ':
i += s.skipUntil('\n', i)
# Demote other headers
var inFencedCodeBlock = false
while i < s.len:
result.add s[i]
if s[i] == '\n' and i+1 < s.len and s[i+1] == '#':
result.add '#'
if s[i] == '\n':
# When inside a fenced code block, don't alter a line that begins with '#'
if i+1 < s.len and s[i+1] == '#' and not inFencedCodeBlock:
result.add '#'
elif i+3 < s.len and s[i+1] == '`' and s[i+2] == '`' and s[i+3] == '`':
inFencedCodeBlock = not inFencedCodeBlock
result.add "```"
i += 3
inc i
strip result

Expand Down
10 changes: 8 additions & 2 deletions tests/test_generate.nim
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ proc testGenerate =
The quick brown fox jumps over a lazy dog.
The five boxing wizards jump quickly.
```nim
# This line is not a header
echo "hi"
```
## Header 4
Expand All @@ -45,7 +48,10 @@ proc testGenerate =
The quick brown fox jumps over a lazy dog.
The five boxing wizards jump quickly.
```nim
# This line is not a header
echo "hi"
```
### Header 4
Expand Down

0 comments on commit e3111b5

Please sign in to comment.