SPB Git

Repository Public

MarkdownImport.swift 28.2 KB 606 lines swift

1// SP Notes Core2// File: Sources/SPNotesDocument/MarkdownImport.swift3// Description: Markdown to document, following the server import (markdown.ts + markdown-client.ts): GFM blocks and4//              inlines, task lists, tables, math, images as blocks. The result is always valid for the web schema.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension NoteDocument {11    /// Imports Markdown, turning `[[Wiki links]]` into mentions when `resolvePage` returns a page id for the target12    /// (otherwise they become plain text, as on the server when the page is unknown).13    public init(markdown: String, resolvePage: (String) -> String?) {14        self = withoutActuallyEscaping(resolvePage) { MarkdownImport.document(markdown, resolvePage: $0) }15    }16}1718enum MarkdownImport {19    static func document(_ md: String, resolvePage: ((String) -> String?)?) -> NoteDocument {20        let text = md.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")21        let parser = BlockParser(inline: InlineParser(resolvePage: resolvePage))22        var nodes = parser.blocks(JS.splitLines(text).map(expandTabs)).flatMap(liftImages).map(finish)23        if nodes.isEmpty { nodes = [PMNode(type: NodeType.paragraph)].map(finish) }24        var doc = NoteDocument(node: PMNode(type: NodeType.doc, content: nodes))25        doc.ensureBlockIds()26        return doc27    }2829    static func expandTabs(_ line: String) -> String {30        guard line.unicodeScalars.contains("\t") else { return line }31        var out = "", leading = true32        for u in line.unicodeScalars {33            if leading, u == "\t" { out += "    " } else {34                if u != " " { leading = false }35                out.unicodeScalars.append(u)36            }37        }38        return out39    }4041    /// The server's `walk`: images are block nodes, a paragraph or heading is split around them.42    static func liftImages(_ n: PMNode) -> [PMNode] {43        guard let kids = n.content else { return [n] }44        var node = n45        let children = kids.flatMap(liftImages)46        guard n.type == NodeType.paragraph || n.type == NodeType.heading else {47            node.content = children48            return [node]49        }50        var out: [PMNode] = [], buf: [PMNode] = []51        func flush() {52            if !buf.isEmpty { var p = n; p.content = buf; out.append(p) }53            buf = []54        }55        for c in children {56            if c.type == NodeType.image { flush(); out.append(c) } else { buf.append(c) }57        }58        flush()59        if out.isEmpty { node.content = []; return [node] }60        return out61    }6263    /// Makes a node what the web editor would serialize: every schema attribute present, containers never empty,64    /// list items starting with a paragraph, no empty `content`.65    static func finish(_ n: PMNode) -> PMNode {66        var node = n67        if let defaults = Schema.nodeDefaults[n.type] { node.attrs = defaults.merging(n.attrs ?? [:]) { _, given in given } }68        var kids = (n.content ?? []).map(finish)69        let emptyParagraph = PMNode(type: NodeType.paragraph, attrs: Schema.nodeDefaults[NodeType.paragraph])70        switch n.type {71        case NodeType.listItem, NodeType.taskItem:72            if kids.first?.type != NodeType.paragraph { kids.insert(emptyParagraph, at: 0) }73        case NodeType.blockquote, NodeType.tableHeader, NodeType.tableCell:74            if kids.isEmpty { kids = [emptyParagraph] }75        default: break76        }77        node.content = kids.isEmpty ? nil : kids78        return node79    }8081    static func unsafeURL(_ s: String) -> Bool {82        let l = JS.trimStart(s).lowercased()83        return l.hasPrefix("javascript") || l.hasPrefix("vbscript") || l.hasPrefix("data:text/html")84    }85}8687// MARK: - Blocks8889struct BlockParser {90    let inline: InlineParser9192    private func isBlank(_ l: String) -> Bool { l.unicodeScalars.allSatisfy { $0 == " " || $0 == "\t" } }93    private func indent(_ l: String) -> Int { l.unicodeScalars.prefix { $0 == " " }.count }94    private func dropLeadingSpace(_ l: String) -> String { String(l.unicodeScalars.drop { $0 == " " || $0 == "\t" }) }95    private func dropTrailingSpace(_ l: String) -> String {96        var u = Array(l.unicodeScalars)97        while let last = u.last, last == " " || last == "\t" || last == "\n" { u.removeLast() }98        var v = String.UnicodeScalarView()99        v.append(contentsOf: u)100        return String(v)101    }102103    private func fenceOpen(_ l: String) -> (indent: Int, char: Character, count: Int, info: String)? {104        guard let m = l.wholeMatch(of: #/( {0,3})(`{3,}|~{3,})[ \t]*(.*?)[ \t]*/#) else { return nil }105        let fence = m.2106        if fence.first == "`", m.3.contains("`") { return nil }107        return (m.1.count, fence.first!, fence.count, String(m.3))108    }109110    private func isFenceClose(_ l: String, _ char: Character, _ count: Int) -> Bool {111        guard let m = l.wholeMatch(of: #/ {0,3}(`{3,}|~{3,})[ \t]*/#) else { return false }112        return m.1.first == char && m.1.count >= count113    }114115    private func atxHeading(_ l: String) -> (level: Int, text: String)? {116        guard let m = l.wholeMatch(of: #/ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*/#) else { return nil }117        var text = String(m.2 ?? "")118        if text.wholeMatch(of: #/#+/#) != nil { text = "" }119        return (m.1.count, text)120    }121122    private func isRule(_ l: String) -> Bool {123        l.wholeMatch(of: #/ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})/#) != nil124    }125126    private func quoteContent(_ l: String) -> String? {127        guard let m = l.wholeMatch(of: #/ {0,3}> ?(.*)/#) else { return nil }128        return String(m.1)129    }130131    struct Marker {132        var indent: Int133        var ordered: Bool134        var kind: Character // bullet character, or the delimiter of an ordered marker135        var start: Int136        var contentIndent: Int137        var rest: String138    }139140    private func listMarker(_ l: String) -> Marker? {141        guard !isRule(l), let m = l.wholeMatch(of: #/( {0,3})([-*+]|\d{1,9}[.)])(?:( +)(.*))?/#) else { return nil }142        let marker = String(m.2)143        let ordered = marker.count > 1 || marker.first!.isNumber144        let spaces = m.3?.count ?? 0145        var rest = String(m.4 ?? "")146        let base = m.1.count + marker.count147        var contentIndent = base + 1148        if !isBlank(rest), spaces <= 4 { contentIndent = base + spaces } else if spaces > 1 {149            rest = String(repeating: " ", count: spaces - 1) + rest150        }151        return Marker(indent: m.1.count, ordered: ordered, kind: marker.last!, start: ordered ? Int(marker.dropLast()) ?? 1 : 1,152                      contentIndent: contentIndent, rest: rest)153    }154155    /// Whether the line starts a block that interrupts a paragraph.156    private func startsBlock(_ l: String) -> Bool {157        if indent(l) >= 4 { return false }158        if fenceOpen(l) != nil || atxHeading(l) != nil || isRule(l) || quoteContent(l) != nil { return true }159        if let m = listMarker(l), !isBlank(m.rest), !m.ordered || m.start == 1 { return true }160        return false161    }162163    private func tableCells(_ l: String) -> [String] {164        var s = Array(JS.trim(l).unicodeScalars)165        if s.first == "|" { s.removeFirst() }166        if s.last == "|", !(s.count >= 2 && s[s.count - 2] == "\\") { s.removeLast() }167        var cells: [String] = [], cur = String.UnicodeScalarView()168        var i = 0169        while i < s.count {170            if s[i] == "\\", i + 1 < s.count, s[i + 1] == "|" { cur.append("|"); i += 2; continue }171            if s[i] == "|" { cells.append(JS.trim(String(cur))); cur = String.UnicodeScalarView() } else { cur.append(s[i]) }172            i += 1173        }174        cells.append(JS.trim(String(cur)))175        return cells176    }177178    private func isTableDelimiter(_ l: String) -> Bool {179        l.contains("-") && l.wholeMatch(of: #/ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*/#) != nil180    }181182    private func paragraph(_ content: [PMNode]) -> PMNode {183        PMNode(type: NodeType.paragraph, content: content.isEmpty ? nil : content)184    }185186    func blocks(_ lines: [String]) -> [PMNode] {187        var out: [PMNode] = []188        var i = 0189        while i < lines.count {190            let line = lines[i]191            if isBlank(line) { i += 1; continue }192            if indent(line) >= 4 {193                var code: [String] = []194                while i < lines.count, isBlank(lines[i]) || indent(lines[i]) >= 4 {195                    code.append(String(lines[i].unicodeScalars.dropFirst(min(4, indent(lines[i])))))196                    i += 1197                }198                while let last = code.last, isBlank(last) { code.removeLast() }199                out.append(codeBlock(code.joined(separator: "\n"), lang: ""))200                continue201            }202            if let f = fenceOpen(line) {203                var code: [String] = []204                i += 1205                while i < lines.count, !isFenceClose(lines[i], f.char, f.count) {206                    code.append(String(lines[i].unicodeScalars.dropFirst(min(f.indent, indent(lines[i])))))207                    i += 1208                }209                i += 1210                out.append(codeBlock(code.joined(separator: "\n"), lang: f.info))211                continue212            }213            if let h = atxHeading(line) {214                out.append(PMNode(type: NodeType.heading, attrs: ["level": .int(Int64(min(3, h.level)))], content: inline.parse(h.text)))215                i += 1216                continue217            }218            if isRule(line) { out.append(.horizontalRule()); i += 1; continue }219            if quoteContent(line) != nil {220                var inner: [String] = []221                while i < lines.count {222                    if let q = quoteContent(lines[i]) { inner.append(q); i += 1; continue }223                    if isBlank(lines[i]) { break }224                    if let last = inner.last, !isBlank(last), !startsBlock(last), !startsBlock(lines[i]), listMarker(lines[i]) == nil {225                        inner.append(lines[i]); i += 1; continue226                    }227                    break228                }229                out.append(PMNode(type: NodeType.blockquote, content: blocks(inner)))230                continue231            }232            if let first = listMarker(line) { out.append(list(lines, &i, first)); continue }233            if line.contains("|"), i + 1 < lines.count, isTableDelimiter(lines[i + 1]), tableCells(line).count == tableCells(lines[i + 1]).count {234                let header = tableCells(line)235                var rows: [[String]] = []236                i += 2237                while i < lines.count, !isBlank(lines[i]), !startsBlock(lines[i]) {238                    var cells = tableCells(lines[i])239                    while cells.count < header.count { cells.append("") }240                    rows.append(Array(cells.prefix(header.count)))241                    i += 1242                }243                func row(_ cells: [String], _ isHeader: Bool) -> PMNode {244                    PMNode(type: NodeType.tableRow, content: cells.map {245                        PMNode(type: isHeader ? NodeType.tableHeader : NodeType.tableCell, content: [paragraph(inline.parse($0))])246                    })247                }248                out.append(PMNode(type: NodeType.table, content: [row(header, true)] + rows.map { row($0, false) }))249                continue250            }251            // Paragraph (or setext heading).252            var para = [dropLeadingSpace(line)]253            var setext: Int?254            i += 1255            while i < lines.count {256                let l = lines[i]257                if isBlank(l) { break }258                if indent(l) < 4, let m = l.wholeMatch(of: #/ {0,3}(=+|-+)[ \t]*/#) { setext = m.1.first == "=" ? 1 : 2; i += 1; break }259                if startsBlock(l) { break }260                para.append(dropLeadingSpace(l))261                i += 1262            }263            let text = dropTrailingSpace(para.joined(separator: "\n"))264            if let setext {265                out.append(PMNode(type: NodeType.heading, attrs: ["level": .int(Int64(setext))], content: inline.parse(text)))266            } else if let m = text.wholeMatch(of: #/(?s)\$\$(.+?)\$\$/#) {267                out.append(PMNode(type: NodeType.blockMath, attrs: ["latex": .string(JS.trim(String(m.1)))]))268            } else {269                out.append(paragraph(inline.parse(text)))270            }271        }272        return out273    }274275    private func codeBlock(_ text: String, lang: String) -> PMNode {276        if lang == "math" { return PMNode(type: NodeType.blockMath, attrs: ["latex": .string(text)]) }277        return PMNode(type: NodeType.codeBlock, attrs: ["language": lang.isEmpty ? .null : .string(lang)],278                      content: text.isEmpty ? nil : [.text(text)])279    }280281    private func list(_ lines: [String], _ i: inout Int, _ first: Marker) -> PMNode {282        var items: [(lines: [String], task: Bool, checked: Bool)] = []283        while i < lines.count, let m = listMarker(lines[i]), m.ordered == first.ordered, m.kind == first.kind {284            var body = [m.rest]285            i += 1286            while i < lines.count {287                let l = lines[i]288                if isBlank(l) {289                    var j = i290                    while j < lines.count, isBlank(lines[j]) { j += 1 }291                    guard j < lines.count, indent(lines[j]) >= m.contentIndent else { break }292                    body.append(contentsOf: repeatElement("", count: j - i))293                    i = j294                    continue295                }296                if indent(l) >= m.contentIndent { body.append(String(l.unicodeScalars.dropFirst(m.contentIndent))); i += 1; continue }297                if listMarker(l) != nil || startsBlock(l) { break }298                if let last = body.last, !isBlank(last) { body.append(dropLeadingSpace(l)); i += 1; continue }299                break300            }301            var task = false, checked = false302            if let t = body[0].wholeMatch(of: #/\[([ xX])\](?:[ \t]+(.*))?/#) {303                task = true304                checked = t.1 != " "305                body[0] = String(t.2 ?? "")306            }307            items.append((body, task, checked))308            var j = i309            while j < lines.count, isBlank(lines[j]) { j += 1 }310            if j < lines.count, let next = listMarker(lines[j]), next.ordered == first.ordered, next.kind == first.kind { i = j } else { break }311        }312        let isTask = items.contains { $0.task }313        let nodes = items.map { item -> PMNode in314            let content = blocks(item.lines)315            return isTask ? PMNode(type: NodeType.taskItem, attrs: ["checked": .bool(item.checked)], content: content)316                : PMNode(type: NodeType.listItem, content: content)317        }318        if isTask { return PMNode(type: NodeType.taskList, content: nodes) }319        if first.ordered { return PMNode(type: NodeType.orderedList, attrs: ["start": .int(Int64(first.start == 0 ? 1 : first.start))], content: nodes) }320        return PMNode(type: NodeType.bulletList, content: nodes)321    }322}323324// MARK: - Inlines325326struct InlineParser {327    let resolvePage: ((String) -> String?)?328329    indirect enum Item {330        case text(String)331        case node(PMNode)332        case code(String)333        case span(PMMark, [Item])334        case delim(ch: Unicode.Scalar, count: Int, canOpen: Bool, canClose: Bool)335        case image(alt: String, src: String)336    }337338    func parse(_ s: String) -> [PMNode] { merged(render(items(Array(s.unicodeScalars)), marks: [])) }339340    private func str(_ s: ArraySlice<Unicode.Scalar>) -> String {341        var v = String.UnicodeScalarView()342        v.append(contentsOf: s)343        return String(v)344    }345346    private func isSpace(_ u: Unicode.Scalar?) -> Bool { u.map { JS.isSpace($0) } ?? true }347    private func isPunct(_ u: Unicode.Scalar?) -> Bool {348        guard let u else { return false }349        switch u.properties.generalCategory {350        case .connectorPunctuation, .dashPunctuation, .openPunctuation, .closePunctuation, .initialPunctuation, .finalPunctuation,351             .otherPunctuation, .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol: return true352        default: return false353        }354    }355356    private func unescapeEntities(_ s: String) -> String {357        s.replacingOccurrences(of: "&amp;", with: "&").replacingOccurrences(of: "&lt;", with: "<").replacingOccurrences(of: "&gt;", with: ">")358            .replacingOccurrences(of: "&quot;", with: "\"").replacingOccurrences(of: "&#39;", with: "'")359    }360361    /// End index (exclusive) of the code span opened by the backtick run at `i`, with its content.362    private func codeSpan(_ s: [Unicode.Scalar], _ i: Int) -> (end: Int, content: String)? {363        var n = 0364        while i + n < s.count, s[i + n] == "`" { n += 1 }365        var j = i + n366        while j < s.count {367            guard s[j] == "`" else { j += 1; continue }368            var k = 0369            while j + k < s.count, s[j + k] == "`" { k += 1 }370            if k == n {371                var content = s[(i + n)..<j].map { $0 == "\n" ? " " : $0 }372                if content.count >= 2, content.first == " ", content.last == " ", content.contains(where: { $0 != " " }) {373                    content.removeFirst()374                    content.removeLast()375                }376                return (j + k, str(content[...]))377            }378            j += k379        }380        return nil381    }382383    /// A `[text](destination "title")` link starting at `i`.384    private func link(_ s: [Unicode.Scalar], _ i: Int) -> (end: Int, text: ArraySlice<Unicode.Scalar>, href: String)? {385        var depth = 0386        var j = i387        var close = -1388        while j < s.count {389            if s[j] == "\\", j + 1 < s.count { j += 2; continue }390            if s[j] == "`", let c = codeSpan(s, j) { j = c.end; continue }391            if s[j] == "[" { depth += 1 } else if s[j] == "]" {392                depth -= 1393                if depth == 0 { close = j; break }394            }395            j += 1396        }397        guard close > 0, close + 1 < s.count, s[close + 1] == "(" else { return nil }398        var k = close + 2399        while k < s.count, s[k] == " " || s[k] == "\n" { k += 1 }400        var href = String.UnicodeScalarView()401        if k < s.count, s[k] == "<" {402            k += 1403            while k < s.count, s[k] != ">", s[k] != "\n" { href.append(s[k]); k += 1 }404            guard k < s.count, s[k] == ">" else { return nil }405            k += 1406        } else {407            var parens = 0408            while k < s.count, !JS.isSpace(s[k]) {409                if s[k] == "\\", k + 1 < s.count, isPunct(s[k + 1]) { href.append(s[k + 1]); k += 2; continue }410                if s[k] == "(" { parens += 1 } else if s[k] == ")" {411                    if parens == 0 { break }412                    parens -= 1413                }414                href.append(s[k])415                k += 1416            }417        }418        while k < s.count, s[k] == " " || s[k] == "\n" { k += 1 }419        if k < s.count, s[k] == "\"" || s[k] == "'" {420            let quote = s[k]421            k += 1422            while k < s.count, s[k] != quote { k += s[k] == "\\" ? 2 : 1 }423            guard k < s.count else { return nil }424            k += 1425            while k < s.count, s[k] == " " || s[k] == "\n" { k += 1 }426        }427        guard k < s.count, s[k] == ")" else { return nil }428        return (k + 1, s[(i + 1)..<close], String(href))429    }430431    func items(_ s: [Unicode.Scalar]) -> [Item] {432        var out: [Item] = []433        var buf = String.UnicodeScalarView()434        func flush() {435            if !buf.isEmpty { out.append(.text(String(buf))); buf = String.UnicodeScalarView() }436        }437        var i = 0438        while i < s.count {439            let c = s[i]440            switch c {441            case "\\":442                if i + 1 < s.count, s[i + 1] == "\n" { flush(); out.append(.node(.hardBreak())); i += 2; continue }443                if i + 1 < s.count, s[i + 1].isASCII, isPunct(s[i + 1]) { flush(); out.append(.text(String(Character(s[i + 1])))); i += 2; continue }444                buf.append(c); i += 1445            case "`":446                if let span = codeSpan(s, i) {447                    flush()448                    if let m = span.content.wholeMatch(of: #/\$(.+)\$/#) { out.append(.node(.inlineMath(latex: String(m.1)))) }449                    else { out.append(.code(unescapeEntities(span.content))) }450                    i = span.end451                } else {452                    while i < s.count, s[i] == "`" { buf.append("`"); i += 1 }453                }454            case "!":455                if i + 1 < s.count, s[i + 1] == "[",456                   let m = str(s[i...]).prefixMatch(of: #/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/#) {457                    flush()458                    out.append(.image(alt: String(m.1), src: String(m.2)))459                    i += m.0.unicodeScalars.count460                } else { buf.append(c); i += 1 }461            case "[":462                if i + 1 < s.count, s[i + 1] == "[",463                   let m = str(s[i...]).prefixMatch(of: #/\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|([^\]]+))?\]\]/#) {464                    flush()465                    let target = JS.trim(String(m.1))466                    let label = m.2.map { JS.trim(String($0)) } ?? target467                    if let id = resolvePage?(target) { out.append(.node(.mention(id: id, label: label))) } else { out.append(.text(label)) }468                    i += m.0.unicodeScalars.count469                } else if let l = link(s, i) {470                    flush()471                    out.append(.span(.link(href: l.href), items(Array(l.text))))472                    i = l.end473                } else { buf.append(c); i += 1 }474            case "<":475                if let m = str(s[i...]).prefixMatch(of: #/<((?:https?:\/\/|mailto:)[^\s<>]*)>/#) {476                    flush()477                    out.append(.span(.link(href: String(m.1)), [.text(String(m.1))]))478                    i += m.0.unicodeScalars.count479                } else { buf.append(c); i += 1 }480            case "&":481                let rest = str(s[i..<min(s.count, i + 6)])482                if let (entity, char) = [("&amp;", "&"), ("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&#39;", "'")].first(where: { rest.hasPrefix($0.0) }) {483                    flush()484                    out.append(.text(char))485                    i += entity.unicodeScalars.count486                } else { buf.append(c); i += 1 }487            case "\n":488                var spaces = 0489                while let last = buf.last, last == " " { buf.removeLast(); spaces += 1 }490                if spaces >= 2 { flush(); out.append(.node(.hardBreak())) } else { buf.append("\n") }491                i += 1492                while i < s.count, s[i] == " " { i += 1 }493            case "*", "_", "~":494                var n = 0495                while i + n < s.count, s[i + n] == c { n += 1 }496                let prev: Unicode.Scalar? = i > 0 ? s[i - 1] : nil497                let next: Unicode.Scalar? = i + n < s.count ? s[i + n] : nil498                let left = !isSpace(next) && (!isPunct(next) || isSpace(prev) || isPunct(prev))499                let right = !isSpace(prev) && (!isPunct(prev) || isSpace(next) || isPunct(next))500                if c == "~", n > 2 { for _ in 0..<n { buf.append(c) } }501                else {502                    flush()503                    let canOpen = c == "_" ? left && (!right || isPunct(prev)) : left504                    let canClose = c == "_" ? right && (!left || isPunct(next)) : right505                    out.append(.delim(ch: c, count: n, canOpen: canOpen, canClose: canClose))506                }507                i += n508            case "h", "w":509                let boundary = i == 0 || isSpace(s[i - 1]) || ["(", "*", "_", "~"].contains(s[i - 1])510                if boundary, let m = str(s[i...]).prefixMatch(of: #/(?:https?:\/\/|www\.)[^\s<]+/#) {511                    var url = Array(String(m.0).unicodeScalars)512                    while let last = url.last, "?!.,:*_~;\"'".unicodeScalars.contains(last)513                            || (last == ")" && url.filter { $0 == ")" }.count > url.filter { $0 == "(" }.count) { url.removeLast() }514                    let text = str(url[...])515                    if text.contains(".") {516                        flush()517                        out.append(.span(.link(href: text.hasPrefix("www.") ? "http://" + text : text), [.text(text)]))518                        i += url.count519                        continue520                    }521                }522                buf.append(c); i += 1523            default:524                buf.append(c); i += 1525            }526        }527        flush()528        return emphasis(out)529    }530531    /// CommonMark delimiter matching (strong, emphasis, strikethrough), simplified.532    private func emphasis(_ input: [Item]) -> [Item] {533        var items = input534        var closer = 0535        while closer < items.count {536            guard case .delim(let c, let n, let cOpen, true) = items[closer] else { closer += 1; continue }537            var found = -1538            var o = closer - 1539            while o >= 0 {540                if case .delim(let oc, let on, true, let oClose) = items[o], oc == c {541                    let oddMatch = c != "~" && (oClose || cOpen) && (on + n) % 3 == 0 && !(on % 3 == 0 && n % 3 == 0)542                    if c == "~" ? on == n : !oddMatch { found = o; break }543                }544                o -= 1545            }546            guard found >= 0, case .delim(_, let on, let oOpen, let oClose) = items[found] else { closer += 1; continue }547            let use = c == "~" ? n : (n >= 2 && on >= 2 ? 2 : 1)548            let mark = PMMark(type: c == "~" ? "strike" : (use == 2 ? "bold" : "italic"))549            var replacement: [Item] = []550            if on - use > 0 { replacement.append(.delim(ch: c, count: on - use, canOpen: oOpen, canClose: oClose)) }551            replacement.append(.span(mark, Array(items[(found + 1)..<closer])))552            let spanIndex = found + replacement.count - 1553            if n - use > 0 { replacement.append(.delim(ch: c, count: n - use, canOpen: cOpen, canClose: true)) }554            items.replaceSubrange(found...closer, with: replacement)555            closer = spanIndex + 1556        }557        return items558    }559560    private func render(_ items: [Item], marks: [PMMark]) -> [PMNode] {561        var out: [PMNode] = []562        func text(_ s: String) {563            var last = s.startIndex564            for m in s.matches(of: #/\$([^$\n]+?)\$/#) {565                if m.range.lowerBound > last { out.append(.text(String(s[last..<m.range.lowerBound]), marks: InlineTools.validMarks(marks))) }566                out.append(.inlineMath(latex: String(m.1)))567                last = m.range.upperBound568            }569            if last < s.endIndex { out.append(.text(String(s[last...]), marks: InlineTools.validMarks(marks))) }570        }571        for item in items {572            switch item {573            case .text(let s): text(s)574            case .node(let n): out.append(n)575            case .code(let s): if !s.isEmpty { out.append(.text(s, marks: [.mark(.code)])) }576            case .span(let mark, let kids):577                let unsafe = mark.type == "link" && MarkdownImport.unsafeURL(mark.attrs?["href"]?.stringValue ?? "")578                out += render(kids, marks: unsafe ? marks : marks + [mark])579            case .delim(let ch, let count, _, _): text(String(repeating: String(Character(ch)), count: count))580            case .image(let alt, let src):581                let l = src.lowercased()582                let resolved = l.hasPrefix("http://") || l.hasPrefix("https://") || l.hasPrefix("//") || src.hasPrefix("data:") || src.hasPrefix("/api/files/")583                if resolved, !MarkdownImport.unsafeURL(src) {584                    out.append(PMNode(type: NodeType.image, attrs: ["src": .string(src), "alt": alt.isEmpty ? .null : .string(alt), "title": .null]))585                } else {586                    text("[image: \(alt.isEmpty ? src : alt)]")587                }588            }589        }590        return out591    }592593    /// Adjacent text nodes with identical marks become one (ProseMirror never holds two).594    private func merged(_ nodes: [PMNode]) -> [PMNode] {595        var out: [PMNode] = []596        for n in nodes {597            if n.type == NodeType.text, let last = out.last, last.type == NodeType.text, last.marks == n.marks {598                out[out.count - 1].text = (last.text ?? "") + (n.text ?? "")599            } else if n.type != NodeType.text || !(n.text ?? "").isEmpty {600                out.append(n)601            }602        }603        return out604    }605}606
Files main
Menu

Theme