| 1 | import Foundation |
| 2 | #if os(macOS) |
| 3 | import AppKit |
| 4 | #elseif os(iOS) |
| 5 | import UIKit |
| 6 | #endif |
| 7 | |
| 8 | /// A rich paste (a web page, Docs, Mail) as the Markdown the chat draws: |
| 9 | /// bold (**x**), italics (*x*), links ([text](url), http(s) only, as |
| 10 | /// BaseJSON.webURL), bullet and numbered lists (nested by indent), headings |
| 11 | /// (# x), and line breaks and paragraphs. Everything else is its text. Nil |
| 12 | /// when the paste formats nothing, or is mostly code (a monospace font, or |
| 13 | /// pre, code, tt, samp, kbd; RTF in a fixed-pitch font), so a plain paste |
| 14 | /// or code stays exactly as copied. HTML is only tokenised here and walked |
| 15 | /// (nothing loads or runs): elements deeper than 32 are flattened, the |
| 16 | /// walk stops once the Markdown passes the composer's 16,000 characters, |
| 17 | /// and more than 2 MB of HTML is left plain. RTF is read by Foundation, |
| 18 | /// which loads nothing either. ask.js's pasteMarkdown is the same walk |
| 19 | /// (keep them in step: the samples in |
| 20 | /// internal/browsertest/testdata/paste.json check both). |
| 21 | enum PasteMarkdown { |
| 22 | static let maxDepth = 32, maxOut = 16_000, maxHTML = 2_000_000 |
| 23 | |
| 24 | static func fromHTML(_ html: String) -> String? { |
| 25 | guard html.utf16.count <= maxHTML else { return nil } |
| 26 | var walker = Walker() |
| 27 | // (A NUL marks a <pre>'s place in the walk's output, as a page's |
| 28 | // parser never leaves one in text.) |
| 29 | return walker.markdown(HTMLTree.parse(html.replacingOccurrences(of: "\0", with: ""))) |
| 30 | } |
| 31 | |
| 32 | /// A clipboard's HTML bytes as text: UTF-8, or UTF-16 with its mark. |
| 33 | static func html(_ data: Data) -> String? { |
| 34 | if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]) { return String(data: data, encoding: .utf16) } |
| 35 | return String(data: data, encoding: .utf8) |
| 36 | } |
| 37 | |
| 38 | static func fromRTF(_ data: Data) -> String? { |
| 39 | guard let text = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) else { return nil } |
| 40 | return fromAttributed(text) |
| 41 | } |
| 42 | |
| 43 | /// An attributed string's paragraphs as lines (lists by their text |
| 44 | /// lists), its runs bold, italic or linked by their attributes: the |
| 45 | /// same tree HTML makes, so the same walk. |
| 46 | static func fromAttributed(_ text: NSAttributedString) -> String? { |
| 47 | var walker = Walker() |
| 48 | return walker.markdown(HTMLTree.from(text)) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /// Just enough HTML: elements with their attributes, and text. Tags that |
| 53 | /// are never closed close with their parent; a stray end tag is dropped. |
| 54 | struct HTMLTree: Equatable { |
| 55 | var tag = "" // "" is text |
| 56 | var attributes: [String: String] = [:] |
| 57 | var text = "" |
| 58 | var children: [HTMLTree] = [] |
| 59 | |
| 60 | static let void: Set<String> = ["br", "img", "hr", "input", "meta", "link", "area", "base", "col", "embed", "source", "track", "wbr", "param"] |
| 61 | static let raw: Set<String> = ["script", "style", "textarea", "title", "template", "noscript", "iframe", "xmp", "plaintext"] |
| 62 | /// What a new block closes when it opens, as a page would. |
| 63 | static let closesP: Set<String> = ["p", "div", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "table", "blockquote", "section", "article", "header", "footer", "hr", "dl", "form"] |
| 64 | |
| 65 | static func parse(_ html: String) -> HTMLTree { |
| 66 | let s = Array(html.unicodeScalars) |
| 67 | var stack = [HTMLTree(tag: "body")] |
| 68 | // Elements opened past the depth cap: not in the tree (their text |
| 69 | // and line breaks go to the deepest one that is; a block is a line |
| 70 | // of its own, a cell a space, and what the walk skips is skipped), |
| 71 | // but their end tags still match them. |
| 72 | enum Drop { case inline, block, cell, skip } |
| 73 | var dropped: [(name: String, kind: Drop)] = [] |
| 74 | var skipping = 0 |
| 75 | func mark(_ tag: String) { stack[stack.count - 1].children.append(HTMLTree(tag: tag)) } |
| 76 | var at = 0 |
| 77 | func appendText(_ t: String) { |
| 78 | guard !t.isEmpty, skipping == 0 else { return } |
| 79 | stack[stack.count - 1].children.append(HTMLTree(text: MarkdownEntities.link(t))) |
| 80 | } |
| 81 | func close(_ index: Int) { |
| 82 | while stack.count > index { |
| 83 | let done = stack.removeLast() |
| 84 | stack[stack.count - 1].children.append(done) |
| 85 | } |
| 86 | } |
| 87 | func open(_ name: String) -> Int? { stack.lastIndex { $0.tag == name } } |
| 88 | var text = "" |
| 89 | while at < s.count { |
| 90 | guard s[at] == "<" else { text.unicodeScalars.append(s[at]); at += 1; continue } |
| 91 | // A comment, doctype or processing instruction: skipped. |
| 92 | if at + 3 < s.count, s[at + 1] == "!", s[at + 2] == "-", s[at + 3] == "-" { |
| 93 | appendText(text); text = "" |
| 94 | var end = at + 4 |
| 95 | while end + 2 < s.count, !(s[end] == "-" && s[end + 1] == "-" && s[end + 2] == ">") { end += 1 } |
| 96 | at = min(s.count, end + 3) |
| 97 | continue |
| 98 | } |
| 99 | if at + 1 < s.count, s[at + 1] == "!" || s[at + 1] == "?" { |
| 100 | appendText(text); text = "" |
| 101 | while at < s.count, s[at] != ">" { at += 1 } |
| 102 | at += 1 |
| 103 | continue |
| 104 | } |
| 105 | let closing = at + 1 < s.count && s[at + 1] == "/" |
| 106 | var cursor = at + (closing ? 2 : 1) |
| 107 | var name = "" |
| 108 | while cursor < s.count, s[cursor].properties.isAlphabetic || ("0"..."9").contains(s[cursor]) || s[cursor] == "-" || s[cursor] == ":" { |
| 109 | name.unicodeScalars.append(s[cursor]); cursor += 1 |
| 110 | } |
| 111 | guard !name.isEmpty else { text.unicodeScalars.append(s[at]); at += 1; continue } |
| 112 | name = name.lowercased() |
| 113 | // The attributes, to the tag's end. |
| 114 | var attributes: [String: String] = [:] |
| 115 | var selfClosing = false |
| 116 | while cursor < s.count, s[cursor] != ">" { |
| 117 | if s[cursor] == "/" { selfClosing = true; cursor += 1; continue } |
| 118 | if s[cursor].properties.isWhitespace { cursor += 1; continue } |
| 119 | selfClosing = false |
| 120 | var key = "" |
| 121 | while cursor < s.count, !s[cursor].properties.isWhitespace, !"=>/".unicodeScalars.contains(s[cursor]) { |
| 122 | key.unicodeScalars.append(s[cursor]); cursor += 1 |
| 123 | } |
| 124 | while cursor < s.count, s[cursor].properties.isWhitespace { cursor += 1 } |
| 125 | var value = "" |
| 126 | if cursor < s.count, s[cursor] == "=" { |
| 127 | cursor += 1 |
| 128 | while cursor < s.count, s[cursor].properties.isWhitespace { cursor += 1 } |
| 129 | if cursor < s.count, s[cursor] == "\"" || s[cursor] == "'" { |
| 130 | let quote = s[cursor]; cursor += 1 |
| 131 | while cursor < s.count, s[cursor] != quote { value.unicodeScalars.append(s[cursor]); cursor += 1 } |
| 132 | cursor += 1 |
| 133 | } else { |
| 134 | while cursor < s.count, !s[cursor].properties.isWhitespace, s[cursor] != ">" { value.unicodeScalars.append(s[cursor]); cursor += 1 } |
| 135 | } |
| 136 | } |
| 137 | if key.isEmpty { cursor += 1; continue } |
| 138 | let k = key.lowercased() |
| 139 | if attributes[k] == nil { attributes[k] = MarkdownEntities.link(value) } |
| 140 | } |
| 141 | at = min(s.count, cursor + 1) |
| 142 | appendText(text); text = "" |
| 143 | if closing { |
| 144 | if dropped.last?.name == name { |
| 145 | switch dropped.removeLast().kind { |
| 146 | case .skip: skipping -= 1 |
| 147 | case .block: mark(Walker.line) |
| 148 | case .cell: mark(Walker.cell) |
| 149 | case .inline: break |
| 150 | } |
| 151 | } else if let index = open(name), index > 0 { close(index) } |
| 152 | continue |
| 153 | } |
| 154 | if closesP.contains(name), let p = open("p"), !(stack[(p + 1)...].contains { $0.tag == "li" || $0.tag == "td" || $0.tag == "th" }) { close(p) } |
| 155 | if name == "li", let li = open("li"), !stack[(li + 1)...].contains(where: { $0.tag == "ul" || $0.tag == "ol" }) { close(li) } |
| 156 | let element = HTMLTree(tag: name, attributes: attributes) |
| 157 | if raw.contains(name) { |
| 158 | // Its content is text to its end tag; none of it is kept |
| 159 | // (the walk skips all of these). |
| 160 | var end = at |
| 161 | let closer = Array("</\(name)".unicodeScalars) |
| 162 | while end < s.count { |
| 163 | if s[end] == "<", end + closer.count <= s.count, |
| 164 | String(String.UnicodeScalarView(s[end..<end + closer.count])).lowercased() == "</\(name)" { break } |
| 165 | end += 1 |
| 166 | } |
| 167 | stack[stack.count - 1].children.append(element) |
| 168 | at = end |
| 169 | while at < s.count, s[at] != ">" { at += 1 } |
| 170 | at += 1 |
| 171 | continue |
| 172 | } |
| 173 | if skipping > 0 { |
| 174 | if !void.contains(name), !selfClosing { dropped.append((name, .skip)); skipping += 1 } |
| 175 | } else if void.contains(name) || selfClosing { |
| 176 | stack[stack.count - 1].children.append(element) |
| 177 | } else if stack.count > PasteMarkdown.maxDepth { |
| 178 | let kind: Drop = Walker.skip.contains(name) ? .skip : Walker.blocks.contains(name) ? .block : name == "td" || name == "th" ? .cell : .inline |
| 179 | if kind == .skip { skipping += 1 } |
| 180 | if kind == .block { mark(Walker.line) } |
| 181 | dropped.append((name, kind)) |
| 182 | } else { |
| 183 | stack.append(element) |
| 184 | } |
| 185 | } |
| 186 | appendText(text) |
| 187 | close(1) |
| 188 | return stack[0] |
| 189 | } |
| 190 | |
| 191 | /// The tree an attributed string's paragraphs and runs make. |
| 192 | static func from(_ text: NSAttributedString) -> HTMLTree { |
| 193 | var body = HTMLTree(tag: "body") |
| 194 | // The open lists: each the list node path from body. |
| 195 | var lists: [(ordered: Bool, node: HTMLTree)] = [] |
| 196 | func closeLists(to depth: Int) { |
| 197 | while lists.count > depth { |
| 198 | let done = lists.removeLast().node |
| 199 | if lists.isEmpty { |
| 200 | body.children.append(done) |
| 201 | } else { |
| 202 | lists[lists.count - 1].node.children.append(done) |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | let string = text.string as NSString |
| 207 | string.enumerateSubstrings(in: NSRange(location: 0, length: string.length), options: [.byParagraphs, .substringNotRequired]) { _, content, _, _ in |
| 208 | let style = content.length > 0 ? text.attribute(.paragraphStyle, at: content.location, effectiveRange: nil) as? NSParagraphStyle : nil |
| 209 | let textLists = style?.textLists ?? [] |
| 210 | var line = HTMLTree(tag: textLists.isEmpty ? "div" : "li") |
| 211 | var runsFrom = content.location |
| 212 | if !textLists.isEmpty, let marker = Self.listMarker.firstMatch(in: text.string, range: content) { |
| 213 | // A list's marker is in the text ("\t•\t", "\t1.\t"): it goes. |
| 214 | runsFrom += marker.range.length |
| 215 | } |
| 216 | if runsFrom < NSMaxRange(content) { |
| 217 | text.enumerateAttributes(in: NSRange(location: runsFrom, length: NSMaxRange(content) - runsFrom)) { attributes, run, _ in |
| 218 | var node = HTMLTree(text: string.substring(with: run).replacingOccurrences(of: "\0", with: "")) |
| 219 | if let link = attributes[.link] { |
| 220 | let href = (link as? URL)?.absoluteString ?? (link as? String) ?? "" |
| 221 | node = HTMLTree(tag: "a", attributes: ["href": href], children: [node]) |
| 222 | } |
| 223 | let (bold, italic, mono) = traits(attributes) |
| 224 | if italic { node = HTMLTree(tag: "i", children: [node]) } |
| 225 | if bold { node = HTMLTree(tag: "b", children: [node]) } |
| 226 | if mono { node = HTMLTree(tag: "code", children: [node]) } |
| 227 | line.children.append(node) |
| 228 | } |
| 229 | } else if textLists.isEmpty { |
| 230 | line.children.append(HTMLTree(tag: "br")) |
| 231 | } |
| 232 | // The paragraph's lists, outermost first. |
| 233 | let depth = textLists.count |
| 234 | var shared = 0 |
| 235 | while shared < min(depth, lists.count), lists[shared].ordered == ordered(textLists[shared]) { shared += 1 } |
| 236 | closeLists(to: shared) |
| 237 | while lists.count < depth { |
| 238 | let ordered = ordered(textLists[lists.count]) |
| 239 | lists.append((ordered, HTMLTree(tag: ordered ? "ol" : "ul"))) |
| 240 | } |
| 241 | if depth == 0 { body.children.append(line) } else { lists[lists.count - 1].node.children.append(line) } |
| 242 | } |
| 243 | closeLists(to: 0) |
| 244 | return body |
| 245 | } |
| 246 | |
| 247 | private static let listMarker = try! NSRegularExpression(pattern: #"\G\t?[^\t\n]{0,12}\t"#) |
| 248 | |
| 249 | private static func ordered(_ list: NSTextList) -> Bool { |
| 250 | !["disc", "circle", "square", "box", "check", "diamond", "hyphen"].contains { list.markerFormat.rawValue.contains($0) } |
| 251 | } |
| 252 | |
| 253 | private static func traits(_ attributes: [NSAttributedString.Key: Any]) -> (bold: Bool, italic: Bool, mono: Bool) { |
| 254 | #if os(macOS) |
| 255 | guard let font = attributes[.font] as? NSFont else { return (false, false, false) } |
| 256 | let t = font.fontDescriptor.symbolicTraits |
| 257 | return (t.contains(.bold), t.contains(.italic), t.contains(.monoSpace) || font.isFixedPitch) |
| 258 | #elseif os(iOS) |
| 259 | guard let font = attributes[.font] as? UIFont else { return (false, false, false) } |
| 260 | let t = font.fontDescriptor.symbolicTraits |
| 261 | return (t.contains(.traitBold), t.contains(.traitItalic), t.contains(.traitMonoSpace)) |
| 262 | #else |
| 263 | return (false, false, false) |
| 264 | #endif |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | /// ask.js's pasteMarkdown walk, line for line. |
| 269 | private struct Walker { |
| 270 | struct Run { var text: String; var bold: Bool; var italic: Bool; var href: String } |
| 271 | struct Style { var bold = false, italic = false, href = "", heading = false, mono = false } |
| 272 | static let code: Set<String> = ["code", "tt", "samp", "kbd"] |
| 273 | static let blocks = lines.union(["p", "li", "ul", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "pre"]) |
| 274 | /// Marks HTMLTree.parse leaves for blocks and cells past the depth |
| 275 | /// cap (no tag a page can write starts with "_"). |
| 276 | static let line = "_line", cell = "_cell" |
| 277 | static let raw: Set<String> = ["script", "style", "textarea", "title", "template", "noscript", "iframe"] |
| 278 | static let monoFont = try! NSRegularExpression(pattern: "monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console", options: .caseInsensitive) |
| 279 | final class List { let ordered: Bool; var n: Int; let indent: String; var inner: String |
| 280 | init(ordered: Bool, n: Int, indent: String) { self.ordered = ordered; self.n = n; self.indent = indent; inner = indent } |
| 281 | } |
| 282 | static let skip: Set<String> = ["script", "style", "head", "title", "template", "noscript", "iframe", "object", "embed", "svg", "math", "canvas", "video", "audio", "picture", "img", "button", "select", "input", "textarea"] |
| 283 | static let lines: Set<String> = ["div", "section", "article", "header", "footer", "main", "nav", "aside", "blockquote", "figure", "figcaption", "address", "center", "details", "summary", "form", "fieldset", "table", "thead", "tbody", "tfoot", "tr", "caption", "dl", "dt", "dd", "hr"] |
| 284 | |
| 285 | var out = "" |
| 286 | var runs: [Run] = [] |
| 287 | var open = false |
| 288 | var marker: String? |
| 289 | var indent = "" |
| 290 | var formatted = false |
| 291 | var lists: [List] = [] |
| 292 | /// Characters of text (not spaces), and how many of them are code's. |
| 293 | var chars = 0, mono = 0 |
| 294 | /// Each <pre>'s text, standing in the output as NUL, its number, NUL |
| 295 | /// until the clean-up is done: its spaces and blank lines are the |
| 296 | /// code's. |
| 297 | var verbatim: [String] = [] |
| 298 | |
| 299 | mutating func markdown(_ tree: HTMLTree) -> String? { |
| 300 | walk(tree, Style(), depth: -1) |
| 301 | flush() |
| 302 | guard formatted, mono * 2 <= chars else { return nil } |
| 303 | let trimmed = out.components(separatedBy: "\n").map { line in |
| 304 | var line = line |
| 305 | while line.last == " " || line.last == "\t" { line.removeLast() } |
| 306 | return line |
| 307 | }.joined(separator: "\n") |
| 308 | var result = trimmed.replacingOccurrences(of: #"\n{3,}"#, with: "\n\n", options: .regularExpression) |
| 309 | while result.first == "\n" { result.removeFirst() } |
| 310 | while result.last == "\n" { result.removeLast() } |
| 311 | for (n, code) in verbatim.enumerated().reversed() { result = result.replacingOccurrences(of: "\0\(n)\0", with: code) } |
| 312 | return result |
| 313 | } |
| 314 | |
| 315 | mutating func flush() { |
| 316 | var s = inline(runs) |
| 317 | runs = [] |
| 318 | while s.first == " " { s.removeFirst() } |
| 319 | guard !s.isEmpty else { return } |
| 320 | if open { out += s } else { |
| 321 | out += (marker ?? indent) + s |
| 322 | if marker != nil { formatted = true } |
| 323 | } |
| 324 | marker = nil |
| 325 | open = true |
| 326 | } |
| 327 | |
| 328 | mutating func ensure(_ n: Int) { |
| 329 | flush() |
| 330 | open = false |
| 331 | guard !out.isEmpty else { return } |
| 332 | var have = 0 |
| 333 | for c in out.reversed() { if c == "\n" { have += 1 } else { break } } |
| 334 | while have < n { out += "\n"; have += 1 } |
| 335 | } |
| 336 | |
| 337 | mutating func walk(_ node: HTMLTree, _ st: Style, depth: Int) { |
| 338 | if out.utf16.count > PasteMarkdown.maxOut { return } |
| 339 | if node.tag.isEmpty { |
| 340 | let counted = node.text.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) } |
| 341 | chars += counted |
| 342 | if st.mono { mono += counted } |
| 343 | var t = node.text.replacingOccurrences(of: "[ \\t\\n\\r\\f\u{00a0}]+", with: " ", options: .regularExpression) |
| 344 | // One space between words, whichever side of a tag it was. |
| 345 | if t.first == " ", runs.last?.text.last == " " { t.removeFirst() } |
| 346 | if !t.isEmpty { runs.append(Run(text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href)) } |
| 347 | return |
| 348 | } |
| 349 | let tag = node.tag |
| 350 | if tag == "br" { |
| 351 | flush() |
| 352 | if !out.isEmpty { out += "\n"; open = false } |
| 353 | return |
| 354 | } |
| 355 | // (The body is depth -1; its children 0. HTMLTree.parse never makes |
| 356 | // anything deeper than the cap, and marks what it flattened.) |
| 357 | if tag == Self.line { ensure(1); return } |
| 358 | if tag == Self.cell { runs.append(Run(text: " ", bold: false, italic: false, href: "")); return } |
| 359 | if Self.skip.contains(tag) { return } |
| 360 | var next = st |
| 361 | if tag == "b" || tag == "strong" { next.bold = true } |
| 362 | if tag == "i" || tag == "em" { next.italic = true } |
| 363 | if Self.code.contains(tag) { next.mono = true } |
| 364 | let style = node.attributes["style"] ?? "" |
| 365 | if let weight = Self.declared(style, "font-weight") { |
| 366 | next.bold = weight.range(of: "^(bold|bolder|[6-9]00)$", options: [.regularExpression, .caseInsensitive]) != nil |
| 367 | } |
| 368 | if let slant = Self.declared(style, "font-style") { |
| 369 | next.italic = slant.range(of: "^(italic|oblique)", options: [.regularExpression, .caseInsensitive]) != nil |
| 370 | } |
| 371 | if let family = Self.declared(style, "font-family") { |
| 372 | next.mono = Self.monoFont.firstMatch(in: family, range: NSRange(family.startIndex..., in: family)) != nil |
| 373 | } |
| 374 | if tag == "a", st.href.isEmpty { next.href = Self.link(node.attributes["href"] ?? "") } |
| 375 | func children(_ w: inout Walker) { for c in node.children { w.walk(c, next, depth: depth + 1) } } |
| 376 | |
| 377 | if tag.count == 2, tag.first == "h", let level = Int(String(tag.last!)), (1...6).contains(level) { |
| 378 | ensure(2) |
| 379 | marker = String(repeating: "#", count: level) + " " |
| 380 | next.heading = true |
| 381 | let before = formatted |
| 382 | children(&self) |
| 383 | flush() |
| 384 | if marker != nil { marker = nil; formatted = before } |
| 385 | ensure(2) |
| 386 | return |
| 387 | } |
| 388 | if tag == "ul" || tag == "ol" { |
| 389 | let top = lists.isEmpty |
| 390 | let parent = lists.last |
| 391 | ensure(top ? 2 : 1) |
| 392 | let start = Int(node.attributes["start"]?.trimmingCharacters(in: .whitespaces) ?? "") |
| 393 | lists.append(List(ordered: tag == "ol", n: tag == "ol" ? max(0, start ?? 1) : 0, indent: parent?.inner ?? indent)) |
| 394 | let saved = indent |
| 395 | children(&self) |
| 396 | lists.removeLast() |
| 397 | indent = saved |
| 398 | ensure(top ? 2 : 1) |
| 399 | return |
| 400 | } |
| 401 | if tag == "li" { |
| 402 | ensure(1) |
| 403 | let list = lists.last ?? List(ordered: false, n: 0, indent: "") |
| 404 | let m = list.ordered ? "\(list.n). " : "- " |
| 405 | if list.ordered { list.n += 1 } |
| 406 | marker = list.indent + m |
| 407 | list.inner = list.indent + String(repeating: " ", count: m.count) |
| 408 | let saved = indent |
| 409 | indent = list.inner |
| 410 | children(&self) |
| 411 | flush() |
| 412 | marker = nil |
| 413 | indent = saved |
| 414 | ensure(1) |
| 415 | return |
| 416 | } |
| 417 | if tag == "p" { |
| 418 | if !lists.isEmpty { |
| 419 | flush() |
| 420 | if open { out += "\n"; open = false } |
| 421 | children(&self) |
| 422 | return |
| 423 | } |
| 424 | ensure(2); children(&self); ensure(2) |
| 425 | return |
| 426 | } |
| 427 | if tag == "pre" { |
| 428 | // Verbatim, as a fenced code block longer than any run of |
| 429 | // backticks in it. |
| 430 | var code = "" |
| 431 | func read(_ n: HTMLTree) { |
| 432 | if n.tag.isEmpty { code += n.text } else if n.tag == "br" { code += "\n" } else if !Self.skip.contains(n.tag) { n.children.forEach(read) } |
| 433 | } |
| 434 | read(node) |
| 435 | code = code.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") |
| 436 | // A page drops the line break just after <pre>. |
| 437 | if code.hasPrefix("\n") { code.removeFirst() } |
| 438 | if code.hasSuffix("\n") { code.removeLast() } |
| 439 | let counted = code.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) } |
| 440 | chars += counted |
| 441 | mono += counted |
| 442 | guard !code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } |
| 443 | var longest = 0, run = 0 |
| 444 | for c in code { run = c == "`" ? run + 1 : 0; longest = max(longest, run) } |
| 445 | let fence = String(repeating: "`", count: max(3, longest + 1)) |
| 446 | ensure(2) |
| 447 | out += fence + "\n\0\(verbatim.count)\0\n" + fence |
| 448 | verbatim.append(code) |
| 449 | formatted = true |
| 450 | ensure(2) |
| 451 | return |
| 452 | } |
| 453 | if Self.lines.contains(tag) { |
| 454 | ensure(1); children(&self); ensure(1) |
| 455 | return |
| 456 | } |
| 457 | if tag == "td" || tag == "th" { |
| 458 | children(&self) |
| 459 | runs.append(Run(text: " ", bold: false, italic: false, href: "")) |
| 460 | return |
| 461 | } |
| 462 | children(&self) |
| 463 | } |
| 464 | |
| 465 | /// A line's runs as Markdown: neighbours alike are one run, and a run's |
| 466 | /// outer spaces stand outside its marks. |
| 467 | mutating func inline(_ rs: [Run]) -> String { |
| 468 | var merged: [Run] = [] |
| 469 | for r in rs { |
| 470 | if let last = merged.last, last.href == r.href, !r.href.isEmpty || (last.bold == r.bold && last.italic == r.italic) { |
| 471 | merged[merged.count - 1].text += r.text |
| 472 | } else { |
| 473 | merged.append(r) |
| 474 | } |
| 475 | } |
| 476 | var s = "" |
| 477 | for r in merged { |
| 478 | let lead = String(r.text.prefix { $0 == " " }) |
| 479 | let rest = r.text.dropFirst(lead.count) |
| 480 | let trail = String(rest.reversed().prefix { $0 == " " }) |
| 481 | let core = String(rest.dropLast(trail.count)) |
| 482 | if core.isEmpty { s += r.text; continue } |
| 483 | if !r.href.isEmpty { |
| 484 | let label = core.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "") |
| 485 | let href = r.href.replacingOccurrences(of: "(", with: "%28").replacingOccurrences(of: ")", with: "%29") |
| 486 | s += lead + (label == r.href ? href : label.utf16.count > 300 ? "\(label) (\(href))" : "[\(label)](\(href))") + trail |
| 487 | formatted = true |
| 488 | } else if r.bold || r.italic { |
| 489 | let mark = r.bold ? "**" : "*" |
| 490 | s += lead + mark + core + mark + trail |
| 491 | formatted = true |
| 492 | } else { |
| 493 | s += r.text |
| 494 | } |
| 495 | } |
| 496 | while s.last == " " { s.removeLast() } |
| 497 | return s |
| 498 | } |
| 499 | |
| 500 | /// A declaration's value in a style attribute (never |
| 501 | /// mso-bidi-font-weight and the like). |
| 502 | static func declared(_ style: String, _ name: String) -> String? { |
| 503 | guard let re = try? NSRegularExpression(pattern: "(?:^|;)\\s*\(name)\\s*:\\s*([^;]*)", options: .caseInsensitive), |
| 504 | let m = re.firstMatch(in: style, range: NSRange(style.startIndex..., in: style)), |
| 505 | let r = Range(m.range(at: 1), in: style) else { return nil } |
| 506 | return style[r].replacingOccurrences(of: #"!\s*important\s*$"#, with: "", options: [.regularExpression, .caseInsensitive]).trimmingCharacters(in: .whitespaces) |
| 507 | } |
| 508 | |
| 509 | /// An href as a page reads it (spaces at its ends go, tabs and line |
| 510 | /// breaks in it go, other spaces are escaped), if it is http(s). |
| 511 | static func link(_ href: String) -> String { |
| 512 | let cleaned = href.trimmingCharacters(in: .whitespacesAndNewlines).filter { $0 != "\t" && $0 != "\n" && $0 != "\r" } |
| 513 | guard let url = URL(string: cleaned, encodingInvalidCharacters: true) else { return "" } |
| 514 | return BaseJSON.webURL(url.absoluteString)?.absoluteString ?? "" |
| 515 | } |
| 516 | } |
| 517 | |