import Foundation /// The web's steady/open-link rules. Unmatched delimiters are removed only /// from text leaves in the final open paragraph, after CommonMark parsing. enum MarkdownDraft { static func matches(_ pattern: String, _ text: String) -> Bool { text.range(of: pattern, options: .regularExpression) != nil } static func entities(_ value: String) -> String { MarkdownEntities.link(value) } static func decodeText(_ value: String) -> String { let bytes = Array(value.utf8) var out: [UInt8] = [], at = 0 while at < bytes.count { if bytes[at] == 92, at + 1 < bytes.count, (33...47).contains(bytes[at+1]) || (58...64).contains(bytes[at+1]) || (91...96).contains(bytes[at+1]) || (123...126).contains(bytes[at+1]) { at += 1 } out.append(bytes[at]); at += 1 } return MarkdownEntities.text(String(decoding: out, as: UTF8.self)) } static func steady(_ source: String) -> String { // CRLF is one Swift Character, but the web splits on the LF byte. let bytes = Array(source.utf8) let start = bytes.lastIndex(of: 10).map { $0 + 1 } ?? 0 let tail = Array(bytes[start...]) return markerOnly(tail) || fenceLine(tail) ? String(decoding: bytes[.. Bool { c == 32 || c == 9 } private static func suffix(_ b: [UInt8], _ start: Int) -> Bool { var i = start while i < b.count, space(b[i]) { i += 1 } while i < b.count, [42, 95, 96].contains(b[i]) { i += 1 } return i == b.count } // Each alternative is scanned once. No backtracking through whitespace. static func markerOnly(_ b: [UInt8]) -> Bool { var i = 0 while i < b.count, space(b[i]) { i += 1 } if suffix(b, i) { return true } guard i < b.count else { return true } if [45, 43, 42, 62].contains(b[i]), suffix(b, i + 1) { return true } var j = i while j < b.count, (48...57).contains(b[j]), j - i < 9 { j += 1 } if j > i { if j < b.count, [46, 41].contains(b[j]) { j += 1 } if suffix(b, j) { return true } } j = i while j < b.count, b[j] == 35, j - i < 6 { j += 1 } if j > i, suffix(b, j) { return true } j = i while j < b.count, [96, 126].contains(b[j]) { j += 1 } if j > i, suffix(b, j) { return true } j = i while j < b.count, [45, 61, 95, 42, 32, 9].contains(b[j]) { j += 1 } return j > i && suffix(b, j) } static func fenceLine(_ b: [UInt8]) -> Bool { var i = 0 while i < b.count, space(b[i]) || b[i] == 62 { i += 1 } func fence(_ j: Int) -> Bool { j + 2 < b.count && (b[j] == 96 || b[j] == 126) && b[j+1] == b[j] && b[j+2] == b[j] } if fence(i) { return true } guard i < b.count else { return false } if [45, 43, 42].contains(b[i]) { i += 1 } else { let start = i while i < b.count, (48...57).contains(b[i]), i - start < 9 { i += 1 } guard i > start, i < b.count, [46, 41].contains(b[i]) else { return false } i += 1 } guard i < b.count, space(b[i]) else { return false } while i < b.count, space(b[i]) { i += 1 } return fence(i) } }