Skip to content

Commit 8ef8d70

Browse files
committed
fix: #67 idempotent format issue
1 parent 16b20d0 commit 8ef8d70

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

src/context.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@ impl Comment {
114114
self.metadata.has_empty_line_above
115115
}
116116

117+
pub fn has_prev_node_else_keyword(&self) -> bool {
118+
self.metadata.has_prev_node_else_keyword
119+
}
120+
117121
pub fn is_followed_by_bracket_composite_node(&self) -> bool {
118122
self.metadata.is_followed_by_bracket_composite_node
119123
}
@@ -163,22 +167,26 @@ pub struct CommentMetadata {
163167
has_empty_line_above: bool,
164168
has_empty_line_below: bool,
165169
has_prev_node: bool,
170+
has_prev_node_else_keyword: bool,
166171
is_followed_by_bracket_composite_node: bool,
167172
}
168173

169174
impl CommentMetadata {
170175
pub fn from(node: &Node, comment_type: CommentType) -> Self {
171176
let prev = node.prev_named_sibling();
172-
let next = node.next_named_sibling();
173-
174177
let has_prev_node = prev.is_some();
175178

179+
180+
let prev_unnamed = node.prev_sibling();
181+
let has_prev_node_else_keyword = prev_unnamed.map(|n| n.kind() == "else").unwrap_or(false);
182+
176183
let has_leading_content = if let Some(prev_node) = prev {
177184
node.start_position().row == prev_node.end_position().row
178185
} else {
179186
false
180187
};
181188

189+
let next = node.next_named_sibling();
182190
let has_trailing_content = match comment_type {
183191
CommentType::Line => false,
184192
CommentType::Block => {
@@ -214,6 +222,7 @@ impl CommentMetadata {
214222
has_empty_line_above,
215223
has_empty_line_below,
216224
has_prev_node,
225+
has_prev_node_else_keyword,
217226
is_followed_by_bracket_composite_node,
218227
}
219228
}

src/utility.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,13 @@ pub fn handle_pre_comments<'a>(
357357
// if it's in group(), then multi-line mode is selected in fits()
358358
// otherwise, do nothing
359359
docs.push(b.force_break());
360+
360361
// 1st element heading logic is handled in the preceding node;
362+
// except the preceding is an unnamed node like `else`
363+
if comment.has_prev_node_else_keyword() {
364+
docs.push(b.nl());
365+
}
366+
361367
if i != 0 {
362368
if comment.has_newline_above() {
363369
docs.push(b.empty_new_line());

tests/to-do/twice_format_issue3.in

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class TestClass {
2+
{
3+
if (true)
4+
// comment 1
5+
{}
6+
}
7+
}

0 commit comments

Comments
 (0)