@@ -62,21 +62,39 @@ def format(node, stackable: true)
6262 # If there are comments, then we're going to format them around the node
6363 # so that they get printed properly.
6464 if node . comments . any?
65- leading , trailing = node . comments . partition ( &:leading? )
65+ trailing = [ ]
66+ last_leading = nil
6667
67- # Print all comments that were found before the node.
68- leading . each do |comment |
69- comment . format ( self )
70- breakable ( force : true )
68+ # First, we're going to print all of the comments that were found before
69+ # the node. We'll also gather up any trailing comments that we find.
70+ node . comments . each do |comment |
71+ if comment . leading?
72+ comment . format ( self )
73+ breakable ( force : true )
74+ last_leading = comment
75+ else
76+ trailing << comment
77+ end
7178 end
7279
7380 # If the node has a stree-ignore comment right before it, then we're
7481 # going to just print out the node as it was seen in the source.
7582 doc =
76- if leading . last &.ignore?
83+ if last_leading &.ignore?
7784 range = source [ node . location . start_char ...node . location . end_char ]
78- separator = -> { breakable ( indent : false , force : true ) }
79- seplist ( range . split ( /\r ?\n / , -1 ) , separator ) { |line | text ( line ) }
85+ first = true
86+
87+ range . each_line ( chomp : true ) do |line |
88+ if first
89+ first = false
90+ else
91+ breakable_return
92+ end
93+
94+ text ( line )
95+ end
96+
97+ breakable_return if range . end_with? ( "\n " )
8098 else
8199 node . format ( self )
82100 end
@@ -101,12 +119,53 @@ def format_each(nodes)
101119 nodes . each { |node | format ( node ) }
102120 end
103121
122+ def grandparent
123+ stack [ -3 ]
124+ end
125+
104126 def parent
105127 stack [ -2 ]
106128 end
107129
108130 def parents
109131 stack [ 0 ...-1 ] . reverse_each
110132 end
133+
134+ # This is a simplified version of prettyprint's group. It doesn't provide
135+ # any of the more advanced options because we don't need them and they take
136+ # up expensive computation time.
137+ def group
138+ contents = [ ]
139+ doc = Group . new ( 0 , contents : contents )
140+
141+ groups << doc
142+ target << doc
143+
144+ with_target ( contents ) { yield }
145+ groups . pop
146+ doc
147+ end
148+
149+ # A similar version to the super, except that it calls back into the
150+ # separator proc with the instance of `self`.
151+ def seplist ( list , sep = nil , iter_method = :each )
152+ first = true
153+ list . __send__ ( iter_method ) do |*v |
154+ if first
155+ first = false
156+ elsif sep
157+ sep . call ( self )
158+ else
159+ comma_breakable
160+ end
161+ yield ( *v )
162+ end
163+ end
164+
165+ # This is a much simplified version of prettyprint's text. It avoids
166+ # calculating width by pushing the string directly onto the target.
167+ def text ( string )
168+ target << string
169+ end
111170 end
112171end
0 commit comments