fish_indent: Collapse successive newlines

This makes it so code like

```fish
echo foo

echo bar
```

is collapsed into

```fish
echo foo

echo bar
```

One empty line is allowed, more is overkill.

We could also allow more than one for e.g. function endings.
This commit is contained in:
Fabian Boehm 2024-02-26 16:12:42 +01:00
parent 73d760560b
commit f93a3e9e9b
2 changed files with 30 additions and 16 deletions

View File

@ -127,7 +127,8 @@ impl<'source, 'ast> PrettyPrinter<'source, 'ast> {
},
output: WString::default(),
current_indent: 0,
gap_text_mask_newline: false,
// Start with true to ignore leading empty lines.
gap_text_mask_newline: true,
gaps: vec![],
preferred_semi_locations: vec![],
errors: None,
@ -430,15 +431,16 @@ impl<'source, 'ast> PrettyPrinterState<'source, 'ast> {
if needs_nl {
self.emit_newline();
needs_nl = false;
if tok_text == "\n" {
continue;
}
} else if self.gap_text_mask_newline {
// We only respect mask_newline the first time through the loop.
self.gap_text_mask_newline = false;
if tok_text == "\n" {
continue;
}
} else if self.gap_text_mask_newline {
// When told to mask newlines, we do it as long as we get semicolon or newline.
if tok.type_ == TokenType::end {
continue;
}
self.gap_text_mask_newline = false;
}
if tok.type_ == TokenType::comment {
@ -451,6 +453,8 @@ impl<'source, 'ast> PrettyPrinterState<'source, 'ast> {
// Newlines are preserved unless mask_newline is set.
if tok_text == "\n" {
self.emit_newline();
// Ignore successive ends.
self.gap_text_mask_newline = true;
}
} else {
// Anything else we write a space.
@ -620,11 +624,6 @@ impl<'source, 'ast> PrettyPrinterState<'source, 'ast> {
} else {
self.emit_newline();
}
// If it was a semi but we emitted a newline, swallow a subsequent newline.
if !prefer_semi && self.substr(range) == ";" {
self.gap_text_mask_newline = true;
}
}
}

View File

@ -74,7 +74,6 @@ end | cat | cat | begin ; echo hi ; end | begin ; begin ; echo hi ; end ; end ar
#CHECK: begin
#CHECK: {{ }}echo hi
#CHECK:
#CHECK:
#CHECK: end | cat | cat | begin
#CHECK: {{ }}echo hi
#CHECK: end | begin
@ -96,10 +95,8 @@ end
' | $fish_indent
#CHECK: switch aloha
#CHECK:
#CHECK: {{ }}case alpha
#CHECK: {{ }}{{ }}echo sup
#CHECK:
#CHECK: {{ }}case beta gamma
#CHECK: {{ }}{{ }}echo hi
#CHECK:
@ -150,7 +147,6 @@ qqq
case "*"
echo sup
end' | $fish_indent
#CHECK:
#CHECK: echo alpha #comment1
#CHECK: #comment2
#CHECK:
@ -324,7 +320,6 @@ echo bye
#CHECK: end
#CHECK:
#CHECK: echo hi |
#CHECK:
#CHECK: {{ }}echo bye
echo 'a;;;;;;' | $fish_indent
@ -449,3 +444,23 @@ echo "\'\\\\\x00\'" | string unescape | $fish_indent | string escape
echo '\"\"\|\x00' | string unescape | $fish_indent | string unescape
# CHECK: |
echo 'a
;
b
' | $fish_indent
#CHECK: a
#CHECK:
#CHECK: b
echo "
echo this file starts late
" | $fish_indent
#CHECK: echo this file starts late