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