File: helpers.ex

package info (click to toggle)
elixir-earmark-parser 1.4.44-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,148 kB
  • sloc: makefile: 9
file content (95 lines) | stat: -rw-r--r-- 2,083 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
defmodule Support.Helpers do
  alias EarmarkParser.Block.IdDef
  alias EarmarkParser.Context

  ###############
  # Helpers.... #
  ###############

  def context do
    %EarmarkParser.Context{}
  end

  def annotated(meta, annotation) do
    Map.put(meta, :annotation, annotation)
  end

  def as_ast(markdown, options \\ []) do
    EarmarkParser.as_ast(markdown, options)
  end

  def parse_html(html, metadata_fun \\ &default_metadata_fun/1) do
    if System.get_env("DEBUG") do
      _parse_html(html) |> _add_4th(metadata_fun) |> IO.inspect()
    else
      _parse_html(html) |> _add_4th(metadata_fun)
    end
  end

  # Floki does not keep track of lines so let's pretend it does for code spans
  defp default_metadata_fun({"code", attrs, _}) do
    case List.keyfind(attrs, "class", 0) do
      {"class", "inline" <> _} ->
        %{line: 1}

      {"class", "math-" <> _} ->
        %{line: 1}

      _ ->
        %{}
    end
  end

  defp default_metadata_fun(_other) do
    %{}
  end

  def test_links do
    [
      {"id1", %IdDef{url: "url 1", title: "title 1"}},
      {"id2", %IdDef{url: "url 2"}},
      {"img1", %IdDef{url: "img 1", title: "image 1"}},
      {"img2", %IdDef{url: "img 2"}}
    ]
    |> Enum.into(Map.new())
  end

  def pedantic_context do
    ctx = put_in(context().options.gfm, false)
    ctx = put_in(ctx.options.pedantic, true)
    ctx = put_in(ctx.links, test_links())
    Context.update_context(ctx)
  end

  def gfm_context do
    Context.update_context(context())
  end

  defp _add_4th(node, metadata_fun)

  defp _add_4th(nodes, metadata_fun) when is_list(nodes) do
    nodes
    |> Enum.map(&_add_4th(&1, metadata_fun))
  end

  defp _add_4th({t, a, c}, metadata_fun) do
    c = _add_4th(c, metadata_fun)
    {t, a, c, metadata_fun.({t, a, c})}
  end

  defp _add_4th({:comment, content}, _) do
    {:comment, [], content, %{comment: true}}
  end

  defp _add_4th(other, _) do
    other
  end

  defp _parse_html(html) do
    with {_, ast} = Floki.parse_fragment(html) do
      ast
    end
  end
end

# SPDX-License-Identifier: Apache-2.0