MichaelHatherly / CommonMark.jl

A CommonMark-compliant Markdown parser for Julia.
Other
84 stars 11 forks source link

Interpolation Error (?) #22

Open jeremiahpslewis opened 3 years ago

jeremiahpslewis commented 3 years ago
using CommonMark

cat = "test!"

# Works:
cm"""<b>Well done, your cat is called $(cat) now.</b>"""
cm"""<b>Well done, your cat is called $cat now.</b>"""

# Doesn't work:
cm"""<p><b>Well done, your cat is called $(cat) now.</b></p>"""
cm"""<p><b>Well done, your cat is called $cat now.</b></p>"""

Does not interpolate variable $cat.

Seems related to the nested xml...

MichaelHatherly commented 3 years ago

Seems related to the nested xml...

Yeah, it's just being caused by certain types of HTML blocks and their precedence: https://github.com/MichaelHatherly/CommonMark.jl/blob/master/src/parsers/blocks.jl#L3-L11.

This is something that's defined within the spec so can't be adjusted here. There may be a way to have interpolation happen prior to the HTML tags being parsed, but quite honestly it'll likely just lead to a lot of weird edge cases.

jeremiahpslewis commented 3 years ago

Don't think this is an 'issue', necessarily, in the sense that if you're writing html, you shouldn't necessarily want to / need to use markdown, maybe worth adding to a doc page at some point in the future, I'll post a snippet below that could be used.

jeremiahpslewis commented 3 years ago

Interpolation and HTML Snippets: Oil and Water

CommonMark.jl works great with html snippets, like:

<p><b>Well done, your cat is called Jimmy now.</b></p>

it also works seamlessly with variable interpolation in CommonMark markdown:

# This is a dynamically populated $variable and calculation $(1+1)

Unfortunately, like oil and water, html snippets and variable interpolation don’t mix, so please don’t expect:

<p><b>Well done, your cat is called $cat now.</b></p>

to return anything but the html, with the interpolation step ignored:

<p><b>Well done, your cat is called $cat now.</b></p>

If you want html and interpolation, then you're looking for:

HTML("<p><b>Well done, your cat is called $cat now.</b></p>")
MichaelHatherly commented 3 years ago

Yeah, something to that effect in the readme would be worth adding. In addition probably worth noting other places where interpolation can't work:

julia> using CommonMark

julia> a = cm"""
   $(1 + 2)
   ```
   """

│ $(1 + 2)

julia> using Markdown

julia> b = md"""

       $(1 + 2)
   """

$(1 + 2)


Luckily `Markdown` also fails there...

> If you want html and interpolation, then you're looking for:

Or just parsing the string with `CommonMark` _after_ it's interpolated using

p = Parser() p("

$(1 + 2)

")

jeremiahpslewis commented 3 years ago

+1 agree. Still fighting though for a 'give to Cesar what is Cesar's' in terms of using html utilities for html strings ;)