Skip to content

Commit

Permalink
Escape <> at rendenring instead of lexer
Browse files Browse the repository at this point in the history
  • Loading branch information
khlopko committed Jun 26, 2024
1 parent a891c44 commit 38064d1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
19 changes: 18 additions & 1 deletion Markdown/HTMLRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public struct HTMLRenderer {
case let .p(text):
"<p>\(text.map { render($0) }.joined())</p>"
case let .text(value, style):
"<span class=\"\(style)\">\(value)</span>"
render(text: value, style: style)
case let .list(blocks):
"<ul>\(blocks.map { "<li>\(render($0))</li>" }.joined())</ul>"
case let .code(value, info):
Expand All @@ -78,6 +78,23 @@ public struct HTMLRenderer {
}
}

private func render(text: String, style: TextStyle) -> String {
var value = text
for i in value.indices {
var newValue: String?
if value[i] == "<" {
newValue = "&lt;"
} else if value[i] == ">" {
newValue = "&gt;"
}
if let newValue {
value.remove(at: i)
value.insert(contentsOf: newValue, at: i)
}
}
return "<span class=\"\(style)\">\(value)</span>"
}

private func render(code: String, lang: String?) -> String {
let className = lang.map { " class=\"language-\($0)\"" } ?? ""
return "<pre><code\(className)>\(code)</code></pre>"
Expand Down
13 changes: 1 addition & 12 deletions Markdown/Lexer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,18 +113,7 @@ internal struct Lexer {
lastPos += 1
}
var value = String(contents[start..<lastPos])
for i in value.indices {
var newValue: String?
if value[i] == "<" {
newValue = "&lt;"
} else if value[i] == ">" {
newValue = "&gt;"
}
if let newValue {
value.remove(at: i)
value.insert(contentsOf: newValue, at: i)
}
}

return .line(value)
}
}
Expand Down

0 comments on commit 38064d1

Please sign in to comment.