super-slim 3.2.2 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2dd1011e0ac6372401bfc8b9f1ae5dad00cfc9208fc845e892eb1d0b7ebf2aae
4
- data.tar.gz: 2ceb2fe0dc641bd9ccbd49c7841cdaf1f8124c7b2b1340ec7961be80b30a9421
3
+ metadata.gz: d9189c83ed4be022cdc4c2a3bd54f130e6fe66826811fa47c15149a72dc04419
4
+ data.tar.gz: 63648f18984eb4fe426be14a8af378c94703ae4e02793fadd4182608531db72f
5
5
  SHA512:
6
- metadata.gz: ad7f7c44edd4bb989722855e7baa362ca0285fcb3168eedc474205f7f9817b0f7bf296ebb566edaa867f8fe7f73d850aa20881859b88a1e32bab76f58f6123da
7
- data.tar.gz: 6842ed4614918cd699dcaae1d9115257dc5755e343699bfcdf2c387da90bb731bc106cac062f9c0cd84f75cea351e13c82b388c9f46053382819f91ba3b08b8d
6
+ metadata.gz: 635a722ab669d1e1f3410592759c5a3055ebaead833178884a848e3bfbcf1cd2af5044c8cd33e5974cf8c17607e1ffde37bc3fb5ae21d282b6337da3f240e049
7
+ data.tar.gz: 505ca7cbfdf29e34a6ba0ef46ccb981066ae72e0321a0bf442428b6965f99b20cf247a4bafa10271c533fa6d52144d0d28949bc7eecc918e4f2bda6fc1379249
data/CHANGELOG.md CHANGED
@@ -2,6 +2,51 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.4.0] — 2026-11-07
6
+
7
+ One layout for inline tags, short children, `ruby:` blocks and negated conditions.
8
+
9
+ **New**
10
+ - `super-slim format` puts tags nested inline after a colon (`tr: td = total`) one per line, their children going as
11
+ many levels deeper. A line whose text goes on below keeps its inline tags.
12
+ - `-` lines and `ruby:` blocks next to each other at one depth make one run of code: three lines or more go in a
13
+ `ruby:` block, as the ConsecutiveControlStatements rule asks, and fewer on `-` lines. Only lines of Ruby complete on
14
+ their own move.
15
+ - With `max_line_length`, a tag whose only child is one `=` output or one line of `|` text takes it on its own line
16
+ when both fit: `td = total`, `p Hello`. Text that could read as an attribute stays below.
17
+ - `- if !condition` becomes `- unless condition` when the `!` covers the whole condition and no `else` follows. The
18
+ formatter's check takes the two for the same code.
19
+ - Lines under `/ super-slim:format off` stay out of these rules.
20
+
21
+ ## [3.3.0] — 2026-11-07
22
+
23
+ Formatted templates that Slim and Brakeman read, lines and rules you can opt out of, and a formatter about 30% faster.
24
+
25
+ **New**
26
+ - `/ super-slim:format off` keeps the lines after it as written, up to `/ super-slim:format on` or the end of their
27
+ block, and `/ super-slim:disable Rule, OtherRule` silences rules for the next tag or line of code. An unknown rule
28
+ name, or a directive with no line after it, is reported.
29
+ - The `SlimSyntax` lint rule, on by default, flags what Slim, and so Brakeman, can't read: code continued after an
30
+ opening bracket, and a comment after code.
31
+ - The `AriaBooleanValue` lint rule, on by default, flags `aria-*=true`, which renders without a value, and
32
+ `aria-*=false`, which Slim leaves out.
33
+ - `super-slim format` removes a blank line at the start of a block, sets a partial's first-line `/# locals:`
34
+ signature apart with a blank line, and writes the `do` that Slim adds to a line of code whose children render
35
+ something.
36
+
37
+ **Faster**
38
+ - `super-slim format` is about 30% faster: it compares the compiled Ruby as text before parsing it, and reads each
39
+ template once.
40
+
41
+ **Fixed**
42
+ - With `max_line_length`, `super-slim format` spreads a long call one argument per line, each line but the last
43
+ ending with a comma, instead of between brackets that close on a line of their own. Slim only continues code after
44
+ a comma or a backslash, so since 3.2.0 Brakeman could check nothing in a wrapped template. Formatting again
45
+ repairs the templates already written, a tag's output after its attributes included. A first argument too long to
46
+ follow its call, or the brackets or the `do` that close the last one, go to the next line after a backslash.
47
+ - Code spread by hand with a comment inside stays as written, instead of keeping the formatter from wrapping
48
+ anything else in its file.
49
+
5
50
  ## [3.2.2] — 2026-11-06
