Skip to content

Commit

Permalink
remove leading and trailing empty lines in a block
Browse files Browse the repository at this point in the history
see mvdan#284.
trailing empty lines are removed only if it is not followed by an
else-if statement.
  • Loading branch information
flan6 committed Aug 23, 2024
1 parent 8e69a67 commit d9ac15c
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -514,23 +514,23 @@ func (f *fumpter) applyPre(c *astutil.Cursor) {
}

var sign *ast.FuncType
var elseIf *ast.IfStmt
var cond ast.Expr

switch parent := c.Parent().(type) {
case *ast.FuncDecl:
sign = parent.Type
case *ast.FuncLit:
sign = parent.Type
case *ast.IfStmt:
cond = parent.Cond
if e, ok := parent.Else.(*ast.IfStmt); ok {
elseIf = e
}
case *ast.ForStmt:
cond = parent.Cond
}

if len(node.List) > 1 && sign == nil {
// only if we have a single statement, or if
// it's a func body.
break
}
var bodyPos, bodyEnd token.Pos

if len(node.List) > 0 {
Expand All @@ -546,8 +546,6 @@ func (f *fumpter) applyPre(c *astutil.Cursor) {
}
}

f.removeLinesBetween(bodyEnd, node.Rbrace)

if cond != nil && f.Line(cond.Pos()) != f.Line(cond.End()) {
// The body is preceded by a multi-line condition, so an
// empty line can help readability.
Expand Down Expand Up @@ -603,6 +601,14 @@ func (f *fumpter) applyPre(c *astutil.Cursor) {

f.removeLinesBetween(node.Lbrace, bodyPos)

if elseIf != nil {
// The body is succeded by an else-if statement
// so an empty line can be useful for readability.
return
}

f.removeLinesBetween(bodyEnd, node.Rbrace)

case *ast.CaseClause:
f.stmts(node.Body)
openLine := f.Line(node.Case)
Expand Down

0 comments on commit d9ac15c

Please sign in to comment.