Skip to content

Better formatting on parse: true #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 7, 2023
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
1 change: 1 addition & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ GEM

PLATFORMS
arm64-darwin-22
x86_64-linux

DEPENDENCIES
bundler
Expand Down
36 changes: 27 additions & 9 deletions lib/syntax_tree/haml/format.rb
Original file line number Diff line number Diff line change
Expand Up @@ -377,15 +377,8 @@ def visit_tag(node)
# tag.
q.breakable_empty

if node.value[:parse] && value.match?(/#[{$@]/)
# There's a weird case here where if the value includes
# interpolation and it's marked as { parse: true }, then we
# don't actually want the = prefix, and we want to remove extra
# escaping.
q.if_break { q.text("") }.if_flat { q.text(" ") }
q.text(value[1...-1].gsub(/\\"/, "\""))
elsif node.value[:parse]
q.text("= #{value}")
if node.value[:parse]
format_tag_value(q, value)
else
q.if_break { q.text("") }.if_flat { q.text(" ") }
q.text(value)
Expand All @@ -399,6 +392,31 @@ def visit_tag(node)

private

def format_tag_value(q, value)
program = SyntaxTree.parse(value)
if !program || program.statements.body.length > 1
return q.text("= #{value}")
end

statement = program.statements.body.first
formatter = SyntaxTree::Formatter.new(value, [], Float::INFINITY)
formatter.format(statement)
formatter.flush
formatted = formatter.output.join

if statement.is_a?(StringLiteral) && statement.parts.length > 1
# There's a weird case here where if the value includes interpolation
# and it's marked as { parse: true }, then we don't actually want the
# = prefix, and we want to remove extra escaping.
q.if_break { q.text("") }.if_flat { q.text(" ") }
q.text(formatted[1...-1].gsub(/\\"/, "\""))
else
q.text("= #{formatted}")
end
rescue Parser::ParseError
q.text("= #{value}")
end

# When printing out sequences of silent scripts, sometimes subsequent nodes
# will be continuations of previous nodes. In that case we want to dedent
# them to match.
Expand Down