6
51
 
7
52
  `super-slim format` no longer joins code spread by hand into lines past `max_line_length`.
@@ -193,7 +238,9 @@ renders what Slim 5 renders with `format: :html, sort_attrs: false`, byte for by
193
238
  - Ruby 3.3 or later, every Ruby still maintained, Rails 8.0 or 8.1 for the railtie, and strscan 3.1.1 or later,
194
239
  newer than the one Ruby 3.3 ships.
195
240
 
196
- [Unreleased]: https://github.com/levups/super-slim/compare/v3.2.2...HEAD
241
+ [Unreleased]: https://github.com/levups/super-slim/compare/v3.4.0...HEAD
242
+ [3.4.0]: https://github.com/levups/super-slim/compare/v3.3.0...v3.4.0
243
+ [3.3.0]: https://github.com/levups/super-slim/compare/v3.2.2...v3.3.0
197
244
  [3.2.2]: https://github.com/levups/super-slim/compare/v3.2.1...v3.2.2
198
245
  [3.2.1]: https://github.com/levups/super-slim/compare/v3.2.0...v3.2.1
199
246
  [3.2.0]: https://github.com/levups/super-slim/compare/v3.1.1...v3.2.0
data/README.md CHANGED
@@ -94,7 +94,11 @@ Templates for XML formats (`.xml`, `.rss`, `.atom`) render as XML automatically,
94
94
 
95
95
  `super-slim format` rewrites templates in one layout: two spaces per level, a space after `-` and `=`, no `div`
96
96
  where a `.class` or `#id` is enough, no trailing whitespace unless it renders, single blank lines and a final
97
- newline. This template:
97
+ newline. A block starts right after the line that opens it, a partial's `/# locals:` signature stands apart from its
98
+ body, and Ruby code with children ends with the `do` that Slim would add. Tags nested inline (`tr: td`) go one per
99
+ line, three `-` lines in a row or more make a `ruby:` block, and a `ruby:` block of one or two lines turns back into
100
+ `-` lines. `- if !condition` with no `else` reads as `- unless condition` when the `!` covers the whole condition.
101
+ This template:
98
102
 
99
103
  ```slim
100
104
  div.card
@@ -140,18 +144,24 @@ format:
140
144
 
141
145
  The formatter then gives each line one layout, whatever its author chose. Ruby code spread over several lines is
142
146
  joined back when it fits. A longer line spreads the arguments of its call, or the elements of its array or hash, one
143
- per line between brackets that close on a line of their own, each followed by a comma:
147
+ per line, each line but the last ending with a comma:
144
148
 
145
149
  ```slim
