Add links to headlines
This commit is contained in:
@@ -19,20 +19,20 @@ struct MarkdownHeadlineProcessor: MarkdownProcessor {
|
||||
/**
|
||||
Modify headlines by extracting an id from the headline and adding it into the html element
|
||||
|
||||
Format: ##<title>#<id>
|
||||
|
||||
The id is created by lowercasing the string, removing all special characters, and replacing spaces with scores
|
||||
*/
|
||||
func process(html: String, markdown: Substring) -> String {
|
||||
let id = markdown
|
||||
.last(after: "#")
|
||||
.trimmed
|
||||
.filter { $0.isNumber || $0.isLetter || $0 == " " }
|
||||
.lowercased()
|
||||
.components(separatedBy: " ")
|
||||
.filter { $0 != "" }
|
||||
.joined(separator: "-")
|
||||
let parts = html.components(separatedBy: ">")
|
||||
return parts[0] + " id=\"\(id)\">" + parts.dropFirst().joined(separator: ">")
|
||||
let parts2 = markdown.components(separatedBy: "#")
|
||||
// Determine the type of heading, e.g. 2 for <h2>
|
||||
let headlineParts = parts2.drop { $0.isEmpty }
|
||||
let headlineType = parts2.count - headlineParts.count
|
||||
|
||||
guard headlineType > 1 && headlineType < 4 else {
|
||||
return html
|
||||
}
|
||||
|
||||
let title = headlineParts.joined(separator: "#")
|
||||
let headline = HeadlineLink(level: headlineType, title: title)
|
||||
return headline.content
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user