Sources/OrgCore/Links/Coderef.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/OrgCore/Links/Coderef.swift history · blame · raw

145 lines · 7484 bytes

  1import Foundation
  2
  3// Code references (Org 9.8.7): labels such as `(ref:name)` at the end of lines in src and
  4// example blocks, the switches that number lines and strip labels, and `[[(name)]]` links.
  5
  6public enum Coderef {
  7    /// `org-coderef-label-format`.
  8    public static let defaultFormat = "(ref:%s)"
  9
 10    /// A block's switches, as `org-element-src-block-parser` reads them.
 11    public struct Switches: Sendable, Equatable {
 12        /// `-n` (`new`) or `+n` (continued) and the lines before the first: `-n 10` is 9.
 13        public var numberLines: (continued: Bool, before: Int)?
 14        public var retainLabels = true
 15        public var useLabels = true
 16        public var labelFormat = Coderef.defaultFormat
 17
 18        public static func == (a: Switches, b: Switches) -> Bool {
 19            a.numberLines?.continued == b.numberLines?.continued && a.numberLines?.before == b.numberLines?.before
 20                && a.retainLabels == b.retainLabels && a.useLabels == b.useLabels && a.labelFormat == b.labelFormat
 21        }
 22
 23        public init(_ switches: String?) {
 24            guard let switches, !switches.isEmpty else { return }
 25            if let m = switches.firstMatch(of: /([-+])n(?: *([0-9]+))?\b/) {
 26                numberLines = (m.1 == "+", m.2.flatMap { Int($0) }.map { $0 - 1 } ?? 0)
 27            }
 28            let r = switches.contains(/-r\b/)
 29            let k = switches.contains(/-k\b/)
 30            retainLabels = !r || (numberLines != nil && k)
 31            useLabels = retainLabels && !k
 32            if let m = switches.firstMatch(of: /-l +"([^"\n]+)"/) { labelFormat = String(m.1) }
 33        }
 34    }
 35
 36    /// A src or example block's switches and its code, commas unescaped, from its lines.
 37    public static func block(_ lines: [String]) -> (switches: Switches, body: [String])? {
 38        guard let first = lines.first else { return nil }
 39        let switches: String?
 40        if let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin_src)(?: +\S+)?((?: +(?:-(?:l ".+"|[ikr])|[-+]n(?: *[0-9]+)?))+)?/) {
 41            switches = m.1.map(String.init)
 42        } else if let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin_example)(?: +(.*))?/) {
 43            switches = m.1.map(String.init)
 44        } else {
 45            return nil
 46        }
 47        var body = Array(lines.dropFirst())
 48        if let last = body.last, last.range(of: "^[ \\t]*#\\+(?i:end_)", options: .regularExpression) != nil { body.removeLast() }
 49        body = body.map { $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) }
 50        return (Switches(switches), body)
 51    }
 52
 53    /// `org-src-coderef-regexp`: group 1 the label with the blanks around it, 2 without them,
 54    /// 3 the name.
 55    public static func regex(_ format: String, label: String? = nil) -> NSRegularExpression {
 56        let name = label.map(NSRegularExpression.escapedPattern(for:)) ?? "([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*)"
 57        let pattern = NSRegularExpression.escapedPattern(for: format).replacingOccurrences(of: "%s", with: name)
 58        return try! NSRegularExpression(pattern: "([ \\t]*(" + pattern + ")[ \\t]*)$")
 59    }
 60
 61    /// `org-export-unravel-code`: the lines without their labels, and the label on each line
 62    /// that had one, by line (1-based).
 63    public static func unravel(_ lines: [String], format: String) -> (code: [String], refs: [Int: String]) {
 64        let re = regex(format)
 65        var refs: [Int: String] = [:]
 66        let code = lines.enumerated().map { index, line -> String in
 67            let ns = line as NSString
 68            guard let m = re.firstMatch(in: line, range: NSRange(location: 0, length: ns.length)) else { return line }
 69            refs[index + 1] = ns.substring(with: m.range(at: 3))
 70            return ns.replacingCharacters(in: m.range(at: 1), with: "")
 71        }
 72        return (code, refs)
 73    }
 74
 75    /// The src and example blocks of `text`, in order, as their lines.
 76    static func blocks(_ tree: OrgTree) -> [[String]] {
 77        tree.root.descendants().filter { $0.kind == .block }.compactMap { node in
 78            var lines = node.text.components(separatedBy: "\n")
 79            if lines.last == "" { lines.removeLast() }
 80            return block(lines) == nil ? nil : lines
 81        }
 82    }
 83
 84    /// `org-export-get-loc` for each block: the lines numbered before its first, or nil.
 85    public static func locs(_ blocks: [(switches: Switches, body: [String])]) -> [Int?] {
 86        var loc = 0
 87        return blocks.map { block in
 88            guard let numbering = block.switches.numberLines else { return nil }
 89            let mine = numbering.continued ? loc + numbering.before : numbering.before
 90            let lines = block.body.count
 91            loc = numbering.continued ? loc + numbering.before + lines : numbering.before + lines
 92            return mine
 93        }
 94    }
 95
 96    /// `org-export-resolve-coderef`: the label, or its line's number for blocks that number
 97    /// lines instead; nil when no block has it.
 98    public static func resolve(_ ref: String, in tree: OrgTree) -> String? {
 99        let parsed = blocks(tree).compactMap(block)
100        let locs = locs(parsed)
101        for (block, loc) in zip(parsed, locs) {
102            let lines = trimmedLines(block.body)
103            let re = regex(block.switches.labelFormat, label: ref)
104            guard let index = lines.lastIndex(where: { re.firstMatch(in: $0, range: NSRange(location: 0, length: ($0 as NSString).length)) != nil }) else { continue }
105            return block.switches.useLabels ? ref : String((loc ?? 0) + index + 1)
106        }
107        return nil
108    }
109
110    /// `org-trim` of the block's value, as lines.
111    static func trimmedLines(_ body: [String]) -> [String] {
112        let text = body.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
113        return text.components(separatedBy: "\n")
114    }
115
116    /// `org-export-get-coderef-format`: a description with `%s` is the format, another one
117    /// replaces the reference.
118    public static func linkText(_ resolved: String, description: String?) -> String {
119        guard let description, !description.isEmpty else { return resolved }
120        return description.contains("%s") ? description.replacingOccurrences(of: "%s", with: resolved) : description
121    }
122
123    /// `org-link-search` for `(name)`: the start of the label in the block that has it.
124    static func search(_ name: String, text: String, tree: OrgTree) -> Int? {
125        let ns = text as NSString
126        for node in tree.root.descendants() where node.kind == .block {
127            var lines = node.text.components(separatedBy: "\n")
128            if lines.last == "" { lines.removeLast() }
129            guard let parsed = block(lines) else { continue }
130            let re = regex(parsed.switches.labelFormat, label: name)
131            // The block's lines after its first.
132            var start = NSMaxRange(ns.lineRange(for: NSRange(location: node.range.lowerBound, length: 0)))
133            while start < node.range.upperBound {
134                let range = ns.lineRange(for: NSRange(location: start, length: 0))
135                var line = ns.substring(with: range)
136                if line.hasSuffix("\n") { line.removeLast() }
137                if let m = re.firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) {
138                    return range.location + m.range(at: 2).location
139                }
140                start = NSMaxRange(range)
141            }
142        }
143        return nil
144    }
145}