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 {
64 if included.contains("{{{") { 64 if included.contains("{{{") {
65 if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") } 65 if included.contains(marker) { throw LaTeXExport.Unsupported(reason: "U+E000 in the text") }
66 let ns = included as NSString 66 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
68 .filter { [.verbatim, .code, .block, .fixedWidth, .comment, .latexEnvironment, .exportSnippet].contains($0.kind) }.map(\.range) 76 .filter { [.verbatim, .code, .block, .fixedWidth, .comment, .latexEnvironment, .exportSnippet].contains($0.kind) }.map(\.range)
69 var out = "" 77 var out = ""
70 var at = 0 78 var at = 0
@@ -1299,6 +1307,7 @@ final class LaTeXRenderer {
1299 /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`), 1307 /// `org-export-data` over objects: math objects merged (`org-latex--wrap-latex-math-block`),
1300 /// objects that export nothing taking their blanks with them unless they are needed. 1308 /// objects that export nothing taking their blanks with them unless they are needed.
1301 func transcode(_ items: [Inline]) throws -> String { 1309 func transcode(_ items: [Inline]) throws -> String {
1310 if !inDescription { try refusePlainLinksIntoObjects(items) }
1302 var out = "" 1311 var out = ""
1303 var index = 0 1312 var index = 0
1304 var dropBlanks = false 1313 var dropBlanks = false
@@ -1580,10 +1589,6 @@ final class LaTeXRenderer {
1580 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true { 1589 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
1581 throw Unsupported(reason: "Links in link descriptions") 1590 throw Unsupported(reason: "Links in link descriptions")
1582 } 1591 }
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 }
1587 if let d = node.firstChild(.linkDescription)?.text, d.firstMatch(of: /^(?:[A-Za-z]+:\S+|<[^>]+>)$/) != nil { 1592 if let d = node.firstChild(.linkDescription)?.text, d.firstMatch(of: /^(?:[A-Za-z]+:\S+|<[^>]+>)$/) != nil {
1588 throw Unsupported(reason: "Images as link descriptions") 1593 throw Unsupported(reason: "Images as link descriptions")
1589 } 1594 }
@@ -1629,6 +1634,29 @@ final class LaTeXRenderer {
1629 return path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path 1634 return path.hasPrefix("//") ? "file:" + path : path.hasPrefix("/") ? "file://" + path : path
1630 } 1635 }
1631 1636
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
1632 /// Text with the plain links the parser leaves in it, `shell:ls` and the like, written as Emacs does. 1660 /// Text with the plain links the parser leaves in it, `shell:ls` and the like, written as Emacs does.
1633 private func plainTextAndLinks(_ t: String) throws -> String { 1661 private func plainTextAndLinks(_ t: String) throws -> String {
1634 guard !inDescription else { return plainText(t) } 1662 guard !inDescription else { return plainText(t) }
@@ -1645,11 +1673,11 @@ final class LaTeXRenderer {
1645 before = String(repeating: " ", count: blanks.count) + before.dropFirst(blanks.count) 1673 before = String(repeating: " ", count: blanks.count) + before.dropFirst(blanks.count)
1646 } 1674 }
1647 out += plainText(before) 1675 out += plainText(before)
1676 if type.lowercased() == "file", !path.hasPrefix("//"), let range = path.range(of: "::") { path = String(path[..<range.lowerBound]) }
1648 let ext = (path as NSString).pathExtension.lowercased() 1677 let ext = (path as NSString).pathExtension.lowercased()
1649 switch type.lowercased() { 1678 switch type.lowercased() {
1650 case "file": 1679 case "file":
1651 if ["pdf", "jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"].contains(ext) { throw Unsupported(reason: "Plain image links") } 1680 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]) }
1653 out += "\\url{\(Self.protect(try fileURI(path)))}" 1681 out += "\\url{\(Self.protect(try fileURI(path)))}"
1654 case "http", "https", "ftp", "mailto", "news", "elisp", "shell", "help", "shortdoc": 1682 case "http", "https", "ftp", "mailto", "news", "elisp", "shell", "help", "shortdoc":
1655 if ["jpeg", "jpg", "png", "ps", "eps", "tikz", "pgf", "svg"].contains(ext) { throw Unsupported(reason: "Plain image links") } 1683 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 {
312 let path = (i + 2)..<j 312 let path = (i + 2)..<j
313 if chars[j + 1] == "]" { return .link(path: path, description: nil, whole: i..<(j + 2)) } 313 if chars[j + 1] == "]" { return .link(path: path, description: nil, whole: i..<(j + 2)) }
314 guard chars[j + 1] == "[" else { return nil } 314 guard chars[j + 1] == "[" else { return nil }
315 // `org-link-bracket-re`: the description is at least one character, up to the first `]]`.
315 let descriptionStart = j + 2 316 let descriptionStart = j + 2
316 var depth = 0 317 var k = descriptionStart + 1
317 var k = descriptionStart 318 while k + 1 < limit, !(chars[k] == "]" && chars[k + 1] == "]") { k += 1 }
318 while k < limit { 319 guard k + 1 < limit else { return nil }
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 }
328 return .link(path: path, description: descriptionStart..<k, whole: i..<(k + 2)) 320 return .link(path: path, description: descriptionStart..<k, whole: i..<(k + 2))
329 } 321 }
330 322
Sources/OrgCore/Syntax/SyntaxNode.swift +1 −1
@@ -107,7 +107,7 @@ public final class SyntaxNode: Sendable {
107 /// A bracket link's path as `org-element-link-parser` reads it: each run of blanks 107 /// A bracket link's path as `org-element-link-parser` reads it: each run of blanks
108 /// holding a newline made one space. 108 /// holding a newline made one space.
109 var linkPath: String? { 109 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: " ") }
111 } 111 }
112} 112}
113 113
Tests/OrgCoreTests/InlineTests.swift +9
@@ -50,6 +50,15 @@ struct InlineTests {
50 @Test func linkPathsSpanLines() { 50 @Test func linkPathsSpanLines() {
51 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 } 51 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 }
52 #expect(links.map(\.linkPath) == ["elisp:(+ 1 2)", "a b"]) 52 #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"])
53 } 62 }
54 63
55 @Test func noLinksInsideLinkDescriptions() { 64 @Test func noLinksInsideLinkDescriptions() {
Tests/OrgCoreTests/LaTeXExportTests.swift +13 −2
@@ -110,6 +110,9 @@ struct LaTeXExportTests {
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", 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", 111 "* Heading shell:ls\nx\n",
112 "[[https://a.b][[x] y]] and [[https://a.b][x [y] z]] after.\n", 112 "[[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",
113 "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", 116 "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",
114 "* 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", 117 "* 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",
115 "#+OPTIONS: num:nil\n* Head\nSee [[*Head]].\n", 118 "#+OPTIONS: num:nil\n* Head\nSee [[*Head]].\n",
@@ -326,6 +329,12 @@ struct LaTeXExportTests {
326 } 329 }
327 } 330 }
328 331
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
329 /// What Emacs exports differently or refuses is refused, naming it. 338 /// What Emacs exports differently or refuses is refused, naming it.
330 @Test func refusesWhatItCannotMatch() { 339 @Test func refusesWhatItCannotMatch() {
331 func reason(_ org: String) -> String? { 340 func reason(_ org: String) -> String? {
@@ -355,12 +364,14 @@ struct LaTeXExportTests {
355 let pre = "* Top\n:PROPERTIES:\n:EXPORT_LATEX_CLASS_PRE: \\x\n:END:\nBody.\n" 364 let pre = "* Top\n:PROPERTIES:\n:EXPORT_LATEX_CLASS_PRE: \\x\n:END:\nBody.\n"
356 #expect(ExportScope.subtree(pre, at: 0).flatMap(reason) == "#+LATEX_CLASS_PRE") 365 #expect(ExportScope.subtree(pre, at: 0).flatMap(reason) == "#+LATEX_CLASS_PRE")
357 #expect(reason("#+OPTIONS: tags:not-in-toc\n* 100% done :a:\n")?.hasPrefix("% in a heading") == true) 366 #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"] { 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",
359 #expect(reason(org) == "]] in link descriptions") 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)")
360 } 370 }
361 #expect(reason("See id:abc.\n") == "Plain links of type id") 371 #expect(reason("See id:abc.\n") == "Plain links of type id")
362 #expect(reason("See info:emacs here.\n") == "Plain links of type info") 372 #expect(reason("See info:emacs here.\n") == "Plain links of type info")
363 #expect(reason("See FILE:a.png here.\n") == "Plain image links") 373 #expect(reason("See FILE:a.png here.\n") == "Plain image links")
374 #expect(reason("See FILE:a.png::x here.\n") == "Plain image links")
364 #expect(reason("See FILE:~/a here.\n") == "File links under ~") 375 #expect(reason("See FILE:~/a here.\n") == "File links under ~")
365 } 376 }
366 377
docs/manual/guide/12-export.org +1 −1
@@ -236,7 +236,7 @@ It reads:
236 236
237=#+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. 237=#+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.
238 238
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/).
240 240
241* Word, RTF and plain text 241* Word, RTF and plain text
242 242