Commit 9eb6f4c04a

9eb6f4c04a55eaffdec91ebfb1793694c8c2aecf

parent: d11e92f195

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 20:35 UTC

End link descriptions at the first ]], read CRLF link paths, refuse plain links into objects

Bracket link descriptions run to the first ]] as org-link-bracket-re reads
them. Link paths collapse CRLF line breaks. LaTeX export refuses a plain
link that runs on into an object or macro, and strips ::search before
checking a FILE: link for an image.

Layout: unified · split

Sources/OrgCore/Export/LaTeXExport.swift +34 −6
@@ -64,7 +64,15 @@ public enum LaTeXExport {
6464 if included.contains("{{{") {
6565 if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") }
6666 let ns = included as NSString
67 let kept = OrgParser.parse(included, defaults: settings).root.descendants()
67 let nodes = OrgParser.parse(included, defaults: settings).root.descendants()
68 // A macro a plain link runs on into is part of the link in Org, not expanded.
69 let links = ASCIIRenderer.plainLink.matches(in: included, range: NSRange(location: 0, length: ns.length)).map(\.range)
70 for macro in nodes where macro.kind == .macro {
71 if links.contains(where: { $0.location < macro.range.lowerBound && NSMaxRange($0) > macro.range.lowerBound }) {
72 throw LaTeXExport.Unsupported(reason: "Plain links running into other objects")
73 }
74 }
75 let kept = nodes
6876 .filter { [.verbatim, .code, .block, .fixedWidth, .comment, .latexEnvironment, .exportSnippet].contains($0.kind) }.map(\.range)
6977 var out = ""
7078 var at = 0
@@ -1299,6 +1307,7 @@ final class LaTeXRenderer {
12991307 /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`),
13001308 /// objects that export nothing taking their blanks with them unless they are needed.
13011309 func transcode(_ items: [Inline]) throws -> String {
1310 if !inDescription { try refusePlainLinksIntoObjects(items) }
13021311 var out = ""
13031312 var index = 0
13041313 var dropBlanks = false
@@ -1580,10 +1589,6 @@ final class LaTeXRenderer {
15801589 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
15811590 throw Unsupported(reason: "Links in link descriptions")
15821591 }
1583 // Org's description ends at the first `]]`, where the parser's ends at the balancing `]`.
1584 if let d = node.firstChild(.linkDescription)?.text, (d.dropFirst() + "]").contains("]]") {
1585 throw Unsupported(reason: "]] in link descriptions")
1586 }
15871592 if let d = node.firstChild(.linkDescription)?.text, d.firstMatch(of: /^(?:[A-Za-z]+:\S+|<[^>]+>)$/) != nil {
15881593 throw Unsupported(reason: "Images as link descriptions")
15891594 }
@@ -1629,6 +1634,29 @@ final class LaTeXRenderer {
16291634 return path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path
16301635 }
16311636
1637 /// Org matches `org-link-plain-re` on the source, so a plain link the parser leaves as text
1638 /// can run on into what the parser reads as an object after it, such as `shell:a_b`.
1639 private func refusePlainLinksIntoObjects(_ items: [Inline]) throws {
1640 var raw = ""
1641 var textRuns: [(start: Int, end: Int)] = []
1642 for item in items {
1643 let start = (raw as NSString).length
1644 switch item {
1645 case .text(let t):
1646 raw += t
1647 textRuns.append((start, (raw as NSString).length))
1648 case .object(let node, _):
1649 raw += node.text
1650 }
1651 }
1652 guard textRuns.count < items.count else { return }
1653 for m in ASCIIRenderer.plainLink.matches(in: raw, range: NSRange(location: 0, length: (raw as NSString).length)) {
1654 if let text = textRuns.first(where: { $0.start <= m.range.location && m.range.location < $0.end }), NSMaxRange(m.range) > text.end {
1655 throw Unsupported(reason: "Plain links running into other objects")
1656 }
1657 }
1658 }
1659
16321660 /// Text with the plain links the parser leaves in it, `shell:ls` and the like, written as Emacs does.
16331661 private func plainTextAndLinks(_ t: String) throws -> String {
16341662 guard !inDescription else { return plainText(t) }
@@ -1645,11 +1673,11 @@ final class LaTeXRenderer {
16451673 before = String(repeating: " ", count: blanks.count) + before.dropFirst(blanks.count)
16461674 }
16471675 out += plainText(before)
1676 if type.lowercased() == "file", !path.hasPrefix("//"), let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) }
16481677 let ext = (path as NSString).pathExtension.lowercased()
16491678 switch type.lowercased() {
16501679 case "file":
16511680 if ["pdf", "jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"].contains(ext) { throw Unsupported(reason: "Plain image links") }
1652 if !path.hasPrefix("//"), let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) }
16531681 out += "\\url{\(Self.protect(try fileURI(path)))}"
16541682 case "http", "https", "ftp", "mailto", "news", "elisp", "shell", "help", "shortdoc":
16551683 if ["jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"].contains(ext) { throw Unsupported(reason: "Plain image links") }
Sources/OrgCore/Parser/Inline.swift +4 −12
@@ -312,19 +312,11 @@ struct InlineScanner {
312312 let path = (i + 2)..<j
313313 if chars[j + 1] == "]" { return .link(path: path, description: nil, whole: i..<(j + 2)) }
314314 guard chars[j + 1] == "[" else { return nil }
315 // `org-link-bracket-re`: the description is at least one character, up to the first `]]`.
315316 let descriptionStart = j + 2
316 var depth = 0
317 var k = descriptionStart
318 while k < limit {
319 if chars[k] == "[" {
320 depth += 1
321 } else if chars[k] == "]" {
322 if depth == 0 { break }
323 depth -= 1
324 }
325 k += 1
326 }
327 guard k > descriptionStart, k + 1 < limit, chars[k + 1] == "]" else { return nil }
317 var k = descriptionStart + 1
318 while k + 1 < limit, !(chars[k] == "]" && chars[k + 1] == "]") { k += 1 }
319 guard k + 1 < limit else { return nil }
328320 return .link(path: path, description: descriptionStart..<k, whole: i..<(k + 2))
329321 }
330322
Sources/OrgCore/Syntax/SyntaxNode.swift +1 −1
@@ -107,7 +107,7 @@ public final class SyntaxNode: Sendable {
107107 /// A bracket link's path as `org-element-link-parser` reads it: each run of blanks
108108 /// holding a newline made one space.
109109 var linkPath: String? {
110 tokens.first { $0.kind == .linkPath }.map { $0.text.replacing(/[ \t]*\n[ \t]*/, with: " ") }
110 tokens.first { $0.kind == .linkPath }.map { $0.text.replacing(/[ \t]*\r?\n[ \t]*/.matchingSemantics(.unicodeScalar), with: " ") }
111111 }
112112}
113113
Tests/OrgCoreTests/InlineTests.swift +9
@@ -50,6 +50,15 @@ struct InlineTests {
5050 @Test func linkPathsSpanLines() {
5151 let links = OrgParser.parse("[[elisp:(+ 1\n 2)]] and [[a \n\tb][c]]\n\n[[x\n\ny]]\n").root.descendants().filter { $0.kind == .link }
5252 #expect(links.map(\.linkPath) == ["elisp:(+ 1 2)", "a b"])
53 let crlf = OrgParser.parse("[[elisp:(+ 1\r\n 2)]] ok\r\n").root.descendants().filter { $0.kind == .link }
54 #expect(crlf.map(\.linkPath) == ["elisp:(+ 1 2)"])
55 }
56
57 /// `org-link-bracket-re`: a description runs to the first `]]`, brackets in it balanced or not.
58 @Test func linkDescriptionsEndAtFirstDoubleBracket() {
59 let text = "[[a][x]b]] [[a][x [y]] [[a][]x]] [[a][[z]]]\n"
60 let descriptions = OrgParser.parse(text).root.descendants().filter { $0.kind == .linkDescription }.map(\.text)
61 #expect(descriptions == ["x]b", "x [y", "]x", "[z"])
5362 }
5463
5564 @Test func noLinksInsideLinkDescriptions() {
Tests/OrgCoreTests/LaTeXExportTests.swift +13 −2
@@ -110,6 +110,9 @@ struct LaTeXExportTests {
110110 "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",
111111 "* Heading shell:ls\nx\n",
112112 "[[https://a.b][[x] y]] and [[https://a.b][x [y] z]] after.\n",
113 "A [[https://a.b][a]b]] z [[https://a.b][x [y]] z [[https://a.b][=v]=]] z [[https://a.b][]x]] z [[https://a.b][a\\]b]] z.\n",
114 "[[elisp:foo][[[file:a.png]]]]\n\n[[https://a.b][[[x]] y]]\n\n[[https://a.b][[x]]]\n",
115 "See FILE:a.org::foo.png here.\n",
113116 "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",
114117 "* 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",
115118 "#+OPTIONS: num:nil\n* Head\nSee [[*Head]].\n",
@@ -326,6 +329,12 @@ struct LaTeXExportTests {
326329 }
327330 }
328331
332 /// A bracket link path broken across a CRLF line end is read as Emacs reads it once it decodes the file.
333 @Test func linkPathsAcrossCRLF() throws {
334 let body = try LaTeXExport.document("Text [[elisp:(+ 1\r\n 2)]] and [[https://a.b/c\r\n d]] ok.\r\n", bodyOnly: true)
335 #expect(body.hasPrefix("Text \\url{elisp:(+ 1 2)} and \\url{https://a.b/c d} ok."))
336 }
337
329338 /// What Emacs exports differently or refuses is refused, naming it.
330339 @Test func refusesWhatItCannotMatch() {
331340 func reason(_ org: String) -> String? {
@@ -355,12 +364,14 @@ struct LaTeXExportTests {
355364 let pre = "* Top\n:PROPERTIES:\n:EXPORT_LATEX_CLASS_PRE: \\x\n:END:\nBody.\n"
356365 #expect(ExportScope.subtree(pre, at: 0).flatMap(reason) == "#+LATEX_CLASS_PRE")
357366 #expect(reason("#+OPTIONS: tags:not-in-toc\n* 100% done :a:\n")?.hasPrefix("% in a heading") == true)
358 for org in ["[[elisp:foo][[[file:a.png]]]]\n", "[[https://a.b][[[x]] y]]\n", "[[https://a.b][[x]]]\n", "[[a][b [fn:1]]]\n\n[fn:1] d\n"] {
359 #expect(reason(org) == "]] in link descriptions")
367 for org in ["shell:ls^2 x\n", "x shell:a_b\n", "ftp://a/b_c\n", "elisp:x^{2}\n", "help:a_{b}\n", "shell:a\\alpha\n", "shell:a$x$ y\n",
368 "shell:a@@latex:Z@@\n", "shell:a{{{date}}}\n", "shell:ls[fn:1] x\n\n[fn:1] d\n", "*shell:ab_c*\n"] {
369 #expect(reason(org) == "Plain links running into other objects", "\(org)")
360370 }
361371 #expect(reason("See id:abc.\n") == "Plain links of type id")
362372 #expect(reason("See info:emacs here.\n") == "Plain links of type info")
363373 #expect(reason("See FILE:a.png here.\n") == "Plain image links")
374 #expect(reason("See FILE:a.png::x here.\n") == "Plain image links")
364375 #expect(reason("See FILE:~/a here.\n") == "File links under ~")
365376 }
366377
docs/manual/guide/12-export.org +1 −1
@@ -236,7 +236,7 @@ It reads:
236236
237237=#+TITLE=, =#+SUBTITLE=, =#+AUTHOR=, =#+DATE=, =#+KEYWORDS=, =#+DESCRIPTION=, =#+LANGUAGE= and =#+OPTIONS= work as in Emacs, as do the tags and =COMMENT= that leave headings out (see /Which headings are exported/). Body-only and subtree export are in the export dialog. In a subtree export, the heading's =EXPORT_LATEX_CLASS=, =EXPORT_LATEX_CLASS_OPTIONS=, =EXPORT_LATEX_HEADER=, =EXPORT_LATEX_HEADER_EXTRA=, =EXPORT_LATEX_COMPILER=, =EXPORT_SUBTITLE=, =EXPORT_KEYWORDS=, =EXPORT_DESCRIPTION= and =EXPORT_LANGUAGE= properties replace the file's keywords. As in Emacs, a =PROPERTY+= line adds its value to the property's, after a space.
238238
239A file with something this export doesn't handle stops with "Can't export to LaTeX: " and what it was, rather than giving a =.tex= that differs from Emacs's: a LaTeX class other than the three, Babel or Polyglossia in the header, citations, radio targets, inline tasks, table.el tables, inline source blocks and calls, =#+CALL=, source blocks exported with their results, footnote definitions of several paragraphs, footnotes in headings, tables or item tags, =:mode math= and long tables, =UNNUMBERED= and =ALT_TITLE=, =tex:verbatim=, a quote or center block whose first line holds only spaces and whose second line is not blank, a keyword such as =#+SUBTITLE= repeated with an empty value, plain (unbracketed) links of types it doesn't write, such as =id:= and =info:=, plain links to images, a link description holding =]]=, and =#+OPTIONS= items other than =toc=, =num=, =H=, =tags=, =todo=, =pri=, =^=, =tex=, =title=, =author=, =date=, =-= and =timestamp= set to something other than Org's default. A link Emacs can't resolve stops the export in both, including a link to a heading, target or named element the export leaves out. On iOS the share sheet stops and the message shows at the bottom of the screen. Publishing to LaTeX stops with the file's name in the message. In the download version, when Emacs is installed, such a file is exported by Emacs instead (see /Exporting through Emacs/).
239A file with something this export doesn't handle stops with "Can't export to LaTeX: " and what it was, rather than giving a =.tex= that differs from Emacs's: a LaTeX class other than the three, Babel or Polyglossia in the header, citations, radio targets, inline tasks, table.el tables, inline source blocks and calls, =#+CALL=, source blocks exported with their results, footnote definitions of several paragraphs, footnotes in headings, tables or item tags, =:mode math= and long tables, =UNNUMBERED= and =ALT_TITLE=, =tex:verbatim=, a quote or center block whose first line holds only spaces and whose second line is not blank, a keyword such as =#+SUBTITLE= repeated with an empty value, plain (unbracketed) links of types it doesn't write, such as =id:= and =info:=, plain links to images, a plain link that runs on into markup such as =shell:a_b=, and =#+OPTIONS= items other than =toc=, =num=, =H=, =tags=, =todo=, =pri=, =^=, =tex=, =title=, =author=, =date=, =-= and =timestamp= set to something other than Org's default. A link Emacs can't resolve stops the export in both, including a link to a heading, target or named element the export leaves out. On iOS the share sheet stops and the message shows at the bottom of the screen. Publishing to LaTeX stops with the file's name in the message. In the download version, when Emacs is installed, such a file is exported by Emacs instead (see /Exporting through Emacs/).
240240
241241* Word, RTF and plain text
242242