philomena/lib/textile/parser_helpers.ex

46 lines
1.4 KiB
Elixir
Raw Normal View History

2019-11-09 02:43:38 +01:00
defmodule Textile.ParserHelpers do
2019-11-09 03:11:06 +01:00
import Phoenix.HTML
2019-11-09 02:43:38 +01:00
defmacro attribute_parser(name, open_token, close_token, open_tag, close_tag) do
quote do
defp unquote(name)(parser, [{unquote(open_token), open} | r_tokens]) do
2019-11-11 00:35:52 +01:00
case well_formed(parser, r_tokens) do
{:ok, tree, [{unquote(close_token), _close} | r2_tokens]} ->
{:ok, [{:markup, unquote(open_tag)}, tree, {:markup, unquote(close_tag)}], r2_tokens}
{:ok, tree, r2_tokens} ->
{:ok, [{:text, escape_html(open)}, tree], r2_tokens}
2019-11-09 02:43:38 +01:00
end
end
defp unquote(name)(parser, [{unquote(:"b_#{open_token}"), open} | r_tokens]) do
2019-11-11 00:35:52 +01:00
case well_formed(parser, r_tokens) do
{:ok, tree, [{unquote(:"b_#{close_token}"), _close} | r2_tokens]} ->
{:ok, [{:markup, unquote(open_tag)}, tree, {:markup, unquote(close_tag)}], r2_tokens}
{:ok, tree, r2_tokens} ->
{:ok, [{:text, escape_html(open)}, tree], r2_tokens}
2019-11-09 02:43:38 +01:00
end
end
defp unquote(name)(_parser, _tokens),
do: {:error, "Expected #{unquote(name)} tag"}
end
end
2019-11-09 03:11:06 +01:00
2019-11-11 00:35:52 +01:00
def remove_linefeeds(text) do
text
|> String.replace("\r", "")
end
2019-11-09 03:11:06 +01:00
def escape_nl2br(text) do
text
|> String.split("\n", trim: true)
|> Enum.map(&escape_html(&1))
|> Enum.join("<br/>")
end
def escape_html(text) do
html_escape(text) |> safe_to_string()
end
2019-11-09 02:43:38 +01:00
end