Word export and table CSV/TSV import and export on iOS !279
8 files changed, +221 −40
Layout: unified · split
Sources/OrgApp/DocxWriter.swift +79 −32
| @@ -1,13 +1,24 @@ | |||
| 1 | import Foundation | ||
| 1 | #if os(macOS) | 2 | #if os(macOS) |
| 2 | import AppKit | 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 | /// Word's `.docx` from styled text: paragraphs with their runs' fonts, colors and links, and | 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 | enum DocxWriter { | 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 | var links: [String] = [] | 20 | var links: [String] = [] |
| 10 | let body = paragraphs(text, links: &links) | 21 | let body = paragraphs(text, tables: tables, links: &links) |
| 11 | let document = """ | 22 | let document = """ |
| 12 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> | 23 | <?xml version="1.0" encoding="UTF-8" standalone="yes"?> |
| 13 | <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \ | 24 | <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \ |
| @@ -42,33 +53,49 @@ enum DocxWriter { | |||
| 42 | } | 53 | } |
| 43 | 54 | ||
| 44 | /// Paragraphs in order, consecutive ones in the same table gathered into `<w:tbl>`. | 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 | let string = text.string as NSString | 73 | let string = text.string as NSString |
| 47 | var out = "" | 74 | var out = "" |
| 75 | #if os(macOS) | ||
| 48 | var table: (block: NSTextTable, cells: [[Int: [String]]])? | 76 | var table: (block: NSTextTable, cells: [[Int: [String]]])? |
| 49 | func flushTable() { | 77 | func flushTable() { |
| 50 | guard let current = table else { return } | 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 | let columns = max(current.block.numberOfColumns, current.cells.map { ($0.keys.max() ?? 0) + 1 }.max() ?? 1) | 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>" | 80 | out += Self.table(current.cells.map { row in (0..<columns).map { row[$0]?.joined() ?? "" } }, columns: columns) |
| 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 | 81 | table = nil |
| 65 | } | 82 | } |
| 83 | #else | ||
| 84 | func flushTable() {} | ||
| 85 | #endif | ||
| 66 | var location = 0 | 86 | var location = 0 |
| 67 | while location < string.length { | 87 | while location < string.length { |
| 68 | let range = string.paragraphRange(for: NSRange(location: location, length: 0)) | 88 | let range = string.paragraphRange(for: NSRange(location: location, length: 0)) |
| 69 | location = NSMaxRange(range) | 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 | let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle | 96 | let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle |
| 71 | let paragraph = self.paragraph(text, range, style, links: &links) | 97 | let paragraph = self.paragraph(text, range, style, links: &links) |
| 98 | #if os(macOS) | ||
| 72 | if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last { | 99 | if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last { |
| 73 | if table?.block !== cell.table { | 100 | if table?.block !== cell.table { |
| 74 | flushTable() | 101 | flushTable() |
| @@ -76,10 +103,11 @@ enum DocxWriter { | |||
| 76 | } | 103 | } |
| 77 | while table!.cells.count <= cell.startingRow { table!.cells.append([:]) } | 104 | while table!.cells.count <= cell.startingRow { table!.cells.append([:]) } |
| 78 | table!.cells[cell.startingRow][cell.startingColumn, default: []].append(paragraph) | 105 | table!.cells[cell.startingRow][cell.startingColumn, default: []].append(paragraph) |
| 79 | } else { | 106 | continue |
| 80 | flushTable() | ||
| 81 | out += paragraph | ||
| 82 | } | 107 | } |
| 108 | #endif | ||
| 109 | flushTable() | ||
| 110 | out += paragraph | ||
| 83 | } | 111 | } |
| 84 | flushTable() | 112 | flushTable() |
| 85 | return out | 113 | return out |
| @@ -118,18 +146,18 @@ enum DocxWriter { | |||
| 118 | 146 | ||
| 119 | private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any]) -> String { | 147 | private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any]) -> String { |
| 120 | var properties = "" | 148 | var properties = "" |
| 121 | if let font = attributes[.font] as? NSFont { | 149 | if let font = attributes[.font] as? DocxFont { |
| 122 | let traits = font.fontDescriptor.symbolicTraits | 150 | let traits = self.traits(font) |
| 123 | let name = traits.contains(.monoSpace) ? "Menlo" : (font.familyName ?? "Helvetica Neue") | 151 | let name = traits.mono ? "Menlo" : traits.family |
| 124 | properties += "<w:rFonts w:ascii=\"\(escape(name))\" w:hAnsi=\"\(escape(name))\" w:cs=\"\(escape(name))\"/>" | 152 | properties += "<w:rFonts w:ascii=\"\(escape(name))\" w:hAnsi=\"\(escape(name))\" w:cs=\"\(escape(name))\"/>" |
| 125 | if traits.contains(.bold) { properties += "<w:b/>" } | 153 | if traits.bold { properties += "<w:b/>" } |
| 126 | if traits.contains(.italic) { properties += "<w:i/>" } | 154 | if traits.italic { properties += "<w:i/>" } |
| 127 | properties += "<w:sz w:val=\"\(Int((font.pointSize * 2).rounded()))\"/>" | 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 | if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "<w:u w:val=\"single\"/>" } | 158 | if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "<w:u w:val=\"single\"/>" } |
| 131 | if (attributes[.strikethroughStyle] as? Int ?? 0) != 0 { properties += "<w:strike/>" } | 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 | properties += "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"\(hex(background))\"/>" | 161 | properties += "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"\(hex(background))\"/>" |
| 134 | } | 162 | } |
| 135 | if let offset = attributes[.baselineOffset] as? Double, offset != 0 { properties += "<w:vertAlign w:val=\"\(offset > 0 ? "superscript" : "subscript")\"/>" } | 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 | return "<w:r><w:rPr>\(properties)</w:rPr>\(content)</w:r>" | 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 | /// `#rrggbb` of the color laid on white paper: Word has no transparency. | 203 | /// `#rrggbb` of the color laid on white paper: Word has no transparency. |
| 155 | private static func hex(_ color: NSColor) -> String { | 204 | private static func hex(_ color: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)) -> String { |
| 156 | let a = color.alphaComponent | 205 | func on(_ c: CGFloat) -> Int { Int(((c * color.a + (1 - color.a)) * 255).rounded()) } |
| 157 | func on(_ c: CGFloat) -> Int { Int(((c * a + (1 - a)) * 255).rounded()) } | 206 | return String(format: "%02X%02X%02X", on(color.r), on(color.g), on(color.b)) |
| 158 | return String(format: "%02X%02X%02X", on(color.redComponent), on(color.greenComponent), on(color.blueComponent)) | ||
| 159 | } | 207 | } |
| 160 | 208 | ||
| 161 | static func escape(_ s: String) -> String { | 209 | static func escape(_ s: String) -> String { |
| @@ -208,4 +256,3 @@ struct ZipWriter { | |||
| 208 | return c ^ 0xFFFFFFFF | 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 | #endif | 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 | /// The HTML export as RTF. | 97 | /// The HTML export as RTF. |
| 53 | public static func rtf(html: String, directory: URL?) throws -> Data { | 98 | public static func rtf(html: String, directory: URL?) throws -> Data { |
| 54 | try rtf(attributed(html: html, directory: directory)) | 99 | try rtf(attributed(html: html, directory: directory)) |
Sources/OrgstarMobile/EditorScreen.swift +63
| @@ -4,6 +4,7 @@ import OrgCore | |||
| 4 | import OrgDocument | 4 | import OrgDocument |
| 5 | import SwiftUI | 5 | import SwiftUI |
| 6 | import UIKit | 6 | import UIKit |
| 7 | import UniformTypeIdentifiers | ||
| 7 | 8 | ||
| 8 | /// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard, | 9 | /// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard, |
| 9 | /// and every command in a palette. The editor is the open file's live state, so autosave and | 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 | /// One sheet at a time: two presenters on this screen interfere. | 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 | enum Sheet: Identifiable { | 48 | enum Sheet: Identifiable { |
| 43 | case palette, conflict, syncCopies, recovery | 49 | case palette, conflict, syncCopies, recovery |
| 44 | /// `app.refile`, `app.refile.copy` or `app.refile.goto`. | 50 | /// `app.refile`, `app.refile.copy` or `app.refile.goto`. |
| @@ -82,6 +88,11 @@ struct EditorScreen: View { | |||
| 82 | Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") } | 88 | Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") } |
| 83 | Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") } | 89 | Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") } |
| 84 | Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") } | 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 | Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) { | 96 | Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) { |
| 86 | Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right") | 97 | Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right") |
| 87 | } | 98 | } |
| @@ -148,6 +159,14 @@ struct EditorScreen: View { | |||
| 148 | ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) } | 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 | .onChange(of: session.conflict) { _, conflict in | 170 | .onChange(of: session.conflict) { _, conflict in |
| 152 | if conflict != nil, session.path == path { sheet = .conflict } | 171 | if conflict != nil, session.path == path { sheet = .conflict } |
| 153 | } | 172 | } |
| @@ -237,6 +256,10 @@ struct EditorScreen: View { | |||
| 237 | _ = session.save(path) | 256 | _ = session.save(path) |
| 238 | } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) { | 257 | } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) { |
| 239 | sheet = .refile(id) | 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 | } else if id == "app.toggle-markup" { | 263 | } else if id == "app.toggle-markup" { |
| 241 | model.showMarkup.toggle() | 264 | model.showMarkup.toggle() |
| 242 | } else if MobileEditor.linkCommands.contains(id) { | 265 | } else if MobileEditor.linkCommands.contains(id) { |
| @@ -258,6 +281,25 @@ struct EditorScreen: View { | |||
| 258 | } | 281 | } |
| 259 | 282 | ||
| 260 | extension EditorScreen { | 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 | /// `org-refile` of the entry at the caret, to a target worked out again from the files | 303 | /// `org-refile` of the entry at the caret, to a target worked out again from the files |
| 262 | /// now, as the agenda's Refile… does. | 304 | /// now, as the agenda's Refile… does. |
| 263 | func refile(to target: RefileTarget, keep: Bool = false) { | 305 | func refile(to target: RefileTarget, keep: Bool = false) { |
| @@ -550,6 +592,7 @@ struct CommandPalette: View { | |||
| 550 | ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), | 592 | ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), |
| 551 | ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"), | 593 | ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"), |
| 552 | ("org.table.expand", "Expand Table Columns"), | 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 | /// The commands that apply at the caret and their keys, worked out once when the palette | 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 | #endif | 653 | #endif |
Sources/OrgstarMobile/ExportMenu.swift +11 −4
| @@ -6,17 +6,18 @@ import OrgPresentation | |||
| 6 | import SwiftUI | 6 | import SwiftUI |
| 7 | import UniformTypeIdentifiers | 7 | import UniformTypeIdentifiers |
| 8 | 8 | ||
| 9 | /// A file exported as HTML, Markdown, PDF, RTF, plain text or iCalendar, written when the share | 9 | /// A file exported as HTML, Markdown, PDF, Word, RTF, plain text or iCalendar, written when the |
| 10 | /// sheet takes it. | 10 | /// share sheet takes it. |
| 11 | struct OrgExport: Transferable { | 11 | struct OrgExport: Transferable { |
| 12 | enum Format: CaseIterable { | 12 | enum Format: CaseIterable { |
| 13 | case html, markdown, pdf, rtf, plainText, icalendar | 13 | case html, markdown, pdf, docx, rtf, plainText, icalendar |
| 14 | 14 | ||
| 15 | var name: String { | 15 | var name: String { |
| 16 | switch self { | 16 | switch self { |
| 17 | case .html: "HTML" | 17 | case .html: "HTML" |
| 18 | case .markdown: "Markdown" | 18 | case .markdown: "Markdown" |
| 19 | case .pdf: "PDF" | 19 | case .pdf: "PDF" |
| 20 | case .docx: "Word" | ||
| 20 | case .rtf: "Rich Text (RTF)" | 21 | case .rtf: "Rich Text (RTF)" |
| 21 | case .plainText: "Plain Text" | 22 | case .plainText: "Plain Text" |
| 22 | case .icalendar: "iCalendar" | 23 | case .icalendar: "iCalendar" |
| @@ -28,6 +29,7 @@ struct OrgExport: Transferable { | |||
| 28 | case .html: "html" | 29 | case .html: "html" |
| 29 | case .markdown: "md" | 30 | case .markdown: "md" |
| 30 | case .pdf: "pdf" | 31 | case .pdf: "pdf" |
| 32 | case .docx: "docx" | ||
| 31 | case .rtf: "rtf" | 33 | case .rtf: "rtf" |
| 32 | case .plainText: "txt" | 34 | case .plainText: "txt" |
| 33 | case .icalendar: "ics" | 35 | case .icalendar: "ics" |
| @@ -55,6 +57,8 @@ struct OrgExport: Transferable { | |||
| 55 | .exportingCondition { $0.format == .markdown } | 57 | .exportingCondition { $0.format == .markdown } |
| 56 | FileRepresentation(exportedContentType: .pdf) { try await $0.write() } | 58 | FileRepresentation(exportedContentType: .pdf) { try await $0.write() } |
| 57 | .exportingCondition { $0.format == .pdf } | 59 | .exportingCondition { $0.format == .pdf } |
| 60 | FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() } | ||
| 61 | .exportingCondition { $0.format == .docx } | ||
| 58 | FileRepresentation(exportedContentType: .rtf) { try await $0.write() } | 62 | FileRepresentation(exportedContentType: .rtf) { try await $0.write() } |
| 59 | .exportingCondition { $0.format == .rtf } | 63 | .exportingCondition { $0.format == .rtf } |
| 60 | FileRepresentation(exportedContentType: .plainText) { try await $0.write() } | 64 | FileRepresentation(exportedContentType: .plainText) { try await $0.write() } |
| @@ -77,6 +81,9 @@ struct OrgExport: Transferable { | |||
| 77 | try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8) | 81 | try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8) |
| 78 | case .icalendar: | 82 | case .icalendar: |
| 79 | try ICalendarFiles.export(text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(), destination: url) | 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 | case .pdf, .rtf, .plainText: | 87 | case .pdf, .rtf, .plainText: |
| 81 | let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle) | 88 | let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle) |
| 82 | let directory = URL(fileURLWithPath: path).deletingLastPathComponent() | 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 | /// Save to Files; or copying it as rich text. | 102 | /// Save to Files; or copying it as rich text. |
| 96 | struct ExportMenu: View { | 103 | struct ExportMenu: View { |
| 97 | let path: String | 104 | let path: String |
Sources/OrgstarMobile/MobileEditor.swift +2 −1
| @@ -297,7 +297,8 @@ final class MobileEditor: NSObject, DocumentBuffer { | |||
| 297 | case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true | 297 | case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true |
| 298 | case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last", | 298 | case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last", |
| 299 | "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil | 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 | case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil | 302 | case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil |
| 302 | case _ where Self.linkCommands.contains(id): return onAppCommand != nil | 303 | case _ where Self.linkCommands.contains(id): return onAppCommand != nil |
| 303 | case "org.link.open": return OpenLinkAtPoint().applies(in: context) | 304 | case "org.link.open": return OpenLinkAtPoint().applies(in: context) |
Tests/OrgAppTests/RichTextExportTests.swift +15
| @@ -35,6 +35,21 @@ struct RichTextExportTests { | |||
| 35 | #expect(font?.fontDescriptor.symbolicTraits.contains(.bold) == true) | 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 | @Test func plainTextAndDarkSystemsStayReadable() throws { | 53 | @Test func plainTextAndDarkSystemsStayReadable() throws { |
| 39 | let text = try RichTextExport.attributed(html: Self.html, directory: nil) | 54 | let text = try RichTextExport.attributed(html: Self.html, directory: nil) |
| 40 | let plain = RichTextExport.plain(text) | 55 | let plain = RichTextExport.plain(text) |
docs/manual/guide/10-tables.org +4 −1
| @@ -153,7 +153,10 @@ tables at full width. | |||
| 153 | | Import Table from File… (command palette) | =org-table-import= | | 153 | | Import Table from File… (command palette) | =org-table-import= | |
| 154 | | Export Table to File… (command palette) | =org-table-export= | | 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 | Import asks for a CSV, TSV or plain text file, inserts its contents at the caret on a | 161 | Import asks for a CSV, TSV or plain text file, inserts its contents at the caret on a |
| 159 | line of its own, and converts them to a table with the separator guessed as for a | 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 | ** On iOS | 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 | * HTML export | 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 | * Word, RTF and plain text | 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 | For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text with Emacs. | 217 | For Org's own ASCII layout, with underlined headings and drawn tables, use Export to Plain Text with Emacs. |
| 218 | 218 | ||