Sources/OrgCore/MarkdownImport/MarkdownInline.swift

bd275bd1a81b85a03549d5435d6a0bd32c2cbd66
orgstar/Sources/OrgCore/MarkdownImport/MarkdownInline.swift

431 lines · 19266 bytes

  1import Foundation
  2
  3/// Converts Markdown inline text to org: emphasis, code, links, images, footnote references,
  4/// math and entities; with `obsidian`, also wikilinks, embeds, highlights and `#tags`.
  5final class MarkdownInline {
  6    let obsidian: Bool
  7    let definitions: [String: String]
  8    let targets: MarkdownTargets
  9    /// Links written, wikilinks and embeds included.
 10    var links = 0
 11    /// `#tags` found since the last `takeTags`.
 12    private(set) var tags: [String] = []
 13    var issues: [MarkdownImportIssue] = []
 14
 15    init(obsidian: Bool, definitions: [String: String], targets: MarkdownTargets) {
 16        self.obsidian = obsidian
 17        self.definitions = definitions
 18        self.targets = targets
 19    }
 20
 21    func takeTags() -> [String] {
 22        defer { tags = [] }
 23        return tags
 24    }
 25
 26    func convert(_ text: String) -> String {
 27        convert(Array(text)[...])
 28    }
 29
 30    private func convert(_ chars: ArraySlice<Character>) -> String {
 31        var out = ""
 32        var i = chars.startIndex
 33        let end = chars.endIndex
 34        func at(_ k: Int) -> Character? { k >= chars.startIndex && k < end ? chars[k] : nil }
 35        while i < end {
 36            let c = chars[i]
 37            switch c {
 38            case "\\":
 39                if let next = at(i + 1), next.isASCII, next.isPunctuation || next.isSymbol {
 40                    out.append(next)
 41                    i += 2
 42                    continue
 43                }
 44            case "`":
 45                let run = runLength(chars, i, "`")
 46                if let close = findRun(chars, from: i + run, "`", run) {
 47                    var body = String(chars[(i + run)..<close]).replacingOccurrences(of: "\n", with: " ")
 48                    if body.count >= 2, body.first == " ", body.last == " ", body.contains(where: { $0 != " " }) { body = String(body.dropFirst().dropLast()) }
 49                    out += code(body)
 50                    i = close + run
 51                    continue
 52                }
 53                out += String(repeating: "`", count: run)
 54                i += run
 55                continue
 56            case "$":
 57                if let math = math(chars, i) {
 58                    out += math.text
 59                    i = math.end
 60                    continue
 61                }
 62            case "!":
 63                if obsidian, at(i + 1) == "[", at(i + 2) == "[", let close = findClose(chars, from: i + 3, "]]") {
 64                    out += wikilink(String(chars[(i + 3)..<close]), embed: true)
 65                    i = close + 2
 66                    continue
 67                }
 68                if at(i + 1) == "[", let link = link(chars, i + 1) {
 69                    out += image(destination: link.destination, alt: link.text)
 70                    i = link.end
 71                    continue
 72                }
 73            case "^":
 74                if at(i + 1) == "[", let close = matchingBracket(chars, i + 1) {
 75                    out += "[fn:: " + convert(chars[(i + 2)..<close]) + "]"
 76                    i = close + 1
 77                    continue
 78                }
 79            case "[":
 80                if obsidian, at(i + 1) == "[", let close = findClose(chars, from: i + 2, "]]") {
 81                    out += wikilink(String(chars[(i + 2)..<close]), embed: false)
 82                    i = close + 2
 83                    continue
 84                }
 85                if at(i + 1) == "^", let close = chars[i...].firstIndex(of: "]"), close > i + 2,
 86                   !chars[(i + 2)..<close].contains(where: { $0 == " " || $0 == "\n" }) {
 87                    out += "[fn:" + MarkdownToOrg.footnoteLabel(String(chars[(i + 2)..<close])) + "]"
 88                    i = close + 1
 89                    continue
 90                }
 91                if let link = link(chars, i) {
 92                    out += linkText(destination: link.destination, text: link.text)
 93                    i = link.end
 94                    continue
 95                }
 96            case "<":
 97                if let close = chars[i...].firstIndex(of: ">") {
 98                    let inner = String(chars[(i + 1)..<close])
 99                    if !inner.contains(" "), !inner.contains("\n"), let colon = inner.firstIndex(of: ":"),
100                       inner[..<colon].allSatisfy({ $0.isLetter || $0.isNumber || "+.-".contains($0) }), inner.distance(from: inner.startIndex, to: colon) >= 2 {
101                        links += 1
102                        out += "[[" + MarkdownToOrg.escapeLinkPath(inner) + "]]"
103                        i = close + 1
104                        continue
105                    }
106                    if !inner.contains(" "), inner.contains("@"), inner.contains(".") {
107                        links += 1
108                        out += "[[mailto:" + inner + "]]"
109                        i = close + 1
110                        continue
111                    }
112                    if let first = inner.first, first.isLetter || first == "/" || first == "!" {
113                        out += "@@html:<" + inner + ">@@"
114                        i = close + 1
115                        continue
116                    }
117                }
118            case "&":
119                if let entity = entity(chars, i) {
120                    out += entity.text
121                    i = entity.end
122                    continue
123                }
124            case "*", "_":
125                if let emphasis = emphasis(chars, i, c, previous: at(i - 1)) {
126                    out += emphasis.text
127                    i = emphasis.end
128                    continue
129                }
130                let run = runLength(chars, i, c)
131                out += String(repeating: c, count: run)
132                i += run
133                continue
134            case "~":
135                if at(i + 1) == "~", at(i + 2).map({ !$0.isWhitespace }) == true, let close = findDelimiter(chars, from: i + 2, "~", 2) {
136                    out += "+" + convert(chars[(i + 2)..<close]) + "+"
137                    i = close + 2
138                    continue
139                }
140            case "=":
141                if obsidian, at(i + 1) == "=", at(i + 2).map({ !$0.isWhitespace }) == true, let close = findDelimiter(chars, from: i + 2, "=", 2) {
142                    out += "*" + convert(chars[(i + 2)..<close]) + "*"
143                    i = close + 2
144                    continue
145                }
146            case "#":
147                if obsidian, at(i - 1).map({ $0.isWhitespace || $0 == "(" }) ?? true {
148                    var j = i + 1
149                    while let next = at(j), next.isLetter || next.isNumber || next == "_" || next == "-" || next == "/" { j += 1 }
150                    let tag = String(chars[(i + 1)..<j])
151                    if !tag.isEmpty, tag.contains(where: { !$0.isNumber }) {
152                        tags.append(MarkdownToOrg.tag(tag))
153                        out += "#" + tag
154                        i = j
155                        continue
156                    }
157                }
158            default:
159                break
160            }
161            out.append(c)
162            i += 1
163        }
164        return out
165    }
166
167    // MARK: - Pieces
168
169    private func code(_ body: String) -> String {
170        if !body.contains("~") { return "~" + body + "~" }
171        if !body.contains("=") { return "=" + body + "=" }
172        return "~" + body + "~"
173    }
174
175    private func runLength(_ chars: ArraySlice<Character>, _ i: Int, _ c: Character) -> Int {
176        var j = i
177        while j < chars.endIndex, chars[j] == c { j += 1 }
178        return j - i
179    }
180
181    /// A run of exactly `count` `c`s at or after `from`.
182    private func findRun(_ chars: ArraySlice<Character>, from: Int, _ c: Character, _ count: Int) -> Int? {
183        var j = from
184        while j < chars.endIndex {
185            if chars[j] == c {
186                let run = runLength(chars, j, c)
187                if run == count { return j }
188                j += run
189            } else {
190                j += 1
191            }
192        }
193        return nil
194    }
195
196    private func findClose(_ chars: ArraySlice<Character>, from: Int, _ close: String) -> Int? {
197        let pattern = Array(close)
198        var j = from
199        while j + pattern.count <= chars.endIndex {
200            if chars[j] == "\n" { return nil }
201            if Array(chars[j..<(j + pattern.count)]) == pattern { return j }
202            j += 1
203        }
204        return nil
205    }
206
207    /// The `]` matching the `[` at `open`, skipping code spans and escapes.
208    private func matchingBracket(_ chars: ArraySlice<Character>, _ open: Int) -> Int? {
209        var depth = 0
210        var j = open
211        while j < chars.endIndex {
212            switch chars[j] {
213            case "\\": j += 1
214            case "`":
215                let run = runLength(chars, j, "`")
216                if let close = findRun(chars, from: j + run, "`", run) { j = close + run - 1 } else { j += run - 1 }
217            case "[": depth += 1
218            case "]":
219                depth -= 1
220                if depth == 0 { return j }
221            default: break
222            }
223            j += 1
224        }
225        return nil
226    }
227
228    /// A closing delimiter run of `count` `c`s after a non-space, skipping code spans.
229    private func findDelimiter(_ chars: ArraySlice<Character>, from: Int, _ c: Character, _ count: Int) -> Int? {
230        var j = from
231        while j < chars.endIndex {
232            let char = chars[j]
233            if char == "\\" {
234                j += 2
235                continue
236            }
237            if char == "`" {
238                let run = runLength(chars, j, "`")
239                if let close = findRun(chars, from: j + run, "`", run) { j = close + run } else { j += run }
240                continue
241            }
242            if char == "[", let close = matchingBracket(chars, j) {
243                // Links and their destinations are skipped whole.
244                j = close + 1
245                if j < chars.endIndex, chars[j] == "(", let paren = destinationEnd(chars, j) { j = paren + 1 }
246                continue
247            }
248            if char == c {
249                let run = runLength(chars, j, c)
250                let before = chars[j - 1]
251                let after = j + run < chars.endIndex ? chars[j + run] : nil
252                if run == count, j > from, !before.isWhitespace, c != "_" || !(after.map { $0.isLetter || $0.isNumber } ?? false) { return j }
253                j += run
254                continue
255            }
256            j += 1
257        }
258        return nil
259    }
260
261    private func emphasis(_ chars: ArraySlice<Character>, _ i: Int, _ c: Character, previous: Character?) -> (text: String, end: Int)? {
262        let run = runLength(chars, i, c)
263        guard (1...3).contains(run), i + run < chars.endIndex, !chars[i + run].isWhitespace else { return nil }
264        if c == "_", let previous, previous.isLetter || previous.isNumber { return nil }
265        guard let close = findDelimiter(chars, from: i + run, c, run) else { return nil }
266        let body = convert(chars[(i + run)..<close])
267        guard !body.isEmpty else { return nil }
268        switch run {
269        case 1: return ("/" + body + "/", close + 1)
270        case 2: return ("*" + body + "*", close + 2)
271        default: return ("*/" + body + "/*", close + 3)
272        }
273    }
274
275    private func math(_ chars: ArraySlice<Character>, _ i: Int) -> (text: String, end: Int)? {
276        var j = i + 1
277        if j < chars.endIndex, chars[j] == "$" {
278            j += 1
279            while j + 1 < chars.endIndex {
280                if chars[j] == "$", chars[j + 1] == "$" { return ("\\[" + String(chars[(i + 2)..<j]) + "\\]", j + 2) }
281                j += 1
282            }
283            return nil
284        }
285        guard j < chars.endIndex, !chars[j].isWhitespace, !chars[j].isNumber || obsidian else { return nil }
286        while j < chars.endIndex {
287            if chars[j] == "\n", j + 1 < chars.endIndex, chars[j + 1] == "\n" { return nil }
288            if chars[j] == "\\" {
289                j += 2
290                continue
291            }
292            if chars[j] == "$" {
293                let after = j + 1 < chars.endIndex ? chars[j + 1] : nil
294                if !chars[j - 1].isWhitespace, !(after?.isNumber ?? false) { return ("\\(" + String(chars[(i + 1)..<j]) + "\\)", j + 1) }
295                return nil
296            }
297            j += 1
298        }
299        return nil
300    }
301
302    private static let entities: [String: String] = ["amp": "&", "lt": "<", "gt": ">", "quot": "\"", "apos": "'", "nbsp": "\u{a0}", "copy": "©", "mdash": "—", "ndash": "–", "hellip": "…"]
303
304    private func entity(_ chars: ArraySlice<Character>, _ i: Int) -> (text: String, end: Int)? {
305        guard let semicolon = chars[i...].prefix(12).firstIndex(of: ";") else { return nil }
306        let name = String(chars[(i + 1)..<semicolon])
307        if let value = Self.entities[name] { return (value, semicolon + 1) }
308        if name.hasPrefix("#") {
309            let digits = name.dropFirst()
310            let value = digits.lowercased().hasPrefix("x") ? UInt32(digits.dropFirst(), radix: 16) : UInt32(digits)
311            if let value, let scalar = Unicode.Scalar(value) { return (String(Character(scalar)), semicolon + 1) }
312        }
313        return nil
314    }
315
316    /// The end of a `(destination "title")` starting at `open`, parentheses balanced.
317    private func destinationEnd(_ chars: ArraySlice<Character>, _ open: Int) -> Int? {
318        var depth = 0
319        var j = open
320        var angle = false
321        while j < chars.endIndex {
322            let char = chars[j]
323            if char == "\\" {
324                j += 2
325                continue
326            }
327            if char == "<", j == open + 1 { angle = true }
328            if angle, char == ">" { angle = false }
329            if !angle {
330                if char == "(" { depth += 1 }
331                if char == ")" {
332                    depth -= 1
333                    if depth == 0 { return j }
334                }
335            }
336            if char == "\n", j + 1 < chars.endIndex, chars[j + 1] == "\n" { return nil }
337            j += 1
338        }
339        return nil
340    }
341
342    /// `[text](destination)`, `[text][label]`, `[label][]` or `[label]` with a definition.
343    private func link(_ chars: ArraySlice<Character>, _ open: Int) -> (text: ArraySlice<Character>, destination: String, end: Int)? {
344        guard let close = matchingBracket(chars, open) else { return nil }
345        let text = chars[(open + 1)..<close]
346        let after = close + 1
347        if after < chars.endIndex, chars[after] == "(", let end = destinationEnd(chars, after) {
348            var inside = String(chars[(after + 1)..<end]).trimmingCharacters(in: .whitespacesAndNewlines)
349            var destination: String
350            if inside.hasPrefix("<"), let angle = inside.firstIndex(of: ">") {
351                destination = String(inside[inside.index(after: inside.startIndex)..<angle])
352            } else {
353                if let space = inside.firstIndex(where: { $0 == " " || $0 == "\n" }) {
354                    let title = inside[space...].trimmingCharacters(in: .whitespacesAndNewlines)
355                    if title.first == "\"" || title.first == "'" || title.first == "(" { inside = String(inside[..<space]) }
356                }
357                destination = inside
358            }
359            destination = destination.replacingOccurrences(of: "\\(", with: "(").replacingOccurrences(of: "\\)", with: ")")
360            return (text, destination, end + 1)
361        }
362        if after < chars.endIndex, chars[after] == "[", let labelClose = chars[after...].firstIndex(of: "]") {
363            var label = String(chars[(after + 1)..<labelClose])
364            if label.isEmpty { label = String(text) }
365            if let destination = definitions[MarkdownBlocks.normalizeLabel(label)] { return (text, destination, labelClose + 1) }
366            return nil
367        }
368        if let destination = definitions[MarkdownBlocks.normalizeLabel(String(text))] { return (text, destination, after) }
369        return nil
370    }
371
372    private static func isURL(_ destination: String) -> Bool {
373        guard let colon = destination.firstIndex(of: ":") else { return false }
374        let scheme = destination[..<colon]
375        return scheme.count >= 2 && scheme.allSatisfy { $0.isLetter || $0.isNumber || "+.-".contains($0) }
376    }
377
378    private func path(for destination: String, image: Bool) -> String {
379        if let resolved = targets.link(destination, image) { return resolved }
380        if Self.isURL(destination) { return destination }
381        let decoded = destination.removingPercentEncoding ?? destination
382        return decoded.hasPrefix("#") ? decoded : "file:" + decoded
383    }
384
385    private func linkText(destination: String, text: ArraySlice<Character>) -> String {
386        links += 1
387        var description = convert(text).replacingOccurrences(of: "\n", with: " ")
388        // An image as the description is written as its path, which org shows as the image.
389        if description.hasPrefix("[["), description.hasSuffix("]]"), description.components(separatedBy: "[[").count == 2, !description.contains("][") {
390            description = String(description.dropFirst(2).dropLast(2))
391        }
392        let target = path(for: destination, image: false)
393        let path = target.hasPrefix("#") ? "*" + target.dropFirst() : target
394        if description.isEmpty || description == destination { return "[[" + MarkdownToOrg.escapeLinkPath(path) + "]]" }
395        return "[[" + MarkdownToOrg.escapeLinkPath(path) + "][" + description.replacingOccurrences(of: "]]", with: "] ]") + "]]"
396    }
397
398    private func image(destination: String, alt: ArraySlice<Character>) -> String {
399        links += 1
400        return "[[" + MarkdownToOrg.escapeLinkPath(path(for: destination, image: true)) + "]]"
401    }
402
403    /// `target#heading|alias`, `target#^block` or `target|300` for an embedded image.
404    private func wikilink(_ body: String, embed: Bool) -> String {
405        var target = body
406        var alias: String?
407        if let bar = body.firstIndex(of: "|") {
408            target = String(body[..<bar])
409            alias = String(body[body.index(after: bar)...]).trimmingCharacters(in: .whitespaces)
410        }
411        var fragment: String?
412        if let hash = target.firstIndex(of: "#") {
413            fragment = String(target[target.index(after: hash)...])
414            target = String(target[..<hash])
415        }
416        target = target.trimmingCharacters(in: .whitespaces)
417        guard let resolved = targets.wikilink(target, fragment, embed) else {
418            issues.append(.unresolvedLink(body))
419            return alias ?? body
420        }
421        links += 1
422        if embed, resolved.image { return "[[" + MarkdownToOrg.escapeLinkPath(resolved.path) + "]]" }
423        var description = alias.flatMap { $0.allSatisfy(\.isNumber) || $0.isEmpty ? nil : $0 }
424        if description == nil {
425            let name = target.isEmpty ? "" : (target as NSString).lastPathComponent
426            let heading = fragment.map { $0.split(separator: "#").last.map(String.init) ?? $0 }?.trimmingCharacters(in: CharacterSet(charactersIn: "^"))
427            description = [name, heading].compactMap { $0?.isEmpty == false ? $0 : nil }.joined(separator: " > ")
428        }
429        return "[[" + MarkdownToOrg.escapeLinkPath(resolved.path) + "][" + (description ?? target) + "]]"
430    }
431}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form