Implementing custom Markdown parser with the MD Library

Guilty.

The docs of md must be updated and extended widely.

In the first place, you’ve found a bug in the custom parsers implementation, thanks for that. Fixed in v0.9.7.

Second, you kinda mix up custom parsers and syntax. The very correct change in config.exs would now be handled properly, the correct syntax is:

import Config

config :md, syntax: %{
  custom: [{"<.", {MasWeb.MdParser, %{}}}]
}

The custom parser is an implementation of Md.Parser behaviour, so copy-pasting from the library source wouldn’t help much. Instead, you are supposed to implement the whole parser. The very naïve implementation would look like this:

defmodule MasWeb.MdParser do
  alias Md.Parser.State

  @behaviour Md.Parser

  @impl true
  def parse(input, state) do
    # <.card image_path="/images/awesome.svg">
    #   Some nice card with an image on the left.
    # </.card>
    # Continuing after the card.

    [tag, rest] = String.split(input, " ", parts: 2)
    [content, rest] = String.split(rest, "</.#{tag}>", parts: 2)
    {rest, %State{state | ast: [content | state.ast]}}
  end
end

Once we use <. as a tag, <. would not be passed to the handler itself. Hence we got card in the first split and the inner tag content in the second split. We end up with rest, which must be passed back to the “main” parser as a continuation, and content which you should translate to AST yourself (because it’s a custom parser.) Here we simply return back a text node.

Sidenote: custom name is essential, common would not work, it’s used as a tag type.


Thanks for giving the library a try, please, don’t hesitate to ask if anything. I’d love to make some progress with its docs and tests, but unfortunately, it serves our current needs and I am like, ok, later, then :slight_smile: