From 07abee79ed6d4c8031213a8bec743299f4892071 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sat, 18 Jul 2020 22:33:24 -0400 Subject: [PATCH] Keep preformatting start/end lines when parsing --- lib/gemini.ex | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/lib/gemini.ex b/lib/gemini.ex index f11a81e..98d4b1d 100644 --- a/lib/gemini.ex +++ b/lib/gemini.ex @@ -49,7 +49,9 @@ defmodule Gemini do @type line :: {:text, String.t()} | {:link, URI.t(), String.t() | nil} - | {:preformatted, String.t(), String.t() | nil} + | {:preformatted_start, String.t() | nil} + | :preformatted_end + | {:preformatted, String.t()} | {:heading, String.t(), 1 | 2 | 3} | {:list_item, String.t()} | {:quoted, String.t()} @@ -62,19 +64,20 @@ defmodule Gemini do {lines, _, _} = doc |> String.split("\n") - |> Enum.reduce({[], false, nil}, fn line, {lines, in_preformatting, preformatting_alt} -> + |> Enum.reduce({[], false}, fn line, {lines, in_preformatting} -> preformatting_toggle = match?("```" <> _, line) cond do preformatting_toggle && in_preformatting -> - {lines, false, nil} + {[:preformatting_end | lines], false} preformatting_toggle && !in_preformatting -> "```" <> alt = line - {lines, true, alt} + alt = if length(alt) == 0, do: nil, else: alt + {[{:preformatting_start, alt} | lines], true} in_preformatting -> - {[{:preformatted, line, preformatting_alt} | lines], true, preformatting_alt} + {[{:preformatted, line} | lines], true} true -> case line do @@ -85,25 +88,25 @@ defmodule Gemini do [_, link, text] -> {link, text} end - {[{:link, URI.parse(link), text} | lines], false, nil} + {[{:link, URI.parse(link), text} | lines], false} "###" <> rest -> - {[{:heading, String.trim(rest), 3} | lines], false, nil} + {[{:heading, String.trim(rest), 3} | lines], false} "##" <> rest -> - {[{:heading, String.trim(rest), 2} | lines], false, nil} + {[{:heading, String.trim(rest), 2} | lines], false} "#" <> rest -> - {[{:heading, String.trim(rest), 1} | lines], false, nil} + {[{:heading, String.trim(rest), 1} | lines], false} "* " <> rest -> - {[{:list_item, String.trim(rest)} | lines], false, nil} + {[{:list_item, String.trim(rest)} | lines], false} ">" <> rest -> - {[{:quoted, String.trim(rest)} | rest], false, nil} + {[{:quoted, String.trim(rest)} | rest], false} line -> - {[{:text, line} | lines], false, nil} + {[{:text, line} | lines], false} end end end)