2019-03-15 20:24:53 +01:00
|
|
|
/**
|
|
|
|
* Splash
|
|
|
|
* Copyright (c) John Sundell 2019
|
|
|
|
* MIT license - see LICENSE.md
|
|
|
|
*/
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
/// Type used to decorate a Markdown file with Splash-highlighted code blocks
|
|
|
|
public struct MarkdownDecorator {
|
2019-09-05 11:54:56 +02:00
|
|
|
private let highlighter: SyntaxHighlighter<HTMLOutputFormat>
|
2019-03-15 20:24:53 +01:00
|
|
|
private let skipHighlightingPrefix = "no-highlight"
|
|
|
|
|
2019-09-05 11:54:56 +02:00
|
|
|
/// Create a Markdown decorator with a given prefix to apply to all CSS
|
|
|
|
/// classes used when highlighting code blocks within a Markdown string.
|
|
|
|
public init(classPrefix: String = "") {
|
|
|
|
highlighter = SyntaxHighlighter(format: HTMLOutputFormat(classPrefix: classPrefix))
|
|
|
|
}
|
2019-03-15 20:24:53 +01:00
|
|
|
|
|
|
|
/// Decorate all code blocks within a given Markdown string. This API assumes
|
|
|
|
/// that the passed Markdown is valid. Each code block will be replaced by
|
|
|
|
/// Splash-highlighted HTML for that block's code. To skip highlighting for
|
|
|
|
/// any given code block, add "no-highlight" next to the opening row of
|
|
|
|
/// backticks for that block.
|
|
|
|
public func decorate(_ markdown: String) -> String {
|
|
|
|
let components = markdown.components(separatedBy: "```")
|
|
|
|
var output = ""
|
|
|
|
|
|
|
|
for (index, component) in components.enumerated() {
|
|
|
|
guard index % 2 != 0 else {
|
|
|
|
output.append(component)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
var code = component.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
|
|
|
|
|
|
if code.hasPrefix(skipHighlightingPrefix) {
|
|
|
|
let charactersToDrop = skipHighlightingPrefix + "\n"
|
2019-11-23 23:59:16 +00:00
|
|
|
code = code.dropFirst(charactersToDrop.count).escapingHTMLEntities()
|
2019-03-15 20:24:53 +01:00
|
|
|
} else {
|
|
|
|
code = highlighter.highlight(code)
|
|
|
|
}
|
|
|
|
|
|
|
|
output.append("""
|
2019-07-25 16:10:55 +02:00
|
|
|
<pre class="splash"><code>\(code)</code></pre>
|
2019-03-15 20:24:53 +01:00
|
|
|
""")
|
|
|
|
}
|
|
|
|
|
|
|
|
return output
|
|
|
|
}
|
|
|
|
}
|