From 748e6582302699ede4098bcb965c411ae5f20908 Mon Sep 17 00:00:00 2001 From: nojaf Date: Sat, 11 Jun 2022 17:26:06 +0200 Subject: [PATCH] Print leading newlines when formatting a selection. --- src/Fantomas.Core.Tests/ContextTests.fs | 2 ++ src/Fantomas.Core.Tests/FormattingSelectionOnlyTests.fs | 4 ++-- src/Fantomas.Core/CodeFormatterImpl.fs | 2 +- src/Fantomas.Core/Context.fs | 9 +++++++-- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/Fantomas.Core.Tests/ContextTests.fs b/src/Fantomas.Core.Tests/ContextTests.fs index fc0f369d98..a927dd3d48 100644 --- a/src/Fantomas.Core.Tests/ContextTests.fs +++ b/src/Fantomas.Core.Tests/ContextTests.fs @@ -7,6 +7,8 @@ open Fantomas.Core.Tests.TestHelper open Fantomas.Core.FormatConfig open Fantomas.Core +let private dump = dump false + [] let ``sepSpace should not add an additional space if the line ends with a space`` () = let expr = !- "let a = " +> sepSpace diff --git a/src/Fantomas.Core.Tests/FormattingSelectionOnlyTests.fs b/src/Fantomas.Core.Tests/FormattingSelectionOnlyTests.fs index 2fc25ce81f..f175540ad4 100644 --- a/src/Fantomas.Core.Tests/FormattingSelectionOnlyTests.fs +++ b/src/Fantomas.Core.Tests/FormattingSelectionOnlyTests.fs @@ -74,6 +74,7 @@ let x = |> should equal " + try something () with ex -> @@ -125,8 +126,7 @@ let a = 9 equal """ -let a = 9 -""" +let a = 9""" // 10 25 10 82 //[] diff --git a/src/Fantomas.Core/CodeFormatterImpl.fs b/src/Fantomas.Core/CodeFormatterImpl.fs index 8e79a31021..16ac976823 100644 --- a/src/Fantomas.Core/CodeFormatterImpl.fs +++ b/src/Fantomas.Core/CodeFormatterImpl.fs @@ -65,7 +65,7 @@ let formatWith context |> genParsedInput ASTContext.Default ast - |> Context.dump + |> Context.dump (Option.isSome selection) formattedSourceCode diff --git a/src/Fantomas.Core/Context.fs b/src/Fantomas.Core/Context.fs index 0ec30fef50..0ffa009647 100644 --- a/src/Fantomas.Core/Context.fs +++ b/src/Fantomas.Core/Context.fs @@ -295,7 +295,7 @@ let finalizeWriterModel (ctx: Context) = else ctx -let dump (ctx: Context) = +let dump (isSelection: bool) (ctx: Context) = let ctx = finalizeWriterModel ctx match ctx.WriterModel.Lines with @@ -304,7 +304,12 @@ let dump (ctx: Context) = // Always trim the last line h.TrimEnd() :: tail |> List.rev - |> List.skipWhile ((=) "") + |> fun lines -> + // Don't skip leading newlines when formatting a selection. + if isSelection then + lines + else + List.skipWhile ((=) "") lines |> String.concat ctx.Config.EndOfLine.NewLineString let dumpAndContinue (ctx: Context) =