diff --git a/src/Fantomas.Tests/CommentTests.fs b/src/Fantomas.Tests/CommentTests.fs index ec266ce077..37e692993c 100644 --- a/src/Fantomas.Tests/CommentTests.fs +++ b/src/Fantomas.Tests/CommentTests.fs @@ -297,7 +297,7 @@ type IlxGenOptions = alwaysCallVirt : bool } """ -[] +[] let ``should keep comments on else if``() = formatSourceString false """ if true then () diff --git a/src/Fantomas/CodePrinter.fs b/src/Fantomas/CodePrinter.fs index 28707a3716..2dbbe51ca7 100644 --- a/src/Fantomas/CodePrinter.fs +++ b/src/Fantomas/CodePrinter.fs @@ -599,11 +599,15 @@ and genExpr astContext = function // It seems too annoying to use sepSemiNln | Sequentials es -> atCurrentColumn (col sepNln es (genExpr astContext)) // A generalization of IfThenElse - | ElIf((e1,e2, _)::es, enOpt) -> + | ElIf((e1,e2, _, _)::es, enOpt) -> atCurrentColumn (!- "if " +> ifElse (checkBreakForExpr e1) (genExpr astContext e1 ++ "then") (genExpr astContext e1 +- "then") -- " " +> preserveBreakNln astContext e2 - +> fun ctx -> col sepNone es (fun (e1, e2, r) -> - ifElse (startWith "elif" r ctx) (!+ "elif ") (!+ "else if ") + +> fun ctx -> col sepNone es (fun (e1, e2, r, fullRange) -> + let elsePart = + ifElse (ctx.Comments.ContainsKey fullRange.Start) + (!+ "else" +> indent +> sepNln -- "if ") + (!+ "else if ") + ifElse (startWith "elif" r ctx) (!+ "elif ") elsePart +> ifElse (checkBreakForExpr e1) (genExpr astContext e1 ++ "then") (genExpr astContext e1 +- "then") -- " " +> preserveBreakNln astContext e2) ctx +> opt sepNone enOpt (fun en -> !+ "else " +> preserveBreakNln astContext en)) diff --git a/src/Fantomas/SourceParser.fs b/src/Fantomas/SourceParser.fs index 375988dce7..e09654146b 100644 --- a/src/Fantomas/SourceParser.fs +++ b/src/Fantomas/SourceParser.fs @@ -784,10 +784,10 @@ let (|IfThenElse|_|) = function | _ -> None let rec (|ElIf|_|) = function - | SynExpr.IfThenElse(e1, e2, Some(ElIf(es, e3)), _, _, r, _) -> - Some((e1, e2, r)::es, e3) - | SynExpr.IfThenElse(e1, e2, e3, _, _, r, _) -> - Some([(e1, e2, r)], e3) + | SynExpr.IfThenElse(e1, e2, Some(ElIf(es, e3)), _, _, r, fullRange) -> + Some((e1, e2, r, fullRange)::es, e3) + | SynExpr.IfThenElse(e1, e2, e3, _, _, r, fullRange) -> + Some([(e1, e2, r, fullRange)], e3) | _ -> None let (|Record|_|) = function