iCalendar export !277
18 files changed, +1588 −12
Layout: unified · split
Sources/OrgApp/EmacsImport.swift +12
| @@ -532,6 +532,18 @@ public struct EmacsImport: Sendable { | ||
| 532 | 532 | } else { |
| 533 | 533 | add(name, .bool(truthy)) |
| 534 | 534 | } |
| 535 | case "org-icalendar-use-deadline", "org-icalendar-use-scheduled": | |
| 536 | let symbols = (value.elements ?? []).compactMap(\.symbol) | |
| 537 | guard symbols.count == value.elements?.count || value.symbol == "nil" else { return note("not a list of symbols") } | |
| 538 | add(name, .string(symbols.joined(separator: " "))) | |
| 539 | case "org-icalendar-include-todo": | |
| 540 | if let symbol = value.symbol, ["nil", "t", "all", "unblocked"].contains(symbol) { add(name, .string(symbol)) } | |
| 541 | else if let keywords = value.elements?.compactMap(\.string), !keywords.isEmpty, keywords.count == value.elements?.count { | |
| 542 | add(name, .string(keywords.joined(separator: " "))) | |
| 543 | } else { note("unexpected value \(value.description)") } | |
| 544 | case "org-icalendar-combined-agenda-file": | |
| 545 | guard let file = value.string ?? Self.evaluate(value, env)?.string else { return note("not a file name") } | |
| 546 | add(name, .string(file)) | |
| 535 | 547 | case "org-refile-targets": |
| 536 | 548 | switch RefileSettings.parseTargets(value.description) { |
| 537 | 549 | case .success: add(name, .string(value.description)) |
Sources/OrgApp/ICalendarFiles.swift added +44
| @@ -0,0 +1,44 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | ||
| 4 | /// Writing iCalendar files: one file or subtree (`org-icalendar-export-to-ics`), each agenda | |
| 5 | /// file beside itself (`org-icalendar-export-agenda-files`), or all of them in one | |
| 6 | /// (`org-icalendar-combine-agenda-files`). | |
| 7 | public enum ICalendarFiles { | |
| 8 | /// Exports `text`, the file at `path`, to `destination` or where `EXPORT_FILE_NAME` says, | |
| 9 | /// else beside it. `subtree` exports the subtree at that offset alone. | |
| 10 | @discardableResult | |
| 11 | public static func export( | |
| 12 | _ text: String, path: String, settings: OrgSettings, options: ICalendarOptions, subtree: Int? = nil, destination: URL? = nil | |
| 13 | ) throws -> URL { | |
| 14 | let target = destination ?? ExportScope.output( | |
| 15 | for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: subtree, settings: settings), extension: "ics") | |
| 16 | let text = ExportPreprocess.includes(text, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) | |
| 17 | let calendar = ICalendarExport.calendar(text, name: (path as NSString).lastPathComponent, settings: settings, options: options, subtree: subtree) | |
| 18 | try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) | |
| 19 | try calendar.write(to: target, atomically: true, encoding: .utf8) | |
| 20 | return target | |
| 21 | } | |
| 22 | ||
| 23 | /// Each file in `paths` to its own calendar. `read` gives a file's text and settings. | |
| 24 | public static func exportEach(_ paths: [String], options: ICalendarOptions, read: (String) -> (text: String, settings: OrgSettings)?) throws -> [URL] { | |
| 25 | try paths.compactMap { path in | |
| 26 | guard let file = read(path) else { return nil } | |
| 27 | return try export(file.text, path: path, settings: file.settings, options: options) | |
| 28 | } | |
| 29 | } | |
| 30 | ||
| 31 | /// The files in `paths` in one calendar at `destination`. | |
| 32 | @discardableResult | |
| 33 | public static func combine( | |
| 34 | _ paths: [String], to destination: String, options: ICalendarOptions, read: (String) -> (text: String, settings: OrgSettings)? | |
| 35 | ) throws -> URL { | |
| 36 | let files = paths.compactMap { path in | |
| 37 | read(path).map { ((path as NSString).lastPathComponent, ExportPreprocess.includes($0.text, directory: URL(fileURLWithPath: path).deletingLastPathComponent()), $0.settings) } | |
| 38 | } | |
| 39 | let url = URL(fileURLWithPath: destination) | |
| 40 | try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) | |
| 41 | try ICalendarExport.combined(files, options: options).write(to: url, atomically: true, encoding: .utf8) | |
| 42 | return url | |
| 43 | } | |
| 44 | } | |
Sources/OrgApp/OrgPreferences.swift +20
| @@ -127,6 +127,26 @@ public enum OrgPreferences { | ||
| 127 | 127 | return RefileSettings(targets: targets, outlinePath: RefileSettings.OutlinePath(rawValue: string("refileUseOutlinePath", defaults)) ?? .file, |
| 128 | 128 | creating: RefileSettings.Creating(rawValue: string("refileAllowCreatingParentNodes", defaults)) ?? .no) |
| 129 | 129 | } |
| 130 | /// `org-icalendar-use-deadline`, `-use-scheduled` and `-include-todo`; the owner is the | |
| 131 | /// user's full name. | |
| 132 | public static func icalendarOptions(_ defaults: UserDefaults = .standard) -> ICalendarOptions { | |
| 133 | var options = ICalendarOptions() | |
| 134 | options.useDeadline = words(string("icalendarUseDeadline", defaults)) | |
| 135 | options.useScheduled = words(string("icalendarUseScheduled", defaults)) | |
| 136 | options.includeTodo = switch string("icalendarIncludeTodo", defaults).trimmingCharacters(in: .whitespaces) { | |
| 137 | case "", "nil": .none | |
| 138 | case "t": .unfinished | |
| 139 | case "all": .all | |
| 140 | case "unblocked": .unblocked | |
| 141 | case let list: .keywords(words(list)) | |
| 142 | } | |
| 143 | options.userFullName = NSFullUserName() | |
| 144 | return options | |
| 145 | } | |
| 146 | /// `org-icalendar-combined-agenda-file`, `~` expanded. | |
| 147 | public static func icalendarCombinedFile(_ defaults: UserDefaults = .standard) -> String { | |
| 148 | (string("icalendarCombinedAgendaFile", defaults) as NSString).expandingTildeInPath | |
| 149 | } | |
| 130 | 150 | /// `org-stuck-projects`. |
| 131 | 151 | public static func stuckProjects(_ defaults: UserDefaults = .standard) -> StuckProjects { |
| 132 | 152 | StuckProjects(match: string("stuckProjectsMatch", defaults), todo: words(string("stuckProjectsTodo", defaults)), |
Sources/OrgApp/UserConfig.swift +8
| @@ -211,6 +211,14 @@ public enum UserConfig { | ||
| 211 | 211 | comment: "a target typed as parent/new adds the heading: t, confirm (asks first) or nil", legacy: ""), |
| 212 | 212 | Setting(section: "", key: "org-agenda-files", defaultsKey: "agendaFiles", kind: .string, fallback: .string(""), |
| 213 | 213 | comment: "files and folders the agenda reads, separated by \\n; a file that isn't .org lists more, one per line; \"\" reads the folders' files", legacy: ""), |
| 214 | Setting(section: "", key: "org-icalendar-use-deadline", defaultsKey: "icalendarUseDeadline", kind: .string, fallback: .string("event-if-not-todo todo-due"), | |
| 215 | comment: "iCalendar export: what a DEADLINE makes, of event-if-not-todo, event-if-todo, event-if-todo-not-done and todo-due", legacy: ""), | |
| 216 | Setting(section: "", key: "org-icalendar-use-scheduled", defaultsKey: "icalendarUseScheduled", kind: .string, fallback: .string("todo-start"), | |
| 217 | comment: "iCalendar export: what SCHEDULED makes, of event-if-not-todo, event-if-todo, event-if-todo-not-done and todo-start", legacy: ""), | |
| 218 | Setting(section: "", key: "org-icalendar-include-todo", defaultsKey: "icalendarIncludeTodo", kind: .string, fallback: .string("nil"), | |
| 219 | comment: "iCalendar export: tasks as VTODOs: nil, t (not done), all, unblocked, or TODO keywords separated by spaces", legacy: ""), | |
| 220 | Setting(section: "", key: "org-icalendar-combined-agenda-file", defaultsKey: "icalendarCombinedAgendaFile", kind: .string, fallback: .string("~/org.ics"), | |
| 221 | comment: "where Combine Agenda Files into iCalendar writes", legacy: ""), | |
| 214 | 222 | Setting(section: "", key: "org-agenda-use-time-grid", defaultsKey: "agendaUseTimeGrid", kind: .bool, fallback: .bool(true), |
| 215 | 223 | comment: "time grid lines among timed entries, as [org-agenda-time-grid] says", legacy: ""), |
| 216 | 224 | Setting(section: "", key: "org-agenda-show-current-time-in-grid", defaultsKey: "agendaShowCurrentTime", kind: .bool, fallback: .bool(true), |
Sources/OrgCore/Export/ASCIIText.swift added +470
| @@ -0,0 +1,470 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// What ox-ascii (Org 9.8.7) makes of a section's elements and a heading's title with | |
| 4 | /// `:ascii-charset utf-8` and links in place (`:ascii-links-to-notes nil`), as the iCalendar | |
| 5 | /// export writes summaries and descriptions: paragraphs filled to the text width, lists with | |
| 6 | /// `•` bullets, blocks in a partial box, tables drawn with box characters. | |
| 7 | struct ASCIIText { | |
| 8 | let options: ExportOptions | |
| 9 | /// Heading numbers by title, for fuzzy links without a description. | |
| 10 | var headingNumbers: [String: String] = [:] | |
| 11 | ||
| 12 | static let textWidth = 72 | |
| 13 | static let innerMargin = 2 | |
| 14 | static let quoteMargin = 6 | |
| 15 | ||
| 16 | /// The text width inside a section under a heading at `level` (`org-ascii--current-text-width`). | |
| 17 | func width(level: Int?) -> Int { | |
| 18 | guard let level else { return Self.textWidth } | |
| 19 | return Self.textWidth - (level > options.headlineLevels ? (level - options.headlineLevels) * 2 : Self.innerMargin) | |
| 20 | } | |
| 21 | ||
| 22 | // MARK: - Elements | |
| 23 | ||
| 24 | /// `nodes`, each followed by the blank lines after it in `source`, as `org-export-data` | |
| 25 | /// joins elements. Elements the export leaves out add nothing. | |
| 26 | func elements(_ nodes: [SyntaxNode], end: Int, source: NSString, width: Int) -> String { | |
| 27 | var out = "" | |
| 28 | for (index, node) in nodes.enumerated() { | |
| 29 | guard let text = element(node, source: source, width: width), !text.isEmpty else { continue } | |
| 30 | let next = index + 1 < nodes.count ? nodes[index + 1].range.lowerBound : end | |
| 31 | out += Self.normalized(text) + String(repeating: "\n", count: Self.blankLines(source, from: node.range.upperBound, to: next)) | |
| 32 | } | |
| 33 | return out | |
| 34 | } | |
| 35 | ||
| 36 | /// Blank lines between `from`, a line start, and `to`. | |
| 37 | static func blankLines(_ source: NSString, from: Int, to: Int) -> Int { | |
| 38 | guard to > from, from < source.length else { return 0 } | |
| 39 | let gap = source.substring(with: NSRange(location: from, length: min(to, source.length) - from)) | |
| 40 | return gap.components(separatedBy: "\n").dropLast().count | |
| 41 | } | |
| 42 | ||
| 43 | /// `org-element-normalize-string`: one final newline. | |
| 44 | static func normalized(_ s: String) -> String { | |
| 45 | var s = s | |
| 46 | while s.hasSuffix("\n") || s.hasSuffix(" ") || s.hasSuffix("\t") { s.removeLast() } | |
| 47 | return s + "\n" | |
| 48 | } | |
| 49 | ||
| 50 | func element(_ node: SyntaxNode, source: NSString, width: Int) -> String? { | |
| 51 | switch node.kind { | |
| 52 | case .paragraph: | |
| 53 | return paragraph(node, width: width) | |
| 54 | case .plainList: | |
| 55 | return list(node, source: source, width: width) | |
| 56 | case .table: | |
| 57 | return table(node) | |
| 58 | case .tableEl: | |
| 59 | return Self.removeIndentation(node.text.trimmingCharacters(in: .newlines)) | |
| 60 | case .block: | |
| 61 | return block(node, width: width) | |
| 62 | case .fixedWidth: | |
| 63 | let lines = node.text.components(separatedBy: "\n").filter { !$0.isEmpty }.map { line -> String in | |
| 64 | let trimmed = line.drop { $0 == " " || $0 == "\t" } | |
| 65 | return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(1)) | |
| 66 | } | |
| 67 | return Self.box(Self.removeIndentation(lines.joined(separator: "\n"))) | |
| 68 | case .horizontalRule: | |
| 69 | return String(repeating: "―", count: width) | |
| 70 | case .drawer: | |
| 71 | let name = node.text.firstMatch(of: /^[ \t]*:([\w-]+):/).map { String($0.1).uppercased() } ?? "" | |
| 72 | if name == "LOGBOOK" { return nil } | |
| 73 | return elements(node.children, end: node.range.upperBound, source: source, width: width) | |
| 74 | case .dynamicBlock: | |
| 75 | return elements(node.children, end: node.range.upperBound, source: source, width: width) | |
| 76 | case .latexEnvironment: | |
| 77 | return options.tex ? Self.removeIndentation(node.text.trimmingCharacters(in: .newlines)) : nil | |
| 78 | case .keyword: | |
| 79 | guard let m = node.text.firstMatch(of: /(?i)^[ \t]*#\+ASCII:[ \t]*(.*?)[ \t]*\n?$/) else { return nil } | |
| 80 | return String(m.1) | |
| 81 | default: | |
| 82 | // Planning, drawers of properties, clocks, comments, keywords and footnote | |
| 83 | // definitions export nothing here. | |
| 84 | return nil | |
| 85 | } | |
| 86 | } | |
| 87 | ||
| 88 | // MARK: Paragraphs | |
| 89 | ||
| 90 | func paragraph(_ node: SyntaxNode, width: Int) -> String { | |
| 91 | var text = inline(node, skippingTimestamps: Self.isolatedTimestamps(node)) | |
| 92 | // `org-remove-blank-lines`. | |
| 93 | text = text.replacing(#/\n[ \t]*\n(?:[ \t]*\n)*/#, with: "\n") | |
| 94 | return Self.fill(text, width: width) | |
| 95 | } | |
| 96 | ||
| 97 | /// Whether the paragraph holds only timestamps and whitespace, whose timestamps | |
| 98 | /// `:with-timestamps` decides. | |
| 99 | static func isolatedTimestamps(_ node: SyntaxNode) -> Bool { | |
| 100 | var any = false | |
| 101 | for element in node.elements { | |
| 102 | switch element { | |
| 103 | case .token(let token): | |
| 104 | if !token.text.allSatisfy(\.isWhitespace) { return false } | |
| 105 | case .node(let child): | |
| 106 | guard child.kind == .timestamp else { return false } | |
| 107 | any = true | |
| 108 | } | |
| 109 | } | |
| 110 | return any | |
| 111 | } | |
| 112 | ||
| 113 | /// `org-ascii--fill-string`: `fill-region` with `fill-column` `width`, | |
| 114 | /// `sentence-end-double-space` and hard newlines from line breaks. | |
| 115 | static func fill(_ text: String, width: Int) -> String { | |
| 116 | text.components(separatedBy: hardNewline).map { fillParagraph($0, width: width) }.joined(separator: "\n") | |
| 117 | } | |
| 118 | ||
| 119 | static let hardNewline = "\u{1}" | |
| 120 | ||
| 121 | static func fillParagraph(_ text: String, width: Int) -> String { | |
| 122 | var lines = text.components(separatedBy: "\n") | |
| 123 | while lines.count > 1, lines.last!.allSatisfy({ $0 == " " || $0 == "\t" }) { lines.removeLast() } | |
| 124 | guard !lines.isEmpty else { return "" } | |
| 125 | func indentation(_ line: String) -> String { String(line.prefix { $0 == " " || $0 == "\t" }) } | |
| 126 | let first = indentation(lines[0]) | |
| 127 | // `fill-context-prefix`: the second line's indentation when the first starts with it. | |
| 128 | let prefix = lines.count >= 2 ? (lines[0].hasPrefix(indentation(lines[1])) ? indentation(lines[1]) : "") : first | |
| 129 | var parts: [String] = [] | |
| 130 | for (i, line) in lines.enumerated() { | |
| 131 | var content = String(line.dropFirst(indentation(line).count)) | |
| 132 | while content.hasSuffix(" ") || content.hasSuffix("\t") { content.removeLast() } | |
| 133 | // A sentence ending a line gets the second space it would have. | |
| 134 | if i < lines.count - 1, content.range(of: "[.?!…‽][]\"'”’)}»›]*$", options: .regularExpression) != nil { content += " " } | |
| 135 | parts.append(content) | |
| 136 | } | |
| 137 | let joined = parts.joined(separator: " ").replacingOccurrences(of: "\t", with: " ") | |
| 138 | // Words and the spaces after them, with `canonically-space-region`'s spacing. | |
| 139 | var words: [(word: String, spaces: Int)] = [] | |
| 140 | var index = joined.startIndex | |
| 141 | while index < joined.endIndex { | |
| 142 | let wordEnd = joined[index...].firstIndex(of: " ") ?? joined.endIndex | |
| 143 | let word = String(joined[index..<wordEnd]) | |
| 144 | let spaceEnd = joined[wordEnd...].firstIndex { $0 != " " } ?? joined.endIndex | |
| 145 | var spaces = joined.distance(from: wordEnd, to: spaceEnd) | |
| 146 | if spaces >= 2 { | |
| 147 | let closers = word.reversed().drop { "]})\"'".contains($0) } | |
| 148 | spaces = closers.first.map { ".?!".contains($0) } == true ? 2 : 1 | |
| 149 | } | |
| 150 | if !word.isEmpty { words.append((word, spaces)) } else if var last = words.popLast() { | |
| 151 | last.spaces += spaces | |
| 152 | words.append(last) | |
| 153 | } | |
| 154 | index = spaceEnd | |
| 155 | } | |
| 156 | guard !words.isEmpty else { return first } | |
| 157 | /// `fill-nobreak-p`: not after a period followed by a single space. | |
| 158 | func breakable(after i: Int) -> Bool { !(words[i].spaces == 1 && words[i].word.hasSuffix(".")) } | |
| 159 | var out: [String] = [] | |
| 160 | var start = 0 | |
| 161 | while start < words.count { | |
| 162 | let lead = out.isEmpty ? first : prefix | |
| 163 | var length = lead.count + words[start].word.count | |
| 164 | var end = start | |
| 165 | var lastBreak: Int? | |
| 166 | while end + 1 < words.count { | |
| 167 | let next = length + words[end].spaces + words[end + 1].word.count | |
| 168 | if next > width { | |
| 169 | if breakable(after: end) { | |
| 170 | lastBreak = end | |
| 171 | break | |
| 172 | } | |
| 173 | if lastBreak != nil { break } | |
| 174 | } else if breakable(after: end) { | |
| 175 | lastBreak = end | |
| 176 | } | |
| 177 | length = next | |
| 178 | end += 1 | |
| 179 | } | |
| 180 | let stop = end + 1 < words.count ? (lastBreak ?? end) : end | |
| 181 | var line = lead | |
| 182 | for i in start...stop { | |
| 183 | line += words[i].word | |
| 184 | if i < stop { line += String(repeating: " ", count: words[i].spaces) } | |
| 185 | } | |
| 186 | out.append(line) | |
| 187 | start = stop + 1 | |
| 188 | } | |
| 189 | return out.joined(separator: "\n") | |
| 190 | } | |
| 191 | ||
| 192 | // MARK: Lists | |
| 193 | ||
| 194 | func list(_ node: SyntaxNode, source: NSString, width: Int) -> String { | |
| 195 | let items = node.children.filter { $0.kind == .item } | |
| 196 | var out = "" | |
| 197 | var number = 0 | |
| 198 | // The first item decides the list's type, as `org-list-get-list-type` does. | |
| 199 | let firstBullet = (items.first?.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces) | |
| 200 | let descriptive = items.first?.firstChild(.itemTag) != nil | |
| 201 | let ordered = !descriptive && firstBullet.first.map { $0.isNumber || $0.isLetter } == true | |
| 202 | for (index, item) in items.enumerated() { | |
| 203 | let bulletText = (item.tokens.first { $0.kind == .bullet }?.text ?? "-").trimmingCharacters(in: .whitespaces) | |
| 204 | let checkbox: String = switch item.tokens.first(where: { $0.kind == .checkbox })?.text { | |
| 205 | case "[X]"?, "[x]"?: "☑ " | |
| 206 | case "[ ]"?: "☐ " | |
| 207 | case "[-]"?: "☒ " | |
| 208 | default: "" | |
| 209 | } | |
| 210 | let tag = descriptive ? item.firstChild(.itemTag) : nil | |
| 211 | let bullet: String | |
| 212 | let indentation: Int | |
| 213 | if descriptive { | |
| 214 | bullet = checkbox + (tag.map { inline($0).trimmingCharacters(in: .whitespaces) } ?? "") | |
| 215 | indentation = Self.quoteMargin | |
| 216 | } else if ordered { | |
| 217 | if let counter = item.tokens.first(where: { $0.kind == .counter })?.text, | |
| 218 | let n = Int(counter.trimmingCharacters(in: CharacterSet(charactersIn: "[@] "))) { | |
| 219 | number = n | |
| 220 | } else { | |
| 221 | number += 1 | |
| 222 | } | |
| 223 | bullet = bulletText.replacing(/[0-9A-Za-z]+/, with: String(number)) + " " | |
| 224 | indentation = bullet.count | |
| 225 | } else { | |
| 226 | bullet = ["-": "• ", "+": "⁃ ", "*": "‣ "][bulletText] ?? bulletText + " " | |
| 227 | indentation = bullet.count | |
| 228 | } | |
| 229 | let children = item.children.filter { $0.kind != .itemTag } | |
| 230 | let inner = descriptive ? width - Self.quoteMargin : width - indentation - checkbox.count | |
| 231 | let contents = elements(children, end: item.range.upperBound, source: source, width: inner) | |
| 232 | let indented = Self.indent(contents, indentation) | |
| 233 | let firstIsParagraph = children.first { (element($0, source: source, width: inner) ?? "").contains(where: { !$0.isWhitespace }) }?.kind == .paragraph | |
| 234 | var text = bullet + checkbox | |
| 235 | if !descriptive, indented.contains(where: { !$0.isWhitespace }), firstIsParagraph { | |
| 236 | text += indented.trimmingCharacters(in: .whitespacesAndNewlines) | |
| 237 | } else { | |
| 238 | text += "\n" + indented | |
| 239 | } | |
| 240 | let next = index + 1 < items.count ? items[index + 1].range.lowerBound : item.range.upperBound | |
| 241 | out += Self.normalized(text) + String(repeating: "\n", count: Self.blankLines(source, from: item.range.upperBound, to: next)) | |
| 242 | } | |
| 243 | return out | |
| 244 | } | |
| 245 | ||
| 246 | /// `org-ascii--indent-string`: `width` spaces before each line that isn't blank. | |
| 247 | static func indent(_ s: String, _ width: Int) -> String { | |
| 248 | let pad = String(repeating: " ", count: width) | |
| 249 | return s.components(separatedBy: "\n").map { $0.contains(where: { !$0.isWhitespace }) ? pad + $0 : $0 }.joined(separator: "\n") | |
| 250 | } | |
| 251 | ||
| 252 | static func removeIndentation(_ s: String) -> String { | |
| 253 | let lines = s.components(separatedBy: "\n") | |
| 254 | let common = lines.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }.min() ?? 0 | |
| 255 | return lines.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }.joined(separator: "\n") | |
| 256 | } | |
| 257 | ||
| 258 | /// `org-ascii--box-string` in UTF-8. | |
| 259 | static func box(_ s: String) -> String { | |
| 260 | let body = s.replacing(#/\n[ \t]*\z/#, with: "") | |
| 261 | return "┌────\n" + body.components(separatedBy: "\n").map { "│ " + $0 }.joined(separator: "\n") + "\n└────" | |
| 262 | } | |
| 263 | ||
| 264 | // MARK: Blocks | |
| 265 | ||
| 266 | func block(_ node: SyntaxNode, width: Int) -> String? { | |
| 267 | var lines = node.text.components(separatedBy: "\n") | |
| 268 | if lines.last == "" { lines.removeLast() } | |
| 269 | guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return nil } | |
| 270 | let type = m.1.lowercased() | |
| 271 | var body = Array(lines.dropFirst().dropLast()).map { | |
| 272 | $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression) | |
| 273 | } | |
| 274 | body = Self.removeIndentation(body.joined(separator: "\n")).components(separatedBy: "\n") | |
| 275 | switch type { | |
| 276 | case "src", "example": | |
| 277 | let code = body.joined(separator: "\n") | |
| 278 | return code.isEmpty ? "" : Self.box(code) | |
| 279 | case "quote": | |
| 280 | return Self.indent(nested(body.joined(separator: "\n"), width: width - 2 * Self.quoteMargin), Self.quoteMargin) | |
| 281 | case "verse": | |
| 282 | let tree = OrgParser.parse(body.joined(separator: "\n")) | |
| 283 | let text = tree.root.descendants().filter { $0.kind == .paragraph }.map { inline($0) }.joined(separator: "\n\n") | |
| 284 | return Self.indent(text, Self.quoteMargin) | |
| 285 | case "export": | |
| 286 | return m.2.lowercased().hasPrefix("ascii") ? body.joined(separator: "\n") : nil | |
| 287 | case "comment": | |
| 288 | return nil | |
| 289 | default: | |
| 290 | return nested(body.joined(separator: "\n"), width: width) | |
| 291 | } | |
| 292 | } | |
| 293 | ||
| 294 | /// A block's contents, parsed as elements. | |
| 295 | func nested(_ text: String, width: Int) -> String { | |
| 296 | let tree = OrgParser.parse(text) | |
| 297 | let ns = text as NSString | |
| 298 | let children = tree.root.children.flatMap { $0.kind == .zerothSection ? $0.children : [$0] } | |
| 299 | return elements(children, end: ns.length, source: ns, width: width) | |
| 300 | } | |
| 301 | ||
| 302 | // MARK: Tables | |
| 303 | ||
| 304 | func table(_ node: SyntaxNode) -> String { | |
| 305 | let rows = node.children.filter { $0.kind == .tableRow } | |
| 306 | let cells: [[String]?] = rows.map { row in | |
| 307 | let cells = row.children.filter { $0.kind == .tableCell } | |
| 308 | if cells.isEmpty { return nil } | |
| 309 | return cells.map { inline($0).trimmingCharacters(in: .whitespaces) } | |
| 310 | } | |
| 311 | let data = cells.compactMap { $0 } | |
| 312 | guard !data.isEmpty else { return "" } | |
| 313 | let columns = data.map(\.count).max() ?? 0 | |
| 314 | let filled = data.map { $0 + Array(repeating: "", count: columns - $0.count) } | |
| 315 | var widths = (0..<columns).map { c in filled.map { $0[c].count }.max() ?? 0 } | |
| 316 | // Width cookies such as `<10>` widen the column, as `org-ascii-table-widen-columns`. | |
| 317 | for row in filled where row.allSatisfy({ $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil }) { | |
| 318 | for (c, cell) in row.enumerated() { if let n = Int(cell.filter(\.isNumber)) { widths[c] = max(widths[c], n) } } | |
| 319 | } | |
| 320 | let cookieRows = Set(filled.indices.filter { r in | |
| 321 | filled[r].contains { !$0.isEmpty } && filled[r].allSatisfy { $0.isEmpty || $0.range(of: "^<[lrc]?[0-9]*>$", options: .regularExpression) != nil } | |
| 322 | }) | |
| 323 | let right = (0..<columns).map { c -> Bool in | |
| 324 | let values = filled.indices.filter { !cookieRows.contains($0) }.map { filled[$0][c] }.filter { !$0.isEmpty } | |
| 325 | guard !values.isEmpty else { return false } | |
| 326 | let numbers = values.filter { $0.range(of: "^([><]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[-+]?0[xX][0-9a-fA-F.]+|[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$", options: .regularExpression) != nil } | |
| 327 | return Double(numbers.count) / Double(values.count) >= 0.5 | |
| 328 | } | |
| 329 | func line(_ char: String) -> String { widths.map { String(repeating: char, count: $0 + 2) }.joined() } | |
| 330 | var out = "" | |
| 331 | var dataIndex = 0 | |
| 332 | let lastData = cells.lastIndex { $0 != nil }! | |
| 333 | let firstData = cells.firstIndex { $0 != nil }! | |
| 334 | for (r, row) in cells.enumerated() { | |
| 335 | guard row != nil else { continue } | |
| 336 | let rowIndex = dataIndex | |
| 337 | dataIndex += 1 | |
| 338 | if cookieRows.contains(rowIndex) { continue } | |
| 339 | if r == firstData { | |
| 340 | out += line("━") + "\n" | |
| 341 | } else if r > 0, cells[r - 1] == nil { | |
| 342 | out += line("─") + "\n" | |
| 343 | } | |
| 344 | out += filled[rowIndex].enumerated().map { c, cell in | |
| 345 | let pad = String(repeating: " ", count: max(0, widths[c] - cell.count)) | |
| 346 | return " " + (right[c] ? pad + cell : cell + pad) + " " | |
| 347 | }.joined() + "\n" | |
| 348 | if r == lastData { out += line("━") + "\n" } | |
| 349 | } | |
| 350 | return out | |
| 351 | } | |
| 352 | ||
| 353 | // MARK: - Objects | |
| 354 | ||
| 355 | /// The objects in `node`, as ox-ascii writes them. | |
| 356 | func inline(_ node: SyntaxNode, skippingTimestamps isolated: Bool = false) -> String { | |
| 357 | var out = "" | |
| 358 | for element in node.elements { | |
| 359 | switch element { | |
| 360 | case .token(let token): | |
| 361 | switch token.kind { | |
| 362 | case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority, .counter: continue | |
| 363 | default: out += special(token.text) | |
| 364 | } | |
| 365 | case .node(let child): | |
| 366 | if isolated, child.kind == .timestamp, ICalendarExport.skipsTimestamp(child.text, with: options.timestamps ?? "t") { continue } | |
| 367 | out += object(child) | |
| 368 | } | |
| 369 | } | |
| 370 | return out | |
| 371 | } | |
| 372 | ||
| 373 | /// `org-ascii-plain-text` with `:with-special-strings`. | |
| 374 | func special(_ text: String) -> String { | |
| 375 | guard options.specialStrings else { return text } | |
| 376 | return text.replacingOccurrences(of: "\\-", with: "").replacingOccurrences(of: "---", with: "—") | |
| 377 | .replacingOccurrences(of: "--", with: "–").replacingOccurrences(of: "...", with: "…") | |
| 378 | } | |
| 379 | ||
| 380 | /// The text between the markers. | |
| 381 | static func value(_ node: SyntaxNode) -> String { | |
| 382 | node.elements.compactMap { element -> String? in | |
| 383 | guard case .token(let token) = element, token.kind != .marker else { return nil } | |
| 384 | return token.text | |
| 385 | }.joined() | |
| 386 | } | |
| 387 | ||
| 388 | func object(_ node: SyntaxNode) -> String { | |
| 389 | switch node.kind { | |
| 390 | case .bold: return "*\(inline(node))*" | |
| 391 | case .italic: return "/\(inline(node))/" | |
| 392 | case .underline: return "_\(inline(node))_" | |
| 393 | case .strikeThrough: return "+\(inline(node))+" | |
| 394 | case .verbatim, .code: return "`\(Self.value(node))'" | |
| 395 | case .link: return link(node) | |
| 396 | case .linkDescription: return inline(node) | |
| 397 | case .timestamp: return special(Self.timestamp(node.text)) | |
| 398 | // The iCalendar backend leaves footnote references out. | |
| 399 | case .footnoteReference: return "" | |
| 400 | case .entity: | |
| 401 | let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "") | |
| 402 | return OrgEntities.display[name] ?? node.text | |
| 403 | case .radioTarget: return String(node.text.dropFirst(3).dropLast(3)) | |
| 404 | case .target: return "" | |
| 405 | case .superscript, .subscript: | |
| 406 | let body = node.text.dropFirst() | |
| 407 | let braced = body.hasPrefix("{") && body.hasSuffix("}") | |
| 408 | if options.scripts == .off || (options.scripts == .braces && !braced) { return special(node.text) } | |
| 409 | let mark = node.text.hasPrefix("_") ? "_" : "^" | |
| 410 | return braced ? mark + "{" + String(body.dropFirst().dropLast()) + "}" : mark + String(body) | |
| 411 | case .lineBreak: return Self.hardNewline | |
| 412 | case .latexFragment: return options.tex ? node.text : "" | |
| 413 | case .inlineSourceBlock: | |
| 414 | if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return "`\(m.1)'" } | |
| 415 | return node.text | |
| 416 | case .exportSnippet: | |
| 417 | guard node.tokens.first?.text.lowercased() == "@@ascii:" else { return "" } | |
| 418 | return node.tokens.filter { $0.kind != .marker }.map(\.text).joined() | |
| 419 | case .statisticsCookie: return node.text | |
| 420 | case .inlineBabelCall, .macro: return "" | |
| 421 | default: return inline(node) | |
| 422 | } | |
| 423 | } | |
| 424 | ||
| 425 | func link(_ node: SyntaxNode) -> String { | |
| 426 | let description = node.firstChild(.linkDescription).map { inline($0) } | |
| 427 | guard let path = node.tokens.first(where: { $0.kind == .linkPath })?.text else { | |
| 428 | var target = node.text | |
| 429 | if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) } | |
| 430 | // A radio link is its text. | |
| 431 | if !target.contains(":") { return target } | |
| 432 | return "<\(target)>" | |
| 433 | } | |
| 434 | if path.hasPrefix("("), path.hasSuffix(")") { return description ?? String(path.dropFirst().dropLast()) } | |
| 435 | let scheme = path.firstMatch(of: /^([A-Za-z][A-Za-z0-9+.-]*):/).map { String($0.1).lowercased() } | |
| 436 | let isInternal = scheme == nil || scheme == "id" || path.hasPrefix("#") || path.hasPrefix("*") | |
| 437 | if isInternal, !(scheme == nil && (path.hasPrefix("/") || path.hasPrefix("./") || path.hasPrefix("~"))) { | |
| 438 | let title = path.hasPrefix("*") ? String(path.dropFirst()) : path | |
| 439 | let number = headingNumbers[title] | |
| 440 | if let description { return "[\(description)]" + (number.map { " (See section \($0))" } ?? "") } | |
| 441 | return number ?? title | |
| 442 | } | |
| 443 | guard let description, description.contains(where: { !$0.isWhitespace }) else { return "<\(path)>" } | |
| 444 | return "[\(description)] (<\(path)>)" | |
| 445 | } | |
| 446 | ||
| 447 | /// `org-timestamp-translate`: the timestamp as Org writes it, `9:00` as `09:00`. | |
| 448 | static func timestamp(_ text: String) -> String { | |
| 449 | guard let stamp = Timestamp.parse(text) else { return text } | |
| 450 | let open = stamp.active ? "<" : "[" | |
| 451 | let close = stamp.active ? ">" : "]" | |
| 452 | func day(_ p: Timestamp.Point) -> String { | |
| 453 | let name = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][Days.weekday(Days.absolute(year: p.year, month: p.month, day: p.day))] | |
| 454 | return String(format: "%04d-%02d-%02d ", p.year, p.month, p.day) + name | |
| 455 | } | |
| 456 | func time(_ p: Timestamp.Point) -> String { p.hour.map { String(format: " %02d:%02d", $0, p.minute ?? 0) } ?? "" } | |
| 457 | var suffix = "" | |
| 458 | if let r = stamp.repeater { | |
| 459 | suffix += " " + r.kind.rawValue + "\(r.interval.value)\(r.interval.unit.rawValue)" | |
| 460 | if let d = r.habitDeadline { suffix += "/\(d.value)\(d.unit.rawValue)" } | |
| 461 | } | |
| 462 | if let w = stamp.warning { suffix += " " + (w.firstOccurrenceOnly ? "--" : "-") + "\(w.interval.value)\(w.interval.unit.rawValue)" } | |
| 463 | let start = stamp.start | |
| 464 | guard let end = stamp.end else { return open + day(start) + time(start) + suffix + close } | |
| 465 | if (end.year, end.month, end.day) == (start.year, start.month, start.day), start.hour != nil, end.hour != nil { | |
| 466 | return open + day(start) + time(start) + "-" + String(time(end).dropFirst()) + suffix + close | |
| 467 | } | |
| 468 | return open + day(start) + time(start) + suffix + close + "--" + open + day(end) + time(end) + suffix + close | |
| 469 | } | |
| 470 | } | |
Sources/OrgCore/Export/ExportOptions.swift +6
| @@ -25,6 +25,10 @@ public struct ExportOptions: Sendable, Equatable { | ||
| 25 | 25 | public var author = true |
| 26 | 26 | public var date = true |
| 27 | 27 | public var title = true |
| 28 | /// `-`: `--`, `---`, `...` and `\-` as special strings. | |
| 29 | public var specialStrings = true | |
| 30 | /// `<`, as written: nil, t, active, inactive; nil when not given. | |
| 31 | public var timestamps: String? | |
| 28 | 32 | public var excludeTags = ["noexport"] |
| 29 | 33 | public var selectTags = ["export"] |
| 30 | 34 | /// `#+HTML_HEAD` and `#+HTML_HEAD_EXTRA` lines, in order. |
| @@ -72,6 +76,8 @@ public struct ExportOptions: Sendable, Equatable { | ||
| 72 | 76 | case "author": options.author = on |
| 73 | 77 | case "date": options.date = on |
| 74 | 78 | case "title": options.title = on |
| 79 | case "-": options.specialStrings = on | |
| 80 | case "<": options.timestamps = v | |
| 75 | 81 | default: break |
| 76 | 82 | } |
| 77 | 83 | } |
Sources/OrgCore/Export/ICalendarExport.swift added +551
| @@ -0,0 +1,551 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// The `org-icalendar-*` variables (ox-icalendar.el, Org 9.8.7). | |
| 4 | public struct ICalendarOptions: Sendable, Equatable { | |
| 5 | /// `org-icalendar-include-todo`. | |
| 6 | public enum IncludeTodo: Sendable, Equatable { | |
| 7 | case none | |
| 8 | /// `t`: entries not done. | |
| 9 | case unfinished | |
| 10 | case all | |
| 11 | /// Not done, and not blocked by children or an `ORDERED` parent. | |
| 12 | case unblocked | |
| 13 | case keywords([String]) | |
| 14 | } | |
| 15 | ||
| 16 | /// `org-icalendar-include-body`. | |
| 17 | public enum Body: Sendable, Equatable { | |
| 18 | case none, all | |
| 19 | case characters(Int) | |
| 20 | } | |
| 21 | ||
| 22 | /// `org-icalendar-use-deadline`: `event-if-not-todo`, `event-if-todo`, | |
| 23 | /// `event-if-todo-not-done`, `todo-due`. | |
| 24 | public var useDeadline: [String] = ["event-if-not-todo", "todo-due"] | |
| 25 | /// `org-icalendar-use-scheduled`: as `useDeadline`, with `todo-start`. | |
| 26 | public var useScheduled: [String] = ["todo-start"] | |
| 27 | public var includeTodo = IncludeTodo.none | |
| 28 | /// `org-icalendar-exclude-tags`, unless the file has `#+ICALENDAR_EXCLUDE_TAGS`. | |
| 29 | public var excludeTags: [String] = [] | |
| 30 | /// `org-icalendar-categories`: `category`, `todo-state`, `local-tags`, `all-tags`. | |
| 31 | public var categories = ["local-tags", "category"] | |
| 32 | /// `org-icalendar-with-timestamps`: `active`, `inactive`, `t`, `nil`, unless the file's | |
| 33 | /// `#+OPTIONS` has `<:`. | |
| 34 | public var withTimestamps = "active" | |
| 35 | public var includeBody = Body.all | |
| 36 | /// `org-icalendar-alarm-time`, minutes; 0 for none. | |
| 37 | public var alarmTime = 0 | |
| 38 | public var forceAlarm = false | |
| 39 | public var scheduledSummaryPrefix = "S: " | |
| 40 | public var deadlineSummaryPrefix = "DL: " | |
| 41 | /// `org-icalendar-todo-unscheduled-start`: `recurring-deadline-warning`, | |
| 42 | /// `deadline-warning`, `current-datetime`, `nil`. | |
| 43 | public var todoUnscheduledStart = "recurring-deadline-warning" | |
| 44 | /// `org-icalendar-timezone`; nil or empty for the time zone's abbreviation. | |
| 45 | public var timezone: String? | |
| 46 | /// `org-icalendar-date-time-format`: `:%Y%m%dT%H%M%S`, or with `Z` for UTC. | |
| 47 | public var dateTimeFormat = ":%Y%m%dT%H%M%S" | |
| 48 | /// `org-icalendar-ttl`, unless the file has `#+ICAL-TTL`. | |
| 49 | public var ttl: String? | |
| 50 | public var combinedName = "OrgMode" | |
| 51 | public var combinedDescription = "" | |
| 52 | /// `org-agenda-default-appointment-duration`, minutes. | |
| 53 | public var appointmentDuration: Int? | |
| 54 | /// `user-full-name`: the owner when a file has no `#+AUTHOR`, and of a combined calendar. | |
| 55 | public var userFullName = "" | |
| 56 | ||
| 57 | public init() {} | |
| 58 | } | |
| 59 | ||
| 60 | /// iCalendar export (`org-icalendar-export-to-ics`, `org-icalendar-combine-agenda-files`): | |
| 61 | /// VEVENTs from deadlines, scheduled dates and other timestamps, VTODOs from tasks, with | |
| 62 | /// lines folded at 75 characters and CRLF line ends. Diary sexps are left out. | |
| 63 | public enum ICalendarExport { | |
| 64 | /// The calendar for a file named `name` (its base name is the calendar's), or for the | |
| 65 | /// subtree at `subtree` alone. | |
| 66 | public static func calendar( | |
| 67 | _ text: String, name: String, settings: OrgSettings = .default, options: ICalendarOptions = ICalendarOptions(), | |
| 68 | subtree: Int? = nil, now: Date = Date(), calendar: Calendar = .current | |
| 69 | ) -> String { | |
| 70 | let file = File(text, name: name, settings: settings, options: options, subtree: subtree, now: now, calendar: calendar) | |
| 71 | let author = file.keyword("AUTHOR") ?? options.userFullName | |
| 72 | return vcalendar( | |
| 73 | name: (name as NSString).deletingPathExtension, owner: file.export.author ? file.ascii.inlineString(author) : "", | |
| 74 | timezone: zone(options, calendar), description: file.title, ttl: file.keyword("ICAL-TTL") ?? options.ttl, contents: file.components() | |
| 75 | ) | |
| 76 | } | |
| 77 | ||
| 78 | /// One calendar of every file's entries, named `combinedName`. | |
| 79 | public static func combined( | |
| 80 | _ files: [(name: String, text: String, settings: OrgSettings)], options: ICalendarOptions = ICalendarOptions(), | |
| 81 | now: Date = Date(), calendar: Calendar = .current | |
| 82 | ) -> String { | |
| 83 | let contents = files.map { | |
| 84 | File($0.text, name: $0.name, settings: $0.settings, options: options, subtree: nil, now: now, calendar: calendar).components() | |
| 85 | }.joined() | |
| 86 | return vcalendar(name: options.combinedName, owner: options.userFullName, timezone: zone(options, calendar), | |
| 87 | description: options.combinedDescription, ttl: options.ttl, contents: contents) | |
| 88 | } | |
| 89 | ||
| 90 | static func zone(_ options: ICalendarOptions, _ calendar: Calendar) -> String { | |
| 91 | if let tz = options.timezone, !tz.isEmpty { return tz } | |
| 92 | return calendar.timeZone.abbreviation() ?? calendar.timeZone.identifier | |
| 93 | } | |
| 94 | ||
| 95 | /// `org-icalendar--vcalendar`, folded, with CRLF line ends. | |
| 96 | static func vcalendar(name: String, owner: String, timezone: String, description: String, ttl: String?, contents: String) -> String { | |
| 97 | var out = "BEGIN:VCALENDAR\nVERSION:2.0\nX-WR-CALNAME:\(cleanup(name))\nPRODID:-//\(cleanup(owner))//Emacs with Org mode//EN\n" | |
| 98 | + "X-WR-TIMEZONE:\(cleanup(timezone))\nX-WR-CALDESC:\(cleanup(description))\n" | |
| 99 | if let ttl { out += "X-PUBLISHED-TTL:\(cleanup(ttl))\n" } | |
| 100 | out += "CALSCALE:GREGORIAN\n" + contents + "END:VCALENDAR\n" | |
| 101 | return fold(out).replacingOccurrences(of: "\n", with: "\r\n") | |
| 102 | } | |
| 103 | ||
| 104 | /// `org-icalendar-cleanup-string`: `\`, `,` and `;` escaped, newlines as `\n`. | |
| 105 | static func cleanup(_ s: String) -> String { | |
| 106 | var out = "" | |
| 107 | for c in s { | |
| 108 | if c == "\\" || c == "," || c == ";" { out.append("\\") } | |
| 109 | out.append(c) | |
| 110 | } | |
| 111 | return out.replacing(#/[ \t]*\n/#, with: "\\n") | |
| 112 | } | |
| 113 | ||
| 114 | /// `org-icalendar-fold-string`: lines over 75 characters continue on lines starting with a | |
| 115 | /// space. | |
| 116 | static func fold(_ s: String) -> String { | |
| 117 | let lines = s.components(separatedBy: "\n").filter { !$0.isEmpty } | |
| 118 | return lines.map { line -> String in | |
| 119 | let scalars = Array(line.unicodeScalars) | |
| 120 | guard scalars.count > 75 else { return line } | |
| 121 | var parts = [String(String.UnicodeScalarView(scalars[0..<75]))] | |
| 122 | var start = 75 | |
| 123 | while start < scalars.count { | |
| 124 | let end = min(start + 74, scalars.count) | |
| 125 | parts.append(" " + String(String.UnicodeScalarView(scalars[start..<end]))) | |
| 126 | start = end | |
| 127 | } | |
| 128 | return parts.joined(separator: "\n") | |
| 129 | }.joined(separator: "\n") + "\n" | |
| 130 | } | |
| 131 | ||
| 132 | /// `org-export--skip-timestamp-p` for a timestamp written `text`. | |
| 133 | static func skipsTimestamp(_ text: String, with: String) -> Bool { | |
| 134 | let diary = text.hasPrefix("<%%") | |
| 135 | let active = text.hasPrefix("<") | |
| 136 | switch with { | |
| 137 | case "nil": return true | |
| 138 | case "active": return !active | |
| 139 | case "active-exclude-diary": return !active || diary | |
| 140 | case "inactive": return active | |
| 141 | default: return false | |
| 142 | } | |
| 143 | } | |
| 144 | ||
| 145 | // MARK: - A file's entries | |
| 146 | ||
| 147 | struct File { | |
| 148 | let text: String | |
| 149 | let source: NSString | |
| 150 | let tree: OrgTree | |
| 151 | let model: DocumentModel | |
| 152 | let options: ICalendarOptions | |
| 153 | var export: ExportOptions | |
| 154 | let ascii: ASCIIText | |
| 155 | let name: String | |
| 156 | let subtree: Int? | |
| 157 | let now: Date | |
| 158 | let calendar: Calendar | |
| 159 | let selected: Set<Int>? | |
| 160 | let headingIndex: [Int: Int] | |
| 161 | let settings: OrgSettings | |
| 162 | ||
| 163 | init(_ text: String, name: String, settings: OrgSettings, options: ICalendarOptions, subtree: Int?, now: Date, calendar: Calendar) { | |
| 164 | let text = ExportPreprocess.macros(text, path: name, now: now, setup: settings.setupKeywords) | |
| 165 | self.text = text | |
| 166 | source = text as NSString | |
| 167 | tree = OrgParser.parse(text, defaults: settings) | |
| 168 | model = DocumentModel(tree: tree) | |
| 169 | self.options = options | |
| 170 | self.settings = settings | |
| 171 | var export = ExportOptions.parse(settings.setupKeywords + "\n" + text) | |
| 172 | export.excludeTags = Self.keyword("ICALENDAR_EXCLUDE_TAGS", tree: tree, settings: settings) | |
| 173 | .map { $0.split(whereSeparator: \.isWhitespace).map(String.init) } ?? options.excludeTags | |
| 174 | if export.timestamps == nil { export.timestamps = options.withTimestamps } | |
| 175 | self.export = export | |
| 176 | var ascii = ASCIIText(options: export) | |
| 177 | var numbers = Array(repeating: 0, count: max(1, export.headlineLevels)) | |
| 178 | for heading in model.headings where heading.level <= export.headlineLevels { | |
| 179 | numbers[heading.level - 1] += 1 | |
| 180 | for deeper in heading.level..<numbers.count { numbers[deeper] = 0 } | |
| 181 | let plain = Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces) | |
| 182 | if ascii.headingNumbers[plain] == nil { ascii.headingNumbers[plain] = numbers.prefix(heading.level).map(String.init).joined(separator: ".") } | |
| 183 | } | |
| 184 | self.ascii = ascii | |
| 185 | self.name = name | |
| 186 | self.subtree = subtree | |
| 187 | self.now = now | |
| 188 | self.calendar = calendar | |
| 189 | selected = HTMLRenderer.selection(tree, tags: export.selectTags) | |
| 190 | headingIndex = Dictionary(model.headings.enumerated().map { ($1.headingRange.lowerBound, $0) }, uniquingKeysWith: { a, _ in a }) | |
| 191 | } | |
| 192 | ||
| 193 | static func keyword(_ key: String, tree: OrgTree, settings: OrgSettings) -> String? { | |
| 194 | var value: String? | |
| 195 | let lines = settings.setupKeywords.split(separator: "\n").map(String.init) | |
| 196 | + tree.root.descendants().filter { $0.kind == .keyword }.map(\.text) | |
| 197 | for line in lines { | |
| 198 | if let m = line.firstMatch(of: #/(?i)^[ \t]*#\+([^:\s]+):[ \t]*(.*?)[ \t]*\n?$/#), m.1.uppercased() == key { value = String(m.2) } | |
| 199 | } | |
| 200 | return value | |
| 201 | } | |
| 202 | ||
| 203 | func keyword(_ key: String) -> String? { Self.keyword(key, tree: tree, settings: settings) } | |
| 204 | ||
| 205 | /// The heading whose subtree is exported. | |
| 206 | var subtreeHeading: Int? { subtree.flatMap { offset in model.headings.lastIndex { $0.headingRange.lowerBound <= offset } } } | |
| 207 | ||
| 208 | /// `#+TITLE`; for a subtree, its `EXPORT_TITLE` or title. | |
| 209 | var title: String { | |
| 210 | if let index = subtreeHeading { | |
| 211 | return ascii.inlineString(property("EXPORT_TITLE", index) ?? Links.displayFormat(model.headings[index].title).trimmingCharacters(in: .whitespaces)) | |
| 212 | } | |
| 213 | return keyword("TITLE").map { ascii.inlineString($0) } ?? "" | |
| 214 | } | |
| 215 | ||
| 216 | /// The components of every entry, in order. | |
| 217 | func components() -> String { | |
| 218 | var out = "" | |
| 219 | for node in tree.root.children where node.kind == .section { out += section(node) } | |
| 220 | return out | |
| 221 | } | |
| 222 | ||
| 223 | func section(_ node: SyntaxNode) -> String { | |
| 224 | guard let heading = node.firstChild(.heading), let index = headingIndex[heading.range.lowerBound] else { return "" } | |
| 225 | let info = model.headings[index] | |
| 226 | if subtree != nil, let target = subtreeHeading { | |
| 227 | // Only the subtree at `subtree`, as Org narrows to it. | |
| 228 | if model.ancestors(of: target).contains(index) { return node.children.filter { $0.kind == .section }.map(section).joined() } | |
| 229 | if index != target, !model.ancestors(of: index).contains(target) { return "" } | |
| 230 | } | |
| 231 | let what = HTMLRenderer.sectionExport(heading, options: export, selected: selected) | |
| 232 | if what == .nothing { return "" } | |
| 233 | let title = Links.displayFormat(info.title).trimmingCharacters(in: .whitespaces) | |
| 234 | if title == "Footnotes" { return "" } | |
| 235 | let body = what == .all ? node.children.filter { ![.heading, .section, .planning, .propertyDrawer].contains($0.kind) } : [] | |
| 236 | var out = entry(index, heading: heading, body: body, end: node.children.first { $0.kind == .section }?.range.lowerBound ?? node.range.upperBound) | |
| 237 | if what == .all { for child in node.children where child.kind == .section { out += section(child) } } | |
| 238 | return out | |
| 239 | } | |
| 240 | ||
| 241 | // MARK: Entries | |
| 242 | ||
| 243 | func property(_ key: String, _ index: Int) -> String? { model.property(key, of: index)?.value } | |
| 244 | ||
| 245 | func entry(_ index: Int, heading: SyntaxNode, body: [SyntaxNode], end: Int) -> String { | |
| 246 | let info = model.headings[index] | |
| 247 | let todoType: String? = info.todo == nil ? nil : info.isDone ? "done" : "todo" | |
| 248 | let uid = info.id ?? UUID().uuidString | |
| 249 | let titleNode = heading.firstChild(.title) | |
| 250 | let summary = cleanup(model.headings[index].properties.contains { $0.key.uppercased() == "SUMMARY" } || model.inherits("SUMMARY") | |
| 251 | ? property("SUMMARY", index) ?? titleNode.map { ascii.inline($0) }?.trimmingCharacters(in: .whitespaces) ?? "" | |
| 252 | : titleNode.map { ascii.inline($0) }?.trimmingCharacters(in: .whitespaces) ?? "") | |
| 253 | let location = property("LOCATION", index).map(cleanup) | |
| 254 | let klass = property("CLASS", index).map(cleanup) | |
| 255 | var description: String? | |
| 256 | if let own = property("DESCRIPTION", index) { | |
| 257 | description = own | |
| 258 | } else { | |
| 259 | let contents = ascii.elements(body, end: end, source: source, width: ascii.width(level: info.level)) | |
| 260 | if contents.contains(where: { !$0.isWhitespace }) { | |
| 261 | let trimmed = contents.trimmingCharacters(in: .whitespacesAndNewlines) | |
| 262 | switch options.includeBody { | |
| 263 | case .none: description = nil | |
| 264 | case .all: description = trimmed | |
| 265 | case .characters(let n): description = String(trimmed.unicodeScalars.prefix(n)) | |
| 266 | } | |
| 267 | } | |
| 268 | } | |
| 269 | description = description.map(cleanup) | |
| 270 | let categories = self.categories(index) | |
| 271 | let timezone = property("TIMEZONE", index) | |
| 272 | var out = "" | |
| 273 | func wants(_ list: [String]) -> Bool { | |
| 274 | switch todoType { | |
| 275 | case "todo": list.contains("event-if-todo-not-done") || list.contains("event-if-todo") | |
| 276 | case "done": list.contains("event-if-todo") | |
| 277 | default: list.contains("event-if-not-todo") | |
| 278 | } | |
| 279 | } | |
| 280 | let entry = Entry(uid: uid, summary: summary, location: location, description: description, categories: categories, timezone: timezone, klass: klass, warnTime: info.properties.last { $0.key.uppercased() == "APPT_WARNTIME" }.flatMap { Int($0.value.trimmingCharacters(in: .whitespaces)) }) | |
| 281 | if let deadline = info.deadline, wants(options.useDeadline) { | |
| 282 | out += vevent(entry, deadline, uid: "DL-" + uid, summary: cleanup(options.deadlineSummaryPrefix) + summary) | |
| 283 | } | |
| 284 | if let scheduled = info.scheduled, wants(options.useScheduled) { | |
| 285 | out += vevent(entry, scheduled, uid: "SC-" + uid, summary: cleanup(options.scheduledSummaryPrefix) + summary) | |
| 286 | } | |
| 287 | var counter = 0 | |
| 288 | for text in timestamps(titleNode) + body.flatMap(timestamps) where !skipsTimestamp(text, with: export.timestamps ?? "active") { | |
| 289 | guard !text.hasPrefix("<%%"), let stamp = Timestamp.parse(text) else { continue } | |
| 290 | counter += 1 | |
| 291 | out += vevent(entry, stamp, uid: "TS\(counter)-" + uid, summary: summary) | |
| 292 | } | |
| 293 | if let todoType, includesTodo(index, todoType: todoType) { | |
| 294 | out += vtodo(entry, index, todoType: todoType) | |
| 295 | } | |
| 296 | return out | |
| 297 | } | |
| 298 | ||
| 299 | struct Entry { | |
| 300 | let uid: String | |
| 301 | let summary: String | |
| 302 | let location: String? | |
| 303 | let description: String? | |
| 304 | let categories: String | |
| 305 | let timezone: String? | |
| 306 | let klass: String? | |
| 307 | let warnTime: Int? | |
| 308 | } | |
| 309 | ||
| 310 | /// The timestamps `org-element-map` finds, leaving out what the export ignores. | |
| 311 | func timestamps(_ node: SyntaxNode?) -> [String] { | |
| 312 | guard let node else { return [] } | |
| 313 | switch node.kind { | |
| 314 | case .timestamp: return [node.text] | |
| 315 | case .planning, .propertyDrawer, .clock, .comment, .keyword, .block, .inlineTask, .fixedWidth, .heading, .section: return [] | |
| 316 | case .drawer: | |
| 317 | if node.text.firstMatch(of: /^[ \t]*:LOGBOOK:/) != nil { return [] } | |
| 318 | default: break | |
| 319 | } | |
| 320 | return node.children.flatMap(timestamps) | |
| 321 | } | |
| 322 | ||
| 323 | func categories(_ index: Int) -> String { | |
| 324 | let info = model.headings[index] | |
| 325 | var out: [String] = [] | |
| 326 | func tags(_ list: [String]) -> [String] { list.filter { !export.selectTags.contains($0) && !export.excludeTags.contains($0) } } | |
| 327 | for kind in options.categories { | |
| 328 | switch kind { | |
| 329 | case "category": | |
| 330 | out.append(property("CATEGORY", index) ?? keyword("CATEGORY") ?? (name as NSString).deletingPathExtension) | |
| 331 | case "todo-state": if let todo = info.todo { out.append(todo) } | |
| 332 | case "local-tags": out += tags(info.localTags) | |
| 333 | case "all-tags": out += tags(model.tags(of: index).map(\.value)) | |
| 334 | default: break | |
| 335 | } | |
| 336 | } | |
| 337 | var seen: Set<String> = [] | |
| 338 | return out.filter { seen.insert($0).inserted }.joined(separator: ",") | |
| 339 | } | |
| 340 | ||
| 341 | func includesTodo(_ index: Int, todoType: String) -> Bool { | |
| 342 | switch options.includeTodo { | |
| 343 | case .none: return false | |
| 344 | case .all: return true | |
| 345 | case .unfinished: return todoType == "todo" | |
| 346 | case .keywords(let list): return model.headings[index].todo.map(list.contains) ?? false | |
| 347 | case .unblocked: return !blocked(index) | |
| 348 | } | |
| 349 | } | |
| 350 | ||
| 351 | /// `org-icalendar-blocked-headline-p`. | |
| 352 | func blocked(_ index: Int) -> Bool { | |
| 353 | let level = model.headings[index].level | |
| 354 | for child in model.headings[(index + 1)...].prefix(while: { $0.level > level }) where child.todo != nil && !child.isDone { return true } | |
| 355 | var current = index | |
| 356 | for parent in model.ancestors(of: index).reversed() { | |
| 357 | guard model.headings[parent].todo != nil else { return false } | |
| 358 | let ordered = model.headings[parent].properties.last { $0.key.uppercased() == "ORDERED" }?.value | |
| 359 | if let ordered, !ordered.isEmpty, ordered != "nil" { | |
| 360 | let siblings = model.headings.indices.filter { model.headings[$0].parent == parent && $0 < current } | |
| 361 | if siblings.contains(where: { model.headings[$0].todo != nil && !model.headings[$0].isDone }) { return true } | |
| 362 | } else { | |
| 363 | current = parent | |
| 364 | } | |
| 365 | } | |
| 366 | return false | |
| 367 | } | |
| 368 | ||
| 369 | // MARK: Components | |
| 370 | ||
| 371 | func vevent(_ entry: Entry, _ stamp: Timestamp, uid: String, summary: String) -> String { | |
| 372 | var out = "BEGIN:VEVENT\n" + dtstamp + "\nUID:" + uid + "\n" | |
| 373 | out += convert(stamp, "DTSTART", end: false, tz: entry.timezone) + "\n" | |
| 374 | out += convert(stamp, "DTEND", end: true, tz: entry.timezone) + "\n" | |
| 375 | if let r = stamp.repeater { out += rrule(r.interval) + "\n" } | |
| 376 | out += "SUMMARY:" + summary + "\n" | |
| 377 | if let l = entry.location, l.contains(where: { !$0.isWhitespace }) { out += "LOCATION:\(l)\n" } | |
| 378 | if let c = entry.klass, c.contains(where: { !$0.isWhitespace }) { out += "CLASS:\(c)\n" } | |
| 379 | if let d = entry.description, d.contains(where: { !$0.isWhitespace }) { out += "DESCRIPTION:\(d)\n" } | |
| 380 | out += "CATEGORIES:" + entry.categories + "\n" | |
| 381 | out += valarm(entry, stamp, summary: summary) | |
| 382 | return out + "END:VEVENT\n" | |
| 383 | } | |
| 384 | ||
| 385 | var dtstamp: String { | |
| 386 | var utc = Calendar(identifier: .gregorian) | |
| 387 | utc.timeZone = TimeZone(identifier: "UTC")! | |
| 388 | return "DTSTAMP:" + format(now, "%Y%m%dT%H%M%SZ", utc) | |
| 389 | } | |
| 390 | ||
| 391 | func rrule(_ interval: Timestamp.Interval) -> String { | |
| 392 | let freq = ["h": "HOURLY", "d": "DAILY", "w": "WEEKLY", "m": "MONTHLY", "y": "YEARLY"][String(interval.unit.rawValue)]! | |
| 393 | return "RRULE:FREQ=\(freq);INTERVAL=\(interval.value)" | |
| 394 | } | |
| 395 | ||
| 396 | func valarm(_ entry: Entry, _ stamp: Timestamp, summary: String) -> String { | |
| 397 | let alarm = entry.warnTime | |
| 398 | guard (alarm.map { $0 > 0 } ?? false) || options.alarmTime > 0 || options.forceAlarm, stamp.start.hour != nil else { return "" } | |
| 399 | let minutes: Int | |
| 400 | if let alarm, options.forceAlarm { minutes = alarm } else if let alarm, alarm != 0 { minutes = alarm } else { minutes = options.alarmTime } | |
| 401 | return "BEGIN:VALARM\nACTION:DISPLAY\nDESCRIPTION:\(summary)\nTRIGGER:-P0DT0H\(minutes)M0S\nEND:VALARM\n" | |
| 402 | } | |
| 403 | ||
| 404 | /// `org-icalendar--repeater-type`: only `+` repeaters repeat a VTODO. | |
| 405 | static func repeats(_ stamp: Timestamp?) -> Bool { | |
| 406 | guard let r = stamp?.repeater, r.interval.value > 0 else { return false } | |
| 407 | return r.kind == .cumulate | |
| 408 | } | |
| 409 | ||
| 410 | func vtodo(_ entry: Entry, _ index: Int, todoType: String) -> String { | |
| 411 | let info = model.headings[index] | |
| 412 | let sc = options.useScheduled.contains("todo-start") ? info.scheduled : nil | |
| 413 | let dl = options.useDeadline.contains("todo-due") ? info.deadline : nil | |
| 414 | let scRepeats = Self.repeats(sc) | |
| 415 | let dlRepeats = Self.repeats(dl) | |
| 416 | let repeatInterval = sc?.repeater?.interval ?? dl?.repeater?.interval | |
| 417 | let until = scRepeats && !dlRepeats ? dl : nil | |
| 418 | var start: Timestamp? = sc | |
| 419 | if start == nil { | |
| 420 | switch options.todoUnscheduledStart { | |
| 421 | case "current-datetime": | |
| 422 | let c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: now) | |
| 423 | start = Timestamp(active: true, start: .init(year: c.year!, month: c.month!, day: c.day!, hour: c.hour, minute: c.minute), end: nil, repeater: nil, warning: nil) | |
| 424 | case "deadline-warning" where dl != nil, "recurring-deadline-warning" where dlRepeats: | |
| 425 | start = shifted(dl!, days: -warningDays(dl!)) | |
| 426 | default: break | |
| 427 | } | |
| 428 | } | |
| 429 | var out = "BEGIN:VTODO\nUID:TODO-" + entry.uid + "\n" + dtstamp + "\n" | |
| 430 | if let start { out += convert(start, "DTSTART", end: false, tz: entry.timezone) + "\n" } | |
| 431 | if let dl, until == nil { out += convert(dl, "DUE", end: false, tz: entry.timezone) + "\n" } | |
| 432 | if dlRepeats, repeatInterval != dl?.repeater?.interval { | |
| 433 | // Different repeaters on SCHEDULED and DEADLINE: no RRULE, as Org warns. | |
| 434 | } else if dlRepeats, sc != nil, !scRepeats { | |
| 435 | // A repeater on DEADLINE but not SCHEDULED: no RRULE either. | |
| 436 | } else if scRepeats || dlRepeats, let repeatInterval { | |
| 437 | out += rrule(repeatInterval) | |
| 438 | if let until { | |
| 439 | let local = entry.timezone == nil && options.dateTimeFormat == ":%Y%m%dT%H%M%S" | |
| 440 | let date = self.date(until.start.year, until.start.month, until.start.day, until.start.hour ?? 0, until.start.minute ?? 0) | |
| 441 | var utc = Calendar(identifier: .gregorian) | |
| 442 | utc.timeZone = TimeZone(identifier: "UTC")! | |
| 443 | out += ";UNTIL=" + (start?.start.minute == nil ? format(date, "%Y%m%d", calendar) | |
| 444 | : local ? format(date, "%Y%m%dT%H%M%S", calendar) : format(date, "%Y%m%dT%H%M%SZ", utc)) | |
| 445 | } | |
| 446 | out += "\n" | |
| 447 | } | |
| 448 | out += "SUMMARY:" + entry.summary + "\n" | |
| 449 | if let l = entry.location, l.contains(where: { !$0.isWhitespace }) { out += "LOCATION:\(l)\n" } | |
| 450 | if let c = entry.klass, c.contains(where: { !$0.isWhitespace }) { out += "CLASS:\(c)\n" } | |
| 451 | if let d = entry.description, d.contains(where: { !$0.isWhitespace }) { out += "DESCRIPTION:\(d)\n" } | |
| 452 | out += "CATEGORIES:" + entry.categories + "\n" + "SEQUENCE:1\n" | |
| 453 | out += "PRIORITY:\(priority(info.priority))\n" | |
| 454 | out += "STATUS:" + (todoType == "todo" ? "NEEDS-ACTION" : "COMPLETED") + "\n" | |
| 455 | return out + "END:VTODO\n" | |
| 456 | } | |
| 457 | ||
| 458 | func priority(_ cookie: String?) -> Int { | |
| 459 | func code(_ s: String) -> Int { Int(s) ?? Int(s.unicodeScalars.first?.value ?? 66) } | |
| 460 | let p = settings.priorities | |
| 461 | let highest = code(p.highest), lowest = code(p.lowest) | |
| 462 | let value = code(cookie ?? p.default) | |
| 463 | guard lowest != highest else { return 5 } | |
| 464 | return Int((9 - 8 * (Double(lowest - value) / Double(lowest - highest))).rounded(.down)) | |
| 465 | } | |
| 466 | ||
| 467 | /// `org-get-wdays`: the deadline's warning period in days. | |
| 468 | func warningDays(_ stamp: Timestamp) -> Int { | |
| 469 | guard let w = stamp.warning else { return settings.deadlineWarningDays } | |
| 470 | let n = Double(w.interval.value) | |
| 471 | switch w.interval.unit { | |
| 472 | case .hour: return Int((n / 24).rounded(.down)) | |
| 473 | case .day: return Int(n) | |
| 474 | case .week: return Int(n * 7) | |
| 475 | case .month: return Int((n * 30.4).rounded(.down)) | |
| 476 | case .year: return Int((n * 365.25).rounded(.down)) | |
| 477 | } | |
| 478 | } | |
| 479 | ||
| 480 | func shifted(_ stamp: Timestamp, days: Int) -> Timestamp { | |
| 481 | var copy = stamp | |
| 482 | let absolute = Days.absolute(year: stamp.start.year, month: stamp.start.month, day: stamp.start.day) + days | |
| 483 | let d = Days.date(absolute) | |
| 484 | (copy.start.year, copy.start.month, copy.start.day) = (d.year, d.month, d.day) | |
| 485 | copy.end = nil | |
| 486 | return copy | |
| 487 | } | |
| 488 | ||
| 489 | func date(_ y: Int, _ m: Int, _ d: Int, _ h: Int, _ mi: Int) -> Date { | |
| 490 | calendar.date(from: DateComponents(year: y, month: m, day: d, hour: h, minute: mi, second: 0)) ?? now | |
| 491 | } | |
| 492 | ||
| 493 | /// `org-icalendar-convert-timestamp`. | |
| 494 | func convert(_ stamp: Timestamp, _ keyword: String, end: Bool, tz: String?) -> String { | |
| 495 | let s = stamp.start | |
| 496 | let e = stamp.end ?? stamp.start | |
| 497 | let timed = s.minute != nil || s.hour != nil | |
| 498 | let equal = stamp.end == nil || (s.year, s.month, s.day, s.hour, s.minute) == (e.year, e.month, e.day, e.hour, e.minute) | |
| 499 | let mi = !timed ? 0 : !end ? (s.minute ?? 0) : (options.appointmentDuration != nil && equal) ? (e.minute ?? 0) + options.appointmentDuration! : (e.minute ?? 0) | |
| 500 | let h = !timed ? 0 : !end ? (s.hour ?? 0) : (!equal || options.appointmentDuration != nil) ? (e.hour ?? 0) : (e.hour ?? 0) + 2 | |
| 501 | let d = !end ? s.day : !timed ? e.day + 1 : e.day | |
| 502 | let m = end ? e.month : s.month | |
| 503 | let y = end ? e.year : s.year | |
| 504 | let date = self.date(y, m, d, h, mi) | |
| 505 | var utc = Calendar(identifier: .gregorian) | |
| 506 | utc.timeZone = TimeZone(identifier: "UTC")! | |
| 507 | if tz == "UTC" { return keyword + format(date, ":%Y%m%dT%H%M%SZ", utc) } | |
| 508 | if !timed { return keyword + format(date, ";VALUE=DATE:%Y%m%d", calendar) } | |
| 509 | if let tz { return keyword + ";TZID=" + tz + format(date, ":%Y%m%dT%H%M%S", calendar) } | |
| 510 | let pattern = options.dateTimeFormat.replacingOccurrences(of: "%Z", with: options.timezone ?? "") | |
| 511 | return keyword + format(date, pattern, options.dateTimeFormat.hasSuffix("Z") ? utc : calendar) | |
| 512 | } | |
| 513 | ||
| 514 | /// `format-time-string` for `%Y %m %d %H %M %S`. | |
| 515 | func format(_ date: Date, _ pattern: String, _ calendar: Calendar) -> String { | |
| 516 | let c = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) | |
| 517 | var out = "" | |
| 518 | var i = pattern.startIndex | |
| 519 | while i < pattern.endIndex { | |
| 520 | let ch = pattern[i] | |
| 521 | let next = pattern.index(after: i) | |
| 522 | if ch == "%", next < pattern.endIndex { | |
| 523 | switch pattern[next] { | |
| 524 | case "Y": out += String(format: "%04d", c.year!) | |
| 525 | case "m": out += String(format: "%02d", c.month!) | |
| 526 | case "d": out += String(format: "%02d", c.day!) | |
| 527 | case "H": out += String(format: "%02d", c.hour!) | |
| 528 | case "M": out += String(format: "%02d", c.minute!) | |
| 529 | case "S": out += String(format: "%02d", c.second!) | |
| 530 | case "%": out += "%" | |
| 531 | default: out += String(pattern[i...next]) | |
| 532 | } | |
| 533 | i = pattern.index(after: next) | |
| 534 | } else { | |
| 535 | out.append(ch) | |
| 536 | i = next | |
| 537 | } | |
| 538 | } | |
| 539 | return out | |
| 540 | } | |
| 541 | } | |
| 542 | } | |
| 543 | ||
| 544 | extension ASCIIText { | |
| 545 | /// A line of Org text's objects, as a title is exported. | |
| 546 | func inlineString(_ text: String) -> String { | |
| 547 | let tree = OrgParser.parse(text) | |
| 548 | guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return text } | |
| 549 | return inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) | |
| 550 | } | |
| 551 | } | |
Sources/OrgCore/Keymap/PresetEmacs.swift +9
| @@ -334,6 +334,15 @@ extension KeymapPreset { | ||
| 334 | 334 | [[bind]] |
| 335 | 335 | keys = "C-c C-e t u" |
| 336 | 336 | command = "app.export.text" |
| 337 | [[bind]] | |
| 338 | keys = "C-c C-e c f" | |
| 339 | command = "app.export.icalendar" | |
| 340 | [[bind]] | |
| 341 | keys = "C-c C-e c a" | |
| 342 | command = "app.export.icalendar-agenda" | |
| 343 | [[bind]] | |
| 344 | keys = "C-c C-e c c" | |
| 345 | command = "app.export.icalendar-combined" | |
| 337 | 346 | |
| 338 | 347 | # Org |
| 339 | 348 | [[bind]] |
Sources/OrgEditorAppKit/EditorCommands.swift +3
| @@ -122,6 +122,9 @@ public enum EditorCommands { | ||
| 122 | 122 | EditorCommand(id: "app.export.odt", title: "Export to ODT with Emacs", action: .app), |
| 123 | 123 | EditorCommand(id: "app.export.latex", title: "Export to LaTeX with Emacs", action: .app), |
| 124 | 124 | EditorCommand(id: "app.export.text", title: "Export to Plain Text with Emacs", action: .app), |
| 125 | EditorCommand(id: "app.export.icalendar", title: "Export to iCalendar", action: .app), | |
| 126 | EditorCommand(id: "app.export.icalendar-agenda", title: "Export Agenda Files to iCalendar", action: .app), | |
| 127 | EditorCommand(id: "app.export.icalendar-combined", title: "Combine Agenda Files into iCalendar", action: .app), | |
| 125 | 128 | |
| 126 | 129 | movement("forward-char", "Forward Character", "moveForward:"), |
| 127 | 130 | movement("backward-char", "Backward Character", "moveBackward:"), |
Sources/Orgstar/ContentView.swift +32 −1
| @@ -547,6 +547,7 @@ struct ContentView: View { | ||
| 547 | 547 | /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the |
| 548 | 548 | /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper. |
| 549 | 549 | private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) { |
| 550 | if format == "icalendar-agenda" || format == "icalendar-combined" { return exportAgendaCalendars(combined: format == "icalendar-combined") } | |
| 550 | 551 | guard let path = session.path, var text = session.document?.text else { |
| 551 | 552 | commands.show("No file is open") |
| 552 | 553 | return |
| @@ -562,6 +563,15 @@ struct ContentView: View { | ||
| 562 | 563 | text = narrowed |
| 563 | 564 | } |
| 564 | 565 | switch format { |
| 566 | case "icalendar": | |
| 567 | do { | |
| 568 | let target = try ICalendarFiles.export(whole, path: path, settings: defaults, options: OrgPreferences.icalendarOptions(), | |
| 569 | subtree: subtree ? caret : nil, destination: destination) | |
| 570 | commands.show("Exported to \(target.lastPathComponent)") | |
| 571 | if open { NSWorkspace.shared.open(target) } | |
| 572 | } catch { | |
| 573 | commands.show("Can't export: \(error.localizedDescription)") | |
| 574 | } | |
| 565 | 575 | case "html", "html-open", "markdown": |
| 566 | 576 | let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults) |
| 567 | 577 | let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html") |
| @@ -633,6 +643,27 @@ struct ContentView: View { | ||
| 633 | 643 | } |
| 634 | 644 | } |
| 635 | 645 | |
| 646 | /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`. | |
| 647 | private func exportAgendaCalendars(combined: Bool) { | |
| 648 | let paths = workspace.agendaFilePaths() | |
| 649 | let read = { (path: String) -> (text: String, settings: OrgSettings)? in | |
| 650 | guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil } | |
| 651 | return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)) | |
| 652 | } | |
| 653 | do { | |
| 654 | let options = OrgPreferences.icalendarOptions() | |
| 655 | if combined { | |
| 656 | let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read) | |
| 657 | commands.show("Exported \(paths.count) agenda files to \(url.lastPathComponent)") | |
| 658 | } else { | |
| 659 | let written = try ICalendarFiles.exportEach(paths, options: options, read: read) | |
| 660 | commands.show("Exported \(written.count) agenda files to iCalendar") | |
| 661 | } | |
| 662 | } catch { | |
| 663 | commands.show("Can't export: \(error.localizedDescription)") | |
| 664 | } | |
| 665 | } | |
| 666 | ||
| 636 | 667 | /// Work a command hands to the platform: tables recalculated in Emacs. |
| 637 | 668 | private func runExternal(_ request: ExternalRequest) { |
| 638 | 669 | switch request { |
| @@ -740,7 +771,7 @@ struct ContentView: View { | ||
| 740 | 771 | |
| 741 | 772 | /// Runs a command from a key, the palette or the Org menu. |
| 742 | 773 | private func perform(_ id: String) { |
| 743 | let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.") | |
| 774 | let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.") | |
| 744 | 775 | if orgOnly, !session.isOrg { |
| 745 | 776 | commands.show("Not an org file") |
| 746 | 777 | return |
Sources/Orgstar/ExportSheet.swift +2 −1
| @@ -20,12 +20,13 @@ struct ExportSheet: View { | ||
| 20 | 20 | ("html", "HTML", "html"), ("markdown", "Markdown", "md"), ("print-pdf", "PDF", "pdf"), ("docx", "Word", "docx"), |
| 21 | 21 | ("rtf", "Rich Text (RTF)", "rtf"), ("plain-text", "Plain text", "txt"), ("pdf", "PDF via LaTeX (Emacs)", "pdf"), |
| 22 | 22 | ("odt", "ODT (Emacs)", "odt"), ("latex", "LaTeX (Emacs)", "tex"), ("text", "Plain text, ASCII (Emacs)", "txt"), |
| 23 | ("icalendar", "iCalendar", "ics"), | |
| 23 | 24 | ] |
| 24 | 25 | |
| 25 | 26 | private var ext: String { Self.formats.first { $0.id == format }?.ext ?? "html" } |
| 26 | 27 | private var chosen: URL { destination ?? target(ext, subtree) } |
| 27 | 28 | /// PDF and ODT are whole documents. |
| 28 | private var allowsBodyOnly: Bool { !["pdf", "print-pdf", "odt", "docx", "rtf", "plain-text"].contains(format) } | |
| 29 | private var allowsBodyOnly: Bool { !["pdf", "print-pdf", "odt", "docx", "rtf", "plain-text", "icalendar"].contains(format) } | |
| 29 | 30 | |
| 30 | 31 | var body: some View { |
| 31 | 32 | Form { |
Sources/OrgstarMobile/ExportMenu.swift +10 −3
| @@ -6,10 +6,11 @@ import OrgPresentation | ||
| 6 | 6 | import SwiftUI |
| 7 | 7 | import UniformTypeIdentifiers |
| 8 | 8 | |
| 9 | /// A file exported as HTML, Markdown or PDF, written when the share sheet takes it. | |
| 9 | /// A file exported as HTML, Markdown, PDF, RTF, plain text or iCalendar, written when the share | |
| 10 | /// sheet takes it. | |
| 10 | 11 | struct OrgExport: Transferable { |
| 11 | 12 | enum Format: CaseIterable { |
| 12 | case html, markdown, pdf, rtf, plainText | |
| 13 | case html, markdown, pdf, rtf, plainText, icalendar | |
| 13 | 14 | |
| 14 | 15 | var name: String { |
| 15 | 16 | switch self { |
| @@ -18,6 +19,7 @@ struct OrgExport: Transferable { | ||
| 18 | 19 | case .pdf: "PDF" |
| 19 | 20 | case .rtf: "Rich Text (RTF)" |
| 20 | 21 | case .plainText: "Plain Text" |
| 22 | case .icalendar: "iCalendar" | |
| 21 | 23 | } |
| 22 | 24 | } |
| 23 | 25 | |
| @@ -28,6 +30,7 @@ struct OrgExport: Transferable { | ||
| 28 | 30 | case .pdf: "pdf" |
| 29 | 31 | case .rtf: "rtf" |
| 30 | 32 | case .plainText: "txt" |
| 33 | case .icalendar: "ics" | |
| 31 | 34 | } |
| 32 | 35 | } |
| 33 | 36 | } |
| @@ -56,6 +59,8 @@ struct OrgExport: Transferable { | ||
| 56 | 59 | .exportingCondition { $0.format == .rtf } |
| 57 | 60 | FileRepresentation(exportedContentType: .plainText) { try await $0.write() } |
| 58 | 61 | .exportingCondition { $0.format == .plainText } |
| 62 | FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() } | |
| 63 | .exportingCondition { $0.format == .icalendar } | |
| 59 | 64 | } |
| 60 | 65 | |
| 61 | 66 | private func write() async throws -> SentTransferredFile { |
| @@ -70,6 +75,8 @@ struct OrgExport: Transferable { | ||
| 70 | 75 | .write(to: url, atomically: true, encoding: .utf8) |
| 71 | 76 | case .markdown: |
| 72 | 77 | try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8) |
| 78 | case .icalendar: | |
| 79 | try ICalendarFiles.export(text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(), destination: url) | |
| 73 | 80 | case .pdf, .rtf, .plainText: |
| 74 | 81 | let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle) |
| 75 | 82 | let directory = URL(fileURLWithPath: path).deletingLastPathComponent() |
| @@ -84,7 +91,7 @@ struct OrgExport: Transferable { | ||
| 84 | 91 | } |
| 85 | 92 | } |
| 86 | 93 | |
| 87 | /// Sharing the file as HTML, Markdown, PDF, RTF or plain text: to another app, or saved with | |
| 94 | /// Sharing the file as HTML, Markdown, PDF, RTF, plain text or iCalendar: to another app, or saved with | |
| 88 | 95 | /// Save to Files; or copying it as rich text. |
| 89 | 96 | struct ExportMenu: View { |
| 90 | 97 | let path: String |
Tests/OrgAppTests/AppTests.swift +32
| @@ -1373,3 +1373,35 @@ struct LinkFollowTests { | ||
| 1373 | 1373 | #expect(session.revealRequest?.offset == (text as NSString).range(of: "<<<the plan>>>").location) |
| 1374 | 1374 | } |
| 1375 | 1375 | } |
| 1376 | ||
| 1377 | struct ICalendarFilesTests { | |
| 1378 | @Test func writesBesideEachFileAndCombined() throws { | |
| 1379 | let folder = try Folder() | |
| 1380 | let a = try folder.write("a.org", "#+EXPORT_FILE_NAME: out/cal\n* Meeting <2026-10-12 Mon 10:00>\n") | |
| 1381 | let b = try folder.write("b.org", "* TODO Task\nDEADLINE: <2026-10-20 Tue>\n") | |
| 1382 | var options = ICalendarOptions() | |
| 1383 | options.includeTodo = .unfinished | |
| 1384 | let read = { (path: String) -> (text: String, settings: OrgSettings)? in (try? String(contentsOfFile: path, encoding: .utf8)).map { ($0, OrgSettings.default) } } | |
| 1385 | let written = try ICalendarFiles.exportEach([a.path, b.path], options: options, read: read) | |
| 1386 | #expect(written.map(\.lastPathComponent) == ["cal.ics", "b.ics"]) | |
| 1387 | #expect(written[0].deletingLastPathComponent().lastPathComponent == "out") | |
| 1388 | let first = try String(contentsOf: written[0], encoding: .utf8) | |
| 1389 | #expect(first.hasPrefix("BEGIN:VCALENDAR\r\n") && first.contains("SUMMARY:Meeting <2026-10-12 Mon 10:00>\r\n")) | |
| 1390 | let combined = folder.url.appendingPathComponent("all/org.ics").path | |
| 1391 | let url = try ICalendarFiles.combine([a.path, b.path], to: combined, options: options, read: read) | |
| 1392 | let text = try String(contentsOf: url, encoding: .utf8) | |
| 1393 | #expect(text.contains("X-WR-CALNAME:OrgMode\r\n") && text.contains("BEGIN:VTODO\r\n") && text.contains("DUE;VALUE=DATE:20261020\r\n")) | |
| 1394 | } | |
| 1395 | ||
| 1396 | @Test func readsSettings() { | |
| 1397 | let defaults = UserDefaults(suiteName: "orgstar-ics-\(UUID().uuidString)")! | |
| 1398 | #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .none) | |
| 1399 | #expect(OrgPreferences.icalendarOptions(defaults).useDeadline == ["event-if-not-todo", "todo-due"]) | |
| 1400 | defaults.set("NEXT WAIT", forKey: "icalendarIncludeTodo") | |
| 1401 | defaults.set("event-if-todo", forKey: "icalendarUseScheduled") | |
| 1402 | #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .keywords(["NEXT", "WAIT"])) | |
| 1403 | #expect(OrgPreferences.icalendarOptions(defaults).useScheduled == ["event-if-todo"]) | |
| 1404 | defaults.set("unblocked", forKey: "icalendarIncludeTodo") | |
| 1405 | #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .unblocked) | |
| 1406 | } | |
| 1407 | } | |
Tests/OrgAppTests/EmacsImportTests.swift +17
| @@ -165,6 +165,23 @@ struct EmacsImportTests { | ||
| 165 | 165 | #expect(result.unsupported.contains { $0.name == "C-c l" && $0.reason == "bound to code, not a command" }) |
| 166 | 166 | } |
| 167 | 167 | |
| 168 | @Test func readsICalendarSettings() throws { | |
| 169 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)") | |
| 170 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | |
| 171 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 172 | try #""" | |
| 173 | (setq org-icalendar-use-deadline '(event-if-todo todo-due) | |
| 174 | org-icalendar-use-scheduled '(event-if-not-todo) | |
| 175 | org-icalendar-include-todo '("NEXT" "WAIT") | |
| 176 | org-icalendar-combined-agenda-file (concat "~/cal" "/org.ics")) | |
| 177 | """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8) | |
| 178 | let s = settings(EmacsImport.scan(EmacsImport.files(in: folder))) | |
| 179 | #expect(s["org-icalendar-use-deadline"] == .string("event-if-todo todo-due")) | |
| 180 | #expect(s["org-icalendar-use-scheduled"] == .string("event-if-not-todo")) | |
| 181 | #expect(s["org-icalendar-include-todo"] == .string("NEXT WAIT")) | |
| 182 | #expect(s["org-icalendar-combined-agenda-file"] == .string("~/cal/org.ics")) | |
| 183 | } | |
| 184 | ||
| 168 | 185 | @Test func readsCaptureTargetsFromVariablesAndForms() throws { |
| 169 | 186 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)") |
| 170 | 187 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
Tests/OrgCoreTests/ICalendarTests.swift added +328
| @@ -0,0 +1,328 @@ | ||
| 1 | import Foundation | |
| 2 | import Testing | |
| 3 | @testable import OrgCore | |
| 4 | ||
| 5 | struct ICalendarTests { | |
| 6 | static func lisp(_ s: String) -> String { | |
| 7 | "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" | |
| 8 | } | |
| 9 | ||
| 10 | /// Random UIDs, which differ between runs. | |
| 11 | static func normalized(_ s: String) -> String { | |
| 12 | s.replacing(#/(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/#, with: "UUID") | |
| 13 | } | |
| 14 | ||
| 15 | static let seconds = 1_791_000_000 | |
| 16 | ||
| 17 | static var utc: Calendar { | |
| 18 | var c = Calendar(identifier: .gregorian) | |
| 19 | c.timeZone = TimeZone(identifier: "UTC")! | |
| 20 | return c | |
| 21 | } | |
| 22 | ||
| 23 | /// `org-icalendar-export-to-ics` on each file with `setup`, a `setq` body, in UTC; or with | |
| 24 | /// `combine`, `org-icalendar-combine-agenda-files` over all of them. | |
| 25 | static func emacs(_ files: [String], setup: String, combine: Bool = false) throws -> [String] { | |
| 26 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-ics-\(UUID().uuidString)") | |
| 27 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | |
| 28 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 29 | var paths: [String] = [] | |
| 30 | for (i, file) in files.enumerated() { | |
| 31 | let path = folder.appendingPathComponent("cal\(i).org").path | |
| 32 | try file.write(toFile: path, atomically: true, encoding: .utf8) | |
| 33 | paths.append(path) | |
| 34 | } | |
| 35 | let combined = folder.appendingPathComponent("combined.ics").path | |
| 36 | let body = combine | |
| 37 | ? "(let ((org-agenda-files '(\(paths.map(lisp).joined(separator: " "))))) (org-icalendar-combine-agenda-files))" | |
| 38 | : paths.map { "(with-current-buffer (find-file-noselect \(lisp($0))) (org-icalendar-export-to-ics))" }.joined(separator: "\n") | |
| 39 | let script = folder.appendingPathComponent("ics.el") | |
| 40 | try """ | |
| 41 | ;;; -*- lexical-binding: t -*- | |
| 42 | (require 'org) | |
| 43 | (require 'ox-icalendar) | |
| 44 | (setq org-adapt-indentation nil user-full-name "Ann" org-export-use-babel nil | |
| 45 | org-icalendar-combined-agenda-file \(lisp(combined))) | |
| 46 | (setq \(setup)) | |
| 47 | \(frozenClock(seconds, "(progn " + body + ")")) | |
| 48 | """.write(to: script, atomically: true, encoding: .utf8) | |
| 49 | let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"]) | |
| 50 | let outputs = combine ? [combined] : paths.map { ($0 as NSString).deletingPathExtension + ".ics" } | |
| 51 | return try outputs.map { path in | |
| 52 | guard let data = FileManager.default.contents(atPath: path) else { throw EmacsOracle.EvaluateError(log: log) } | |
| 53 | return String(decoding: data, as: UTF8.self) | |
| 54 | } | |
| 55 | } | |
| 56 | ||
| 57 | static func ours(_ file: String, index: Int, options: ICalendarOptions) -> String { | |
| 58 | var options = options | |
| 59 | options.timezone = "UTC" | |
| 60 | options.userFullName = "Ann" | |
| 61 | return ICalendarExport.calendar(file, name: "cal\(index).org", options: options, now: Date(timeIntervalSince1970: Double(seconds)), calendar: utc) | |
| 62 | } | |
| 63 | ||
| 64 | static let files = [ | |
| 65 | """ | |
| 66 | #+TITLE: My /Cal/ | |
| 67 | #+AUTHOR: Ann | |
| 68 | * TODO Meeting with *Bob* and [[https://x.org][site]] :work: | |
| 69 | SCHEDULED: <2026-10-12 Mon 10:00> | |
| 70 | :PROPERTIES: | |
| 71 | :ID: abc-1 | |
| 72 | :LOCATION: Room 1, floor 2 | |
| 73 | :END: | |
| 74 | Short line with /italic/ and =code= and ~verb~. | |
| 75 | A second line that goes on and on and on and on and on and on and on and on past seventy-two columns for sure. | |
| 76 | ||
| 77 | - item one | |
| 78 | - item two <2026-10-13 Tue> | |
| 79 | continued | |
| 80 | ||
| 81 | #+begin_src sh | |
| 82 | echo hi | |
| 83 | #+end_src | |
| 84 | ||
| 85 | | a | b | | |
| 86 | |---+---| | |
| 87 | | 1 | 2 | | |
| 88 | ** DONE Child :home: | |
| 89 | DEADLINE: <2026-10-20 Tue> | |
| 90 | Text with <2026-10-21 Wed 9:00-10:30> and [2026-10-22 Thu]. | |
| 91 | * Plain heading <2026-10-25 Sun +1w> | |
| 92 | CLOSED: [2026-10-01 Thu 10:00] | |
| 93 | :LOGBOOK: | |
| 94 | CLOCK: [2026-10-01 Thu 09:00]--[2026-10-01 Thu 10:00] => 1:00 | |
| 95 | :END: | |
| 96 | Body. | |
| 97 | """, | |
| 98 | """ | |
| 99 | #+CATEGORY: errands | |
| 100 | #+TODO: TODO NEXT | DONE | |
| 101 | * TODO [#A] Pay rent :home:money: | |
| 102 | DEADLINE: <2026-11-01 Sun -3d +1m> | |
| 103 | :PROPERTIES: | |
| 104 | :ID: rent | |
| 105 | :APPT_WARNTIME: 15 | |
| 106 | :END: | |
| 107 | * NEXT Write report | |
| 108 | SCHEDULED: <2026-10-14 Wed 09:30 +1w> DEADLINE: <2026-12-01 Tue> | |
| 109 | :PROPERTIES: | |
| 110 | :ID: report | |
| 111 | :CATEGORY: work | |
| 112 | :SUMMARY: The quarterly report; draft | |
| 113 | :DESCRIPTION: Numbers, charts \\ and text | |
| 114 | :CLASS: PRIVATE | |
| 115 | :TIMEZONE: Europe/Paris | |
| 116 | :END: | |
| 117 | * TODO Project | |
| 118 | :PROPERTIES: | |
| 119 | :ORDERED: t | |
| 120 | :ID: proj | |
| 121 | :END: | |
| 122 | ** TODO First step | |
| 123 | :PROPERTIES: | |
| 124 | :ID: step1 | |
| 125 | :END: | |
| 126 | ** TODO Second step | |
| 127 | :PROPERTIES: | |
| 128 | :ID: step2 | |
| 129 | :END: | |
| 130 | * Trip <2026-10-30 Fri>--<2026-11-02 Mon> | |
| 131 | :PROPERTIES: | |
| 132 | :ID: trip | |
| 133 | :END: | |
| 134 | Dates --- and ranges... with an entity \\alpha and a footnote[fn:1]. | |
| 135 | Also <2026-10-31 Sat 18:00>--<2026-11-01 Sun 02:30> and an e.g. case that must not break after the period because it is near the edge. | |
| 136 | * Hidden :noexport: | |
| 137 | <2026-10-15 Thu> | |
| 138 | * COMMENT Commented | |
| 139 | <2026-10-16 Fri> | |
| 140 | * Old :ARCHIVE: | |
| 141 | SCHEDULED: <2026-10-17 Sat> | |
| 142 | <2026-10-18 Sun> | |
| 143 | * Deep | |
| 144 | :PROPERTIES: | |
| 145 | :ID: deep | |
| 146 | :END: | |
| 147 | ** Deeper | |
| 148 | :PROPERTIES: | |
| 149 | :ID: deeper | |
| 150 | :END: | |
| 151 | *** Deepest | |
| 152 | :PROPERTIES: | |
| 153 | :ID: deepest | |
| 154 | :END: | |
| 155 | **** Low level <2026-10-19 Mon> | |
| 156 | :PROPERTIES: | |
| 157 | :ID: low | |
| 158 | :END: | |
| 159 | A paragraph under a low level heading, which ox-ascii fills to a narrower width than usual, so this wraps. | |
| 160 | 1. first | |
| 161 | 2. [X] second, done | |
| 162 | - nested | |
| 163 | 3. third | |
| 164 | - term :: definition | |
| 165 | ||
| 166 | #+begin_quote | |
| 167 | A quoted paragraph that is long enough to wrap at the narrower width inside the quote block margins here. | |
| 168 | #+end_quote | |
| 169 | * Footnotes | |
| 170 | [fn:1] The note. | |
| 171 | """, | |
| 172 | """ | |
| 173 | #+ICALENDAR_EXCLUDE_TAGS: private | |
| 174 | #+ICAL-TTL: PT1H | |
| 175 | #+OPTIONS: <:t | |
| 176 | * Event <2026-10-20 Tue 14:00> | |
| 177 | :PROPERTIES: | |
| 178 | :ID: ev | |
| 179 | :END: | |
| 180 | Logged [2026-10-21 Wed] as well. | |
| 181 | * Secret :private: | |
| 182 | <2026-10-22 Thu> | |
| 183 | * Noexport stays :noexport: | |
| 184 | :PROPERTIES: | |
| 185 | :ID: stays | |
| 186 | :END: | |
| 187 | <2026-10-23 Fri> | |
| 188 | """, | |
| 189 | """ | |
| 190 | * Notes <2026-10-24 Sat 08:00> | |
| 191 | :PROPERTIES: | |
| 192 | :ID: notes | |
| 193 | :TIMEZONE: UTC | |
| 194 | :APPT_WARNTIME: 5 | |
| 195 | :END: | |
| 196 | | Item | Cost | | |
| 197 | |--------+------| | |
| 198 | | Apples | 1.5 | | |
| 199 | | Pears | 12 | | |
| 200 | |--------+------| | |
| 201 | | Total | 13.5 | | |
| 202 | ||
| 203 | ----- | |
| 204 | ||
| 205 | #+begin_example | |
| 206 | indented | |
| 207 | example | |
| 208 | #+end_example | |
| 209 | ||
| 210 | : fixed width | |
| 211 | : line | |
| 212 | ||
| 213 | :NOTES: | |
| 214 | In a drawer, see [[*Other][the other]] and [[file:other.org][other]] and https://example.com/x and [[Other]]. | |
| 215 | :END: | |
| 216 | ||
| 217 | - [ ] open box | |
| 218 | - [-] partial | |
| 219 | 1. sub one | |
| 220 | 2. sub two | |
| 221 | ||
| 222 | H_{2}O and x^2 \\ | |
| 223 | on a line of its own. | |
| 224 | ||
| 225 | <2026-10-26 Mon> | |
| 226 | ||
| 227 | #+begin_verse | |
| 228 | Roses are red | |
| 229 | violets blue | |
| 230 | #+end_verse | |
| 231 | * Other | |
| 232 | """, | |
| 233 | ] | |
| 234 | ||
| 235 | static let optionSets: [(lisp: String, ours: ICalendarOptions)] = { | |
| 236 | var sets: [(String, ICalendarOptions)] = [("org-icalendar-timezone \"UTC\"", ICalendarOptions())] | |
| 237 | var todo = ICalendarOptions() | |
| 238 | todo.includeTodo = .unfinished | |
| 239 | todo.useScheduled = ["event-if-todo", "event-if-not-todo", "todo-start"] | |
| 240 | todo.useDeadline = ["event-if-todo-not-done", "todo-due"] | |
| 241 | sets.append(("org-icalendar-include-todo t org-icalendar-use-scheduled '(event-if-todo event-if-not-todo todo-start) org-icalendar-use-deadline '(event-if-todo-not-done todo-due)", todo)) | |
| 242 | var all = ICalendarOptions() | |
| 243 | all.includeTodo = .all | |
| 244 | all.categories = ["todo-state", "all-tags", "category"] | |
| 245 | all.alarmTime = 10 | |
| 246 | all.withTimestamps = "t" | |
| 247 | all.todoUnscheduledStart = "deadline-warning" | |
| 248 | sets.append(("org-icalendar-include-todo 'all org-icalendar-categories '(todo-state all-tags category) org-icalendar-alarm-time 10 org-icalendar-with-timestamps t org-icalendar-todo-unscheduled-start 'deadline-warning", all)) | |
| 249 | var unblocked = ICalendarOptions() | |
| 250 | unblocked.includeTodo = .unblocked | |
| 251 | unblocked.dateTimeFormat = ":%Y%m%dT%H%M%SZ" | |
| 252 | unblocked.includeBody = .characters(20) | |
| 253 | unblocked.scheduledSummaryPrefix = "Sched; " | |
| 254 | sets.append(("org-icalendar-include-todo 'unblocked org-icalendar-date-time-format \":%Y%m%dT%H%M%SZ\" org-icalendar-include-body 20 org-icalendar-scheduled-summary-prefix \"Sched; \"", unblocked)) | |
| 255 | var keywords = ICalendarOptions() | |
| 256 | keywords.includeTodo = .keywords(["NEXT"]) | |
| 257 | keywords.includeBody = .none | |
| 258 | keywords.excludeTags = ["work"] | |
| 259 | keywords.todoUnscheduledStart = "nil" | |
| 260 | sets.append(("org-icalendar-include-todo '(\"NEXT\") org-icalendar-include-body nil org-icalendar-exclude-tags '(\"work\") org-icalendar-todo-unscheduled-start nil", keywords)) | |
| 261 | return sets | |
| 262 | }() | |
| 263 | ||
| 264 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: optionSets.indices) | |
| 265 | func filesMatchEmacs(set: Int) throws { | |
| 266 | let (setup, options) = Self.optionSets[set] | |
| 267 | let emacs = try Self.emacs(Self.files, setup: "org-icalendar-timezone \"UTC\" " + setup) | |
| 268 | for (i, (file, expected)) in zip(Self.files, emacs).enumerated() { | |
| 269 | let mine = Self.normalized(Self.ours(file, index: i, options: options)) | |
| 270 | let theirs = Self.normalized(expected) | |
| 271 | #expect(mine == theirs, "file \(i), options \(set)\n\(Self.diff(mine, theirs))") | |
| 272 | } | |
| 273 | } | |
| 274 | ||
| 275 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 276 | func combinedMatchesEmacs() throws { | |
| 277 | let emacs = try Self.emacs(Self.files, setup: "org-icalendar-timezone \"UTC\" org-icalendar-include-todo t", combine: true) | |
| 278 | var options = ICalendarOptions() | |
| 279 | options.timezone = "UTC" | |
| 280 | options.userFullName = "Ann" | |
| 281 | options.includeTodo = .unfinished | |
| 282 | let mine = ICalendarExport.combined(Self.files.enumerated().map { ("cal\($0.offset).org", $0.element, OrgSettings.default) }, | |
| 283 | options: options, now: Date(timeIntervalSince1970: Double(Self.seconds)), calendar: Self.utc) | |
| 284 | #expect(Self.normalized(mine) == Self.normalized(emacs[0]), "\(Self.diff(Self.normalized(mine), Self.normalized(emacs[0])))") | |
| 285 | } | |
| 286 | ||
| 287 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 288 | func subtreeMatchesEmacs() throws { | |
| 289 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-ics-\(UUID().uuidString)") | |
| 290 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | |
| 291 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 292 | let file = Self.files[1] | |
| 293 | let path = folder.appendingPathComponent("cal1.org").path | |
| 294 | try file.write(toFile: path, atomically: true, encoding: .utf8) | |
| 295 | let offset = (file as NSString).range(of: "* Deep").location | |
| 296 | let script = folder.appendingPathComponent("ics.el") | |
| 297 | try """ | |
| 298 | ;;; -*- lexical-binding: t -*- | |
| 299 | (require 'org) | |
| 300 | (require 'ox-icalendar) | |
| 301 | (setq org-adapt-indentation nil user-full-name "Ann" org-icalendar-timezone "UTC") | |
| 302 | \(frozenClock(Self.seconds, "(with-current-buffer (find-file-noselect \(Self.lisp(path))) (goto-char \(offset + 3)) (org-icalendar-export-to-ics nil t))")) | |
| 303 | """.write(to: script, atomically: true, encoding: .utf8) | |
| 304 | let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"]) | |
| 305 | guard let data = FileManager.default.contents(atPath: folder.appendingPathComponent("cal1.ics").path) else { throw EmacsOracle.EvaluateError(log: log) } | |
| 306 | var options = ICalendarOptions() | |
| 307 | options.timezone = "UTC" | |
| 308 | options.userFullName = "Ann" | |
| 309 | let mine = Self.normalized(ICalendarExport.calendar(file, name: "cal1.org", options: options, subtree: offset + 2, now: Date(timeIntervalSince1970: Double(Self.seconds)), calendar: Self.utc)) | |
| 310 | let theirs = Self.normalized(String(decoding: data, as: UTF8.self)) | |
| 311 | #expect(mine == theirs, "\(Self.diff(mine, theirs))") | |
| 312 | } | |
| 313 | ||
| 314 | @Test func foldsLongLinesAndEscapes() { | |
| 315 | #expect(ICalendarExport.cleanup("a,b;c\\d\n e") == "a\\,b\\;c\\\\d\\n e") | |
| 316 | let line = String(repeating: "x", count: 160) | |
| 317 | #expect(ICalendarExport.fold(line) == String(repeating: "x", count: 75) + "\n " + String(repeating: "x", count: 74) + "\n " + String(repeating: "x", count: 11) + "\n") | |
| 318 | } | |
| 319 | ||
| 320 | /// The first lines that differ. | |
| 321 | static func diff(_ a: String, _ b: String) -> String { | |
| 322 | let x = a.components(separatedBy: "\r\n"), y = b.components(separatedBy: "\r\n") | |
| 323 | for i in 0..<max(x.count, y.count) where (i < x.count ? x[i] : nil) != (i < y.count ? y[i] : nil) { | |
| 324 | return "line \(i)\nours: \((i < x.count ? x[i] : "<none>").debugDescription)\nemacs: \((i < y.count ? y[i] : "<none>").debugDescription)" | |
| 325 | } | |
| 326 | return "same" | |
| 327 | } | |
| 328 | } | |
docs/manual/guide/03-keys.org +3
| @@ -972,6 +972,9 @@ When a key appears in several rows, it runs the command whose condition holds at | ||
| 972 | 972 | | Export to LaTeX with Emacs (=app.export.latex=) | =C-c C-e l l= | — | — | Exports to LaTeX through Emacs (=org-latex-export-to-latex=). | |
| 973 | 973 | | Export to ODT with Emacs (=app.export.odt=) | =C-c C-e o o= | — | — | Exports to ODT through Emacs (=org-odt-export-to-odt=). | |
| 974 | 974 | | Export to Plain Text with Emacs (=app.export.text=) | =C-c C-e t u= | — | — | Exports to plain text through Emacs (=org-ascii-export-to-ascii=). | |
| 975 | | Export to iCalendar (=app.export.icalendar=) | =C-c C-e c f= | — | — | Exports to an =.ics= calendar (=org-icalendar-export-to-ics=). | | |
| 976 | | Export Agenda Files to iCalendar (=app.export.icalendar-agenda=) | =C-c C-e c a= | — | — | Writes an =.ics= beside each agenda file (=org-icalendar-export-agenda-files=). | | |
| 977 | | Combine Agenda Files into iCalendar (=app.export.icalendar-combined=) | =C-c C-e c c= | — | — | Writes the agenda files' entries to one calendar (=org-icalendar-combine-agenda-files=). | | |
| 975 | 978 | |
| 976 | 979 | ** Files, buffers and the app |
| 977 | 980 | |
docs/manual/guide/12-export.org +33 −7
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | #+TITLE: Export |
| 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. | |
| 2 | #+DESCRIPTION: Exporting Org files from orgstar to HTML, Markdown, PDF, Word, RTF, plain text and iCalendar, and to LaTeX, ODT and ASCII through Emacs; copying as rich text. | |
| 3 | #+LEDE: orgstar exports HTML, Markdown, PDF, Word, RTF, plain text and iCalendar itself, and hands LaTeX, ODT, ASCII and LaTeX-made PDF to Emacs on the Mac. | |
| 4 | 4 | |
| 5 | 5 | * Exporting a file |
| 6 | 6 | |
| @@ -21,18 +21,21 @@ Export works on the file in the current editor, using its text as it is now, sav | ||
| 21 | 21 | | LaTeX | Export to LaTeX with Emacs | =C-c C-e l l= | =C-c C-e l l= | yes | |
| 22 | 22 | | ODT | Export to ODT with Emacs | =C-c C-e o o= | =C-c C-e o o= | yes | |
| 23 | 23 | | ASCII text | Export to Plain Text with Emacs | =C-c C-e t u= | =C-c C-e t u= | yes | |
| 24 | | iCalendar | Export to iCalendar | =C-c C-e c f= | =C-c C-e c f= | no | | |
| 25 | | iCalendar, every agenda file | Export Agenda Files to iCalendar | =C-c C-e c a= | =C-c C-e c a= | no | | |
| 26 | | iCalendar, agenda files in one | Combine Agenda Files into iCalendar | =C-c C-e c c= | =C-c C-e c c= | no | | |
| 24 | 27 | |
| 25 | 28 | The 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. |
| 26 | 29 | |
| 27 | All 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/". | |
| 30 | All fourteen 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=, =.txt= or =.ics=. The two agenda-file commands are the exceptions; see [[*iCalendar export][iCalendar export]]. =#+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/". | |
| 28 | 31 | |
| 29 | 32 | ** The export dialog |
| 30 | 33 | |
| 31 | 34 | *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: |
| 32 | 35 | |
| 33 | - *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT (Emacs), LaTeX (Emacs) or Plain text, ASCII (Emacs). | |
| 34 | - *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. | |
| 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. | |
| 36 | - *Format*: HTML, Markdown, PDF, Word, Rich Text (RTF), Plain text, PDF via LaTeX (Emacs), ODT (Emacs), LaTeX (Emacs), Plain text, ASCII (Emacs) or iCalendar. | |
| 37 | - *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. iCalendar is the exception: there the subtree's heading is an entry like any other. 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. | |
| 38 | - *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, ODT and iCalendar. | |
| 36 | 39 | - *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. |
| 37 | 40 | - *Open after export*: opens the file in its default app when the export finishes. |
| 38 | 41 | |
| @@ -40,7 +43,7 @@ The dialog remembers the format and the *Open after export* setting. | ||
| 40 | 43 | |
| 41 | 44 | ** On iOS |
| 42 | 45 | |
| 43 | The 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. | |
| 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. | |
| 44 | 47 | |
| 45 | 48 | * HTML export |
| 46 | 49 | |
| @@ -235,6 +238,29 @@ Markdown export writes GitHub-flavored Markdown: | ||
| 235 | 238 | |
| 236 | 239 | As in HTML export, =#+INCLUDE:= lines are expanded and macros replaced first, and =#+EXCLUDE_TAGS=, =#+SELECT_TAGS=, =COMMENT= headings and =ARCHIVE= tags decide which headings are exported (see /Which headings are exported/). Of the =#+OPTIONS=, Markdown export reads =todo=, =pri=, =tags=, =^= and =title=; the others do not apply. It writes no author or date. |
| 237 | 240 | |
| 241 | * iCalendar export | |
| 242 | ||
| 243 | iCalendar export writes the =.ics= file =org-icalendar-export-to-ics= writes, for calendar apps to read or subscribe to. Each heading can give: | |
| 244 | ||
| 245 | - a =VEVENT= for its =DEADLINE= and one for its =SCHEDULED= date, as =org-icalendar-use-deadline= and =org-icalendar-use-scheduled= say. Their summaries start with =DL: = and =S: =; | |
| 246 | - a =VEVENT= for each other timestamp in its title and text, active ones only unless =#+OPTIONS= has =<:t= or =<:inactive=; | |
| 247 | - a =VTODO= for a task, as =org-icalendar-include-todo= says. Its =DTSTART= is the scheduled date (with =todo-start= in =org-icalendar-use-scheduled=), its =DUE= the deadline (with =todo-due= in =org-icalendar-use-deadline=); without a scheduled date, a deadline with a =+= repeater starts its warning period before it. =STATUS= is =NEEDS-ACTION= or =COMPLETED=, and =PRIORITY= maps =A= to 1, =B= to 5 and =C= to 9. | |
| 248 | ||
| 249 | | Setting | Values | Default | | |
| 250 | |--------------------------------------+-----------------------------------------------------------------------------------------------+--------------------------------| | |
| 251 | | =org-icalendar-use-deadline= | =event-if-not-todo=, =event-if-todo=, =event-if-todo-not-done=, =todo-due=, separated by spaces | ="event-if-not-todo todo-due"= | | |
| 252 | | =org-icalendar-use-scheduled= | the same, with =todo-start= for =todo-due= | ="todo-start"= | | |
| 253 | | =org-icalendar-include-todo= | =nil=, =t= (tasks not done), =all=, =unblocked= (not done, without unfinished children, and not after an unfinished sibling under an =ORDERED= parent), or TODO keywords separated by spaces | ="nil"= | | |
| 254 | | =org-icalendar-combined-agenda-file= | the file Combine Agenda Files into iCalendar writes | ="~/org.ics"= | | |
| 255 | ||
| 256 | The summary is the heading's title, or its =SUMMARY= property. The description is the heading's text as Org's ASCII export writes it, filled to 70 columns, or its =DESCRIPTION= property; =LOCATION=, =CLASS=, =TIMEZONE= and =APPT_WARNTIME= (an alarm, minutes before a timed event) are read too. =CATEGORIES= lists the heading's tags and its category. An =ID= property is the =UID=; a heading without one gets a new random =UID= each time, as in Org with =org-icalendar-store-UID= nil. Repeaters become =RRULE= lines. Times are local times without a zone, as Org writes them by default; a =TIMEZONE= property of =UTC= writes them in UTC, and any other value names the zone (=TZID=). | |
| 257 | ||
| 258 | =#+ICALENDAR_EXCLUDE_TAGS:= lists tags whose subtrees are left out; =#+EXCLUDE_TAGS:= doesn't apply, so =noexport= subtrees are exported unless listed. =#+SELECT_TAGS=, =COMMENT= headings and =ARCHIVE= tags apply as in the other exports. =#+ICAL-TTL:= sets =X-PUBLISHED-TTL=, the refresh period, such as =PT1H=. The calendar is named after the file, its description is =#+TITLE:=, and its owner =#+AUTHOR:= or your full name. Lines longer than 75 characters are folded and lines end in CRLF, as RFC 5545 asks. | |
| 259 | ||
| 260 | Export Agenda Files to iCalendar writes an =.ics= beside each agenda file (see [[file:07-agenda.org][The agenda]]). Combine Agenda Files into iCalendar writes all their entries to one calendar named =OrgMode= at =org-icalendar-combined-agenda-file=. On iOS, the Export menu's iCalendar shares the current file's calendar. | |
| 261 | ||
| 262 | Differences from Org: diary sexps (=%%(…)= lines and =<%%(…)>= timestamps) are left out, as they need Emacs's =icalendar.el=. The other =org-icalendar-*= variables keep Org's defaults: alarms only from =APPT_WARNTIME=, categories =(local-tags category)=, the whole body as the description, and local times. Descriptions of tables with column groups or alignment cookies, center blocks and links to targets can differ from Org's in layout. | |
| 263 | ||
| 238 | 264 | * Exporting through Emacs |
| 239 | 265 | |
| 240 | 266 | On the Mac, PDF, LaTeX, ODT and plain text exports are done by Emacs, with the =ox= functions Emacs's dispatcher uses: |
docs/manual/guide/13-configuration.org +8
| @@ -173,6 +173,7 @@ These settings have no control in the Settings window. Some are in the View menu | ||
| 173 | 173 | | =[org-agenda-time-grid]=, =org-agenda-use-time-grid=, =org-agenda-show-current-time-in-grid= | | |
| 174 | 174 | | =[org-stuck-projects]= | | |
| 175 | 175 | | =org-agenda-files= | | |
| 176 | | =org-icalendar-use-deadline=, =org-icalendar-use-scheduled=, =org-icalendar-include-todo=, =org-icalendar-combined-agenda-file= | | | |
| 176 | 177 | | =org-refile-targets=, =org-refile-use-outline-path=, =org-refile-allow-creating-parent-nodes= | | |
| 177 | 178 | | =theme-file= | | |
| 178 | 179 | |
| @@ -235,6 +236,10 @@ A key you remove from the file goes back to its default. A key that isn't in the | ||
| 235 | 236 | | =org-refile-use-outline-path= | string | ="file"= | How refile targets are written: =nil=, =t=, =file=, =full-file-path=, =buffer-name= or =title=. Mirrors =org-refile-use-outline-path=. | |
| 236 | 237 | | =org-refile-allow-creating-parent-nodes= | string | ="nil"= | =t= or =confirm=: a refile target typed as =TARGET/New heading= adds the heading; =confirm= asks first. Mirrors =org-refile-allow-creating-parent-nodes=. | |
| 237 | 238 | | =org-agenda-files= | string | =""= | Files and folders the agenda reads, separated by =\n=; a file that isn't =.org= lists more, one per line. =""= reads the folders' files. See [[file:07-agenda.org][The agenda]]. Mirrors =org-agenda-files=. | |
| 239 | | =org-icalendar-use-deadline= | string | ="event-if-not-todo todo-due"= | What a =DEADLINE= makes in iCalendar export: =event-if-not-todo=, =event-if-todo=, =event-if-todo-not-done=, =todo-due=. See [[file:12-export.org][Export]]. Mirrors =org-icalendar-use-deadline=. | | |
| 240 | | =org-icalendar-use-scheduled= | string | ="todo-start"= | As the last, for =SCHEDULED=, with =todo-start=. Mirrors =org-icalendar-use-scheduled=. | | |
| 241 | | =org-icalendar-include-todo= | string | ="nil"= | Tasks as =VTODO=: =nil=, =t= (not done), =all=, =unblocked=, or TODO keywords separated by spaces. Mirrors =org-icalendar-include-todo=. | | |
| 242 | | =org-icalendar-combined-agenda-file= | string | ="~/org.ics"= | Where Combine Agenda Files into iCalendar writes. Mirrors =org-icalendar-combined-agenda-file=. | | |
| 238 | 243 | | =org-agenda-use-time-grid= | boolean | =true= | Grid lines at the times in =[org-agenda-time-grid]=, on the days it names. Mirrors =org-agenda-use-time-grid=. | |
| 239 | 244 | | =org-agenda-show-current-time-in-grid= | boolean | =true= | The now line on today's grid. Mirrors =org-agenda-show-current-time-in-grid=. | |
| 240 | 245 | | =org-agenda-sort-notime-is-late= | boolean | =true= | Lines without a time sort after timed ones for =time-up=, and lines without a date after dated ones for the date keys. Mirrors =org-agenda-sort-notime-is-late=. | |
| @@ -528,6 +533,9 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, = | ||
| 528 | 533 | | =org-refile-use-outline-path=, =org-refile-allow-creating-parent-nodes= | The symbol as a string | |
| 529 | 534 | | =org-stuck-projects= | =[org-stuck-projects]=: =match=, =todo=, =tags= and =regexp= from the four elements | |
| 530 | 535 | | =org-agenda-time-grid= | =[org-agenda-time-grid]=: =when= from the first element, =times= from the second; the strings are left out | |
| 536 | | =org-icalendar-use-deadline=, =org-icalendar-use-scheduled= | The list's symbols, separated by spaces | | |
| 537 | | =org-icalendar-include-todo= | =nil=, =t=, =all= or =unblocked=, or a list of keywords separated by spaces | | |
| 538 | | =org-icalendar-combined-agenda-file= | The file name, from a string or a simple form | | |
| 531 | 539 | | =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= | |
| 532 | 540 | | =org-log-into-drawer= | A string as given; =t= becomes ="LOGBOOK"=; =nil= becomes =""= | |
| 533 | 541 | | =display-line-numbers-type= | =true= unless =nil=; =relative= and =visual= become absolute numbers | |