Skip to content

Commit a3bd06e

Browse files
committed
Add support for writing lists of elements with leading commas and inline comments
Fix #153
1 parent edecf6b commit a3bd06e

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

src/formatter.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,26 @@ impl Formatter {
259259
/// with lambdas in data structures like arrays or function arguments.
260260
#[inline(always)]
261261
fn fix_dangling_commas(&mut self) -> &mut Self {
262+
// This is for cases where a team uses commas at the start of lines to
263+
// separate arguments or elements in arrays and use inline comments to
264+
// describe the elements
265+
// This is done in the Godot Nakama repository for example.
266+
let comment_re = RegexBuilder::new(r"(?m)(?P<before>[^\n\r]*?)(?P<comment>#[^\n\r]*)\n\s+,")
267+
.build()
268+
.expect("dangling comma with comment regex should compile");
269+
270+
self.regex_replace_all_outside_strings(comment_re, |caps: &regex::Captures| {
271+
let before = caps.name("before").unwrap().as_str();
272+
let comment = caps.name("comment").unwrap().as_str();
273+
274+
let before_trimmed = before.trim_end();
275+
if before_trimmed.trim().is_empty() || before_trimmed.ends_with(',') {
276+
return caps.get(0).unwrap().as_str().to_string();
277+
}
278+
279+
format!("{}, {}", before_trimmed, comment.trim_start())
280+
});
281+
262282
// This targets cases where a comma is on its own line with only
263283
// whitespace before it instead of being at the end of the previous
264284
// line
@@ -268,7 +288,13 @@ impl Formatter {
268288
.build()
269289
.expect("dangling comma regex should compile");
270290

271-
self.regex_replace_all_outside_strings(re, "$1,");
291+
self.regex_replace_all_outside_strings(re, |caps: &regex::Captures| {
292+
let first_part = caps.get(1).unwrap().as_str();
293+
let mut replacement = String::with_capacity(first_part.len() + 1);
294+
replacement.push_str(first_part);
295+
replacement.push(',');
296+
replacement
297+
});
272298
self
273299
}
274300

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
func t(
2+
a,
3+
b, # comment
4+
c,
5+
)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
func t(
2+
a
3+
, b # comment
4+
, c
5+
)
6+

0 commit comments

Comments
 (0)