Skip to content

Commit

Permalink
Detect newlines in interpolated strings. Fixes #1613. (#1620)
Browse files Browse the repository at this point in the history
  • Loading branch information
nojaf committed Apr 8, 2021
1 parent fa5603a commit 660b03c
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
39 changes: 39 additions & 0 deletions src/Fantomas.Tests/InterpolatedStringTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,42 @@ let percent = 0.1548486
Console.WriteLine($"Formatted: {percent:p2}")
"""

[<Test>]
let ``extra newlines in interpolated string, 1613`` () =
formatSourceString
false
"
$\"\"\"
{1}
{2}
\"\"\"
$\"\"\"
- {1}
- 2
- {4}
- 5
\"\"\"
"
config
|> prepend newline
|> should
equal
"
$\"\"\"
{1}
{2}
\"\"\"
$\"\"\"
- {1}
- 2
- {4}
- 5
\"\"\"
"
24 changes: 23 additions & 1 deletion src/Fantomas/TokenParser.fs
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,16 @@ let private extractContentPreservingNewLines (tokens: Token list) =
| [] -> result
| [ final ] -> final.Content :: result
| current :: ((next :: _) as rest) when (current.LineNumber <> next.LineNumber) ->
loop ("\n" :: current.Content :: result) rest
let delta = next.LineNumber - current.LineNumber

let newlines =
[ 1 .. delta ] |> List.map (fun _ -> "\n")

loop
[ yield! newlines
yield current.Content
yield! result ]
rest
| current :: rest -> loop (current.Content :: result) rest

loop [] tokens |> List.rev
Expand Down Expand Up @@ -892,7 +901,20 @@ let rec private getTriviaFromTokensThemSelves

| EndOfInterpolatedString (stringTokens, interpStringEnd, rest) ->
let stringContent =
let addExtraNewline =
match List.tryLast stringTokens with
| Some lst ->
let delta =
interpStringEnd.LineNumber - lst.LineNumber

if delta > 0 then
[ 1 .. delta ] |> List.map (fun _ -> "\n")
else
[]
| _ -> []

[ yield! extractContentPreservingNewLines stringTokens
yield! addExtraNewline
yield interpStringEnd.Content ]
|> String.concat String.Empty

Expand Down

0 comments on commit 660b03c

Please sign in to comment.