Interpolate values inside math expression

I am trying to interpolate the value of an object inside a math equation in Pluto.
A MWE could be:

begin
    avg = 15
    md"""
        The average would be given by:

        ``\overline{X} = \frac{\sum_{i=1}^N X_i}{N} = $(avg)``
    """
end

However, I am not successful. It works if I move the interpolation to the outside of the math expression. However, this causes the math to display inline and the value to be formatted as plain text.
Can anyone help me?

You need to use CommonMark.jl:

Notice that you need to escape the \.

1 Like

Can’t you just use the Markdown stdlib? That’s what the md"..." macro uses, after all. For example:

import Markdown

Markdown.parse("""
```math
\\overline{X} = $avg
```
""")
1 Like

Thank you a lot!

How can I do this for an inline math expression? I.e.

num_samples = 1
md"""
The number of samples is ``K=$(num_samples)``.
"""

Unfortunately I couldn’t get any of the proposed solutions to work, including those with CommonMark.jl.

EDIT: Actually, although @md_str doesn’t work here, we can do Markdown.parse!

Markdown.parse("""
The number of samples is ``K=$(num_samples)``.
""")

I am not sure why this works, as the code for @md_str suggests that it is just calling Markdown.parse. Perhaps it has to do with how interpolation is escaped in macros?

However, when replacing @md_str with Markdown.parse other issues occur, such as losing the ability to include Plots.jl figures by simply interpolating

md"""
$(plt)
"""

This is on Julia 1.10 and 1.11.

String macros, by default, do no interpolation at all, and the string is treated completely literally. (You also don’t need to escape backslashes.) This allows things like regex macros r"^\s.$" to not require excessive escaping.

(Each string macro has to implement interpolation etc. manually if it wishes. See e.g. _str string interpolation? - #11 by stevengj)

Thanks Steven.
I’ve managed to solve my conundrum by chaining the two ways of parsing mardown like so:

let
c = 1
plt = plot(1:2, 1:2;
	       size=(200, 200), bg="transparent",
           background_color_inside="#FFFFFF66")
centered(content) = PlutoUI.ExperimentalLayout.Div(
	content; style=Dict("display"=>"flex", "justify-content"=>"center"))
str = Markdown.MD(
md"""
Sometimes we use the `@md_str` definition for convenient syntax, like ``\int a(x) dx = 1``.
""",
Markdown.parse("""
Sometimes we use `Markdown.parse`, for example to interpolate into an equation: ``\\int $(c) a(x) = 1``.
"""),
md"""
If we want to show an inline plot, we must put it into the macro:

$(centered(plt))
"""
)
title = "Finally, we can put this into an Admonition like this"
Markdown.MD(
  Markdown.Admonition("correct", title, [str])
)
end