Highlight Words
Mix.install([
{:mdex, "~> 0.8"},
{:kino, "~> 0.16"}
])
Intro
This example demonstrates how to traverse and transform the MDEx document tree. It implements the ==highlighted text== syntax by converting matching text into tags, showing how to use `Access` to navigate and update nodes. ## Example ```elixir import MDEx.Sigil opts = [ render: [unsafe: true] ] markdown = ~MD""" # Highlight Example Transform double equal signals into tags as described at Markdown Guide.
==Because== I need to highlight these ==very important words== and also these ==other words too==. “””
document = Kernel.update_in(markdown, [:document, Access.key!(:nodes), Access.all(), :text], fn %MDEx.Text{literal: literal} ->
# break each text literal into blocks separated by =={text}==
case Regex.split(~r/==.*?==/, literal, include_captures: true, trim: true) do
# single text means no == == found
[text] ->
%MDEx.Text{literal: text}
# return HtmlBlock for each ==
blocks ->
blocks =
Enum.map(blocks, fn
"==" <> rest ->
marked_text = "" <> String.replace_suffix(rest, "==", "")
%MDEx.HtmlBlock{literal: marked_text}
text ->
%MDEx.Text{literal: text}
end)
%MDEx.Paragraph{nodes: blocks}
end
end)
document |> MDEx.to_html!(opts) |> Kino.HTML.new()