Commit 43255df900

43255df90026b1145bb1fdc2ff9b6746190692c3

parent: 7a6860bc2b

Verified · cmc

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

Match ox-ascii on wide translations, link types and escaped line breaks

Underline translated titles by display width. Refuse wide translations
that get filled, Slovenian section references, and link types the
export doesn't write as Emacs does. Don't parse \\ after a backslash
as a line break.

Layout: unified · split

Sources/OrgCore/Export/ASCIIExport.swift +60 −21
@@ -154,18 +154,30 @@ final class ASCIIRenderer {
154154 collectHeadings(tree.root.children)
155155 }
156156
157 static func isWideOrZeroWidth(_ s: Unicode.Scalar) -> Bool {
157 static func isWideOrZeroWidth(_ s: Unicode.Scalar) -> Bool { isWide(s) || isZeroWidth(s) }
158
159 static func isWide(_ s: Unicode.Scalar) -> Bool {
158160 switch s.value {
159161 case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xA000...0xA4CF, 0xAC00...0xD7A3,
160162 0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x1F300...0x1F64F, 0x1F900...0x1F9FF, 0x20000...0x3FFFD:
161163 return true
162 case 0x200B...0x200F, 0xFE00...0xFE0F:
163 return true
164164 default:
165 return s.properties.generalCategory == .nonspacingMark || s.properties.generalCategory == .enclosingMark
165 return false
166166 }
167167 }
168168
169 static func isZeroWidth(_ s: Unicode.Scalar) -> Bool {
170 switch s.value {
171 case 0x200B...0x200F, 0xFE00...0xFE0F: return true
172 default: return s.properties.generalCategory == .nonspacingMark || s.properties.generalCategory == .enclosingMark
173 }
174 }
175
176 /// `string-width`.
177 static func width(_ s: String) -> Int {
178 s.unicodeScalars.reduce(0) { $0 + (isWide($1) ? 2 : isZeroWidth($1) ? 0 : 1) }
179 }
180
169181 /// `org-export--collect-headline-numbering` over the headings the export writes.
170182 private func collectHeadings(_ nodes: [SyntaxNode]) {
171183 var counters: [Int] = []
@@ -249,7 +261,7 @@ final class ASCIIRenderer {
249261 /// `org-ascii--build-toc` over the whole document.
250262 private func tableOfContents(depth: Int?, width: Int, keyword: Bool) throws -> String {
251263 let title = translate("Table of Contents")
252 var out = title + "\n" + String(repeating: utf8 ? "─" : "_", count: title.count) + "\n\n"
264 var out = title + "\n" + String(repeating: utf8 ? "─" : "_", count: Self.width(title)) + "\n\n"
253265 let limit = min(depth ?? options.headlineLevels, options.headlineLevels)
254266 var lines: [String] = []
255267 for (start, level) in exported where level <= limit {
@@ -270,6 +282,13 @@ final class ASCIIRenderer {
270282 ExportDictionary.translate(term, language: language, encoding: utf8 ? .utf8 : charset == .latin1 ? .latin1 : .ascii)
271283 }
272284
285 /// A translation for text that is filled, which counts characters, not columns.
286 func translateFilled(_ term: String) throws -> String {
287 let text = translate(term)
288 if text.unicodeScalars.contains(where: Self.isWideOrZeroWidth) { throw Unsupported(reason: "Wide or combining characters") }
289 return text
290 }
291
273292 /// `org-ascii--justify-lines`: each line centered or flushed right in `width`. `tabs`
274293 /// indents as `fill-region` does, with tabs where they fit.
275294 static func justifyLines(_ s: String, width: Int, _ how: Justify, tabs: Bool = false) -> String {
@@ -355,7 +374,7 @@ final class ASCIIRenderer {
355374 let notes = try footnotes()
356375 if !notes.isEmpty {
357376 let title = translate("Footnotes")
358 out += "\n\n\n" + title + "\n" + String(repeating: utf8 ? "─" : "_", count: title.count) + "\n\n" + notes
377 out += "\n\n\n" + title + "\n" + String(repeating: utf8 ? "─" : "_", count: Self.width(title)) + "\n\n" + notes
359378 }
360379 return Self.normalize(out)
361380 }
@@ -840,7 +859,7 @@ final class ASCIIRenderer {
840859 noting = false
841860 defer { noting = saved }
842861 let text = try inlineString(affiliated.caption[0])
843 return ASCIIText.fill(translate(type).replacingOccurrences(of: "%d", with: String(counter)) + " " + text, width: context.width)
862 return ASCIIText.fill(try translateFilled(type).replacingOccurrences(of: "%d", with: String(counter)) + " " + text, width: context.width)
844863 }
845864
846865 // MARK: Blocks
@@ -1084,6 +1103,9 @@ final class ASCIIRenderer {
10841103 let blanks = t.prefix { $0 == " " || $0 == "\t" }
10851104 t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count)
10861105 }
1106 if let m = Self.plainLink.firstMatch(in: t, range: NSRange(t.startIndex..., in: t)) {
1107 throw Unsupported(reason: "Plain links of type \((t as NSString).substring(with: m.range(at: 1)))")
1108 }
10871109 dropBlanks = false
10881110 afterObject = false
10891111 out += plainText(t)
@@ -1187,7 +1209,13 @@ final class ASCIIRenderer {
11871209 return out
11881210 }
11891211
1190 private static let externalTypes: Set<String> = ["attachment", "file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"]
1212 /// Link types Org registers in an Org buffer that this export doesn't write as Emacs does.
1213 private static let unrenderedTypes: Set<String> = ["attachment", "bbdb", "bibtex", "docview", "doi", "eww", "gnus", "info", "irc", "mhe", "rmail", "w3m"]
1214
1215 /// `org-link-plain-re`, loosely, for the plain links the parser leaves as text.
1216 private static let plainLink = try! NSRegularExpression(pattern: #"(?i)(?<![\p{L}\p{N}_])(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):\S*[\p{L}\p{N}/)\]>-]"#)
1217
1218 private static let externalTypes: Set<String> = ["file+sys", "file+emacs", "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp"]
11911219
11921220 private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? {
11931221 if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true {
@@ -1198,9 +1226,12 @@ final class ASCIIRenderer {
11981226 if pathToken == nil, raw.hasPrefix("<"), raw.hasSuffix(">") { raw = String(raw.dropFirst().dropLast()) }
11991227 var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children)
12001228 if description?.contains(where: { !$0.isWhitespace }) != true { description = nil }
1229 let linkType = raw.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):/).map { String($0.1) }
1230 if let linkType, Self.unrenderedTypes.contains(linkType) { throw Unsupported(reason: "Links of type \(linkType)") }
12011231 let footprint = raw + "\u{0}" + (node.firstChild(.linkDescription)?.text ?? "").split(whereSeparator: { " \t\n\r".contains($0) }).joined(separator: " ")
1202 // Only the link types Org knows have a scheme; `foo:bar` is a fuzzy link.
1203 let scheme = raw.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):/).map { String($0.1).lowercased() }.flatMap { Self.externalTypes.contains($0) || $0 == "id" ? $0 : nil }
1232 // Only the link types Org knows, in any case, have a scheme; `foo:bar` is a fuzzy link.
1233 // Only `id` in lower case is an ID link; `ID:x` and `DOI:x` are written as they are.
1234 let scheme = linkType.map { $0.lowercased() }.flatMap { Self.externalTypes.contains($0) || Self.unrenderedTypes.contains($0) || $0 == "id" ? $0 : nil }
12041235 if raw.hasPrefix("(") && raw.hasSuffix(")") {
12051236 let path = String(raw.dropFirst().dropLast())
12061237 guard let resolved = Coderef.resolve(path, blocks: exportedBlocks) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") }
@@ -1208,9 +1239,9 @@ final class ASCIIRenderer {
12081239 if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") }
12091240 return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%")
12101241 }
1211 let internalLink = raw.hasPrefix("#") || scheme == "id" || (scheme == nil && !raw.hasPrefix("/") && !raw.hasPrefix("./") && !raw.hasPrefix("../") && !raw.hasPrefix("~"))
1242 let internalLink = raw.hasPrefix("#") || linkType == "id" || (scheme == nil && !raw.hasPrefix("/") && !raw.hasPrefix("./") && !raw.hasPrefix("../") && !raw.hasPrefix("~"))
12121243 if internalLink {
1213 let type = raw.hasPrefix("#") ? "custom-id" : scheme == "id" ? "id" : "fuzzy"
1244 let type = raw.hasPrefix("#") ? "custom-id" : linkType == "id" ? "id" : "fuzzy"
12141245 let path = type == "custom-id" ? String(raw.dropFirst()) : type == "id" ? String(raw.dropFirst(3)) : raw
12151246 if type == "fuzzy", !path.hasPrefix("*"), target(path) || namedElement(path) {
12161247 throw Unsupported(reason: "Links to targets and named elements")
@@ -1218,33 +1249,41 @@ final class ASCIIRenderer {
12181249 guard let heading = resolveHeading(type: type, path: path) else {
12191250 throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"")
12201251 }
1221 let datum = try describeHeading(heading)
1252 let reference = try describeHeading(heading)
12221253 if let description {
1223 if noting { noted.append(Noted(footprint: footprint, note: linksToNotes ? "[\(description)] \(datum.see)" : nil)) }
1224 return linksToNotes ? "[\(description)]" : "[\(description)] (\(datum.see))"
1254 let see = try seeSection(reference)
1255 if noting { noted.append(Noted(footprint: footprint, note: linksToNotes ? "[\(description)] \(see)" : nil)) }
1256 return linksToNotes ? "[\(description)]" : "[\(description)] (\(see))"
12251257 }
12261258 if noting { noted.append(Noted(footprint: footprint, note: nil)) }
1227 return datum.reference
1259 return reference
12281260 }
12291261 if noting { noted.append(Noted(footprint: footprint, note: description.map { "[\($0)] <\(raw)>" })) }
12301262 return description.map { "[\($0)]" + (linksToNotes ? "" : " (<\(raw)>)") } ?? "<\(raw)>"
12311263 }
12321264
1233 /// A heading as a link without a description writes it, and as
1234 /// `org-ascii--describe-datum` does.
1235 private func describeHeading(_ heading: HeadingInfo) throws -> (reference: String, see: String) {
1265 /// A heading as a link without a description writes it: its number, else its title.
1266 private func describeHeading(_ heading: HeadingInfo) throws -> String {
12361267 let number = numbers[heading.headingRange.lowerBound]?.map(String.init).joined(separator: ".")
12371268 let text: String
12381269 if let number {
12391270 text = number
12401271 } else {
1241 guard let node = tree.root.descendants().first(where: { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }) else { return ("", "") }
1272 guard let node = tree.root.descendants().first(where: { $0.kind == .heading && $0.range.lowerBound == heading.headingRange.lowerBound }) else { return "" }
12421273 let saved = noting
12431274 noting = false
12441275 defer { noting = saved }
12451276 text = try node.firstChild(.title).map { try transcode(inlineItems($0)) } ?? ""
12461277 }
1247 return (text, translate("See section %s").replacingOccurrences(of: "%s", with: text))
1278 return text
1279 }
1280
1281 /// `org-ascii--describe-datum` for a heading `reference` names.
1282 private func seeSection(_ reference: String) throws -> String {
1283 let format = try translateFilled("See section %s")
1284 // Emacs's `format` stops at `%d` given a string (Slovenian).
1285 if format.contains("%d") { throw Unsupported(reason: "Format specifier doesn't match argument type") }
1286 return format.replacingOccurrences(of: "%s", with: reference)
12481287 }
12491288
12501289 /// Whether a `<<target>>` has the name a fuzzy link gives.
Sources/OrgCore/Parser/Inline.swift +3 −2
@@ -534,9 +534,10 @@ struct InlineScanner {
534534 return hasPrefix("}}}", at: j, limit) ? j + 3 : nil
535535 }
536536
537 /// `\\` at the end of a line, before optional trailing blanks. The line break stays outside.
537 /// `\\` at the end of a line, before optional trailing blanks, not after another `\`. The
538 /// line break stays outside.
538539 func lineBreak(_ i: Int, _ limit: Int) -> Int? {
539 guard hasPrefix("\\\\", at: i, limit) else { return nil }
540 guard hasPrefix("\\\\", at: i, limit), i == 0 || chars[i - 1] != "\\" else { return nil }
540541 var j = i + 2
541542 while j < limit, chars[j] == " " || chars[j] == "\t" { j += 1 }
542543 if j + 1 < limit, chars[j] == "\r", chars[j + 1] == "\n" { return j }
Tests/OrgCoreTests/ASCIIExportTests.swift +27
@@ -208,6 +208,10 @@ struct ASCIIExportTests {
208208 "#+DATE: 2024-01-02\nx\n",
209209 "#+begin_src makefile\nall: x\n\tcc -o x x.c\n#+end_src\n",
210210 "#+begin_src makefile -n -r\nall: x\n \t\tcc\tx (ref:a)\n#+end_src\n\n#+begin_example\nall: x\n\tcc\n#+end_example\n",
211 "#+LANGUAGE: ja\n#+OPTIONS: toc:nil\n* A\nx[fn:1]\n\n[fn:1] n\n",
212 "#+LANGUAGE: zh-CN\n* A\nx\n",
213 "Types [[DOI:10.1/z][d]] [[Attachment:x.png]] [[ID:x]] [[INFO:emacs][i]] b_doi:10.1/x.\n",
214 "a\\\\\\\\\nb\n\nc\\\\\\\\\\\\ \nd\n\ne\\\\\nf\n",
211215 "#+OPTIONS: e:t\n\\alpha\\beta \\ast{} \\S \\para \\deg \\plusmn \\micro \\middot \\cedil \\ordf \\iexcl \\pound \\yen \\euro \\trade\n",
212216 ]
213217
@@ -304,6 +308,16 @@ struct ASCIIExportTests {
304308 }
305309 }
306310
311 /// Slovenian's "See section %d" stops Emacs's `format` when given a section.
312 @Test(.enabled(if: oracle))
313 func abortsOnSlovenianSectionReference() throws {
314 let cases = ASCIIExport.Charset.allCases.map { ASCIIOracle.Case(text: "#+LANGUAGE: sl\n* A\nSee [[*B][b]].\n* B\ny\n", charset: $0) }
315 for (c, theirs) in zip(cases, try ASCIIOracle.export(cases)) {
316 #expect(theirs == "ERROR: Format specifier doesn’t match argument type" || theirs == "ERROR: Format specifier doesn't match argument type", "\(theirs)")
317 #expect(ASCIIOracle.native(c) == "ERROR: Format specifier doesn't match argument type")
318 }
319 }
320
307321 /// What Emacs exports differently or refuses is refused, naming it.
308322 @Test func refusesWhatItCannotMatch() {
309323 func reason(_ org: String) -> String? {
@@ -334,6 +348,19 @@ struct ASCIIExportTests {
334348 #expect(reason("* A\n:PROPERTIES:\n:UNNUMBERED: t\n:END:\n") == "UNNUMBERED and ALT_TITLE properties")
335349 #expect(reason("* A [fn:1]\n\n[fn:1] x\n") == "Footnotes in headings")
336350 #expect(reason("#+begin_quote\n\nq\n#+end_quote\n") == "Blocks opening with a blank line")
351 #expect(reason("Plain doi:10.1/z here.\n") == "Plain links of type doi")
352 #expect(reason("Plain info:emacs#Top\n") == "Plain links of type info")
353 #expect(reason("Run shell:ls and elisp:foo.\n") == "Plain links of type shell")
354 #expect(reason("<irc:/irc.x/chan>\n") == "Plain links of type irc")
355 #expect(reason("| docview:a.pdf |\n") == "Plain links of type docview")
356 #expect(reason("[[doi:10.1/z][d]]\n") == "Links of type doi")
357 #expect(reason("[[attachment:x.png]]\n") == "Links of type attachment")
358 #expect(reason("<info:emacs#Top>\n") == "Links of type info")
359 #expect(reason("Case DOI:10.1/z.\n") == "Plain links of type DOI")
360 #expect(reason("#+LANGUAGE: ja\n#+CAPTION: c\n| a |\n") == "Wide or combining characters")
361 #expect(reason("#+LANGUAGE: ja\n* A\nSee [[*B][b]].\n* B\n") == "Wide or combining characters")
362 #expect(reason("#+LANGUAGE: sl\n* A\nSee [[*B][b]].\n* B\n") == "Format specifier doesn't match argument type")
363 #expect(reason("#+LANGUAGE: sl\n* A\nSee [[*B]].\n* B\n") == nil)
337364 }
338365
339366 private func compare(_ cases: [ASCIIOracle.Case], names: [String]) throws {
docs/manual/guide/12-export.org +1 −1
@@ -271,7 +271,7 @@ Export to Plain Text (ASCII) writes the =.txt= file that Emacs's =org-ascii-expo
271271
272272=#+TITLE=, =#+SUBTITLE=, =#+AUTHOR=, =#+DATE=, =#+LANGUAGE=, =#+TOC: headlines=, =#+ASCII:= lines, =#+BEGIN_EXPORT ascii= blocks, =@@ascii:...@@= snippets, =#+ATTR_ASCII: :width= on horizontal rules, and the =center=, =justifyleft= and =justifyright= blocks 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_TITLE=, =EXPORT_SUBTITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_LANGUAGE=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS= and =EXPORT_EXCLUDE_TAGS= properties replace the file's keywords. Leading tabs in a source block become spaces, as in Emacs.
273273
274A file with something this export doesn't handle stops with "Can't export to plain text: " and what it was, rather than giving a =.txt= that differs from Emacs's: citations and =#+BIBLIOGRAPHY=, radio targets, inline tasks, table.el tables, diary sexps, inline source blocks and calls, =#+CALL=, source blocks exported with their results, =#+RESULTS= without a source block, wide or combining characters (such as CJK text, emoji and combining accents), tabs outside source and example blocks or in the indentation of an indented source block, footnote definitions of several paragraphs, footnotes in headings, keywords, captions or other footnotes, =UNNUMBERED= and =ALT_TITLE=, tables with special columns or column groups, empty list items, alphabetical counters, affiliated keywords in list items, blocks whose first line is blank, headings inside blocks, numbered source blocks inside other blocks, verse blocks with more than text, links inside link descriptions, links to =<<targets>>= and named elements, short or repeated captions, unknown entities, a keyword such as =#+SUBTITLE= repeated with an empty value, =#+TOC:= other than =headlines= or with =local= or =:target=, 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 the export leaves out. On iOS the share sheet stops and the message shows at the bottom of the screen. Publishing to plain text 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/).
274A file with something this export doesn't handle stops with "Can't export to plain text: " and what it was, rather than giving a =.txt= that differs from Emacs's: citations and =#+BIBLIOGRAPHY=, radio targets, inline tasks, table.el tables, diary sexps, inline source blocks and calls, =#+CALL=, source blocks exported with their results, =#+RESULTS= without a source block, wide or combining characters (such as CJK text, emoji and combining accents), also in the =#+LANGUAGE= words for captions and section references, tabs outside source and example blocks or in the indentation of an indented source block, footnote definitions of several paragraphs, footnotes in headings, keywords, captions or other footnotes, =UNNUMBERED= and =ALT_TITLE=, tables with special columns or column groups, empty list items, alphabetical counters, affiliated keywords in list items, blocks whose first line is blank, headings inside blocks, numbered source blocks inside other blocks, verse blocks with more than text, links inside link descriptions, =doi=, =info=, =irc=, =attachment=, =docview=, =bbdb=, =bibtex=, =gnus=, =rmail=, =mhe=, =w3m= and =eww= links, plain links other than =http=, =https=, =mailto= and =file=, links to =<<targets>>= and named elements, short or repeated captions, unknown entities, a keyword such as =#+SUBTITLE= repeated with an empty value, =#+TOC:= other than =headlines= or with =local= or =:target=, 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 the export leaves out, as does a described link to a heading with =#+LANGUAGE: sl=. On iOS the share sheet stops and the message shows at the bottom of the screen. Publishing to plain text 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/).
275275
276276* Markdown export
277277