Export to Word, RTF and plain text; Copy as Rich Text !229

merged merged by cmc on 2026-10-11 02:47 UTC · krz/orgstar:export-rich into main

11 files changed, +445 −21

Layout: unified · split

Sources/OrgApp/DocxWriter.swift added +211
@@ -0,0 +1,211 @@
1#if os(macOS)
2import AppKit
3import Foundation
4
5/// Word's `.docx` from styled text: paragraphs with their runs' fonts, colors and links, and
6/// tables from the text's table blocks, which the system's own writer leaves out.
7enum DocxWriter {
8 static func data(from text: NSAttributedString) -> Data {
9 var links: [String] = []
10 let body = paragraphs(text, links: &links)
11 let document = """
12 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
13 <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \
14 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>\(body)\
15 <w:sectPr><w:pgMar w:top="1134" w:right="1134" w:bottom="1134" w:left="1134" w:header="0" w:footer="0" w:gutter="0"/></w:sectPr>\
16 </w:body></w:document>
17 """
18 let relationships = links.enumerated().map { index, url in
19 "<Relationship Id=\"link\(index + 1)\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\" Target=\"\(escape(url))\" TargetMode=\"External\"/>"
20 }.joined()
21 var zip = ZipWriter()
22 zip.add("[Content_Types].xml", """
23 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
24 <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\
25 <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\
26 <Default Extension="xml" ContentType="application/xml"/>\
27 <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>\
28 </Types>
29 """)
30 zip.add("_rels/.rels", """
31 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
32 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\
33 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>\
34 </Relationships>
35 """)
36 zip.add("word/_rels/document.xml.rels", """
37 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
38 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\(relationships)</Relationships>
39 """)
40 zip.add("word/document.xml", document)
41 return zip.data()
42 }
43
44 /// Paragraphs in order, consecutive ones in the same table gathered into `<w:tbl>`.
45 private static func paragraphs(_ text: NSAttributedString, links: inout [String]) -> String {
46 let string = text.string as NSString
47 var out = ""
48 var table: (block: NSTextTable, cells: [[Int: [String]]])?
49 func flushTable() {
50 guard let current = table else { return }
51 out += "<w:tbl><w:tblPr><w:tblBorders>" + ["top", "left", "bottom", "right", "insideH", "insideV"].map {
52 "<w:\($0) w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"A0A0A0\"/>"
53 }.joined() + "</w:tblBorders><w:tblCellMar><w:left w:w=\"100\" w:type=\"dxa\"/><w:right w:w=\"100\" w:type=\"dxa\"/></w:tblCellMar></w:tblPr>"
54 let columns = max(current.block.numberOfColumns, current.cells.map { ($0.keys.max() ?? 0) + 1 }.max() ?? 1)
55 out += "<w:tblGrid>" + String(repeating: "<w:gridCol/>", count: columns) + "</w:tblGrid>"
56 for row in current.cells {
57 out += "<w:tr>"
58 for column in 0..<columns {
59 out += "<w:tc><w:tcPr/>" + (row[column]?.joined() ?? "<w:p/>") + "</w:tc>"
60 }
61 out += "</w:tr>"
62 }
63 out += "</w:tbl>"
64 table = nil
65 }
66 var location = 0
67 while location < string.length {
68 let range = string.paragraphRange(for: NSRange(location: location, length: 0))
69 location = NSMaxRange(range)
70 let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle
71 let paragraph = self.paragraph(text, range, style, links: &links)
72 if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last {
73 if table?.block !== cell.table {
74 flushTable()
75 table = (cell.table, [])
76 }
77 while table!.cells.count <= cell.startingRow { table!.cells.append([:]) }
78 table!.cells[cell.startingRow][cell.startingColumn, default: []].append(paragraph)
79 } else {
80 flushTable()
81 out += paragraph
82 }
83 }
84 flushTable()
85 return out
86 }
87
88 private static func paragraph(_ text: NSAttributedString, _ range: NSRange, _ style: NSParagraphStyle?, links: inout [String]) -> String {
89 var properties = ""
90 if let style {
91 switch style.alignment {
92 case .center: properties += "<w:jc w:val=\"center\"/>"
93 case .right: properties += "<w:jc w:val=\"right\"/>"
94 default: break
95 }
96 let left = Int(style.headIndent * 20), first = Int((style.firstLineHeadIndent - style.headIndent) * 20)
97 if left != 0 || first != 0 { properties += "<w:ind w:left=\"\(left)\" \(first < 0 ? "w:hanging=\"\(-first)\"" : "w:firstLine=\"\(first)\"")/>" }
98 properties += "<w:spacing w:before=\"\(Int(style.paragraphSpacingBefore * 20))\" w:after=\"\(Int(style.paragraphSpacing * 20))\"/>"
99 if !style.tabStops.isEmpty {
100 properties += "<w:tabs>" + style.tabStops.map { "<w:tab w:val=\"left\" w:pos=\"\(Int($0.location * 20))\"/>" }.joined() + "</w:tabs>"
101 }
102 }
103 var runs = ""
104 text.enumerateAttributes(in: range, options: []) { attributes, runRange, _ in
105 var piece = (text.string as NSString).substring(with: runRange)
106 piece = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\n\r"))
107 guard !piece.isEmpty else { return }
108 var run = run(piece, attributes)
109 let link = (attributes[.link] as? URL)?.absoluteString ?? (attributes[.link] as? String)
110 if let link {
111 links.append(link)
112 run = "<w:hyperlink r:id=\"link\(links.count)\">\(run)</w:hyperlink>"
113 }
114 runs += run
115 }
116 return "<w:p><w:pPr>\(properties)</w:pPr>\(runs)</w:p>"
117 }
118
119 private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any]) -> String {
120 var properties = ""
121 if let font = attributes[.font] as? NSFont {
122 let traits = font.fontDescriptor.symbolicTraits
123 let name = traits.contains(.monoSpace) ? "Menlo" : (font.familyName ?? "Helvetica Neue")
124 properties += "<w:rFonts w:ascii=\"\(escape(name))\" w:hAnsi=\"\(escape(name))\" w:cs=\"\(escape(name))\"/>"
125 if traits.contains(.bold) { properties += "<w:b/>" }
126 if traits.contains(.italic) { properties += "<w:i/>" }
127 properties += "<w:sz w:val=\"\(Int((font.pointSize * 2).rounded()))\"/>"
128 }
129 if let color = (attributes[.foregroundColor] as? NSColor)?.usingColorSpace(.sRGB) { properties += "<w:color w:val=\"\(hex(color))\"/>" }
130 if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "<w:u w:val=\"single\"/>" }
131 if (attributes[.strikethroughStyle] as? Int ?? 0) != 0 { properties += "<w:strike/>" }
132 if let background = (attributes[.backgroundColor] as? NSColor)?.usingColorSpace(.sRGB), background.alphaComponent > 0.05 {
133 properties += "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"\(hex(background))\"/>"
134 }
135 if let offset = attributes[.baselineOffset] as? Double, offset != 0 { properties += "<w:vertAlign w:val=\"\(offset > 0 ? "superscript" : "subscript")\"/>" }
136 // Tabs and line breaks are elements of their own.
137 var content = ""
138 var textRun = ""
139 func flush() {
140 if !textRun.isEmpty { content += "<w:t xml:space=\"preserve\">\(escape(textRun))</w:t>" }
141 textRun = ""
142 }
143 for character in piece {
144 switch character {
145 case "\t": flush(); content += "<w:tab/>"
146 case "\u{2028}", "\n": flush(); content += "<w:br/>"
147 default: textRun.append(character)
148 }
149 }
150 flush()
151 return "<w:r><w:rPr>\(properties)</w:rPr>\(content)</w:r>"
152 }
153
154 /// `#rrggbb` of the color laid on white paper: Word has no transparency.
155 private static func hex(_ color: NSColor) -> String {
156 let a = color.alphaComponent
157 func on(_ c: CGFloat) -> Int { Int(((c * a + (1 - a)) * 255).rounded()) }
158 return String(format: "%02X%02X%02X", on(color.redComponent), on(color.greenComponent), on(color.blueComponent))
159 }
160
161 static func escape(_ s: String) -> String {
162 s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
163 .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
164 }
165}
166
167/// A zip archive with stored (uncompressed) entries, as `.docx` files are read.
168struct ZipWriter {
169 private var entries: [(name: Data, data: Data, crc: UInt32, offset: UInt32)] = []
170 private var archive = Data()
171
172 mutating func add(_ name: String, _ text: String) {
173 let data = Data(text.utf8)
174 let nameData = Data(name.utf8)
175 let crc = Self.crc32(data)
176 let offset = UInt32(archive.count)
177 archive += Self.le32(0x04034b50) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
178 archive += Self.le32(crc) + Self.le32(UInt32(data.count)) + Self.le32(UInt32(data.count))
179 archive += Self.le16(UInt16(nameData.count)) + Self.le16(0) + nameData + data
180 entries.append((nameData, data, crc, offset))
181 }
182
183 func data() -> Data {
184 var central = Data()
185 for entry in entries {
186 central += Self.le32(0x02014b50) + Self.le16(20) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
187 central += Self.le32(entry.crc) + Self.le32(UInt32(entry.data.count)) + Self.le32(UInt32(entry.data.count))
188 central += Self.le16(UInt16(entry.name.count)) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le32(0)
189 central += Self.le32(entry.offset) + entry.name
190 }
191 var end = Self.le32(0x06054b50) + Self.le16(0) + Self.le16(0) + Self.le16(UInt16(entries.count)) + Self.le16(UInt16(entries.count))
192 end += Self.le32(UInt32(central.count)) + Self.le32(UInt32(archive.count)) + Self.le16(0)
193 return archive + central + end
194 }
195
196 private static func le16(_ v: UInt16) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
197 private static func le32(_ v: UInt32) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
198
199 private static let table: [UInt32] = (0..<256).map { n in
200 var c = UInt32(n)
201 for _ in 0..<8 { c = c & 1 != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1 }
202 return c
203 }
204
205 static func crc32(_ data: Data) -> UInt32 {
206 var c: UInt32 = 0xFFFFFFFF
207 for byte in data { c = table[Int((c ^ UInt32(byte)) & 0xFF)] ^ (c >> 8) }
208 return c ^ 0xFFFFFFFF
209 }
210}
211#endif
Sources/OrgApp/RichTextExport.swift added +83
@@ -0,0 +1,83 @@
1import Foundation
2#if os(macOS)
3import AppKit
4#else
5import UIKit
6#endif
7
8/// Word, RTF and plain text from the HTML export, through the system's HTML import, and the
9/// same for the clipboard.
10@MainActor
11public enum RichTextExport {
12 public struct Failure: Error, CustomStringConvertible {
13 public let description: String
14 }
15
16 /// The HTML export as styled text: light colors, and fonts other apps have.
17 public static func attributed(html: String, directory: URL?) throws -> NSAttributedString {
18 // The dark rules would turn the text white wherever the system is dark.
19 let light = html.components(separatedBy: "\n").filter { !$0.contains("prefers-color-scheme: dark") }.joined(separator: "\n")
20 let page = light.replacingOccurrences(of: "</head>", with: """
21 <style>
22 body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #222; background: #fff; }
23 code, pre { font-family: Menlo, Consolas, "Courier New", monospace; }
24 </style>
25 </head>
26 """)
27 var options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
28 .documentType: NSAttributedString.DocumentType.html,
29 .characterEncoding: String.Encoding.utf8.rawValue,
30 ]
31 #if os(macOS)
32 if let directory { options[.baseURL] = directory }
33 #endif
34 do {
35 return try NSAttributedString(data: Data(page.utf8), options: options, documentAttributes: nil)
36 } catch {
37 throw Failure(description: "The text couldn't be converted: \(error.localizedDescription)")
38 }
39 }
40
41 public static func rtf(_ text: NSAttributedString) throws -> Data {
42 try text.data(from: NSRange(location: 0, length: text.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf])
43 }
44
45 #if os(macOS)
46 /// Word's `.docx`, tables included.
47 public static func docx(_ text: NSAttributedString) throws -> Data {
48 DocxWriter.data(from: text)
49 }
50 #endif
51
52 /// The HTML export as RTF.
53 public static func rtf(html: String, directory: URL?) throws -> Data {
54 try rtf(attributed(html: html, directory: directory))
55 }
56
57 /// The HTML export as plain text.
58 public static func plain(html: String, directory: URL?) throws -> String {
59 plain(try attributed(html: html, directory: directory))
60 }
61
62 /// The text without its styles, ending in one newline.
63 public static func plain(_ text: NSAttributedString) -> String {
64 text.string.replacingOccurrences(of: "\u{2028}", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + "\n"
65 }
66
67 /// The export on the clipboard as HTML, RTF and plain text, for pasting formatted.
68 public static func copy(html: String, directory: URL?) throws {
69 let text = try attributed(html: html, directory: directory)
70 let rtf = try rtf(text)
71 #if os(macOS)
72 let pasteboard = NSPasteboard.general
73 pasteboard.clearContents()
74 pasteboard.setString(html, forType: .html)
75 pasteboard.setData(rtf, forType: .rtf)
76 pasteboard.setString(plain(text), forType: .string)
77 #else
78 UIPasteboard.general.setItems([[
79 "public.html": html, "public.rtf": rtf, "public.utf8-plain-text": plain(text),
80 ]])
81 #endif
82 }
83}
Sources/OrgEditorAppKit/EditorCommands.swift +4
@@ -106,6 +106,10 @@ public enum EditorCommands {
106106 EditorCommand(id: "app.export.html-open", title: "Export to HTML and Open", action: .app),
107107 EditorCommand(id: "app.export.markdown", title: "Export to Markdown", action: .app),
108108 EditorCommand(id: "app.export.print-pdf", title: "Export to PDF", action: .app),
109 EditorCommand(id: "app.export.docx", title: "Export to Word", action: .app),
110 EditorCommand(id: "app.export.rtf", title: "Export to RTF", action: .app),
111 EditorCommand(id: "app.export.plain-text", title: "Export to Plain Text", action: .app),
112 EditorCommand(id: "app.copy-rich-text", title: "Copy as Rich Text", action: .app),
109113 EditorCommand(id: "app.export.pdf", title: "Export to PDF with Emacs", action: .app),
110114 EditorCommand(id: "app.export.odt", title: "Export to ODT with Emacs", action: .app),
111115 EditorCommand(id: "app.export.latex", title: "Export to LaTeX with Emacs", action: .app),
Sources/Orgstar/ContentView.swift +35 −5
@@ -395,6 +395,26 @@ struct ContentView: View {
395395 }
396396 }
397397
398 /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
399 /// text, to paste formatted into mail and documents.
400 private func copyRichText() {
401 guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
402 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
403 let selection = editor.context().selection.first { !$0.isEmpty }
404 let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
405 let url = URL(fileURLWithPath: path)
406 let html = HTMLExport.page(
407 selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
408 codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme)
409 )
410 do {
411 try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
412 commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
413 } catch {
414 commands.show("\(error)")
415 }
416 }
417
398418 /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
399419 private var exportSubtreeAvailable: Bool {
400420 guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
@@ -446,17 +466,25 @@ struct ContentView: View {
446466 } catch {
447467 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
448468 }
449 case "print-pdf":
469 case "print-pdf", "docx", "rtf", "plain-text":
470 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
450471 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
451 let target = destination ?? ExportScope.output(for: url, name: name, extension: "pdf")
472 let target = destination ?? ExportScope.output(for: url, name: name, extension: ext)
452473 let html = HTMLExport.page(
453474 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
454475 codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme)
455476 )
456 commands.show("Exporting to PDF…")
477 let directory = url.deletingLastPathComponent()
478 if format == "print-pdf" { commands.show("Exporting to PDF…") }
457479 Task {
458480 do {
459 let data = try await PDFExport.pdf(html: html, directory: url.deletingLastPathComponent())
481 let data: Data
482 switch format {
483 case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory)
484 case "docx": data = try RichTextExport.docx(RichTextExport.attributed(html: html, directory: directory))
485 case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
486 default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
487 }
460488 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
461489 try data.write(to: target, options: .atomic)
462490 commands.show("Exported to \(target.lastPathComponent)")
@@ -595,7 +623,7 @@ struct ContentView: View {
595623
596624 /// Runs a command from a key, the palette or the Org menu.
597625 private func perform(_ id: String) {
598 let orgOnly = ["app.refile", "app.archive", "app.clock.in", "app.clock.default"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
626 let orgOnly = ["app.refile", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
599627 if orgOnly, !session.isOrg {
600628 commands.show("Not an org file")
601629 return
@@ -735,6 +763,8 @@ struct ContentView: View {
735763 case "app.recovery":
736764 guard session.path != nil else { return commands.show("No file is open") }
737765 panel = .recovery(UUID())
766 case "app.copy-rich-text":
767 copyRichText()
738768 case "app.export-dialog":
739769 guard let path = session.path else { return commands.show("No file is open") }
740770 panel = .export(UUID(), URL(fileURLWithPath: path))
Sources/Orgstar/ExportSheet.swift +4 −3
@@ -17,14 +17,15 @@ struct ExportSheet: View {
1717 @Environment(\.dismiss) private var dismiss
1818
1919 static let formats: [(id: String, title: String, ext: String)] = [
20 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
21 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX (Emacs)", "tex"), ("text", "Plain text (Emacs)", "txt"),
20 ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"),
21 ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"),
22 ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX (Emacs)", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"),
2223 ]
2324
2425 private var ext: String { Self.formats.first { $0.id == format }?.ext ?? "html" }
2526 private var chosen: URL { destination ?? target(ext, subtree) }
2627 /// PDF and ODT are whole documents.
27 private var allowsBodyOnly: Bool { !["pdf", "print-pdf", "odt"].contains(format) }
28 private var allowsBodyOnly: Bool { !["pdf", "print-pdf", "odt", "docx", "rtf", "plain-text"].contains(format) }
2829
2930 var body: some View {
3031 Form {
Sources/OrgstarMobile/EditorScreen.swift +1 −1
@@ -71,7 +71,7 @@ struct EditorScreen: View {
7171 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
7272 }
7373 RecentClockMenu(clock: clock) { editor?.run($0) }
74 if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) }
74 if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } }
7575 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
7676 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
7777 }
Sources/OrgstarMobile/ExportMenu.swift +36 −4
@@ -9,13 +9,15 @@ import UniformTypeIdentifiers
99/// A file exported as HTML, Markdown or PDF, written when the share sheet takes it.
1010struct OrgExport: Transferable {
1111 enum Format: CaseIterable {
12 case html, markdown, pdf
12 case html, markdown, pdf, rtf, plainText
1313
1414 var name: String {
1515 switch self {
1616 case .html: "HTML"
1717 case .markdown: "Markdown"
1818 case .pdf: "PDF"
19 case .rtf: "Rich Text (RTF)"
20 case .plainText: "Plain Text"
1921 }
2022 }
2123
@@ -24,6 +26,8 @@ struct OrgExport: Transferable {
2426 case .html: "html"
2527 case .markdown: "md"
2628 case .pdf: "pdf"
29 case .rtf: "rtf"
30 case .plainText: "txt"
2731 }
2832 }
2933 }
@@ -48,6 +52,10 @@ struct OrgExport: Transferable {
4852 .exportingCondition { $0.format == .markdown }
4953 FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
5054 .exportingCondition { $0.format == .pdf }
55 FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
56 .exportingCondition { $0.format == .rtf }
57 FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
58 .exportingCondition { $0.format == .plainText }
5159 }
5260
5361 private func write() async throws -> SentTransferredFile {
@@ -62,20 +70,28 @@ struct OrgExport: Transferable {
6270 .write(to: url, atomically: true, encoding: .utf8)
6371 case .markdown:
6472 try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
65 case .pdf:
73 case .pdf, .rtf, .plainText:
6674 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle)
6775 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
68 try await PDFExport.pdf(html: html, directory: directory).write(to: url, options: .atomic)
76 let data: Data = switch format {
77 case .pdf: try await PDFExport.pdf(html: html, directory: directory)
78 case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
79 default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
80 }
81 try data.write(to: url, options: .atomic)
6982 }
7083 return SentTransferredFile(url)
7184 }
7285}
7386
74/// Sharing the file as HTML, Markdown or PDF: to another app, or saved with Save to Files.
87/// Sharing the file as HTML, Markdown, PDF, RTF or plain text: to another app, or saved with
88/// Save to Files; or copying it as rich text.
7589struct ExportMenu: View {
7690 let path: String
7791 let text: String
7892 @Environment(MobileModel.self) private var model
93 /// Shows what happened, as the screen's message line does.
94 var report: (String) -> Void = { _ in }
7995
8096 var body: some View {
8197 Menu("Export", systemImage: "square.and.arrow.up") {
@@ -84,6 +100,22 @@ struct ExportMenu: View {
84100 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
85101 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
86102 }
103 Divider()
104 Button("Copy as Rich Text", systemImage: "doc.on.doc") { copy() }
105 }
106 }
107
108 /// The file on the clipboard as HTML, RTF and plain text, to paste formatted.
109 private func copy() {
110 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
111 let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
112 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
113 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
114 do {
115 try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
116 report("Copied as rich text")
117 } catch {
118 report("\(error)")
87119 }
88120 }
89121}
Sources/OrgstarMobile/ReaderScreen.swift +1 −1
@@ -98,7 +98,7 @@ struct ReaderScreen: View {
9898 ToolbarItemGroup(placement: .primaryAction) {
9999 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty)
100100 if let path = session.path {
101 if let text = session.document?.text { ExportMenu(path: path, text: text) }
101 if let text = session.document?.text { ExportMenu(path: path, text: text) { message = $0 } }
102102 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "square.and.pencil") }
103103 }
104104 }
Tests/OrgAppTests/RichTextExportTests.swift added +46
@@ -0,0 +1,46 @@
1import AppKit
2import Foundation
3import OrgCore
4import Testing
5@testable import OrgApp
6
7@MainActor
8struct RichTextExportTests {
9 static let html = HTMLExport.page("""
10 #+TITLE: Report
11 * Results
12 Some *bold* text.
13 | Name | Count |
14 |------+-------|
15 | a | 1 |
16 - first
17 - second
18 #+begin_src sh
19 echo hi
20 #+end_src
21 """, fallbackTitle: "t")
22
23 @Test func wordAndRTFReadBackWithTheText() throws {
24 let text = try RichTextExport.attributed(html: Self.html, directory: nil)
25 for data in [try RichTextExport.docx(text), try RichTextExport.rtf(text)] {
26 let back = try NSAttributedString(data: data, options: [:], documentAttributes: nil).string
27 #expect(back.contains("Report") && back.contains("bold") && back.contains("Count") && back.contains("second") && back.contains("echo hi"), "\(back)")
28 }
29 // Word gets a real table, which the system's own writer leaves out.
30 let xml = String(decoding: try RichTextExport.docx(text), as: UTF8.self)
31 #expect(xml.contains("<w:tbl>") && xml.components(separatedBy: "<w:tc>").count - 1 == 4)
32 // Bold survives.
33 let bold = (text.string as NSString).range(of: "bold")
34 let font = text.attribute(.font, at: bold.location, effectiveRange: nil) as? NSFont
35 #expect(font?.fontDescriptor.symbolicTraits.contains(.bold) == true)
36 }
37
38 @Test func plainTextAndDarkSystemsStayReadable() throws {
39 let text = try RichTextExport.attributed(html: Self.html, directory: nil)
40 let plain = RichTextExport.plain(text)
41 #expect(plain.hasPrefix("Report") && plain.contains("Some bold text.") && plain.hasSuffix("echo hi\n"))
42 // The colors are the light ones whatever the appearance.
43 let color = text.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor
44 #expect((color?.usingColorSpace(.sRGB)?.brightnessComponent ?? 0) < 0.5)
45 }
46}
docs/manual/guide/03-keys.org +4
@@ -938,6 +938,10 @@ When a key appears in several rows, it runs the command whose condition holds at
938938| Export to HTML and Open (=app.export.html-open=) | =C-c C-e h o= | — | =SPC m e h o= (N) | Exports to HTML and opens the result. |
939939| Export to Markdown (=app.export.markdown=) | =C-c C-e m m= | — | =SPC m e m m= (N) | Exports to Markdown (=org-md-export-to-markdown=). |
940940| Export to PDF (=app.export.print-pdf=) | — | — | — | Exports to PDF without Emacs, laid out as the HTML export. |
941| Export to Word (=app.export.docx=) | — | — | — | Exports to a Word document (=.docx=). |
942| Export to RTF (=app.export.rtf=) | — | — | — | Exports to Rich Text Format. |
943| Export to Plain Text (=app.export.plain-text=) | — | — | — | Exports the text without styles, without Emacs. |
944| Copy as Rich Text (=app.copy-rich-text=) | — | — | — | Copies the selection, or the file, as HTML, RTF and plain text. |
941945| Export to PDF with Emacs (=app.export.pdf=) | =C-c C-e l p= | — | =SPC m e l p= (N) | Exports to PDF through Emacs (=org-latex-export-to-pdf=). |
942946| Export to LaTeX with Emacs (=app.export.latex=) | =C-c C-e l l= | — | — | Exports to LaTeX through Emacs (=org-latex-export-to-latex=). |
943947| Export to ODT with Emacs (=app.export.odt=) | =C-c C-e o o= | — | — | Exports to ODT through Emacs (=org-odt-export-to-odt=). |
docs/manual/guide/12-export.org +20 −7
@@ -1,6 +1,6 @@
11#+TITLE: Export
2#+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown and PDF, and to LaTeX, ODT and plain text through Emacs.
3#+LEDE: orgstar exports HTML, Markdown and PDF itself, on the Mac and iOS, and hands LaTeX, ODT, plain text and LaTeX-made PDF to Emacs on the Mac.
2#+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown, PDF, Word, RTF and plain text, and to LaTeX, ODT and ASCII through Emacs; copying as rich text.
3#+LEDE: orgstar exports HTML, Markdown, PDF, Word, RTF and plain text itself, and hands LaTeX, ODT, ASCII and LaTeX-made PDF to Emacs on the Mac.
44
55* Exporting a file
66
@@ -14,22 +14,25 @@ Export works on the file in the current editor, using its text as it is now, sav
1414| HTML, then open it | Export to HTML and Open | =C-c C-e h o= | =SPC m e h o=, =C-c C-e h o= | no |
1515| Markdown | Export to Markdown | =C-c C-e m m= | =SPC m e m m=, =C-c C-e m m= | no |
1616| PDF | Export to PDF | — | — | no |
17| Word | Export to Word | — | — | no |
18| RTF | Export to RTF | — | — | no |
19| Plain text | Export to Plain Text | — | — | no |
1720| PDF through LaTeX | Export to PDF with Emacs | =C-c C-e l p= | =SPC m e l p=, =C-c C-e l p= | yes |
1821| LaTeX | Export to LaTeX with Emacs | =C-c C-e l l= | =C-c C-e l l= | yes |
1922| ODT | Export to ODT with Emacs | =C-c C-e o o= | =C-c C-e o o= | yes |
20| Plain text | Export to Plain Text with Emacs | =C-c C-e t u= | =C-c C-e t u= | yes |
23| ASCII text | Export to Plain Text with Emacs | =C-c C-e t u= | =C-c C-e t u= | yes |
2124
2225The keys follow Emacs's export dispatcher (=org-export-dispatch=). =C-c C-e= on its own is only a prefix: pause after it and the key hints list the formats. The =SPC m e= keys work in normal state; the =C-c C-e= keys work in every Doom state. The Mac preset has no keys for the single formats; its =⇧⌘E= opens the export dialog.
2326
24All eight commands are in File ▸ Export and in the command palette. They write the export beside the Org file, with the same name and the format's extension: =.html=, =.md=, =.pdf=, =.tex=, =.odt= or =.txt=. =#+EXPORT_FILE_NAME:= names it instead, as in Org: relative to the Org file's folder (or absolute, or starting with =~=), with its extension replaced by the format's, so =#+EXPORT_FILE_NAME: out/report= writes =out/report.html=. A file already there is replaced. The message area shows "Exported to /name/".
27All eleven commands are in File ▸ Export and in the command palette. They write the export beside the Org file, with the same name and the format's extension: =.html=, =.md=, =.pdf=, =.docx=, =.rtf=, =.tex=, =.odt= or =.txt=. =#+EXPORT_FILE_NAME:= names it instead, as in Org: relative to the Org file's folder (or absolute, or starting with =~=), with its extension replaced by the format's, so =#+EXPORT_FILE_NAME: out/report= writes =out/report.html=. A file already there is replaced. The message area shows "Exported to /name/".
2528
2629** The export dialog
2730
2831*Export…* in the command palette, or =⇧⌘E= in the Mac preset, opens a dialog. The Emacs and Doom presets have no key for it; bind =app.export-dialog= in =keymap.toml= if you want one (see [[file:03-keys.org][Keys and commands]]). The dialog has:
2932
30- *Format*: HTML, Markdown, PDF, PDF via LaTeX (Emacs), ODT (Emacs), LaTeX (Emacs) or Plain text (Emacs).
33- *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT (Emacs), LaTeX (Emacs) or Plain text, ASCII (Emacs).
3134- *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading.
32- *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF and ODT.
35- *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF, Word, RTF, plain text and ODT.
3336- *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension.
3437- *Open after export*: opens the file in its default app when the export finishes.
3538
@@ -37,7 +40,7 @@ The dialog remembers the format and the *Open after export* setting.
3740
3841** On iOS
3942
40The Export menu offers HTML, Markdown and PDF. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac. LaTeX, ODT, plain text and PDF through LaTeX are not available on iOS.
43The Export menu offers HTML, Markdown, PDF, Rich Text (RTF) and Plain Text, and Copy as Rich Text. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac. Word, LaTeX, ODT, ASCII and PDF through LaTeX are not available on iOS; RTF opens in Word and Pages.
4144
4245* HTML export
4346
@@ -204,6 +207,16 @@ Export to PDF makes the HTML export into a PDF, laid out and split into pages by
204207
205208For typeset output with LaTeX's classes and packages, use Export to PDF with Emacs instead (see /Exporting through Emacs/).
206209
210* Word, RTF and plain text
211
212Export to Word, Export to RTF and Export to Plain Text make the HTML export into a document of that kind, as the system reads HTML: headings, emphasis, links, colored keywords and code, lists, and tables. Word files (=.docx=) are written by orgstar itself, so tables come through as Word tables; RTF keeps them too. Plain text is the same text without its styles: list bullets and table cells are kept, separated by tabs. Fonts are Helvetica Neue for text and Menlo for code, and the colors are the light ones. Images are not included.
213
214For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text with Emacs.
215
216** Copying as rich text
217
218*Copy as Rich Text* (the command palette on the Mac, the Export menu on iOS) puts the selection, or the whole file when nothing is selected, on the clipboard as HTML, RTF and plain text. Paste it into Mail, Pages, Word or a web form to get the formatted text. On iOS it copies the whole file.
219
207220* Markdown export
208221
209222Markdown export writes GitHub-flavored Markdown: