Skip to content

Commit

Permalink
Preserve new lines in string portion of interpolated string (#1452)
Browse files Browse the repository at this point in the history
* Preserve new lines in string portion of interpolated string

New lines were not being preserved when combining the string tokens of an interpolated string expression. If consecutive tokens are on different lines, then we add an additional NewLine in between.

Fixes #1451

* Minor tweak

Co-authored-by: nojaf <florian.verdonck@outlook.com>
  • Loading branch information
johlrich and nojaf committed Feb 16, 2021
1 parent e016b1c commit bcdedff
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/Fantomas.Tests/InterpolatedStringTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,20 @@ $"\"{bar}\" {1} {2}"
"""
$"\"{bar}\" {1} {2}"
"""

[<Test>]
let ``multiline string literal, issue 1451`` () =
formatSourceString
false
"
$\"\"\"one: {1}<
>two: {2}\"\"\"
"
config
|> prepend newline
|> should
equal
"
$\"\"\"one: {1}<
>two: {2}\"\"\"
"
13 changes: 12 additions & 1 deletion src/Fantomas/TokenParser.fs
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,17 @@ let private identIsDecompiledOperator (token: Token) =
token.TokenInfo.TokenName = "IDENT"
&& decompiledName <> token.Content

let private extractContentPreservingNewLines (tokens: Token list) =
let rec loop result =
function
| [] -> result
| [ final ] -> final.Content :: result
| current :: ((next :: _) as rest) when (current.LineNumber <> next.LineNumber) ->
loop ("\n" :: current.Content :: result) rest
| current :: rest -> loop (current.Content :: result) rest

loop [] tokens |> List.rev

let ``only whitespaces were found in the remainder of the line`` lineNumber tokens =
tokens
|> List.exists
Expand Down Expand Up @@ -732,7 +743,7 @@ let rec private getTriviaFromTokensThemSelves

| EndOfInterpolatedString (stringTokens, interpStringEnd, rest) ->
let stringContent =
[ yield! (List.map (fun t -> t.Content) stringTokens)
[ yield! extractContentPreservingNewLines stringTokens
yield interpStringEnd.Content ]
|> String.concat String.Empty

Expand Down

0 comments on commit bcdedff

Please sign in to comment.