Commit 848c7b1302

848c7b130274052f194a17fccd4e33e6bb30851d

parent: 85fc511ed2

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 09:20 UTC

Coderef and regexp links

[[(name)]] moves to the label in its src or example block (org-link-search), and export follows org-element's switches: labels removed, -n/+n line numbers, -r/-k, -l label formats, links resolved to the label or line number as org-export-resolve-coderef does, with coderef- anchors in HTML. [[/re/]] shows org-occur's sparse tree on the Mac and moves to the first match on iOS; it exports as text. Oracle-tested resolution and search.

Closes #43

Layout: unified · split

Sources/OrgApp/LinkFollow.swift +6 −1
@@ -43,7 +43,7 @@ extension DocumentSession {
43 } 43 }
44 return followFile(file, isText: isText) 44 return followFile(file, isText: isText)
45 case "coderef": 45 case "coderef":
46 return .message("Coderef links aren't supported") 46 return searchCurrent("(" + link.path + ")")
47 case "shell", "elisp": 47 case "shell", "elisp":
48 return .message("orgstar doesn't run \(link.type) links") 48 return .message("orgstar doesn't run \(link.type) links")
49 default: 49 default:
@@ -100,6 +100,11 @@ extension DocumentSession {
100 return .shown 100 return .shown
101 case .failed(let message): 101 case .failed(let message):
102 return .message(message) 102 return .message(message)
103 case .occur(let regexp):
104 // The first match; the Mac's editor shows the sparse tree.
105 guard let text = document?.text, let matches = try? SparseTree.occur(regexp, in: text) else { return .message("Invalid regexp: \(regexp)") }
106 if let first = matches.points.first { reveal(first) }
107 return .message("\(matches.points.count) match(es) for regexp \(regexp)")
103 } 108 }
104 } 109 }
105} 110}
Sources/OrgCore/Export/HTMLExport.swift +65 −3
@@ -175,8 +175,18 @@ final class HTMLRenderer {
175 175
176 // MARK: - Document 176 // MARK: - Document
177 177
178 /// The document's tree, for code references, and each src and example block's
179 /// `org-export-get-loc`, by the block's text, in order.
180 private var documentTree: OrgTree?
181 private var blockLocs: [String: [Int?]] = [:]
182
178 func document(_ text: String) -> String { 183 func document(_ text: String) -> String {
179 let tree = OrgParser.parse(text, defaults: settings) 184 let tree = OrgParser.parse(text, defaults: settings)
185 documentTree = tree
186 let codeBlocks = Coderef.blocks(tree)
187 for (lines, loc) in zip(codeBlocks, Coderef.locs(codeBlocks.compactMap(Coderef.block))) {
188 blockLocs[lines.joined(separator: "\n"), default: []].append(loc)
189 }
180 collectDefinitions(tree.root) 190 collectDefinitions(tree.root)
181 selected = Self.selection(tree, tags: options.selectTags) 191 selected = Self.selection(tree, tags: options.selectTags)
182 var out = "" 192 var out = ""
@@ -644,12 +654,14 @@ final class HTMLRenderer {
644 switch type { 654 switch type {
645 case "src": 655 case "src":
646 let language = parameters.split(separator: " ").first.map(String.init) 656 let language = parameters.split(separator: " ").first.map(String.init)
647 let source = dedent(unescaped).joined(separator: "\n") 657 let (lines, loc, switches, refs) = code(lines, dedent(unescaped))
658 let source = lines.joined(separator: "\n")
648 let code = language.flatMap { codeStyle?.html(language: $0, code: source) } ?? Self.escape(source) 659 let code = language.flatMap { codeStyle?.html(language: $0, code: source) } ?? Self.escape(source)
649 let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? "" 660 let cls = language.map { " class=\"language-\(Self.escape($0))\"" } ?? ""
650 return "<pre><code\(cls)>\(code)</code></pre>\n" 661 return "<pre><code\(cls)>\(numbered(code, loc: loc, refs: refs, retain: switches.retainLabels))</code></pre>\n"
651 case "example": 662 case "example":
652 return "<pre>\(Self.escape(dedent(unescaped).joined(separator: "\n")))</pre>\n" 663 let (lines, loc, switches, refs) = code(lines, dedent(unescaped))
664 return "<pre>\(numbered(Self.escape(lines.joined(separator: "\n")), loc: loc, refs: refs, retain: switches.retainLabels))</pre>\n"
653 case "quote": 665 case "quote":
654 return "<blockquote>\n\(blocks(text))</blockquote>\n" 666 return "<blockquote>\n\(blocks(text))</blockquote>\n"
655 case "center": 667 case "center":
@@ -669,6 +681,45 @@ final class HTMLRenderer {
669 } 681 }
670 } 682 }
671 683
684 /// A src or example block's code without its labels (`org-export-unravel-code`), the lines
685 /// numbered before it, its switches, and its labels by line.
686 private func code(_ block: [String], _ body: [String]) -> (lines: [String], loc: Int?, switches: Coderef.Switches, refs: [Int: String]) {
687 let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
688 let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
689 let key = block.joined(separator: "\n")
690 let loc = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil
691 return (lines, switches.numberLines == nil ? nil : loc, switches, refs)
692 }
693
694 /// `org-html-do-format-code`: lines numbered from `loc`, and lines with a label marked as
695 /// its `coderef-` anchor, the label kept after them with `retain`.
696 private func numbered(_ html: String, loc: Int?, refs: [Int: String], retain: Bool) -> String {
697 guard loc != nil || !refs.isEmpty else { return html }
698 let lines = Self.splitLines(html)
699 let width = loc.map { String($0 + lines.count).count } ?? 0
700 return lines.enumerated().map { index, line in
701 var out = loc.map { "<span class=\"linenr\">" + String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1): </span>" } ?? ""
702 out += line
703 guard let ref = refs[index + 1] else { return out }
704 if retain { out += " (\(Self.escape(ref)))" }
705 return "<span id=\"coderef-\(Self.escape(ref))\" class=\"coderef-off\">\(out)</span>"
706 }.joined(separator: "\n")
707 }
708
709 /// Highlighted code split into lines, spans open at a line's end closed there and opened
710 /// again on the next.
711 static func splitLines(_ html: String) -> [String] {
712 var open: [String] = []
713 return html.components(separatedBy: "\n").map { line in
714 var out = open.joined() + line
715 for m in line.matches(of: /<span[^>]*>|<\/span>/) {
716 if m.output.hasPrefix("</") { if !open.isEmpty { open.removeLast() } } else { open.append(String(m.output)) }
717 }
718 out += String(repeating: "</span>", count: open.count)
719 return out
720 }
721 }
722
672 private func dedent(_ lines: [String]) -> [String] { 723 private func dedent(_ lines: [String]) -> [String] {
673 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count } 724 let indents = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }
674 let common = indents.min() ?? 0 725 let common = indents.min() ?? 0
@@ -807,6 +858,17 @@ final class HTMLRenderer {
807 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) } 858 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
808 return "<a href=\"\(Self.escape(target))\">\(Self.escape(target))</a>" 859 return "<a href=\"\(Self.escape(target))\">\(Self.escape(target))</a>"
809 } 860 }
861 // A code reference: the label, or its line's number.
862 if path.hasPrefix("("), path.hasSuffix(")"), path.count >= 2 {
863 let name = String(path.dropFirst().dropLast())
864 let resolved = documentTree.flatMap { Coderef.resolve(name, in: $0) } ?? name
865 let text = Coderef.linkText(resolved, description: description.map { $0.text })
866 return "<a href=\"#coderef-\(Self.escape(name))\" class=\"coderef\">\(Self.escape(text))</a>"
867 }
868 // A regexp search has nowhere to go in the export.
869 if path.count >= 2, path.hasPrefix("/"), path.hasSuffix("/") {
870 return description.map(inline) ?? Self.escape(path)
871 }
810 var href = path 872 var href = path
811 var label = path 873 var label = path
812 if path.hasPrefix("file:") { 874 if path.hasPrefix("file:") {
Sources/OrgCore/Export/MarkdownExport.swift +36 −2
@@ -42,8 +42,18 @@ final class MarkdownRenderer {
42 self.options = options 42 self.options = options
43 } 43 }
44 44
45 /// The document's tree, for code references, and each src and example block's
46 /// `org-export-get-loc`, by the block's text, in order.
47 private var documentTree: OrgTree?
48 private var blockLocs: [String: [Int?]] = [:]
49
45 func document(_ text: String) -> String { 50 func document(_ text: String) -> String {
46 let tree = OrgParser.parse(text, defaults: settings) 51 let tree = OrgParser.parse(text, defaults: settings)
52 documentTree = tree
53 let codeBlocks = Coderef.blocks(tree)
54 for (lines, loc) in zip(codeBlocks, Coderef.locs(codeBlocks.compactMap(Coderef.block))) {
55 blockLocs[lines.joined(separator: "\n"), default: []].append(loc)
56 }
47 for node in tree.root.descendants() where node.kind == .footnoteDefinition { 57 for node in tree.root.descendants() where node.kind == .footnoteDefinition {
48 if let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) { 58 if let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
49 definitions[String(m.1)] = String(node.text[m.range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines) 59 definitions[String(m.1)] = String(node.text[m.range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
@@ -226,9 +236,9 @@ final class MarkdownRenderer {
226 body = body.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) } 236 body = body.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
227 switch type { 237 switch type {
228 case "src": 238 case "src":
229 return fence(body, language: parameters.split(separator: " ").first.map(String.init) ?? "", indent: indent) 239 return fence(code(lines, body), language: parameters.split(separator: " ").first.map(String.init) ?? "", indent: indent)
230 case "example": 240 case "example":
231 return fence(body, language: "", indent: indent) 241 return fence(code(lines, body), language: "", indent: indent)
232 case "quote": 242 case "quote":
233 return blocks(text: body.joined(separator: "\n")).trimmingCharacters(in: .newlines) 243 return blocks(text: body.joined(separator: "\n")).trimmingCharacters(in: .newlines)
234 .components(separatedBy: "\n").map { indent + ($0.isEmpty ? ">" : "> " + $0) }.joined(separator: "\n") 244 .components(separatedBy: "\n").map { indent + ($0.isEmpty ? ">" : "> " + $0) }.joined(separator: "\n")
@@ -331,6 +341,22 @@ final class MarkdownRenderer {
331 } 341 }
332 } 342 }
333 343
344 /// `org-export-format-code-default`: the code without its labels, numbered as the block's
345 /// switches say, a label kept after its line with `retain`.
346 private func code(_ block: [String], _ body: [String]) -> [String] {
347 let switches = Coderef.block(block)?.switches ?? Coderef.Switches(nil)
348 let (lines, refs) = Coderef.unravel(body, format: switches.labelFormat)
349 let key = block.joined(separator: "\n")
350 let stored = blockLocs[key]?.isEmpty == false ? blockLocs[key]!.removeFirst() : nil
351 let loc = switches.numberLines == nil ? nil : stored
352 let width = loc.map { String($0 + lines.count).count } ?? 0
353 return lines.enumerated().map { index, line in
354 let number = loc.map { String(repeating: " ", count: max(0, width - String($0 + index + 1).count)) + "\($0 + index + 1) " } ?? ""
355 let label = switches.retainLabels ? refs[index + 1].map { " (\($0))" } ?? "" : ""
356 return number + line + label
357 }
358 }
359
334 private func link(_ node: SyntaxNode) -> String { 360 private func link(_ node: SyntaxNode) -> String {
335 guard let path = node.tokens.first(where: { $0.kind == .linkPath })?.text else { 361 guard let path = node.tokens.first(where: { $0.kind == .linkPath })?.text else {
336 // A radio link is its text. 362 // A radio link is its text.
@@ -339,6 +365,14 @@ final class MarkdownRenderer {
339 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) } 365 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
340 return "<\(target)>" 366 return "<\(target)>"
341 } 367 }
368 // A code reference is its label or its line's number; a regexp search has nowhere to go.
369 if path.hasPrefix("("), path.hasSuffix(")"), path.count >= 2 {
370 let name = String(path.dropFirst().dropLast())
371 return Coderef.linkText(documentTree.flatMap { Coderef.resolve(name, in: $0) } ?? name, description: node.firstChild(.linkDescription)?.text)
372 }
373 if path.count >= 2, path.hasPrefix("/"), path.hasSuffix("/") {
374 return node.firstChild(.linkDescription).map(inline) ?? path
375 }
342 var href = path 376 var href = path
343 if path.hasPrefix("file:") { 377 if path.hasPrefix("file:") {
344 // ox-md drops the search option and, as `org-md-link-org-files-as-md`, writes .org as .md. 378 // ox-md drops the search option and, as `org-md-link-org-files-as-md`, writes .org as .md.
Sources/OrgCore/Links/Coderef.swift added +145
@@ -0,0 +1,145 @@
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}
Sources/OrgCore/Links/Links.swift +12 −2
@@ -206,6 +206,15 @@ public enum Links {
206 public enum SearchResult: Sendable, Equatable { 206 public enum SearchResult: Sendable, Equatable {
207 case found(Int) 207 case found(Int)
208 case failed(String) 208 case failed(String)
209 /// `/regexp/`: `org-occur`'s sparse tree for the regular expression.
210 case occur(String)
211 }
212
213 /// The regular expression of a `[[/regexp/]]` link or a `file:…::/regexp/` search.
214 public static func regexpSearch(_ link: OrgLink) -> String? {
215 let s = link.type == "fuzzy" ? link.path : link.type == "file" ? (link.searchOption ?? "") : ""
216 guard s.count >= 2, s.hasPrefix("/"), s.hasSuffix("/") else { return nil }
217 return String(s.dropFirst().dropLast())
209 } 218 }
210 219
211 /// `org-link-search` in an org file: a `#custom-id`, a `<<target>>`, a `#+NAME:`, or a 220 /// `org-link-search` in an org file: a `#custom-id`, a `<<target>>`, a `#+NAME:`, or a
@@ -227,10 +236,11 @@ public enum Links {
227 return .failed("No match for custom ID: \(id)") 236 return .failed("No match for custom ID: \(id)")
228 } 237 }
229 if normalized.hasPrefix("("), normalized.hasSuffix(")") { 238 if normalized.hasPrefix("("), normalized.hasSuffix(")") {
230 return .failed("Coderef links aren't supported") 239 let name = String(normalized.dropFirst().dropLast())
240 return Coderef.search(name, text: text, tree: tree).map(SearchResult.found) ?? .failed("No match for coderef: \(name)")
231 } 241 }
232 if normalized.count >= 2, normalized.hasPrefix("/"), normalized.hasSuffix("/") { 242 if normalized.count >= 2, normalized.hasPrefix("/"), normalized.hasSuffix("/") {
233 return .failed("Regexp links aren't supported") 243 return .occur(String(s.dropFirst().dropLast()))
234 } 244 }
235 let quoted = words.map(NSRegularExpression.escapedPattern(for:)) 245 let quoted = words.map(NSRegularExpression.escapedPattern(for:))
236 if !starred { 246 if !starred {
Sources/Orgstar/ContentView.swift +4
@@ -614,6 +614,10 @@ struct ContentView: View {
614 switch request { 614 switch request {
615 case .openLink(let link): 615 case .openLink(let link):
616 if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) } 616 if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
617 // `org-occur` for a regexp link, once the editor shows the file.
618 if let regexp = Links.regexpSearch(link) {
619 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
620 }
617 case .tangle(let scope): 621 case .tangle(let scope):
618 commands.show(session.tangle(scope)) 622 commands.show(session.tangle(scope))
619 case .agenda(let start, let days): 623 case .agenda(let start, let days):
Tests/OrgCoreTests/CoderefTests.swift added +73
@@ -0,0 +1,73 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct CoderefTests {
6 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
7
8 static let text = """
9 * Code
10 #+begin_src python -n
11 def f(): (ref:def)
12 return 1 (ref:ret)
13 #+end_src
14
15 #+begin_src python +n 10 -r
16 x = f() (ref:call)
17 print(x)
18 #+end_src
19
20 #+begin_example -n -r -k
21 first
22 second (ref:kept)
23 #+end_example
24
25 #+begin_src sh -l "<<%s>>"
26 echo hi <<echo>>
27 #+end_src
28
29 See [[(def)]], [[(call)][line %s]], [[(kept)]] and [[(echo)]].
30
31 """
32
33 @Test(.enabled(if: oracle))
34 func resolvesLikeOrgExport() throws {
35 let tree = OrgParser.parse(Self.text)
36 let refs = ["def", "ret", "call", "kept", "echo"]
37 let form = "(require 'ox) (let ((info (list :parse-tree (org-element-parse-buffer)))) (mapcar (lambda (r) (format \"%s\" (org-export-resolve-coderef r info))) '(\(refs.map { "\"\($0)\"" }.joined(separator: " ")))))"
38 let emacs = try EmacsOracle.evaluate(Self.text, "(progn \(form))")
39 #expect(refs.map { Coderef.resolve($0, in: tree) ?? "" } == emacs)
40 }
41
42 @Test(.enabled(if: oracle))
43 func followsLikeOrgLinkSearch() throws {
44 let tree = OrgParser.parse(Self.text)
45 let refs = ["def", "ret", "call", "kept", "echo"]
46 let form = "(mapcar (lambda (r) (goto-char (point-min)) (org-link-search (format \"(%s)\" r)) (number-to-string (1- (point)))) '(\(refs.map { "\"\($0)\"" }.joined(separator: " "))))"
47 let emacs = try EmacsOracle.evaluate(Self.text, form)
48 let ours = refs.map { ref -> String in
49 if case .found(let offset) = Links.search("(\(ref))", text: Self.text, tree: tree) { return String(offset) }
50 return "none"
51 }
52 #expect(ours == emacs.map { String(EmacsOracle.offset(Int($0)! + 1, in: Self.text)) })
53 #expect(Links.search("(missing)", text: Self.text, tree: tree) == .failed("No match for coderef: missing"))
54 #expect(Links.search("/ret.*1/", text: Self.text, tree: tree) == .occur("ret.*1"))
55 }
56
57 @Test func exportsLabelsAndNumbers() {
58 let html = HTMLExport.body(Self.text)
59 #expect(html.contains("<span id=\"coderef-def\" class=\"coderef-off\"><span class=\"linenr\">1: </span>def f(): (def)</span>"), "\(html)")
60 #expect(html.contains("<span class=\"linenr\">13: </span>print(x)"))
61 #expect(html.contains("<a href=\"#coderef-def\" class=\"coderef\">def</a>"))
62 #expect(html.contains("<a href=\"#coderef-call\" class=\"coderef\">line 12</a>"))
63 #expect(html.contains("<a href=\"#coderef-kept\" class=\"coderef\">2</a>"))
64 #expect(html.contains("echo hi (echo)"))
65 let markdown = MarkdownExport.document(Self.text)
66 #expect(markdown.contains("12 x = f()\n13 print(x)"), "\(markdown)")
67 #expect(markdown.contains("See def, line 12, 2 and echo."))
68 }
69
70 @Test func splitsHighlightedLines() {
71 #expect(HTMLRenderer.splitLines("<span class=\"s\">a\nb</span> c") == ["<span class=\"s\">a</span>", "<span class=\"s\">b</span> c"])
72 }
73}
Tests/OrgCoreTests/LinkTests.swift +6 −2
@@ -82,9 +82,13 @@ struct LinkTests {
82 let ours: String = switch Links.search(s, text: Self.searchText, tree: tree) { 82 let ours: String = switch Links.search(s, text: Self.searchText, tree: tree) {
83 case .found(let offset): "at \(EmacsOracle.point(offset, in: Self.searchText))" 83 case .found(let offset): "at \(EmacsOracle.point(offset, in: Self.searchText))"
84 case .failed(let message): message 84 case .failed(let message): message
85 case .occur(let regexp): "occur \(regexp)"
86 }
87 // Org opens a sparse tree for regexps.
88 if s == "/re/" {
89 #expect(ours == "occur re")
90 continue
85 } 91 }
86 // Org opens a sparse tree for regexps and finds coderefs only in blocks; Orgstar says so.
87 if s == "(ref)" || s == "/re/" { continue }
88 #expect(ours == expected, "\(s)") 92 #expect(ours == expected, "\(s)")
89 } 93 }
90 } 94 }
docs/manual/guide/09-links.org +11 −1
@@ -59,7 +59,8 @@ A message in the echo area explains a link that can't be followed.
59| Custom ID | =[[#setup]]= | Moves to the heading in this file whose =CUSTOM_ID= property is =setup=. | 59| Custom ID | =[[#setup]]= | Moves to the heading in this file whose =CUSTOM_ID= property is =setup=. |
60| Heading | =[[*Weekly review]]= | Moves to the heading in this file with that title. | 60| Heading | =[[*Weekly review]]= | Moves to the heading in this file with that title. |
61| Text | =[[budget table]]= | Searches this file: a =<<budget table>>= target, then =#+NAME: budget table=, then a heading. | 61| Text | =[[budget table]]= | Searches this file: a =<<budget table>>= target, then =#+NAME: budget table=, then a heading. |
62| Coderef | =[[(ref)]]= | Not supported. The echo area says so. | 62| Coderef | =[[(ref)]]= | Moves to the label =(ref:ref)= in a src or example block; see /Code references/ below. |
63| Regexp | =[[/TODO.*soon/]]= | Shows a sparse tree of the regular expression's matches, as =org-occur=; iOS moves to the first match. |
63| =shell=, =elisp= | =[[shell:ls]]= | Not run. orgstar never executes these links. | 64| =shell=, =elisp= | =[[shell:ls]]= | Not run. orgstar never executes these links. |
64| =attachment= | =[[attachment:scan.pdf]]= | Opens the file in the entry's attachment folder; see /Attachment links/ below. | 65| =attachment= | =[[attachment:scan.pdf]]= | Opens the file in the entry's attachment folder; see /Attachment links/ below. |
65| Radio link | Text matching a =<<<radio target>>>= | Moves to the radio target. | 66| Radio link | Text matching a =<<<radio target>>>= | Moves to the radio target. |
@@ -343,3 +344,12 @@ are in Commands, and on a hardware keyboard the Emacs keys run them; they work a
343described above, and stored links last until the app quits. =org-protocol://store-link= 344described above, and stored links last until the app quits. =org-protocol://store-link=
344links opened on the device are stored and copied too. The backlinks pane is Mac only. 345links opened on the device are stored and copied too. The backlinks pane is Mac only.
345See [[file:14-ios.org][iOS]]. 346See [[file:14-ios.org][iOS]].
347
348* Code references
349
350A label at the end of a line in a src or example block, =(ref:name)= by default, is a code reference, and =[[(name)]]= links to it. Following the link moves to the label. A block's =-l "<<%s>>"= switch changes the label's form for that block; =%s= is the name.
351
352In export, the label is taken off the line. A block with =-n= numbers its lines from 1, or =-n 10= from 10; =+n= goes on from the numbers of the blocks before it. =-r= leaves the label out of the exported line, and then the link shows the line's number instead of the name; =-k= with =-n= keeps the label while the link still shows the number. A link's description may contain =%s= for the name or number: =[[(call)][line %s]]=. In HTML, the line with the label is the link's target, =coderef-name=.
353
354A regexp link, or a =file:…::/regexp/= search, exports as its description, or its text when it has none.
355
docs/manual/guide/12-export.org +1 −1
@@ -158,7 +158,7 @@ Links to =.org= files point to the =.html= file of the same name. Links to headi
158 158
159** Source blocks and their results 159** Source blocks and their results
160 160
161A source block is exported as =<pre><code class="language-LANG">=, with the code escaped and its common indentation removed. Code in a language the editor highlights is colored as the editor colors it: each token is a =<span>= with the class Emacs's htmlize gives its face (=org-keyword=, =org-string=, =org-comment=, =org-function-name=, =org-type=, =org-constant=, =org-property-name=, =org-variable-name=), and the page's stylesheet colors them with the theme's =syntax-= colors, light and dark. Other languages are exported plain; the =language-= class lets a script or stylesheet in =#+HTML_HEAD= highlight them. Noweb references are shown as written. Line-number switches are ignored. 161A source block is exported as =<pre><code class="language-LANG">=, with the code escaped and its common indentation removed. Code in a language the editor highlights is colored as the editor colors it: each token is a =<span>= with the class Emacs's htmlize gives its face (=org-keyword=, =org-string=, =org-comment=, =org-function-name=, =org-type=, =org-constant=, =org-property-name=, =org-variable-name=), and the page's stylesheet colors them with the theme's =syntax-= colors, light and dark. Other languages are exported plain; the =language-= class lets a script or stylesheet in =#+HTML_HEAD= highlight them. Noweb references are shown as written. Code references are covered in [[file:09-links.org][Links]]: labels come off the lines, =-n= and =+n= number them, and =[[(name)]]= links to the labelled line.
162 162
163The block's =:exports= header argument decides what appears. orgstar resolves it as running the block would: from the =#+begin_src= line, =#+HEADER:= lines, =header-args= properties and =#+PROPERTY:= lines (see [[file:11-code-blocks.org][Code blocks]]). Without one, it is =results= for =dot=, =plantuml=, =ditaa=, =gnuplot=, =latex= and =lilypond= blocks, as their Org defaults set it, and =code= for other languages. 163The block's =:exports= header argument decides what appears. orgstar resolves it as running the block would: from the =#+begin_src= line, =#+HEADER:= lines, =header-args= properties and =#+PROPERTY:= lines (see [[file:11-code-blocks.org][Code blocks]]). Without one, it is =results= for =dot=, =plantuml=, =ditaa=, =gnuplot=, =latex= and =lilypond= blocks, as their Org defaults set it, and =code= for other languages.
164 164