Commit a35da9b282
Verified · cmc
Layout: unified · split
Sources/OrgApp/DocxWriter.swift +79 −32
| @@ -1,13 +1,24 @@ | ||
| 1 | import Foundation | |
| 1 | 2 | #if os(macOS) |
| 2 | 3 | import AppKit |
| 3 | import Foundation | |
| 4 | typealias DocxFont = NSFont | |
| 5 | typealias DocxColor = NSColor | |
| 6 | #else | |
| 7 | import UIKit | |
| 8 | typealias DocxFont = UIFont | |
| 9 | typealias DocxColor = UIColor | |
| 10 | #endif | |
| 4 | 11 | |
| 5 | 12 | /// 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. | |
| 13 | /// tables from the text's table blocks, which the system's own writer leaves out. iOS's HTML | |
| 14 | /// import keeps no tables, so there `tables` holds them, each standing for a paragraph that is | |
| 15 | /// its `marker` alone. | |
| 7 | 16 | enum DocxWriter { |
| 8 | static func data(from text: NSAttributedString) -> Data { | |
| 17 | static func marker(_ index: Int) -> String { "\u{E000}\(index)\u{E001}" } | |
| 18 | ||
| 19 | static func data(from text: NSAttributedString, tables: [String] = []) -> Data { | |
| 9 | 20 | var links: [String] = [] |
| 10 | let body = paragraphs(text, links: &links) | |
| 21 | let body = paragraphs(text, tables: tables, links: &links) | |
| 11 | 22 | let document = """ |
| 12 | 23 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> |
| 13 | 24 | <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \ |
| @@ -42,33 +53,49 @@ enum DocxWriter { | ||
| 42 | 53 | } |
| 43 | 54 | |
| 44 | 55 | /// Paragraphs in order, consecutive ones in the same table gathered into `<w:tbl>`. |
| 45 | private static func paragraphs(_ text: NSAttributedString, links: inout [String]) -> String { | |
| 56 | /// A `<w:tbl>` of rows of cells, each cell its paragraphs. | |
| 57 | static func table(_ rows: [[String]], columns: Int) -> String { | |
| 58 | var out = "<w:tbl><w:tblPr><w:tblBorders>" + ["top", "left", "bottom", "right", "insideH", "insideV"].map { | |
| 59 | "<w:\($0) w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"A0A0A0\"/>" | |
| 60 | }.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>" | |
| 61 | out += "<w:tblGrid>" + String(repeating: "<w:gridCol/>", count: columns) + "</w:tblGrid>" | |
| 62 | for row in rows { | |
| 63 | out += "<w:tr>" | |
| 64 | for column in 0..<columns { | |
| 65 | out += "<w:tc><w:tcPr/>" + (column < row.count && !row[column].isEmpty ? row[column] : "<w:p/>") + "</w:tc>" | |
| 66 | } | |
| 67 | out += "</w:tr>" | |
| 68 | } | |
| 69 | return out + "</w:tbl>" | |
| 70 | } | |
| 71 | ||
| 72 | private static func paragraphs(_ text: NSAttributedString, tables: [String], links: inout [String]) -> String { | |
| 46 | 73 | let string = text.string as NSString |
| 47 | 74 | var out = "" |
| 75 | #if os(macOS) | |
| 48 | 76 | var table: (block: NSTextTable, cells: [[Int: [String]]])? |
| 49 | 77 | func flushTable() { |
| 50 | 78 | 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 | 79 | 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>" | |
| 80 | out += Self.table(current.cells.map { row in (0..<columns).map { row[$0]?.joined() ?? "" } }, columns: columns) | |
| 64 | 81 | table = nil |
| 65 | 82 | } |
| 83 | #else | |
| 84 | func flushTable() {} | |
| 85 | #endif | |
| 66 | 86 | var location = 0 |
| 67 | 87 | while location < string.length { |
| 68 | 88 | let range = string.paragraphRange(for: NSRange(location: location, length: 0)) |
| 69 | 89 | location = NSMaxRange(range) |
| 90 | let line = string.substring(with: range).trimmingCharacters(in: .whitespacesAndNewlines) | |
| 91 | if let index = tables.indices.first(where: { line == marker($0) }) { | |
| 92 | flushTable() | |
| 93 | out += tables[index] | |
| 94 | continue | |
| 95 | } | |
| 70 | 96 | let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle |
| 71 | 97 | let paragraph = self.paragraph(text, range, style, links: &links) |
| 98 | #if os(macOS) | |
| 72 | 99 | if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last { |
| 73 | 100 | if table?.block !== cell.table { |
| 74 | 101 | flushTable() |
| @@ -76,10 +103,11 @@ enum DocxWriter { | ||
| 76 | 103 | } |
| 77 | 104 | while table!.cells.count <= cell.startingRow { table!.cells.append([:]) } |
| 78 | 105 | table!.cells[cell.startingRow][cell.startingColumn, default: []].append(paragraph) |
| 79 | } else { | |
| 80 | flushTable() | |
| 81 | out += paragraph | |
| 106 | continue | |
| 82 | 107 | } |
| 108 | #endif | |
| 109 | flushTable() | |
| 110 | out += paragraph | |
| 83 | 111 | } |
| 84 | 112 | flushTable() |
| 85 | 113 | return out |
| @@ -118,18 +146,18 @@ enum DocxWriter { | ||
| 118 | 146 | |
| 119 | 147 | private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any]) -> String { |
| 120 | 148 | 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") | |
| 149 | if let font = attributes[.font] as? DocxFont { | |
| 150 | let traits = self.traits(font) | |
| 151 | let name = traits.mono ? "Menlo" : traits.family | |
| 124 | 152 | 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/>" } | |
| 153 | if traits.bold { properties += "<w:b/>" } | |
| 154 | if traits.italic { properties += "<w:i/>" } | |
| 127 | 155 | properties += "<w:sz w:val=\"\(Int((font.pointSize * 2).rounded()))\"/>" |
| 128 | 156 | } |
| 129 | if let color = (attributes[.foregroundColor] as? NSColor)?.usingColorSpace(.sRGB) { properties += "<w:color w:val=\"\(hex(color))\"/>" } | |
| 157 | if let color = (attributes[.foregroundColor] as? DocxColor).flatMap(rgba) { properties += "<w:color w:val=\"\(hex(color))\"/>" } | |
| 130 | 158 | if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "<w:u w:val=\"single\"/>" } |
| 131 | 159 | if (attributes[.strikethroughStyle] as? Int ?? 0) != 0 { properties += "<w:strike/>" } |
| 132 | if let background = (attributes[.backgroundColor] as? NSColor)?.usingColorSpace(.sRGB), background.alphaComponent > 0.05 { | |
| 160 | if let background = (attributes[.backgroundColor] as? DocxColor).flatMap(rgba), background.a > 0.05 { | |
| 133 | 161 | properties += "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"\(hex(background))\"/>" |
| 134 | 162 | } |
| 135 | 163 | if let offset = attributes[.baselineOffset] as? Double, offset != 0 { properties += "<w:vertAlign w:val=\"\(offset > 0 ? "superscript" : "subscript")\"/>" } |
| @@ -151,11 +179,31 @@ enum DocxWriter { | ||
| 151 | 179 | return "<w:r><w:rPr>\(properties)</w:rPr>\(content)</w:r>" |
| 152 | 180 | } |
| 153 | 181 | |
| 182 | private static func traits(_ font: DocxFont) -> (bold: Bool, italic: Bool, mono: Bool, family: String) { | |
| 183 | let traits = font.fontDescriptor.symbolicTraits | |
| 184 | #if os(macOS) | |
| 185 | return (traits.contains(.bold), traits.contains(.italic), traits.contains(.monoSpace), font.familyName ?? "Helvetica Neue") | |
| 186 | #else | |
| 187 | return (traits.contains(.traitBold), traits.contains(.traitItalic), traits.contains(.traitMonoSpace), font.familyName) | |
| 188 | #endif | |
| 189 | } | |
| 190 | ||
| 191 | /// The color's sRGB components and alpha. | |
| 192 | private static func rgba(_ color: DocxColor) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? { | |
| 193 | #if os(macOS) | |
| 194 | guard let c = color.usingColorSpace(.sRGB) else { return nil } | |
| 195 | return (c.redComponent, c.greenComponent, c.blueComponent, c.alphaComponent) | |
| 196 | #else | |
| 197 | var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 | |
| 198 | guard color.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil } | |
| 199 | return (r, g, b, a) | |
| 200 | #endif | |
| 201 | } | |
| 202 | ||
| 154 | 203 | /// `#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)) | |
| 204 | private static func hex(_ color: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)) -> String { | |
| 205 | func on(_ c: CGFloat) -> Int { Int(((c * color.a + (1 - color.a)) * 255).rounded()) } | |
| 206 | return String(format: "%02X%02X%02X", on(color.r), on(color.g), on(color.b)) | |
| 159 | 207 | } |
| 160 | 208 | |
| 161 | 209 | static func escape(_ s: String) -> String { |
| @@ -208,4 +256,3 @@ struct ZipWriter { | ||
| 208 | 256 | return c ^ 0xFFFFFFFF |
| 209 | 257 | } |
| 210 | 258 | } |
| 211 | #endif | |
Sources/OrgApp/RichTextExport.swift +45
| @@ -49,6 +49,51 @@ public enum RichTextExport { | ||
| 49 | 49 | } |
| 50 | 50 | #endif |
| 51 | 51 | |
| 52 | /// The HTML export as Word's `.docx`, tables included. | |
| 53 | public static func docx(html: String, directory: URL?) throws -> Data { | |
| 54 | #if os(macOS) | |
| 55 | return try docx(attributed(html: html, directory: directory)) | |
| 56 | #else | |
| 57 | let (page, tables) = extractingTables(html) | |
| 58 | return DocxWriter.data(from: try attributed(html: page, directory: directory), tables: tables) | |
| 59 | #endif | |
| 60 | } | |
| 61 | ||
| 62 | /// `html` with each `<table>` replaced by a paragraph holding `DocxWriter.marker`, and the | |
| 63 | /// tables as Word XML, header cells bold. | |
| 64 | static func extractingTables(_ html: String) -> (html: String, tables: [String]) { | |
| 65 | var tables: [String] = [] | |
| 66 | var out = "" | |
| 67 | var rest = Substring(html) | |
| 68 | while let match = rest.firstMatch(of: #/(?is)<table\b.*?</table>/#) { | |
| 69 | out += rest[..<match.range.lowerBound] | |
| 70 | var rows: [[String]] = [] | |
| 71 | for row in match.0.matches(of: #/(?is)<tr\b[^>]*>(.*?)</tr>/#) { | |
| 72 | rows.append(row.1.matches(of: #/(?is)<t([hd])\b[^>]*>(.*?)</t[hd]>/#).map { cell in | |
| 73 | let text = decode(String(cell.2).replacing(#/(?s)<[^>]*>/#, with: "")).trimmingCharacters(in: .whitespacesAndNewlines) | |
| 74 | guard !text.isEmpty else { return "" } | |
| 75 | return "<w:p><w:pPr></w:pPr><w:r><w:rPr>\(cell.1.lowercased() == "h" ? "<w:b/>" : "")</w:rPr><w:t xml:space=\"preserve\">\(DocxWriter.escape(text))</w:t></w:r></w:p>" | |
| 76 | }) | |
| 77 | } | |
| 78 | out += "<p>\(DocxWriter.marker(tables.count))</p>" | |
| 79 | tables.append(DocxWriter.table(rows, columns: rows.map(\.count).max() ?? 1)) | |
| 80 | rest = rest[match.range.upperBound...] | |
| 81 | } | |
| 82 | return (out + rest, tables) | |
| 83 | } | |
| 84 | ||
| 85 | /// HTML character references. | |
| 86 | static func decode(_ s: String) -> String { | |
| 87 | var out = s | |
| 88 | for (entity, character) in [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), (" ", "\u{A0}")] { | |
| 89 | out = out.replacingOccurrences(of: entity, with: character) | |
| 90 | } | |
| 91 | out = out.replacing(#/&#(x?)([0-9a-fA-F]+);/#) { m in | |
| 92 | UInt32(m.2, radix: m.1.isEmpty ? 10 : 16).flatMap(Unicode.Scalar.init).map { String(Character($0)) } ?? String(m.0) | |
| 93 | } | |
| 94 | return out.replacingOccurrences(of: "&", with: "&") | |
| 95 | } | |
| 96 | ||
| 52 | 97 | /// The HTML export as RTF. |
| 53 | 98 | public static func rtf(html: String, directory: URL?) throws -> Data { |
| 54 | 99 | try rtf(attributed(html: html, directory: directory)) |
Sources/OrgstarMobile/EditorScreen.swift +63
| @@ -4,6 +4,7 @@ import OrgCore | ||
| 4 | 4 | import OrgDocument |
| 5 | 5 | import SwiftUI |
| 6 | 6 | import UIKit |
| 7 | import UniformTypeIdentifiers | |
| 7 | 8 | |
| 8 | 9 | /// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard, |
| 9 | 10 | /// and every command in a palette. The editor is the open file's live state, so autosave and |
| @@ -39,6 +40,11 @@ struct EditorScreen: View { | ||
| 39 | 40 | } |
| 40 | 41 | |
| 41 | 42 | /// One sheet at a time: two presenters on this screen interfere. |
| 43 | /// `org-table-import`'s file picker is up. | |
| 44 | @State private var importingTable = false | |
| 45 | /// The table at the caret, for `org-table-export`'s save dialog. | |
| 46 | @State private var exportedTable: TableFile? | |
| 47 | ||
| 42 | 48 | enum Sheet: Identifiable { |
| 43 | 49 | case palette, conflict, syncCopies, recovery |
| 44 | 50 | /// `app.refile`, `app.refile.copy` or `app.refile.goto`. |
| @@ -82,6 +88,11 @@ struct EditorScreen: View { | ||
| 82 | 88 | Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") } |
| 83 | 89 | Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") } |
| 84 | 90 | Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") } |
| 91 | Menu("Table", systemImage: "tablecells") { | |
| 92 | Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true } | |
| 93 | Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) } | |
| 94 | Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) } | |
| 95 | } | |
| 85 | 96 | Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) { |
| 86 | 97 | Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right") |
| 87 | 98 | } |
| @@ -148,6 +159,14 @@ struct EditorScreen: View { | ||
| 148 | 159 | ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) } |
| 149 | 160 | } |
| 150 | 161 | } |
| 162 | .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in | |
| 163 | importTable(result) | |
| 164 | } | |
| 165 | .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }), | |
| 166 | document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText, | |
| 167 | defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in | |
| 168 | if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." } | |
| 169 | } | |
| 151 | 170 | .onChange(of: session.conflict) { _, conflict in |
| 152 | 171 | if conflict != nil, session.path == path { sheet = .conflict } |
| 153 | 172 | } |
| @@ -237,6 +256,10 @@ struct EditorScreen: View { | ||
| 237 | 256 | _ = session.save(path) |
| 238 | 257 | } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) { |
| 239 | 258 | sheet = .refile(id) |
| 259 | } else if id == "app.table-import" { | |
| 260 | importingTable = true | |
| 261 | } else if id == "app.table-export" { | |
| 262 | exportTable(csv: true) | |
| 240 | 263 | } else if id == "app.toggle-markup" { |
| 241 | 264 | model.showMarkup.toggle() |
| 242 | 265 | } else if MobileEditor.linkCommands.contains(id) { |
| @@ -258,6 +281,25 @@ struct EditorScreen: View { | ||
| 258 | 281 | } |
| 259 | 282 | |
| 260 | 283 | extension EditorScreen { |
| 284 | /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret. | |
| 285 | private func importTable(_ result: Result<URL, Error>) { | |
| 286 | guard case .success(let url) = result, let editor else { return } | |
| 287 | let scoped = url.startAccessingSecurityScopedResource() | |
| 288 | defer { if scoped { url.stopAccessingSecurityScopedResource() } } | |
| 289 | guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" } | |
| 290 | _ = editor.perform(ImportTable(contents: contents)) | |
| 291 | } | |
| 292 | ||
| 293 | /// `org-table-export` of the table at the caret, as CSV or TSV. | |
| 294 | private func exportTable(csv: Bool) { | |
| 295 | guard let editor else { return } | |
| 296 | let context = editor.editContext() | |
| 297 | guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else { | |
| 298 | return message = "No table at point" | |
| 299 | } | |
| 300 | exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText) | |
| 301 | } | |
| 302 | ||
| 261 | 303 | /// `org-refile` of the entry at the caret, to a target worked out again from the files |
| 262 | 304 | /// now, as the agenda's Refile… does. |
| 263 | 305 | func refile(to target: RefileTarget, keep: Bool = false) { |
| @@ -550,6 +592,7 @@ struct CommandPalette: View { | ||
| 550 | 592 | ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), |
| 551 | 593 | ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"), |
| 552 | 594 | ("org.table.expand", "Expand Table Columns"), |
| 595 | ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), | |
| 553 | 596 | ] |
| 554 | 597 | |
| 555 | 598 | /// The commands that apply at the caret and their keys, worked out once when the palette |
| @@ -587,4 +630,24 @@ struct CommandPalette: View { | ||
| 587 | 630 | } |
| 588 | 631 | } |
| 589 | 632 | } |
| 633 | /// A table as CSV or TSV, for the save dialog. | |
| 634 | struct TableFile: FileDocument { | |
| 635 | static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] } | |
| 636 | let text: String | |
| 637 | let type: UTType | |
| 638 | ||
| 639 | init(text: String, type: UTType) { | |
| 640 | self.text = text | |
| 641 | self.type = type | |
| 642 | } | |
| 643 | ||
| 644 | init(configuration: ReadConfiguration) throws { | |
| 645 | text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? "" | |
| 646 | type = configuration.contentType | |
| 647 | } | |
| 648 | ||
| 649 | func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { | |
| 650 | FileWrapper(regularFileWithContents: Data(text.utf8)) | |
| 651 | } | |
| 652 | } | |
| 590 | 653 | #endif |
Sources/OrgstarMobile/ExportMenu.swift +11 −4
| @@ -6,17 +6,18 @@ import OrgPresentation | ||
| 6 | 6 | import SwiftUI |
| 7 | 7 | import UniformTypeIdentifiers |
| 8 | 8 | |
| 9 | /// A file exported as HTML, Markdown, PDF, RTF, plain text or iCalendar, written when the share | |
| 10 | /// sheet takes it. | |
| 9 | /// A file exported as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar, written when the | |
| 10 | /// share sheet takes it. | |
| 11 | 11 | struct OrgExport: Transferable { |
| 12 | 12 | enum Format: CaseIterable { |
| 13 | case html, markdown, pdf, rtf, plainText, icalendar | |
| 13 | case html, markdown, pdf, docx, rtf, plainText, icalendar | |
| 14 | 14 | |
| 15 | 15 | var name: String { |
| 16 | 16 | switch self { |
| 17 | 17 | case .html: "HTML" |
| 18 | 18 | case .markdown: "Markdown" |
| 19 | 19 | case .pdf: "PDF" |
| 20 | case .docx: "Word" | |
| 20 | 21 | case .rtf: "Rich Text (RTF)" |
| 21 | 22 | case .plainText: "Plain Text" |
| 22 | 23 | case .icalendar: "iCalendar" |
| @@ -28,6 +29,7 @@ struct OrgExport: Transferable { | ||
| 28 | 29 | case .html: "html" |
| 29 | 30 | case .markdown: "md" |
| 30 | 31 | case .pdf: "pdf" |
| 32 | case .docx: "docx" | |
| 31 | 33 | case .rtf: "rtf" |
| 32 | 34 | case .plainText: "txt" |
| 33 | 35 | case .icalendar: "ics" |
| @@ -55,6 +57,8 @@ struct OrgExport: Transferable { | ||
| 55 | 57 | .exportingCondition { $0.format == .markdown } |
| 56 | 58 | FileRepresentation(exportedContentType: .pdf) { try await $0.write() } |
| 57 | 59 | .exportingCondition { $0.format == .pdf } |
| 60 | FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() } | |
| 61 | .exportingCondition { $0.format == .docx } | |
| 58 | 62 | FileRepresentation(exportedContentType: .rtf) { try await $0.write() } |
| 59 | 63 | .exportingCondition { $0.format == .rtf } |
| 60 | 64 | FileRepresentation(exportedContentType: .plainText) { try await $0.write() } |
| @@ -77,6 +81,9 @@ struct OrgExport: Transferable { | ||
| 77 | 81 | try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8) |
| 78 | 82 | case .icalendar: |
| 79 | 83 | try ICalendarFiles.export(text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(), destination: url) |
| 84 | case .docx: | |
| 85 | let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle) | |
| 86 | try await RichTextExport.docx(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).write(to: url, options: .atomic) | |
| 80 | 87 | case .pdf, .rtf, .plainText: |
| 81 | 88 | let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle) |
| 82 | 89 | let directory = URL(fileURLWithPath: path).deletingLastPathComponent() |
| @@ -91,7 +98,7 @@ struct OrgExport: Transferable { | ||
| 91 | 98 | } |
| 92 | 99 | } |
| 93 | 100 | |
| 94 | /// Sharing the file as HTML, Markdown, PDF, RTF, plain text or iCalendar: to another app, or saved with | |
| 101 | /// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar: to another app, or saved with | |
| 95 | 102 | /// Save to Files; or copying it as rich text. |
| 96 | 103 | struct ExportMenu: View { |
| 97 | 104 | let path: String |
Sources/OrgstarMobile/MobileEditor.swift +2 −1
| @@ -297,7 +297,8 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 297 | 297 | case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true |
| 298 | 298 | case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last", |
| 299 | 299 | "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil |
| 300 | case "app.refile.goto": return onAppCommand != nil | |
| 300 | case "app.refile.goto", "app.table-import": return onAppCommand != nil | |
| 301 | case "app.table-export": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil | |
| 301 | 302 | case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil |
| 302 | 303 | case _ where Self.linkCommands.contains(id): return onAppCommand != nil |
| 303 | 304 | case "org.link.open": return OpenLinkAtPoint().applies(in: context) |
Tests/OrgAppTests/RichTextExportTests.swift +15
| @@ -35,6 +35,21 @@ struct RichTextExportTests { | ||
| 35 | 35 | #expect(font?.fontDescriptor.symbolicTraits.contains(.bold) == true) |
| 36 | 36 | } |
| 37 | 37 | |
| 38 | /// As iOS writes Word, whose HTML import keeps no tables: the tables from the HTML. | |
| 39 | @Test func wordTablesFromTheHTML() throws { | |
| 40 | let (page, tables) = RichTextExport.extractingTables(Self.html) | |
| 41 | #expect(tables.count == 1 && !page.contains("<table") && page.contains(DocxWriter.marker(0))) | |
| 42 | #expect(tables[0].components(separatedBy: "<w:tc>").count - 1 == 4) | |
| 43 | #expect(tables[0].contains("<w:b/></w:rPr><w:t xml:space=\"preserve\">Name</w:t>")) | |
| 44 | #expect(tables[0].contains("<w:r><w:rPr></w:rPr><w:t xml:space=\"preserve\">1</w:t>")) | |
| 45 | let data = DocxWriter.data(from: try RichTextExport.attributed(html: page, directory: nil), tables: tables) | |
| 46 | let xml = String(decoding: data, as: UTF8.self) | |
| 47 | #expect(xml.contains("<w:tbl>") && !xml.contains("\u{E000}")) | |
| 48 | let back = try NSAttributedString(data: data, options: [:], documentAttributes: nil).string | |
| 49 | #expect(back.contains("Report") && back.contains("Count") && back.contains("second"), "\(back)") | |
| 50 | #expect(RichTextExport.decode("a &lt; éA "") == "a < éA \"") | |
| 51 | } | |
| 52 | ||
| 38 | 53 | @Test func plainTextAndDarkSystemsStayReadable() throws { |
| 39 | 54 | let text = try RichTextExport.attributed(html: Self.html, directory: nil) |
| 40 | 55 | let plain = RichTextExport.plain(text) |
docs/manual/guide/10-tables.org +4 −1
| @@ -153,7 +153,10 @@ tables at full width. | ||
| 153 | 153 | | Import Table from File… (command palette) | =org-table-import= | |
| 154 | 154 | | Export Table to File… (command palette) | =org-table-export= | |
| 155 | 155 | |
| 156 | Open the command palette with =⇧⌘P= (=M-x= in the Emacs preset, =SPC := in Doom). | |
| 156 | Open the command palette with =⇧⌘P= (=M-x= in the Emacs preset, =SPC := in Doom). On | |
| 157 | iOS, both are under More › Table in the editor, as Import Table from File…, Export Table | |
| 158 | as CSV… and Export Table as TSV…, and in Commands; the file comes from, and goes to, the | |
| 159 | Files app. | |
| 157 | 160 | |
| 158 | 161 | Import asks for a CSV, TSV or plain text file, inserts its contents at the caret on a |
| 159 | 162 | line of its own, and converts them to a table with the separator guessed as for a |
docs/manual/guide/12-export.org +2 −2
| @@ -43,7 +43,7 @@ The dialog remembers the format and the *Open after export* setting. | ||
| 43 | 43 | |
| 44 | 44 | ** On iOS |
| 45 | 45 | |
| 46 | The Export menu offers HTML, Markdown, PDF, Rich Text (RTF), Plain Text and iCalendar, 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, nor are the agenda-file iCalendar exports; RTF opens in Word and Pages. | |
| 46 | The Export menu offers HTML, Markdown, PDF, Word, Rich Text (RTF), Plain Text and iCalendar, 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. LaTeX, ODT, ASCII and PDF through LaTeX are not available on iOS, nor are the agenda-file iCalendar exports. | |
| 47 | 47 | |
| 48 | 48 | * HTML export |
| 49 | 49 | |
| @@ -212,7 +212,7 @@ For typeset output with LaTeX's classes and packages, use Export to PDF with Ema | ||
| 212 | 212 | |
| 213 | 213 | * Word, RTF and plain text |
| 214 | 214 | |
| 215 | Export 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. | |
| 215 | Export 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 on the Mac. On iOS, where the system's HTML reader keeps no tables, Word's tables are made from the HTML export's tables, with header cells bold and the cells' text without its styles; RTF and plain text there have the cells' text but no table. 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. | |
| 216 | 216 | |
| 217 | 217 | For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text with Emacs. |
| 218 | 218 | |