protect_unescaped {tinkr} | R Documentation |
Protect unescaped square brackets from being escaped
Description
Commonmark allows both [unescaped]
and \[escaped\]
square brackets, but
in the XML representation, it makes no note of which square brackets were
originally escaped and thus will escape both in the output. This function
protects brackets that were unescaped in the source document from being
escaped.
Usage
protect_unescaped(body, txt, ns = md_ns())
Arguments
body |
an XML body |
txt |
the text of a source file |
ns |
an the namespace that resolves the Markdown namespace (defaults to
|
Details
This is an internal function that is run by default via to_xml()
and
yarn$new()
. It uses the original document, parsed as text, to find and
protect unescaped square brackets from being escaped in the output.
Example: child documents and footnotes
For example, let's say you have two R Markdown documents, one references the other as a child, which has a reference-style link:
index.Rmd:
## Title Without protection reference style links (e.g. \[text\]\[link\]) like this [outside link][reflink] would be accidentally escaped. This is a footnote [^1]. [^1]: footnotes are not recognised by commonmark ```{r, child="child.Rmd"} ```
child.Rmd:
... [reflink]: https://example.com
Without protection, the roundtripped index.Rmd document would look like this:
## Title Without protection reference style links (e.g. \[text\]\[link\]) like this \[outside link\]\[reflink\] would be accidentally escaped. This is a footnote \[^1\] \[^1\]: footnotes are not recognised by commonmark ```{r, child="child.Rmd"} ```
This function provides the protection that allows these unescaped brackets to remain unescaped during roundtrip.
Note
Because the This body
to be an XML document with sourcepos
attributes on the
nodes, which is achieved by using sourcepos = TRUE
with to_xml()
or
yarn.
Examples
f <- system.file("extdata", "link-test.md", package = "tinkr")
md <- yarn$new(f, sourcepos = TRUE, unescaped = FALSE)
md$show()
if (requireNamespace("withr")) {
lines <- readLines(f)[-length(md$frontmatter)]
lnks <- withr::with_namespace("tinkr",
protect_unescaped(body = md$body, txt = lines))
md$body <- lnks
md$show()
}