Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions lib/makeup/formatters/html/html_formatter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,28 @@ defmodule Makeup.Formatters.HTML.HTMLFormatter do
defp escape_for(c) when is_integer(c) and c >= 128, do: << c :: utf8 >>

defp escape_for(string) when is_binary(string) do
string
|> to_charlist()
|> Enum.map(&escape_for/1)
escape_binary(string, string, 0, 0, [])
end

for {char, replacement} <- [
{?&, "&amp;"},
{?<, "&lt;"},
{?>, "&gt;"},
{?", "&quot;"},
{?', "&#39;"}
] do
defp escape_binary(<<unquote(char), rest::binary>>, original, skip, len, acc) do
part = binary_part(original, skip, len)
escape_binary(rest, original, skip + len + 1, 0, [acc, part, unquote(replacement)])
end
end

defp escape_binary(<<_char, rest::binary>>, original, skip, len, acc) do
escape_binary(rest, original, skip, len + 1, acc)
end

defp escape_binary(<<>>, original, skip, len, acc) do
[acc | binary_part(original, skip, len)]
end

defp escape(iodata) when is_list(iodata) do
Expand Down
11 changes: 11 additions & 0 deletions test/html_formatter_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,17 @@ defmodule MakeupTest.Lexer.HTMLFormatterTest do
end
end

test "a binary value is escaped, preserving safe characters and utf8" do
value = "a < b & \"c\" é 日"

assert HTMLFormatter.format_as_binary([{:string, %{}, value}]) ==
~S[<pre class="highlight"><code>] <>
~S[<span class="s">] <>
~S[a &lt; b &amp; &quot;c&quot; é 日] <>
~S[</span>] <>
~S[</code></pre>]
end

test "group ids are encoded before being written to data attributes" do
html =
HTMLFormatter.format_as_binary([
Expand Down
Loading