Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/FSharp.Data.Html.Core/HtmlNode.fs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ type HtmlNode =

fun name -> Set.contains name set

let rec serialize (sb: StringBuilder) indentation canAddNewLine html =
let rec serialize (sb: StringBuilder) indentation canAddNewLine insidePre html =
let append (str: string) = sb.Append str |> ignore

let appendEndTag name =
Expand All @@ -135,8 +135,9 @@ type HtmlNode =
| _ -> false)

let isPreTag = name = "pre"
let nowInsidePre = insidePre || isPreTag

if canAddNewLine && not (onlyText || isPreTag) then
if canAddNewLine && not insidePre && not (onlyText || isPreTag) then
newLine 0

append "<"
Expand All @@ -157,16 +158,16 @@ type HtmlNode =
else
append ">"

if not (onlyText || isPreTag) then
if not insidePre && not (onlyText || isPreTag) then
newLine 2

let mutable canAddNewLine = false

for element in elements do
serialize sb (indentation + 2) canAddNewLine element
serialize sb (indentation + 2) canAddNewLine nowInsidePre element
canAddNewLine <- true

if not (onlyText || isPreTag) then
if not insidePre && not (onlyText || isPreTag) then
newLine 0

appendEndTag name
Expand All @@ -181,7 +182,7 @@ type HtmlNode =
append "]]>"

let sb = StringBuilder()
serialize sb 0 false x |> ignore
serialize sb 0 false false x |> ignore
sb.ToString()

/// <exclude />
Expand Down
12 changes: 12 additions & 0 deletions tests/FSharp.Data.Core.Tests/HtmlParser.fs
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,18 @@ let ``Maintain whitespace inside pre tag through round-trip``() =
let expected = html
result |> should equal expected

[<Test>]
let ``Maintain whitespace in deeply nested elements inside pre through round-trip``() =
// Regression test for https://github.com/fsprojects/FSharp.Data/issues/1509
// Syntax highlighters (e.g. shiki) emit <pre><code><span class="line"><span>...</span></span></code></pre>
// Without the insidePre fix, the nested multi-element spans would have newlines inserted between them.
let html = """<pre><code><span class="line"><span style="color:red">let</span> <span style="color:blue">x</span> <span style="color:green">=</span> <span style="color:black">1</span></span></code></pre>"""

let result = HtmlDocument.Parse(html).ToString()

let expected = html
result |> should equal expected

[<Test>]
let ``Can parse national rail mobile site correctly``() =
HtmlDocument.Load "UKDepartures.html"
Expand Down
Loading