Makie: rich text, markdown?

I’m looking for a way to produce rich text easily in Makie plots.

I know LaTeX strings work in Makie: this thread. But the LaTeX font (Computer Modern) is less legible than Makie’s default one. Its rich text produces more pleasant results, and it seems impossible to switch to a sans-serif font for LaTeXStrings. See this thread.

Currently, I end up kind of building my ad-hoc tools:

using Makie

function Base.:*(x::Makie.RichText, y::Makie.RichText)
  rich(x, y)
end
function Base.:*(x::Makie.RichText, y::AbstractString)
  rich(x, y)
end
function Base.:*(x::AbstractString, y::Makie.RichText)
  rich(x, y)
end

itl(s) = rich(s, font=:italic)
paren(s) = "(" * s * ")"

ylabel = itl("c") * superscript(paren(itl("n"))) * " [m/s]"

In this example, I build the rich text « c(n) [m/s] », which in markdown is

*c*<sup>(*n*)</sup> [m/s]

which is much nicer to write. So, I imagine one could write a converter from (a subset of ) markdown to rich text, which you could use as ylabel = md2rich("*c*<sup>(*n*)</sup> [m/s]").

First of all, I don’t know whether this rich text capability is part of Makie or it is an independent library. If the latter is the case, is there a converter from, say, a subset of markdown to rich text?

Searching this forum, I’ve seen threads about converting markdown to HTML . . .

This kind of works with the stdlib, but it doesn’t parse superscript or subscript syntax so you’d have to do something similar with CommonMark.jl or so

using Markdown

macro rich_str(str::String)
    quote
        md = Markdown.@md_str($str)
        markdown_to_rich(md)
    end
end

markdown_to_rich(x::Markdown.MD; italic = false, bold = false) = rich(markdown_to_rich.(x.content; italic, bold)...)
markdown_to_rich(x::Markdown.Paragraph; italic = false, bold = false) = rich(markdown_to_rich.(x.content; italic, bold)...)
markdown_to_rich(x::String; italic = false, bold = false) = rich(x; font = md_font(bold, italic))
markdown_to_rich(x::Markdown.Bold; italic = false, bold = false) = rich(markdown_to_rich.(x.text; italic, bold = !bold)...; font = md_font(!bold, italic))
markdown_to_rich(x::Markdown.Italic; italic = false, bold = false) = rich(markdown_to_rich.(x.text; italic = !italic, bold)...; font = md_font(bold, !italic))

function md_font(bold, italic)
    if bold
        if italic
            :bold_italic
        else
            :bold
        end
    else
        if italic
            :italic
        else
            :regular
        end
    end
end

f = Figure()
Axis(f[1, 1],
    xlabel = rich"**bold** and _italic_ and **_bold and italic_**",
)
f

1 Like