Skip to content

Commit

Permalink
Headings: Trim trailing markers (#13)
Browse files Browse the repository at this point in the history
This change makes Ink trim all trailing markers from headings, making
it consistent with Gruber’s original Markdown implementation.
  • Loading branch information
JohnSundell committed Nov 29, 2019
1 parent 44ce07c commit d2c8dca
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
16 changes: 15 additions & 1 deletion Sources/Ink/Internal/Heading.swift
Expand Up @@ -21,7 +21,21 @@ internal struct Heading: Fragment {

func html(usingURLs urls: NamedURLCollection,
modifiers: ModifierCollection) -> String {
let body = text.html(usingURLs: urls, modifiers: modifiers)
var body = text.html(usingURLs: urls, modifiers: modifiers)

if !body.isEmpty {
let lastCharacterIndex = body.index(before: body.endIndex)
var trimIndex = lastCharacterIndex

while body[trimIndex] == "#", trimIndex != body.startIndex {
trimIndex = body.index(before: trimIndex)
}

if trimIndex != lastCharacterIndex {
body = String(body[..<trimIndex])
}
}

let tagName = "h\(level)"
return "<\(tagName)>\(body)</\(tagName)>"
}
Expand Down
16 changes: 15 additions & 1 deletion Tests/InkTests/HeadingTests.swift
Expand Up @@ -46,6 +46,18 @@ final class HeadingTests: XCTestCase {
let html = MarkdownParser().html(from: markdown)
XCTAssertEqual(html, "<p>\(markdown)</p>")
}

func testRemovingTrailingMarkersFromHeading() {
let markdown = "# Heading #######"
let html = MarkdownParser().html(from: markdown)
XCTAssertEqual(html, "<h1>Heading</h1>")
}

func testHeadingWithOnlyTrailingMarkers() {
let markdown = "# #######"
let html = MarkdownParser().html(from: markdown)
XCTAssertEqual(html, "<h1></h1>")
}
}

extension HeadingTests {
Expand All @@ -56,7 +68,9 @@ extension HeadingTests {
("testHeadingsWithLeadingNumbers", testHeadingsWithLeadingNumbers),
("testHeadingWithPreviousWhitespace", testHeadingWithPreviousWhitespace),
("testHeadingWithPreviousNewlineAndWhitespace", testHeadingWithPreviousNewlineAndWhitespace),
("testInvalidHeaderLevel", testInvalidHeaderLevel)
("testInvalidHeaderLevel", testInvalidHeaderLevel),
("testRemovingTrailingMarkersFromHeading", testRemovingTrailingMarkersFromHeading),
("testHeadingWithOnlyTrailingMarkers", testHeadingWithOnlyTrailingMarkers)
]
}
}

0 comments on commit d2c8dca

Please sign in to comment.