import Foundation /// Base: the person's own message as the chat's Markdown tree, in the web's /// little subset (richText and personText in ask_cards.go, rich and /// strictEmphasis in ask.js), not CommonMark: runs of "- " or "* " lines /// are a bulleted list, runs of "1. " or "1) " lines (1 to 3 digits) a /// numbered one from its first number, and every other line is text with /// its newlines (the one next to a list goes). In text and list items a /// Markdown link or bare URL is a link only to an http(s) address, and /// between links **x** is bold and *x* or _x_ italic, only at word /// boundaries. Nothing else is Markdown: headings, quotes, rules, escapes, /// entities and indented code are text as typed. The samples in /// internal/web/testdata/person.json check the three agree. enum PersonMarkdown { /// `links: false` draws every address as text (LookupMarkdown). static func parse(_ text: String, links: Bool = true) -> [ChatMarkdownNode] { var builder = Builder(links: links) let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") .replacingOccurrences(of: "\0", with: "").components(separatedBy: "\n") var out: [ChatMarkdownNode] = [] var i = 0 while i < lines.count { guard let first = listLine(lines[i]) else { var j = i + 1 while j < lines.count, listLine(lines[j]) == nil { j += 1 } let inline = builder.inline(lines[i.. Bool { nodes.allSatisfy { $0.kind == "paragraph" && $0.children.allSatisfy { $0.kind == "text" } } } private static let number = try! NSRegularExpression(pattern: #"^([0-9]{1,3})[.)] "#) /// A line's list (numbered or not, its number) and the item after the /// marker, which is never empty. static func listLine(_ line: String) -> (ordered: Bool, n: Int, item: String)? { let u = Array(line.utf8) if u.count > 2, u[0] == UInt8(ascii: "-") || u[0] == UInt8(ascii: "*"), u[1] == UInt8(ascii: " ") { return (false, 0, String(decoding: u[2...], as: UTF8.self)) } if let m = number.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)), let whole = Range(m.range, in: line), let digits = Range(m.range(at: 1), in: line), whole.upperBound < line.endIndex { return (true, Int(line[digits]) ?? 1, String(line[whole.upperBound...])) } return nil } private static let link = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+"#) /// A lookup's answer's whitespace, spelled out as Go and ask.js spell /// it (lookupSpace in ask_cards.go). static let lookupSpace = #"\t\n\f\r \x{00a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}"# /// link with lookupSpace for its whitespace (plainLinkRE in ask_cards.go). private static let plainLink = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()"# + lookupSpace + #"]{1,1000})\)|https?://[^"# + lookupSpace + #"<>()\[\]"']+"#) private struct Builder { let links: Bool var offset = 0 /// Every node its own offset: the rows are told apart by it. mutating func node(_ kind: String, text: String? = nil, target: String? = nil, children: [ChatMarkdownNode] = []) -> ChatMarkdownNode { offset += 1 return ChatMarkdownNode(sourceOffset: offset, kind: kind, text: text, target: target, children: children) } mutating func inline(_ text: String) -> [ChatMarkdownNode] { var out: [ChatMarkdownNode] = [] let ns = text as NSString var last = 0 for m in (links ? PersonMarkdown.link : PersonMarkdown.plainLink).matches(in: text, range: NSRange(location: 0, length: ns.length)) { var end = NSMaxRange(m.range), label: String, target: String if m.range(at: 1).location != NSNotFound { label = ns.substring(with: m.range(at: 1)); target = ns.substring(with: m.range(at: 2)) } else { var bare = ns.substring(with: m.range) while let c = bare.last, ".,;:!?".contains(c) { bare.removeLast() } target = bare; label = bare; end = m.range.location + (bare as NSString).length } guard links else { // An address is text, whatever it is, untouched by // emphasis: no URL check decides how it is drawn. out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last))) out.append(node("text", text: ns.substring(with: NSRange(location: m.range.location, length: end - m.range.location)))) last = end continue } guard ChatMarkdown.allowsLink(target) else { continue } out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last))) out.append(node("link", target: target, children: [node("text", text: label)])) last = end } out += emphasis(ns.substring(from: last)) return out } /// strictEmphasis in ask_cards.go, over Unicode scalars (a scalar /// beyond ASCII is a word's, as any byte of one is there). mutating func emphasis(_ text: String) -> [ChatMarkdownNode] { let s = Array(text.unicodeScalars) var out: [ChatMarkdownNode] = [] func str(_ r: Range) -> String { String(String.UnicodeScalarView(s[r])) } func word(_ c: Unicode.Scalar) -> Bool { c.value >= 0x80 || c == "_" || ("0"..."9").contains(c) || ("a"..."z").contains(c) || ("A"..."Z").contains(c) } func run(_ at: Int) -> Int { var n = 1; while at + n < s.count, s[at + n] == s[at] { n += 1 }; return n } func emphasized(_ r: Range) -> Bool { !r.isEmpty && !s[r].contains("\n") && s[r.lowerBound] != " " && s[r.lowerBound] != "\t" && s[r.upperBound - 1] != " " && s[r.upperBound - 1] != "\t" } var last = 0, i = 0 while i < s.count { let c = s[i] guard c == "*" || c == "_" else { i += 1; continue } let n = run(i) if i == 0 || !word(s[i - 1]), n == 1 || (n == 2 && c == "*"), let j = s[(i + n)...].firstIndex(of: c) { let end = j + run(j) if end - j == n, emphasized((i + n).. last { out.append(node("text", text: str(last.. last { out.append(node("text", text: str(last.. [ChatMarkdownNode] { let t = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") .replacingOccurrences(of: "\0", with: "") let words = markdownLink.stringByReplacingMatches(in: t, range: NSRange(t.startIndex..., in: t), withTemplate: "$1") return PersonMarkdown.parse(words, links: false) } }