Commit d30c86872a

d30c86872ab1225085e90ee80d5bfab83d0b9ac3

parent: ad494f660e

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 19:44 UTC

Write plain links in LaTeX export as Emacs does, refusing types it doesn't write

Layout: unified · split

Sources/OrgCore/Export/ASCIIExport.swift +1 −1
@@ -1231,7 +1231,7 @@ final class ASCIIRenderer {
1231 private static let unrenderedTypes: Set<String> = ["attachment", "bbdb", "bibtex", "docview", "doi", "eww", "gnus", "info", "irc", "mhe", "rmail", "w3m"] 1231 private static let unrenderedTypes: Set<String> = ["attachment", "bbdb", "bibtex", "docview", "doi", "eww", "gnus", "info", "irc", "mhe", "rmail", "w3m"]
1232 1232
1233 /// `org-link-plain-re`, in any case, for the plain links the parser leaves as text. 1233 /// `org-link-plain-re`, in any case, for the plain links the parser leaves as text.
1234 private static let plainLink: NSRegularExpression = { 1234 static let plainLink: NSRegularExpression = {
1235 let plain = #"[^\[\]\s()<>]"# 1235 let plain = #"[^\[\]\s()<>]"#
1236 let parens = #"[<(\[](?:\#(plain)|[<(\[]\#(plain)*[\])>])*[\])>]"# 1236 let parens = #"[<(\[](?:\#(plain)|[<(\[]\#(plain)*[\])>])*[\])>]"#
1237 let types = "attachment|bbdb|bibtex|docview|doi|elisp|eww|file\\+emacs|file\\+sys|file|ftp|gnus|help|https?|id|info|irc|mailto|mhe|news|rmail|shell|shortdoc|w3m" 1237 let types = "attachment|bbdb|bibtex|docview|doi|elisp|eww|file\\+emacs|file\\+sys|file|ftp|gnus|help|https?|id|info|irc|mailto|mhe|news|rmail|shell|shortdoc|w3m"
Sources/OrgCore/Export/LaTeXExport.swift +50 −4
@@ -1293,6 +1293,8 @@ final class LaTeXRenderer {
1293 } 1293 }
1294 1294
1295 private var inTitle = false 1295 private var inTitle = false
1296 /// Whether text is a link's description, where Org finds no plain links.
1297 private var inDescription = false
1296 1298
1297 /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`), 1299 /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`),
1298 /// objects that export nothing taking their blanks with them unless they are needed. 1300 /// objects that export nothing taking their blanks with them unless they are needed.
@@ -1314,7 +1316,7 @@ final class LaTeXRenderer {
1314 } 1316 }
1315 dropBlanks = false 1317 dropBlanks = false
1316 afterObject = false 1318 afterObject = false
1317 out += plainText(t) 1319 out += try plainTextAndLinks(t)
1318 index += 1 1320 index += 1
1319 case .object(let node, let children): 1321 case .object(let node, let children):
1320 dropBlanks = false 1322 dropBlanks = false
@@ -1569,7 +1571,11 @@ final class LaTeXRenderer {
1569 1571
1570 private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? { 1572 private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
1571 let (type, path) = linkTarget(node) 1573 let (type, path) = linkTarget(node)
1574 let saved = inDescription
1575 inDescription = true
1576 defer { inDescription = saved }
1572 var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children) 1577 var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children)
1578 inDescription = saved
1573 if description == "" { description = nil } 1579 if description == "" { description = nil }
1574 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true { 1580 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
1575 throw Unsupported(reason: "Links in link descriptions") 1581 throw Unsupported(reason: "Links in link descriptions")
@@ -1604,9 +1610,7 @@ final class LaTeXRenderer {
1604 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") } 1610 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
1605 return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%") 1611 return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%")
1606 case "file": 1612 case "file":
1607 if path.hasPrefix("~") { throw Unsupported(reason: "File links under ~") } 1613 let protected = Self.protect(try fileURI(path))
1608 let uri = path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path
1609 let protected = Self.protect(uri)
1610 return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}" 1614 return description.map { "\\href{\(protected)}{\($0)}" } ?? "\\url{\(protected)}"
1611 case "http", "https", "ftp", "mailto", "news", "elisp", "shell", "help", "shortdoc": 1615 case "http", "https", "ftp", "mailto", "news", "elisp", "shell", "help", "shortdoc":
1612 let protected = Self.protect(type + ":" + path) 1616 let protected = Self.protect(type + ":" + path)
@@ -1616,6 +1620,48 @@ final class LaTeXRenderer {
1616 } 1620 }
1617 } 1621 }
1618 1622
1623 private func fileURI(_ path: String) throws -> String {
1624 if path.hasPrefix("~") { throw Unsupported(reason: "File links under ~") }
1625 return path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path
1626 }
1627
1628 /// Text with the plain links the parser leaves in it, `shell:ls` and the like, written as Emacs does.
1629 private func plainTextAndLinks(_ t: String) throws -> String {
1630 guard !inDescription else { return plainText(t) }
1631 let ns = t as NSString
1632 var out = ""
1633 var last = 0
1634 for m in ASCIIRenderer.plainLink.matches(in: t, range: NSRange(location: 0, length: ns.length)) {
1635 let type = ns.substring(with: m.range(at: 1))
1636 var path = ns.substring(with: NSRange(location: NSMaxRange(m.range(at: 1)) + 1, length: NSMaxRange(m.range) - NSMaxRange(m.range(at: 1)) - 1))
1637 var before = ns.substring(with: NSRange(location: last, length: m.range.location - last))
1638 if last > 0 {
1639 // The previous link's post-blank, which Emacs writes as spaces.
1640 let blanks = before.prefix { $0 == " " || $0 == "\t" }
1641 before = String(repeating: " ", count: blanks.count) + before.dropFirst(blanks.count)
1642 }
1643 out += plainText(before)
1644 let ext = (path as NSString).pathExtension.lowercased()
1645 switch type.lowercased() {
1646 case "file":
1647 if ["pdf", "jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"].contains(ext) { throw Unsupported(reason: "Plain image links") }
1648 if !path.hasPrefix("//"), let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) }
1649 out += "\\url{\(Self.protect(try fileURI(path)))}"
1650 case "http", "https", "ftp", "mailto", "news", "elisp", "shell", "help", "shortdoc":
1651 if ["jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"].contains(ext) { throw Unsupported(reason: "Plain image links") }
1652 out += "\\url{\(Self.protect(type + ":" + path))}"
1653 default:
1654 throw Unsupported(reason: "Plain links of type \(type)")
1655 }
1656 last = NSMaxRange(m.range)
1657 }
1658 guard last > 0 else { return plainText(t) }
1659 var rest = ns.substring(from: last)
1660 let blanks = rest.prefix { $0 == " " || $0 == "\t" }
1661 rest = String(repeating: " ", count: blanks.count) + rest.dropFirst(blanks.count)
1662 return out + plainText(rest)
1663 }
1664
1619 /// Words of a fuzzy link or a title, as `org-export-search-cells` compares them. 1665 /// Words of a fuzzy link or a title, as `org-export-search-cells` compares them.
1620 static func words(_ s: String) -> [String] { 1666 static func words(_ s: String) -> [String] {
1621 s.uppercased().split(whereSeparator: \.isWhitespace).map(String.init) 1667 s.uppercased().split(whereSeparator: \.isWhitespace).map(String.init)
Tests/OrgCoreTests/LaTeXExportTests.swift +6
@@ -107,6 +107,8 @@ struct LaTeXExportTests {
107 "Line one\\\\\nline two \\\\\n\\\\\nafter\n", 107 "Line one\\\\\nline two \\\\\n\\\\\nafter\n",
108 "Links: [[https://orgmode.org][Org & co]] <https://a.b/c_d> https://x.y/%20 [[mailto:me@x.org]] [[file:doc.pdf][the doc]] [[./rel/file.txt]] [[file:/abs/path.org]]\n", 108 "Links: [[https://orgmode.org][Org & co]] <https://a.b/c_d> https://x.y/%20 [[mailto:me@x.org]] [[file:doc.pdf][the doc]] [[./rel/file.txt]] [[file:/abs/path.org]]\n",
109 "Run [[elisp:(+ 1 2)][add]] and [[elisp:(message \"50% #x\")]], [[shell:ls ~/x_y][list]] [[shell:echo $HOME]], [[help:car][car]] [[shortdoc:string]].\n", 109 "Run [[elisp:(+ 1 2)][add]] and [[elisp:(message \"50% #x\")]], [[shell:ls ~/x_y][list]] [[shell:echo $HOME]], [[help:car][car]] [[shortdoc:string]].\n",
110 "Plain shell:ls and elisp:foo and help:car here.\nGet ftp://x.org/f now, news:comp.x and mailto:a@b.c, shortdoc:string HTTPS://a.b/c.\nshell:echo_$x% and shell:ls\tx shell:ls[x elisp:(foo) FILE:a.txt File:b.org::s FILE:/abs FILE://h/p.\n[[https://a.b][see shell:ls]] *shell:ls* and\n| news:x |\n",
111 "* Heading shell:ls\nx\n",
110 "Run [[elisp:(+ 1\n 2)]] and see [[https://a.b/c\n d]] ok, [[shell:a \n\tb][two\n lines]] and [[elisp:a\tb\n c]].\n", 112 "Run [[elisp:(+ 1\n 2)]] and see [[https://a.b/c\n d]] ok, [[shell:a \n\tb][two\n lines]] and [[elisp:a\tb\n c]].\n",
111 "* Target section\nA <<anchor>> here and [[anchor]] and [[anchor][desc]].\n* Other\nSee [[*Target section]] and [[Target section][named]] and [[#cid]].\n* Third\n:PROPERTIES:\n:CUSTOM_ID: cid\n:END:\nx\n", 113 "* Target section\nA <<anchor>> here and [[anchor]] and [[anchor][desc]].\n* Other\nSee [[*Target section]] and [[Target section][named]] and [[#cid]].\n* Third\n:PROPERTIES:\n:CUSTOM_ID: cid\n:END:\nx\n",
112 "#+OPTIONS: num:nil\n* Head\nSee [[*Head]].\n", 114 "#+OPTIONS: num:nil\n* Head\nSee [[*Head]].\n",
@@ -352,6 +354,10 @@ struct LaTeXExportTests {
352 let pre = "* Top\n:PROPERTIES:\n:EXPORT_LATEX_CLASS_PRE: \\x\n:END:\nBody.\n" 354 let pre = "* Top\n:PROPERTIES:\n:EXPORT_LATEX_CLASS_PRE: \\x\n:END:\nBody.\n"
353 #expect(ExportScope.subtree(pre, at: 0).flatMap(reason) == "#+LATEX_CLASS_PRE") 355 #expect(ExportScope.subtree(pre, at: 0).flatMap(reason) == "#+LATEX_CLASS_PRE")
354 #expect(reason("#+OPTIONS: tags:not-in-toc\n* 100% done :a:\n")?.hasPrefix("% in a heading") == true) 356 #expect(reason("#+OPTIONS: tags:not-in-toc\n* 100% done :a:\n")?.hasPrefix("% in a heading") == true)
357 #expect(reason("See id:abc.\n") == "Plain links of type id")
358 #expect(reason("See info:emacs here.\n") == "Plain links of type info")
359 #expect(reason("See FILE:a.png here.\n") == "Plain image links")
360 #expect(reason("See FILE:~/a here.\n") == "File links under ~")
355 } 361 }
356 362
357 @Test func labelsStayTheSame() throws { 363 @Test func labelsStayTheSame() throws {