3
3
module SyntaxTree
4
4
module Haml
5
5
class Format < Visitor
6
+ class Formatter < ::SyntaxTree ::Formatter
7
+ attr_reader :literal_lines , :quote
8
+
9
+ def initialize ( source , ...)
10
+ @literal_lines = { }
11
+ source
12
+ . lines
13
+ . each
14
+ . with_index ( 1 ) do |line , index |
15
+ @literal_lines [ index ] = line . rstrip if line . start_with? ( "!" )
16
+ end
17
+
18
+ super ( source , ...)
19
+ end
20
+ end
21
+
6
22
attr_reader :q
7
23
8
24
def initialize ( q )
@@ -62,12 +78,11 @@ def visit_haml_comment(node)
62
78
text = node . value [ :text ] . strip
63
79
64
80
if text . include? ( "\n " )
81
+ separator = -> { q . breakable ( force : true ) }
82
+
65
83
q . indent do
66
- q . breakable ( force : true )
67
- q . seplist (
68
- text . split ( "\n " ) ,
69
- -> { q . breakable ( force : true ) }
70
- ) { |segment | q . text ( segment ) }
84
+ separator . call
85
+ q . seplist ( text . split ( "\n " ) , separator ) { |segment | q . text ( segment ) }
71
86
end
72
87
else
73
88
q . text ( " #{ text } " )
@@ -76,9 +91,13 @@ def visit_haml_comment(node)
76
91
77
92
# https://haml.info/docs/yardoc/file.REFERENCE.html#plain-text
78
93
def visit_plain ( node )
79
- text = node . value [ :text ]
80
- q . text ( "\\ " ) if escaped? ( text )
81
- q . text ( text )
94
+ if line = q . literal_lines [ node . line ]
95
+ q . text ( line )
96
+ else
97
+ text = node . value [ :text ]
98
+ q . text ( "\\ " ) if escaped? ( text )
99
+ q . text ( text )
100
+ end
82
101
end
83
102
84
103
# Visit the root node of the AST.
@@ -92,12 +111,14 @@ def visit_root(node)
92
111
# https://haml.info/docs/yardoc/file.REFERENCE.html#inserting_ruby
93
112
def visit_script ( node )
94
113
with_children ( node ) do
95
- q . text ( "&" ) if node . value [ :escape_html ]
96
-
97
- node . value [ :preserve ] ? q . text ( "~" ) : q . text ( "=" )
98
-
99
- q . text ( " " )
100
- q . text ( node . value [ :text ] . strip )
114
+ if line = q . literal_lines [ node . line ]
115
+ q . text ( line )
116
+ else
117
+ q . text ( "&" ) if node . value [ :escape_html ]
118
+ q . text ( node . value [ :preserve ] ? "~" : "=" )
119
+ q . text ( " " )
120
+ q . text ( node . value [ :text ] . strip )
121
+ end
101
122
end
102
123
end
103
124
@@ -222,7 +243,7 @@ def length
222
243
private
223
244
224
245
def format_value ( q , hash , level = 0 )
225
- quote = SyntaxTree :: Formatter :: OPTIONS [ : quote]
246
+ quote = q . quote
226
247
227
248
q . group do
228
249
q . text ( "{" )
@@ -244,8 +265,7 @@ def format_value(q, hash, level = 0)
244
265
when LiteralHashValue
245
266
q . text ( value . value )
246
267
when StringLiteral
247
- qq = Formatter . new ( "" )
248
- qq . with_target ( q . target ) { value . format ( qq ) }
268
+ value . format ( q )
249
269
when String
250
270
q . text ( "#{ quote } #{ Quotes . normalize ( value , quote ) } #{ quote } " )
251
271
else
0 commit comments