146
- = render Card.new(
147
- title: post.title,
148
- body: post.body,
149
- )
150
+ = link_to "Read the whole post",
151
+ post_path(post),
152
+ class: "btn btn-primary"
150
153
  ```
151
154
 
152
- A call whose only argument is a call spreads that one, as `Card.new` above. Arguments go four spaces deep and the
153
- closing bracket two, two more when the line opens a block. Code spread by hand stays as it is when this layout
154
- would leave a line longer than the limit, and arguments to `new` go in parentheses.
155
+ Slim, and so Brakeman, reads a line that ends with a comma or a backslash as going on, but not one that ends with an
156
+ opening bracket. A call whose only argument is a call spreads that one: `= render Card.new(title: post.title,`. A
157
+ first argument that would pass the limit goes to the next line after a backslash, and so do the brackets or the `do`
158
+ that close the last one when they would. The lines after the first go two spaces deep, two more when the line opens a
159
+ block. Code spread by hand stays as it is when it holds a comment, or when this layout would leave a line longer than
160
+ the limit and Slim can read it. Arguments to `new` go in parentheses.
161
+
162
+ A tag whose only child is one `=` output or one line of `|` text takes it on its own line when both fit:
163
+ `td = total`, `p Hello`. Text that starts with anything but a letter, a digit or `&`, or whose first word is followed
164
+ by `=`, stays below, where it can't read as an attribute.
155
165
 
156
166
  A tag's attributes stand without delimiters when they fit on its line, and one per line inside the delimiters when
157
167
  they don't, unless its shortcuts alone pass the limit. A literal `id` or `class` becomes a shortcut, a class shortcut
@@ -161,6 +171,17 @@ named twice goes, and the other attributes follow one order: `id`, `class`, what
161
171
  an attribute, and a tag with a `*splat` keeps its order. The formatter takes attribute values to have no side
162
172
  effects: reordering two Ruby values changes the order they run in.
163
173
 
174
+ Lines the formatter should leave alone go between two comments. Without `on`, the rest of the block that holds the
175
+ comment stays as written, the rest of the template at the top level. The lines keep their text and only move with
176
+ their block, and the lint rules that `super-slim format` would fix stay quiet there:
177
+
178
+ ```slim
179
+ table
180
+ / super-slim:format off
181
+ tr: td colspan=8 = t(".empty")
182
+ / super-slim:format on
183
+ ```
184
+
164
185
  ## Linter
165
186
 
166
187
  ```sh
@@ -183,10 +204,11 @@ linters, so most will look familiar:
183
204
  | LineLength (`max: 120`), CommentControlStatement, EmptyControlStatement, ConsecutiveControlStatements (`max: 2`), TagCase | slim-lint | on |
184
205
  | InstanceVariables (in partials) | haml-lint, Rails conventions | on |
185
206
  | StrictLocals (partials declare `/# locals:`) | Rails 7.1 strict locals | off |
186
- | DuplicateId, ImageAlt, IframeTitle, AnchorHref, NestedLinks, PositiveTabindex, BooleanAttributeValue, AriaRole, AriaAttribute | Herb, eslint-plugin-jsx-a11y | on |
207
+ | DuplicateId, ImageAlt, IframeTitle, AnchorHref, NestedLinks, PositiveTabindex, BooleanAttributeValue, AriaBooleanValue (`aria-*=true` renders no value, `aria-*=false` no attribute), AriaRole, AriaAttribute | Herb, eslint-plugin-jsx-a11y | on |
187
208
  | ButtonType, InlineStyles | eslint-plugin-react, haml-lint | off |
188
209
  | DeprecatedClasses (`classes: {old: new}`, `old-*: new-*` for a prefix), DeprecatedAttributes (`attributes: {old: new}`), both with `preset: bootstrap5` | erb_lint | on, but empty |
189
210
  | UnescapedOutput (`==`, `html_safe`, `raw`, `#{{}}`) | Brakeman, erb_lint | off |
211
+ | SlimSyntax (code continued after an opening bracket, a comment after code: Slim and Brakeman can't read them) | Brakeman | on |
190
212
  | EmbeddedEngines (`forbidden_engines: [javascript, css]`) | slim-lint | off |
191
213
  | HardcodedText (text that should be translated) | erb_lint | off |
192
214
  | UnnecessaryInterpolation, UnnecessaryStringOutput | haml-lint | on |
@@ -220,6 +242,14 @@ linters:
220
242
  Every rule accepts `include:` and `exclude:`, lists of glob patterns matched against paths relative to
221
243
  `.super-slim.yml` (`**/` matches any number of directories).
222
244
 
245
+ A comment silences rules on the next tag or code line, blank lines and comments skipped, and on the lines it goes on
246
+ over. The linter reports a rule name it doesn't know:
247
+
248
+ ```slim
249
+ / super-slim:disable ButtonType, InlineStyles
250
+ button style="all: unset" Close
251
+ ```
252
+
223
253
  The `bootstrap5` preset lists the classes and data attributes that Bootstrap 5.3 renamed, including the ones with
224
254
  breakpoints such as `text-md-right`. Its data attributes are only those of Bootstrap's own components
225
255
  (`data-toggle`, `data-target` and the like). If your app also uses generic ones such as `data-content`, add them
@@ -277,6 +307,9 @@ Slim compiles `= render CardComponent.new(post:) # rubocop:disable Some/Cop -- r
277
307
  comment swallows the parenthesis that closes the output, or the `do` of a block. SuperSlim leaves a comment that
278
308
  follows code on its line out of the compiled Ruby, after `=`, `==` and `-` alike, so a RuboCop directive can sit on
279
309
  the line it is about.
310
+ Slim still can't read such a template, and neither can Brakeman, which parses views with Slim: it reports the
311
+ template as an error and checks nothing in it. The `SlimSyntax` linter rule flags these lines; turn it off if you
312
+ don't run Brakeman.
280
313
 
281
314
  ### Tailwind class names
282
315
 
@@ -365,8 +398,9 @@ On top of that:
365
398
  Real templates come from 30 open-source apps, pinned to a commit in `corpus/manifest.yml`. `rake corpus:fetch`
366
399
  downloads only their `.slim` files, into `corpus/cache` (ignored by Git). `rake corpus:check` compiles, formats
367
400
  and lints each of them and compares the result with Slim. `rake corpus:diff BASE=rev` shows what a change does to
368
- them: compiled Ruby, formatting and lint offenses. These templates are never rendered, because rendering would run
369
- their Ruby code. Your own templates can be rendered too: pass their directories in `SUPER_SLIM_CORPUS`.
401
+ them: compiled Ruby, formatting and lint offenses. It fails when formatting changes, unless `FORMATTING_CHANGES=1`
402
+ says the change means to; in CI, a pull request says so with the `formatting change` label. These templates are
403
+ never rendered, because rendering would run their Ruby code. Your own templates can be rendered too: pass their directories in `SUPER_SLIM_CORPUS`.
370
404
 
371
405
  ## Development
372
406
 
@@ -137,15 +137,15 @@ module SuperSlim
137
137
  return compile_children(output.children)
138
138
  end
139
139
 
140
- result = new_variable
141
- emit_code("#{result} = #{code}")
140
+ returned_value = new_variable
141
+ emit_code("#{returned_value} = #{code}")
142
142
  if @rails
143
143
  compile_children(output.children)
144
144
  else
145
145
  capture_into(new_variable) { compile_children(output.children) }
146
146
  end
147
147
  emit_code("end")
148
- emit_output(result, output.escape)
148
+ emit_output(returned_value, output.escape)
149
149
  end
150
150
 
151
151
  def with_do(code, children)
@@ -157,12 +157,9 @@ module SuperSlim
157
157
  # parenthesis of an output or the `do` of a block. It never runs, so it is left out. One alone on a line
158
158
  # stays: a backslash before it carries the code on to that line.
159
159
  def without_trailing_comment(code)
160
- return code unless code.include?("#")
160
+ comment_offset = Parser::RubyBrackets.code_comment_offset(code) or return code
161
161
 
162
- comment_offset = Parser::RubyBrackets.new(code).trailing_comment_offset or return code
163
-
164
- code_before = code.byteslice(0, comment_offset).sub(/[ \t]+\z/, "")
165
- (code_before.empty? || code_before.end_with?("\n")) ? code : code_before
162
+ code.byteslice(0, comment_offset).sub(/[ \t]+\z/, "")
166
163
  end
167
164
 
168
165
  def compile_tag(tag)
@@ -251,9 +248,9 @@ module SuperSlim
251
248
  # separator, so nothing is joined at render time.
252
249
  def compile_class_attribute(values)
253
250
  values = values.reject { |parts| parts.all? { |kind, value| kind == :static && value.empty? } }
254
- if values.empty?
255
- nil
256
- elsif literal_text?(values.first)
251
+ return if values.empty?
252
+
253
+ if literal_text?(values.first)
257
254
  emit_static(' class="')
258
255
  values.each_with_index { |parts, index| emit_class_value(parts, separator: index > 0) }
259
256
  emit_static('"')
@@ -380,8 +377,7 @@ module SuperSlim
380
377
 
381
378
  def compile_embedded(embedded)
382
379
  case embedded.engine
383
- when "ruby"
384
- compile_ruby(embedded.children)
380
+ when "ruby" then compile_ruby(embedded.children)
385
381
  when "javascript" then compile_tag(Tag.new("script", embedded.attributes, [TextBlock.new(embedded.children)]))
386
382
  when "css" then compile_tag(Tag.new("style", embedded.attributes, embedded.children))
387
383
  when "markdown" then compile_markdown(embedded.children)
@@ -3,18 +3,19 @@
3
3
  module SuperSlim
4
4
  class Formatter
5
5
  # Spreads a line of Ruby code over several: the arguments of its call, or the elements of its array or hash,
6
- # one per line, each followed by a comma, between brackets that close on a line of their own. A call whose only
7
- # argument is itself a call, an array or a hash spreads that argument instead: `render Card.new(…)`.
6
+ # one per line, each line but the last ending with a comma. Slim, and Brakeman with it, reads a line ending with
7
+ # a comma or a backslash as going on, but not one ending with an opening bracket. A call whose only argument is
8
+ # itself a call, an array or a hash spreads that argument instead: `render Card.new(…)`.
8
9
  class CodeWrapper
9
10
  METHOD_NAME = /\A[a-z_][a-zA-Z0-9_]*[?!]?\z/
10
11
  # Rails runs a template inside a method, where `yield` is valid.
11
12
  TEMPLATE_METHOD = "def template\n"
12
13
  CODE_OFFSET = TEMPLATE_METHOD.bytesize
13
14
 
14
- # Returns the lines after the first one's indentation, or nil when the code has nothing to spread. An item
15
+ # Returns the lines, the first one starting with head, or nil when the code has nothing to spread. An item
15
16
  # still longer than max_line_length spreads its own arguments or elements.
16
- def self.call(code, indent, opens_block:, max_line_length:)
17
- new(code, indent, opens_block:, max_line_length:).call
17
+ def self.call(code, indent, head:, opens_block:, max_line_length:)
18
+ new(code, indent, head:, opens_block:, max_line_length:).call
18
19
  end
19
20
 
20
21
  # `render Card.new title:` reads as if title went to render: arguments to `new` go in parentheses.
@@ -69,9 +70,10 @@ module SuperSlim
69
70
  end
70
71
 
71
72
  # opens_block: whether the line has children, which Slim passes to its call as a block even without `do`.
72
- def initialize(code, indent, opens_block:, max_line_length:)
73
+ def initialize(code, indent, head:, opens_block:, max_line_length:)
73
74
  @code = code
74
75
  @indent = indent
76
+ @head = head
75
77
  @opens_block = opens_block
76
78
  @max_line_length = max_line_length
77
79
  end
@@ -80,8 +82,9 @@ module SuperSlim
80
82
  statements, opens_block = self.class.parse(@code)
81
83
  return unless statements&.size == 1 && (node = spreadable(statements.first))
82
84
 
83
- closing_indent = @indent + (" " * ((@opens_block || opens_block) ? 2 * INDENT_WIDTH : INDENT_WIDTH))
84
- spread(node, CODE_OFFSET, CODE_OFFSET + @code.bytesize, closing_indent)
85
+ # Set apart from the children of a line that opens a block.
86
+ indent = @indent + (" " * ((@opens_block || opens_block) ? INDENT_WIDTH : 0))
87
+ spread(node, CODE_OFFSET, CODE_OFFSET + @code.bytesize, @head, indent)
85
88
  end
86
89
 
87
90
  private
@@ -103,35 +106,48 @@ module SuperSlim
103
106
  end
104
107
  end
105
108
 
106
- # The lines of the code from first to last, node's items spread between them, the first line unindented.
107
- def spread(node, first, last, closing_indent)
109
+ # The lines of the code from first to last after prefix, node's first item on the first line, and each other
110
+ # one on a line of its own, indented one level deeper than indent.
111
+ def spread(node, first, last, prefix, indent)
108
112
  items = node.is_a?(Prism::CallNode) ? self.class.arguments_of(node) : node.elements
109
113
  # `hint: -> do` ends past the line, with the children of the line.
110
114
  return if self.class.end_offset(items.last) > CODE_OFFSET + @code.bytesize
111
115
 
112
- item_indent = closing_indent + (" " * INDENT_WIDTH)
113
- head, tail =
114
- if node.opening_loc
115
- [slice(first, node.opening_loc.end_offset), slice(node.closing_loc.start_offset, last)]
116
- else
117
- ["#{slice(first, node.message_loc.end_offset)}(", ")#{slice(self.class.end_offset(items.last), last)}"]
118
- end
119
- item_lines = items.flat_map { spread_item(_1, item_indent) }
120
- [head, *item_lines, closing_indent + tail]
116
+ item_indent = indent + (" " * INDENT_WIDTH)
117
+ head = prefix + slice(first, node.opening_loc&.end_offset || items.first.location.start_offset)
118
+ tail = slice(node.closing_loc&.start_offset || self.class.end_offset(items.last), last)
119
+ # The last item carries what closes the node: brackets, a block, a method called on the spread array.
120
+ suffixes = items.map { _1.equal?(items.last) ? tail : "," }
121
+ first_lines = item_lines(items.first, head, item_indent, suffixes.first)
122
+ # A first item that passes the limit after the head goes to a line of its own, after a backslash.
123
+ if first_lines.first.size > @max_line_length && !head.strip.empty?
124
+ backslash = head.match?(Parser::OPENING_BRACKET_AT_LINE_END) ? "\\" : " \\"
125
+ first_lines = ["#{head.rstrip}#{backslash}", *item_lines(items.first, item_indent, item_indent, suffixes.first)]
126
+ end
127
+ *lines, last_line = first_lines + items.zip(suffixes).drop(1).flat_map { |item, suffix| item_lines(item, item_indent, item_indent, suffix) }
128
+ lines + closing_lines(last_line, tail, item_indent)
129
+ end
130
+
131
+ # What closes the last item goes to the next line after a backslash when the last line would pass the limit.
132
+ def closing_lines(last_line, tail, indent)
133
+ return [last_line] if tail.empty? || last_line.size <= @max_line_length
134
+
135
+ after_backslash = ["#{last_line.delete_suffix(tail)} \\", indent + tail.lstrip]
136
+ (after_backslash.map(&:size).max < last_line.size) ? after_backslash : [last_line]
121
137
  end
122
138
 
123
- def spread_item(item, indent)
124
- # A comma after `&block` is a syntax error.
125
- comma = "," unless item.is_a?(Prism::BlockArgumentNode)
139
+ # The lines of item after prefix, then suffix.
140
+ def item_lines(item, prefix, indent, suffix)
126
141
  item_end = self.class.end_offset(item)
127
- line = "#{indent}#{slice(item.location.start_offset, item_end)}#{comma}"
142
+ line = "#{prefix}#{slice(item.location.start_offset, item_end)}#{suffix}"
128
143
  return [line] if line.size <= @max_line_length
129
144
 
130
145
  nested = spreadable(item.is_a?(Prism::AssocNode) ? item.value : item)
131
- lines = nested && spread(nested, item.location.start_offset, item_end, indent)
146
+ lines = nested && spread(nested, item.location.start_offset, item_end, prefix, indent)
132
147
  return [line] unless lines
133
148
 
134
- [indent + lines.first, *lines[1...-1], "#{lines.last}#{comma}"]
149
+ lines[-1] += suffix
150
+ lines
135
151
  end
136
152
 
137
153
  # From offsets in the parsed source, up to the end of the line by default.
@@ -11,6 +11,8 @@ module SuperSlim
11
11
  CONTINUATION_KINDS = %i[continuation text text_blank].freeze
12
12
  CLOSING_BRACKET_AT_START = /\A[)\]}]/
13
13
  NEW_WITHOUT_PARENTHESES = /\.new [^\s=]/
14
+ CHILD_OUTPUT = /\A==?[<>]* \S.*\z/
15
+ CHILD_TEXT = /\A\| ((?![^\s=]*\s*=)[\p{L}\p{N}&]\S*(?:\s.*\S)?)\z/
14
16
 
15
17
  # Templates attach ( and [ to their tag but set { apart, as a Ruby block: 6,097 public templates agree.
16
18
  OPENING_BY_ATTRIBUTE_DELIMITERS = {"()" => "(", "[]" => "[", "{}" => " {"}.freeze
@@ -26,18 +28,43 @@ module SuperSlim
26
28
  @attribute_arranger = AttributeArranger.new(tailwind_classes:)
27
29
  end
28
30
 
29
- def call(source)
31
+ def call(source, parser: nil)
30
32
  lines = source.split("\n")
31
- parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
32
- parser.call(source)
33
+ unless parser
34
+ parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
35
+ parser.call(source)
36
+ end
33
37
  outline = parser.outline
38
+ unformatted_linenos = Parser.unformatted_linenos(lines, outline)
39
+ block_opening_linenos = Formatter.block_opening_linenos(parser)
40
+ single_child_tag_linenos = single_child_tag_linenos(parser)
34
41
  wrapped = []
35
42
  lineno = 1
36
43
  while lineno <= lines.size
37
44
  info = outline[lineno]
38
- last_lineno = lineno
39
- last_lineno += 1 while outline[last_lineno + 1]&.owner == lineno && CONTINUATION_KINDS.include?(outline[last_lineno + 1].kind)
40
- wrapped.concat(layout(lines[(lineno - 1)...last_lineno], info, outline, lineno))
45
+ last_lineno = structure_last_lineno(outline, lineno)
46
+ structure_lines = lines[(lineno - 1)...last_lineno]
47
+ if unformatted_linenos.include?(lineno)
48
+ wrapped.concat(structure_lines)
49
+ else
50
+ laid_out = layout(structure_lines, info, outline, lineno, block_opening_linenos)
51
+ child_lineno = last_lineno + 1
52
+ if laid_out.size == 1 && single_child_tag_linenos.include?(lineno) && outline[child_lineno]&.kind == :structure &&
53
+ !unformatted_linenos.include?(child_lineno)
54
+ # The child is laid out first: code it spreads over lines may join into one.
55
+ child_last_lineno = structure_last_lineno(outline, child_lineno)
56
+ child_lines = layout(lines[(child_lineno - 1)...child_last_lineno], outline[child_lineno], outline, child_lineno, block_opening_linenos)
57
+ joined = with_child(laid_out.first, child_lines.first, info) if child_lines.size == 1
58
+ end
59
+ if joined
60
+ wrapped << joined
61
+ last_lineno = child_last_lineno
62
+ else
63
+ wrapped.concat(laid_out)
64
+ end
65
+ # A `while` keeps its locals from one turn to the next.
66
+ joined = nil
67
+ end
41
68
  lineno = last_lineno + 1
42
69
  end
43
70
  "#{wrapped.join("\n")}\n"
@@ -45,26 +72,63 @@ module SuperSlim
45
72
 
46
73
  private
47
74
 
48
- def layout(lines, info, outline, lineno)
75
+ def structure_last_lineno(outline, lineno)
76
+ last_lineno = lineno
77
+ last_lineno += 1 while outline[last_lineno + 1]&.owner == lineno && CONTINUATION_KINDS.include?(outline[last_lineno + 1].kind)
78
+ last_lineno
79
+ end
80
+
81
+ # Tags whose content is one output or one text block.
82
+ def single_child_tag_linenos(parser)
83
+ parser.line_by_node.filter_map do |node, lineno|
84
+ next unless node.is_a?(AST::Tag) && node.content.is_a?(Array)
85
+
86
+ content = node.content.reject { _1 == AST::NEWLINE }
87
+ lineno if content.size == 1 && (content.first.is_a?(AST::Output) ? AST.empty?(content.first.children) : content.first.is_a?(AST::TextBlock))
88
+ end.to_set
89
+ end
90
+
91
+ # Text moves only when it starts with a letter, a digit or `&`, and its first word isn't followed by `=`: after a
92
+ # tag, anything else may read as an attribute.
93
+ def with_child(tag_line, child_line, info)
94
+ return if info.output_column || info.text || info.nested_tag_columns
95
+
96
+ child = child_line.lstrip
97
+ content = child[CHILD_OUTPUT] || child[CHILD_TEXT, 1]
98
+ joined = "#{tag_line} #{content}" if content
99
+ joined if joined && joined.size <= @max_line_length
100
+ end
101
+
102
+ def layout(lines, info, outline, lineno, block_opening_linenos)
49
103
  return lines unless info.kind == :structure
50
104
 
51
- line = (lines.size > 1) ? joined_code(lines, info) || joined_attributes(lines, info) : lines.first
52
- return lines unless line
105
+ spread = lines.size > 1
106
+ line = lines.first
107
+ if spread
108
+ attributes_end = attributes_end(lines, info)
109
+ code_lines = attributes_end ? lines.drop(attributes_end) : lines
110
+ line = attributes_end ? joined_attributes(lines, attributes_end) : joined_code(lines, info)
111
+ return lines unless line
112
+ end
113
+
114
+ line = line[/\A */] + Formatter.with_do(line.lstrip) if spread && block_opening_linenos.include?(lineno)
53
115
 
54
116
  line, arranged_info = @attribute_arranger.call(line, (info if line == lines.first))
55
117
  info = arranged_info || info
56
118
  line = with_new_parenthesized(line, info)
119
+ return lines if spread && !ruby_reads_joined?(line, info)
57
120
  return [line] if line.size <= @max_line_length
58
121
 
59
122
  broken = wrap(line, info, children?(outline, lineno))
60
- return ((lines.size > 1) ? lines : broken) if broken == [line]
123
+ kept = lines if spread && Parser.slim_continuation?(code_lines)
124
+ return kept || broken if broken == [line]
61
125
 
62
126
  # Joined back, brackets lose the spaces inside them (`{ a: 1 }` becomes `{a: 1}`), which may now fit.
63
127
  rejoined = joined_code(broken, info)
64
128
  return [rejoined] if rejoined && rejoined.size <= @max_line_length
65
129
 
66
130
  # A string continued with `\` comes back on one line, longer than the author's.
67
- return lines if lines.size > 1 && broken.max_by(&:size).size > lines.max_by(&:size).size
131
+ return kept if kept && broken.max_by(&:size).size > lines.max_by(&:size).size
68
132
 
69
133
  broken
70
134
  end
@@ -78,9 +142,29 @@ module SuperSlim
78
142
  # The code of a line continued after a comma, a backslash or an opening bracket, on one line; nil when the
79
143
  # continuation lines hold anything else, such as attributes or text.
80
144
  def joined_code(lines, info)
81
- return unless info.text.nil? && code_start(lines.first, info.output_column) && lines.drop(1).none? { _1.strip.empty? }
145
+ joined(lines.first, lines.drop(1)) if info.text.nil? && code_start(lines.first, info.output_column)
146
+ end
147
+
148
+ # A tag whose attributes stand one per line inside delimiters, on one line, with the code that continues its
149
+ # closing line: `p {`, `title="A"`, `} = format_date post.created_at,`, `:long`.
150
+ def joined_attributes(lines, attributes_end)
151
+ tag = lines.first.rstrip + lines[1...attributes_end].map(&:strip).join(" ") + lines[attributes_end].strip
152
+ joined(tag, lines.drop(attributes_end + 1))
153
+ end
154
+
155
+ # The index of the line that closes the attributes of a tag spread one per line inside delimiters.
156
+ def attributes_end(lines, info)
157
+ return unless info.text.nil? && lines.first.lstrip.match?(Shortcuts::TAG_PATTERN) && !code_start(lines.first, info.output_column)
158
+ return unless lines.first.rstrip.match?(Parser::OPENING_BRACKET_AT_LINE_END)
82
159
 
83
- lines.drop(1).reduce(lines.first.rstrip) do |joined, line|
160
+ closing = lines.index { _1.strip.match?(CLOSING_BRACKET_AT_START) }
161
+ closing if closing && lines[1...closing].none? { _1.strip.empty? }
162
+ end
163
+
164
+ def joined(first_line, continuation_lines)
165
+ return if continuation_lines.any? { _1.strip.empty? }
166
+
167
+ continuation_lines.reduce(first_line.rstrip) do |joined, line|
84
168
  piece = line.strip
85
169
  joined = joined.delete_suffix("\\").rstrip
86
170
  if piece.match?(CLOSING_BRACKET_AT_START)
@@ -93,13 +177,10 @@ module SuperSlim
93
177
  end
94
178
  end
95
179
 
96
- # A tag whose attributes stand one per line inside delimiters, on one line: `p {` `title="A"` `} = text`.
97
- def joined_attributes(lines, info)
98
- return unless info.text.nil? && lines.first.lstrip.match?(Shortcuts::TAG_PATTERN) && !code_start(lines.first, info.output_column)
99
- return unless lines.first.rstrip.match?(Parser::OPENING_BRACKET_AT_LINE_END)
100
- return unless lines.last.strip.match?(CLOSING_BRACKET_AT_START) && lines[1...-1].none? { _1.strip.empty? }
101
-
102
- lines.first.rstrip + lines[1...-1].map(&:strip).join(" ") + lines.last.strip
180
+ # A comment inside code spread by hand comments out the rest of the code once joined.
181
+ def ruby_reads_joined?(line, info)
182
+ start = code_start(line, info.output_column)
183
+ start.nil? || CodeWrapper.parse(line[start..])
103
184
  end
104
185
 
105
186
  def children?(outline, lineno)
@@ -121,10 +202,10 @@ module SuperSlim
121
202
  return lines unless code_start && lines.last.size > @max_line_length
122
203
 
123
204
  last_indent = lines.last[/\A */]
124
- code_lines = CodeWrapper.call(lines.last[code_start..], last_indent, opens_block:, max_line_length: @max_line_length)
205
+ code_lines = CodeWrapper.call(lines.last[code_start..], last_indent, head: lines.last[0...code_start], opens_block:, max_line_length: @max_line_length)
125
206
  return lines unless code_lines
126
207
 
127
- lines[0...-1] + [lines.last[0...code_start] + code_lines.first, *code_lines.drop(1)]
208
+ lines[0...-1] + code_lines
128
209
  end
129
210
 
130
211
  # A dynamic tag, `*{tag: name}` or `li: *{tag: name}`, has no name for its attribute list to follow.