| @@ -154,18 +154,30 @@ final class ASCIIRenderer { |
| 154 | collectHeadings(tree.root.children) |
154 | collectHeadings(tree.root.children) |
| 155 | } |
155 | } |
| 156 | |
156 | |
| 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 { |
| 158 | switch s.value { |
160 | switch s.value { |
| 159 | case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xA000...0xA4CF, 0xAC00...0xD7A3, |
161 | case 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xA000...0xA4CF, 0xAC00...0xD7A3, |
| 160 | 0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x1F300...0x1F64F, 0x1F900...0x1F9FF, 0x20000...0x3FFFD: |
162 | 0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6, 0x1F300...0x1F64F, 0x1F900...0x1F9FF, 0x20000...0x3FFFD: |
| 161 | return true |
163 | return true |
| 162 | case 0x200B...0x200F, 0xFE00...0xFE0F: |
| |
| 163 | return true |
| |
| 164 | default: |
164 | default: |
| 165 | return s.properties.generalCategory == .nonspacingMark || s.properties.generalCategory == .enclosingMark |
165 | return false |
| 166 | } |
166 | } |
| 167 | } |
167 | } |
| 168 | |
168 | |
| |
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 | |
| 169 | /// `org-export--collect-headline-numbering` over the headings the export writes. |
181 | /// `org-export--collect-headline-numbering` over the headings the export writes. |
| 170 | private func collectHeadings(_ nodes: [SyntaxNode]) { |
182 | private func collectHeadings(_ nodes: [SyntaxNode]) { |
| 171 | var counters: [Int] = [] |
183 | var counters: [Int] = [] |
| @@ -249,7 +261,7 @@ final class ASCIIRenderer { |
| 249 | /// `org-ascii--build-toc` over the whole document. |
261 | /// `org-ascii--build-toc` over the whole document. |
| 250 | private func tableOfContents(depth: Int?, width: Int, keyword: Bool) throws -> String { |
262 | private func tableOfContents(depth: Int?, width: Int, keyword: Bool) throws -> String { |
| 251 | let title = translate("Table of Contents") |
263 | 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" |
| 253 | let limit = min(depth ?? options.headlineLevels, options.headlineLevels) |
265 | let limit = min(depth ?? options.headlineLevels, options.headlineLevels) |
| 254 | var lines: [String] = [] |
266 | var lines: [String] = [] |
| 255 | for (start, level) in exported where level <= limit { |
267 | for (start, level) in exported where level <= limit { |
| @@ -270,6 +282,13 @@ final class ASCIIRenderer { |
| 270 | ExportDictionary.translate(term, language: language, encoding: utf8 ? .utf8 : charset == .latin1 ? .latin1 : .ascii) |
282 | ExportDictionary.translate(term, language: language, encoding: utf8 ? .utf8 : charset == .latin1 ? .latin1 : .ascii) |
| 271 | } |
283 | } |
| 272 | |
284 | |
| |
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 | |
| 273 | /// `org-ascii--justify-lines`: each line centered or flushed right in `width`. `tabs` |
292 | /// `org-ascii--justify-lines`: each line centered or flushed right in `width`. `tabs` |
| 274 | /// indents as `fill-region` does, with tabs where they fit. |
293 | /// indents as `fill-region` does, with tabs where they fit. |
| 275 | static func justifyLines(_ s: String, width: Int, _ how: Justify, tabs: Bool = false) -> String { |
294 | static func justifyLines(_ s: String, width: Int, _ how: Justify, tabs: Bool = false) -> String { |
| @@ -355,7 +374,7 @@ final class ASCIIRenderer { |
| 355 | let notes = try footnotes() |
374 | let notes = try footnotes() |
| 356 | if !notes.isEmpty { |
375 | if !notes.isEmpty { |
| 357 | let title = translate("Footnotes") |
376 | 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 |
| 359 | } |
378 | } |
| 360 | return Self.normalize(out) |
379 | return Self.normalize(out) |
| 361 | } |
380 | } |
| @@ -840,7 +859,7 @@ final class ASCIIRenderer { |
| 840 | noting = false |
859 | noting = false |
| 841 | defer { noting = saved } |
860 | defer { noting = saved } |
| 842 | let text = try inlineString(affiliated.caption[0]) |
861 | 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) |
| 844 | } |
863 | } |
| 845 | |
864 | |
| 846 | // MARK: Blocks |
865 | // MARK: Blocks |
| @@ -1084,6 +1103,9 @@ final class ASCIIRenderer { |
| 1084 | let blanks = t.prefix { $0 == " " || $0 == "\t" } |
1103 | let blanks = t.prefix { $0 == " " || $0 == "\t" } |
| 1085 | t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count) |
1104 | t = String(repeating: " ", count: blanks.count) + t.dropFirst(blanks.count) |
| 1086 | } |
1105 | } |
| |
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 | } |
| 1087 | dropBlanks = false |
1109 | dropBlanks = false |
| 1088 | afterObject = false |
1110 | afterObject = false |
| 1089 | out += plainText(t) |
1111 | out += plainText(t) |
| @@ -1187,7 +1209,13 @@ final class ASCIIRenderer { |
| 1187 | return out |
1209 | return out |
| 1188 | } |
1210 | } |
| 1189 | |
1211 | |
| 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"] |
| 1191 | |
1219 | |
| 1192 | private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? { |
1220 | private func link(_ node: SyntaxNode, _ children: [Inline]) throws -> String? { |
| 1193 | if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true { |
1221 | if node.firstChild(.linkDescription)?.descendants().contains(where: { $0.kind == .link }) == true { |
| @@ -1198,9 +1226,12 @@ final class ASCIIRenderer { |
| 1198 | if pathToken == nil, raw.hasPrefix("<"), raw.hasSuffix(">") { raw = String(raw.dropFirst().dropLast()) } |
1226 | if pathToken == nil, raw.hasPrefix("<"), raw.hasSuffix(">") { raw = String(raw.dropFirst().dropLast()) } |
| 1199 | var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children) |
1227 | var description: String? = node.firstChild(.linkDescription) == nil ? nil : try transcode(children) |
| 1200 | if description?.contains(where: { !$0.isWhitespace }) != true { description = nil } |
1228 | 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)") } |
| 1201 | let footprint = raw + "\u{0}" + (node.firstChild(.linkDescription)?.text ?? "").split(whereSeparator: { " \t\n\r".contains($0) }).joined(separator: " ") |
1231 | 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. |
1232 | // Only the link types Org knows, in any case, 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 } |
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 } |
| 1204 | if raw.hasPrefix("(") && raw.hasSuffix(")") { |
1235 | if raw.hasPrefix("(") && raw.hasSuffix(")") { |
| 1205 | let path = String(raw.dropFirst().dropLast()) |
1236 | let path = String(raw.dropFirst().dropLast()) |
| 1206 | guard let resolved = Coderef.resolve(path, blocks: exportedBlocks) else { throw Unsupported(reason: "Unable to resolve code reference: \(path)") } |
1237 | 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 { |
| 1208 | if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") } |
1239 | if let range = format.range(of: "(\(path))") { format.replaceSubrange(range, with: "%s") } |
| 1209 | return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%") |
1240 | return format.replacingOccurrences(of: "%s", with: resolved).replacingOccurrences(of: "%%", with: "%") |
| 1210 | } |
1241 | } |
| 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("~")) |
| 1212 | if internalLink { |
1243 | if internalLink { |
| 1213 | let type = raw.hasPrefix("#") ? "custom-id" : scheme == "id" ? "id" : "fuzzy" |
1244 | let type = raw.hasPrefix("#") ? "custom-id" : linkType == "id" ? "id" : "fuzzy" |
| 1214 | let path = type == "custom-id" ? String(raw.dropFirst()) : type == "id" ? String(raw.dropFirst(3)) : raw |
1245 | let path = type == "custom-id" ? String(raw.dropFirst()) : type == "id" ? String(raw.dropFirst(3)) : raw |
| 1215 | if type == "fuzzy", !path.hasPrefix("*"), target(path) || namedElement(path) { |
1246 | if type == "fuzzy", !path.hasPrefix("*"), target(path) || namedElement(path) { |
| 1216 | throw Unsupported(reason: "Links to targets and named elements") |
1247 | throw Unsupported(reason: "Links to targets and named elements") |
| @@ -1218,33 +1249,41 @@ final class ASCIIRenderer { |
| 1218 | guard let heading = resolveHeading(type: type, path: path) else { |
1249 | guard let heading = resolveHeading(type: type, path: path) else { |
| 1219 | throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"") |
1250 | throw Unsupported(reason: "Unable to resolve link: \"\(type == "custom-id" ? "#" : type == "id" ? "id:" : "")\(path)\"") |
| 1220 | } |
1251 | } |
| 1221 | let datum = try describeHeading(heading) |
1252 | let reference = try describeHeading(heading) |
| 1222 | if let description { |
1253 | if let description { |
| 1223 | if noting { noted.append(Noted(footprint: footprint, note: linksToNotes ? "[\(description)] \(datum.see)" : nil)) } |
1254 | let see = try seeSection(reference) |
| 1224 | return linksToNotes ? "[\(description)]" : "[\(description)] (\(datum.see))" |
1255 | if noting { noted.append(Noted(footprint: footprint, note: linksToNotes ? "[\(description)] \(see)" : nil)) } |
| |
1256 | return linksToNotes ? "[\(description)]" : "[\(description)] (\(see))" |
| 1225 | } |
1257 | } |
| 1226 | if noting { noted.append(Noted(footprint: footprint, note: nil)) } |
1258 | if noting { noted.append(Noted(footprint: footprint, note: nil)) } |
| 1227 | return datum.reference |
1259 | return reference |
| 1228 | } |
1260 | } |
| 1229 | if noting { noted.append(Noted(footprint: footprint, note: description.map { "[\($0)] <\(raw)>" })) } |
1261 | if noting { noted.append(Noted(footprint: footprint, note: description.map { "[\($0)] <\(raw)>" })) } |
| 1230 | return description.map { "[\($0)]" + (linksToNotes ? "" : " (<\(raw)>)") } ?? "<\(raw)>" |
1262 | return description.map { "[\($0)]" + (linksToNotes ? "" : " (<\(raw)>)") } ?? "<\(raw)>" |
| 1231 | } |
1263 | } |
| 1232 | |
1264 | |
| 1233 | /// A heading as a link without a description writes it, and as |
1265 | /// A heading as a link without a description writes it: its number, else its title. |
| 1234 | /// `org-ascii--describe-datum` does. |
1266 | private func describeHeading(_ heading: HeadingInfo) throws -> String { |
| 1235 | private func describeHeading(_ heading: HeadingInfo) throws -> (reference: String, see: String) { |
| |
| 1236 | let number = numbers[heading.headingRange.lowerBound]?.map(String.init).joined(separator: ".") |
1267 | let number = numbers[heading.headingRange.lowerBound]?.map(String.init).joined(separator: ".") |
| 1237 | let text: String |
1268 | let text: String |
| 1238 | if let number { |
1269 | if let number { |
| 1239 | text = number |
1270 | text = number |
| 1240 | } else { |
1271 | } 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 "" } |
| 1242 | let saved = noting |
1273 | let saved = noting |
| 1243 | noting = false |
1274 | noting = false |
| 1244 | defer { noting = saved } |
1275 | defer { noting = saved } |
| 1245 | text = try node.firstChild(.title).map { try transcode(inlineItems($0)) } ?? "" |
1276 | text = try node.firstChild(.title).map { try transcode(inlineItems($0)) } ?? "" |
| 1246 | } |
1277 | } |
| 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) |
| 1248 | } |
1287 | } |
| 1249 | |
1288 | |
| 1250 | /// Whether a `<<target>>` has the name a fuzzy link gives. |
1289 | /// Whether a `<<target>>` has the name a fuzzy link gives. |