From a5e0a7e23708909b05a21fc0f0b25007f3f685a7 Mon Sep 17 00:00:00 2001 From: Kevin Newton Date: Thu, 19 Sep 2024 12:59:15 -0400 Subject: [PATCH] Fix up tag flags --- Gemfile.lock | 1 + lib/syntax_tree/haml/format.rb | 20 +++++++++++++------- test/tag_test.rb | 16 ++++++++++++++++ 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index 43b00f9..286fa15 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -31,6 +31,7 @@ GEM PLATFORMS arm64-darwin-22 + arm64-darwin-23 x86_64-linux DEPENDENCIES diff --git a/lib/syntax_tree/haml/format.rb b/lib/syntax_tree/haml/format.rb index c3cf6cc..7574ba5 100644 --- a/lib/syntax_tree/haml/format.rb +++ b/lib/syntax_tree/haml/format.rb @@ -16,7 +16,9 @@ def initialize( .lines .each .with_index(1) do |line, index| - @literal_lines[index] = line.strip if line.lstrip.start_with?("!") + if (literal_line = line[/\A\s*(?:%[a-z]+)?(!.*)\s*\z/, 1]) + @literal_lines[index] = literal_line + end end super(source, *rest, options: options) @@ -384,8 +386,12 @@ def visit_tag(node) # tag. q.breakable_empty - if node.value[:parse] - format_tag_value(q, value) + if line = q.literal_lines[node.line] + q.text(line) + elsif node.value[:parse] + prefix = node.value[:preserve_script] ? "~" : "=" + prefix = "&#{prefix}" if node.value[:escape_html] + format_tag_value(q, prefix, value) else q.if_break { q.text("") }.if_flat { q.text(" ") } q.text(value) @@ -399,10 +405,10 @@ def visit_tag(node) private - def format_tag_value(q, value) + def format_tag_value(q, prefix, value) program = SyntaxTree.parse(value) if !program || program.statements.body.length > 1 - return q.text("= #{value}") + return q.text("#{prefix} #{value}") end statement = program.statements.body.first @@ -418,10 +424,10 @@ def format_tag_value(q, value) q.if_break { q.text("") }.if_flat { q.text(" ") } q.text(formatted[1...-1].gsub(/\\"/, "\"")) else - q.text("= #{formatted}") + q.text("#{prefix} #{formatted}") end rescue Parser::ParseError - q.text("= #{value}") + q.text("#{prefix} #{value}") end # When printing out sequences of silent scripts, sometimes subsequent nodes diff --git a/test/tag_test.rb b/test/tag_test.rb index c693c9a..93de8ce 100644 --- a/test/tag_test.rb +++ b/test/tag_test.rb @@ -135,4 +135,20 @@ def test_interpolation_in_strings def test_interpolation_in_value assert_format("%p hello\"\#{1 + 2} little pigs\"") end + + def test_preserve + assert_format("%p~ foo") + end + + def test_escape_html + assert_format("%p&= foo") + end + + def test_preserve_escape_html + assert_format("%p&~ foo") + end + + def test_unescape + assert_format("%p!= foo") + end end