Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Highlight Words

examples/highlight_words.livemd

Highlight Words

Mix.install([
  {:mdex, "~> 0.8"},
  {:kino, "~> 0.16"}
])

Example

import MDEx.Sigil

opts = [
  render: [unsafe: true]
]

markdown = ~MD"""
# Highlight Example

Transform double equal signals into `` tags as described at [Markdown Guide](https://www.markdownguide.org/extended-syntax/#highlight).

==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()