Here's a bit of code...
@ {Some other code}
Here's another bit of code...
`. This can add pain to layout and styling, and so I've put a `.. raw:: html` hack to force the first paragraph to be surrounded in `
`.
```nim convert a prose block into html
let toParaHack = ".. raw:: html\n\n" & txblock.content
generatedHtml &=
toParaHack.rstToHtml(
{
roSupportMarkdown, roPreferMarkdown, roSandboxDisabled,
roSupportRawDirective,
},
modeStyleInsensitive.newStringTable(),
)
```
#### Generating the code block HTML
On the other hand, converting code blocks aren't so trivial. At minimum the code block needs to have escapes in order for them not to be interpreted as HTML code when I don't want it, which can lead to incorrect code displays. Then there's also the extra metadata that needs to be laid out so as to easily identify and navigate between them.
```nim convert a code block into html
let escapedCode =
@{make the code block html-friendly}
let normName = txblock.name.normalize()
# start writing converted code block
generatedHtml &= (
@{code block html start}
)
# if the block is used somewhere else, say so
if txblock.name.len > 0 and reflist[txblock.name].len > 0:
@{generate backlinks list for html code block}
# end write block
generatedHtml &= (
@{code block html end}
)
```
First I escape the common HTML characters, and then turn all code block references into links.
```nim make the code block html-friendly
txblock.content
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace(codeBlockRefPtn, nameAsLink)
```
The link-replacement is done by this helper function:
```nim helper function to transform names to links
proc nameAsLink(m: RegexMatch2, s: string): string =
return
"" &
s[m.group(0)] &
"
"
```
Every one of these links needs to refer to valid HTML identifiers, which, to make it consistent, I'll have to make a helper function to convert from the code block's name to a weird HTML identifier.
```nim function to normalize labels
proc normalize(s: string): string =
return s
.replace("_","")
.replace(" ","")
.tolowerascii()
```
After I've converted the main content into something presentable, I can wrap it in an HTML container, having a title tab if the code block has a name, but a plain pre otherwise. In them I also add language information via a class, so that external tools or JavaScript would know what to do with them.
```nim code block html start
if txblock.name.len > 0:
@{starting html for named code block}
else:
@{starting html for anonymous code block}
```
```nim starting html for named code block
"
"
```
```nim starting html for anonymous code block
"" &
escapedCode &
"
"
```
```nim code block html end
"" &
escapedCode &
"