Commit f309469ac6
Verified · cmc
Layout: unified · split
Sources/OrgApp/ConfigSync.swift +2 −1
| @@ -125,7 +125,8 @@ public final class ConfigSync { | ||
| 125 | 125 | |
| 126 | 126 | /// Writes settings that differ from the file into it. |
| 127 | 127 | func writeBack() { |
| 128 | guard !applying, var current = text ?? (try? String(contentsOf: url, encoding: .utf8)) else { return } | |
| 128 | // The file as it is now, so that tables written into it since, as by Emacs import, stay. | |
| 129 | guard !applying, var current = (try? String(contentsOf: url, encoding: .utf8)) ?? text else { return } | |
| 129 | 130 | let values = UserConfig.values(in: current) |
| 130 | 131 | let original = current |
| 131 | 132 | for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil { |
Sources/OrgApp/EmacsImport.swift +62 −2
| @@ -19,6 +19,8 @@ public struct EmacsImport: Sendable { | ||
| 19 | 19 | case structureTemplate(key: String, type: String) |
| 20 | 20 | /// A `[[view]]` table, with its blocks, for views.toml. |
| 21 | 21 | case view(name: String, toml: String) |
| 22 | /// A `[[publish]]` table for config.toml. | |
| 23 | case publish(name: String, toml: String) | |
| 22 | 24 | } |
| 23 | 25 | |
| 24 | 26 | public struct Item: Sendable, Identifiable { |
| @@ -663,6 +665,8 @@ public struct EmacsImport: Sendable { | ||
| 663 | 665 | for entry in value.elements ?? [] { captureTemplate(entry, source: source, env: env, id: id) } |
| 664 | 666 | case "org-agenda-custom-commands": |
| 665 | 667 | for entry in value.elements ?? [] { agendaCommand(entry, source: source, id: id) } |
| 668 | case "org-publish-project-alist": | |
| 669 | for entry in value.elements ?? [] { publishProject(entry, source: source, env: env, id: id) } | |
| 666 | 670 | case "doom-font": |
| 667 | 671 | note("not a font-spec orgstar can read") |
| 668 | 672 | case "doom-variable-pitch-font": |
| @@ -815,6 +819,49 @@ public struct EmacsImport: Sendable { | ||
| 815 | 819 | items.append(Item(id: id(), name: "org-agenda-custom-commands \"\(key)\"", summary: "views.toml view \(name)", source: source, change: .view(name: name, toml: toml))) |
| 816 | 820 | } |
| 817 | 821 | |
| 822 | /// An `org-publish-project-alist` entry as a `[[publish]]` table, when its publishing | |
| 823 | /// functions are ones orgstar has. | |
| 824 | mutating func publishProject(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) { | |
| 825 | guard let parts = entry.elements, let name = parts.first?.string else { return } | |
| 826 | func note(_ reason: String) { unsupported.append(Note(id: id(), name: "publishing project \"\(name)\"", reason: reason, source: source)) } | |
| 827 | func quoted(_ s: String) -> String { UserConfig.format(.string(s)) } | |
| 828 | var toml = "[[publish]]\nname = \(quoted(name))\n" | |
| 829 | var left: [String] = [] | |
| 830 | let rest = Array(parts.dropFirst()) | |
| 831 | for i in stride(from: 0, to: rest.count - 1, by: 2) { | |
| 832 | guard let key = rest[i].symbol else { continue } | |
| 833 | let value = rest[i + 1] | |
| 834 | let truthy = value.symbol != "nil" && value.elements?.isEmpty != true | |
| 835 | let strings = value.elements?.compactMap { $0.string ?? Self.evaluate($0, env)?.string } | |
| 836 | let symbols = value.symbol.map { [$0] } ?? value.elements?.compactMap(\.symbol) | |
| 837 | switch key { | |
| 838 | case ":base-directory", ":publishing-directory", ":exclude", ":sitemap-filename", ":sitemap-title": | |
| 839 | guard let s = value.string ?? Self.evaluate(value, env)?.string else { return note("\(key) isn't a string") } | |
| 840 | toml += "\(key.dropFirst()) = \(quoted(s))\n" | |
| 841 | case ":base-extension": | |
| 842 | guard let s = value.string ?? value.symbol else { return note(":base-extension isn't a string") } | |
| 843 | toml += "base-extension = \(quoted(s))\n" | |
| 844 | case ":recursive", ":auto-sitemap", ":sitemap-ignore-case", ":body-only": | |
| 845 | toml += "\(key.dropFirst()) = \(truthy)\n" | |
| 846 | case ":include", ":components": | |
| 847 | guard let strings, strings.count == value.elements?.count else { return note("\(key) isn't a list of names") } | |
| 848 | toml += "\(key.dropFirst()) = \(quoted(strings.joined(separator: " ")))\n" | |
| 849 | case ":publishing-function": | |
| 850 | guard let symbols, !symbols.isEmpty, symbols.allSatisfy(PublishProject.functions.contains) else { | |
| 851 | return note("publishing function \(value.description) isn't one orgstar has") | |
| 852 | } | |
| 853 | toml += "publishing-function = \(quoted(symbols.joined(separator: " ")))\n" | |
| 854 | case ":sitemap-style", ":sitemap-sort-files", ":sitemap-sort-folders": | |
| 855 | guard let s = value.symbol else { return note("\(key) isn't a symbol") } | |
| 856 | toml += "\(key.dropFirst()) = \(quoted(s))\n" | |
| 857 | default: | |
| 858 | left.append(key) | |
| 859 | } | |
| 860 | } | |
| 861 | if !left.isEmpty { note("\(left.joined(separator: ", ")) left out") } | |
| 862 | items.append(Item(id: id(), name: "publishing project \"\(name)\"", summary: "config.toml [[publish]] \(name)", source: source, change: .publish(name: name, toml: toml))) | |
| 863 | } | |
| 864 | ||
| 818 | 865 | mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) { |
| 819 | 866 | guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return } |
| 820 | 867 | let name = parts[1].string ?? key |
| @@ -940,7 +987,7 @@ extension EmacsImport { | ||
| 940 | 987 | public static func apply( |
| 941 | 988 | _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory |
| 942 | 989 | ) async -> String { |
| 943 | var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0, views = 0 | |
| 990 | var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0, views = 0, projects = 0 | |
| 944 | 991 | var problems: [String] = [] |
| 945 | 992 | for item in items { |
| 946 | 993 | guard case .setting(let key, let value) = item.change, |
| @@ -989,6 +1036,19 @@ extension EmacsImport { | ||
| 989 | 1036 | viewsText += (viewsText.isEmpty ? "# Agenda views. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedViews |
| 990 | 1037 | try? viewsText.write(to: viewsFile, atomically: true, encoding: .utf8) |
| 991 | 1038 | } |
| 1039 | let configFile = directory.appendingPathComponent("config.toml") | |
| 1040 | var config = (try? String(contentsOf: configFile, encoding: .utf8)) ?? "" | |
| 1041 | var projectNames = Set((try? TOML.parse(config))?.filter { $0.name == "publish" }.compactMap { $0.values["name"]?.string } ?? []) | |
| 1042 | var addedProjects = "" | |
| 1043 | for item in items { | |
| 1044 | guard case .publish(let name, let toml) = item.change, projectNames.insert(name).inserted else { continue } | |
| 1045 | addedProjects += "\n" + toml | |
| 1046 | projects += 1 | |
| 1047 | } | |
| 1048 | if !addedProjects.isEmpty { | |
| 1049 | config += (config.isEmpty || config.hasSuffix("\n") ? "" : "\n") + "\n# Publishing projects. Imported from Emacs.\n" + addedProjects | |
| 1050 | try? config.write(to: configFile, atomically: true, encoding: .utf8) | |
| 1051 | } | |
| 992 | 1052 | let keymapFile = directory.appendingPathComponent("keymap.toml") |
| 993 | 1053 | var keymap = (try? String(contentsOf: keymapFile, encoding: .utf8)) ?? "" |
| 994 | 1054 | func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") } |
| @@ -1017,7 +1077,7 @@ extension EmacsImport { | ||
| 1017 | 1077 | if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) } |
| 1018 | 1078 | func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" } |
| 1019 | 1079 | let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"), |
| 1020 | count(blocks, "structure template"), count(views, "agenda view")].compactMap { $0 } | |
| 1080 | count(blocks, "structure template"), count(views, "agenda view"), count(projects, "publishing project")].compactMap { $0 } | |
| 1021 | 1081 | var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "." |
| 1022 | 1082 | if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." } |
| 1023 | 1083 | return summary |
Sources/OrgApp/Publish.swift added +312
| @@ -0,0 +1,312 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | ||
| 4 | /// A publishing project from config.toml (`org-publish-project-alist`, ox-publish.el, Org 9.8.7): | |
| 5 | /// | |
| 6 | /// ```toml | |
| 7 | /// [[publish]] | |
| 8 | /// name = "site" | |
| 9 | /// base-directory = "~/notes" | |
| 10 | /// publishing-directory = "~/public_html" | |
| 11 | /// recursive = true | |
| 12 | /// auto-sitemap = true | |
| 13 | /// ``` | |
| 14 | /// | |
| 15 | /// Other keys: `base-extension` (an Emacs regexp, or `any`), `exclude` (a regexp on the path | |
| 16 | /// under the base directory), `include` (file names separated by spaces), `publishing-function` | |
| 17 | /// (`org-html-publish-to-html`, `org-md-publish-to-md`, `org-publish-attachment`, separated by | |
| 18 | /// spaces), `sitemap-filename`, `sitemap-title`, `sitemap-style` (`tree` or `list`), | |
| 19 | /// `sitemap-sort-files` (`alphabetically`, `chronologically`, `anti-chronologically`, `nil`), | |
| 20 | /// `sitemap-sort-folders` (`ignore`, `first`, `last`, `nil`), `sitemap-ignore-case`, | |
| 21 | /// `body-only`, and `components` (project names separated by spaces) for a project of projects. | |
| 22 | public struct PublishProject: Sendable, Equatable { | |
| 23 | public var name: String | |
| 24 | public var baseDirectory = "" | |
| 25 | public var publishingDirectory = "" | |
| 26 | public var baseExtension = "org" | |
| 27 | public var recursive = false | |
| 28 | public var exclude: String? | |
| 29 | public var include: [String] = [] | |
| 30 | public var publishingFunctions = ["org-html-publish-to-html"] | |
| 31 | public var autoSitemap = false | |
| 32 | public var sitemapFilename = "sitemap.org" | |
| 33 | public var sitemapTitle: String? | |
| 34 | public var sitemapStyle = "tree" | |
| 35 | public var sitemapSortFiles = "alphabetically" | |
| 36 | public var sitemapSortFolders = "ignore" | |
| 37 | public var sitemapIgnoreCase = false | |
| 38 | public var bodyOnly = false | |
| 39 | public var components: [String] = [] | |
| 40 | ||
| 41 | public init(name: String) { self.name = name } | |
| 42 | ||
| 43 | public static let functions = ["org-html-publish-to-html", "org-md-publish-to-md", "org-publish-attachment"] | |
| 44 | } | |
| 45 | ||
| 46 | public enum Publish { | |
| 47 | /// The `[[publish]]` tables of a config.toml, directories resolved against `root`. | |
| 48 | public static func projects(fromConfig text: String, root: String?) -> (projects: [PublishProject], problems: [String]) { | |
| 49 | guard let tables = try? TOML.parse(text) else { return ([], []) } | |
| 50 | var projects: [PublishProject] = [] | |
| 51 | var problems: [String] = [] | |
| 52 | for table in tables where table.name == "publish" { | |
| 53 | let v = table.values | |
| 54 | guard let name = v["name"]?.string, !name.isEmpty else { | |
| 55 | problems.append("config.toml line \(table.line): a [[publish]] project needs a name") | |
| 56 | continue | |
| 57 | } | |
| 58 | var p = PublishProject(name: name) | |
| 59 | func words(_ key: String) -> [String]? { v[key]?.string.map { $0.split(whereSeparator: \.isWhitespace).map(String.init) } } | |
| 60 | p.components = words("components") ?? [] | |
| 61 | if p.components.isEmpty { | |
| 62 | guard let base = v["base-directory"]?.string, let out = v["publishing-directory"]?.string else { | |
| 63 | problems.append("config.toml line \(table.line): project \(name) needs base-directory and publishing-directory") | |
| 64 | continue | |
| 65 | } | |
| 66 | p.baseDirectory = resolve(base, root: root) | |
| 67 | p.publishingDirectory = resolve(out, root: root) | |
| 68 | } | |
| 69 | if let ext = v["base-extension"]?.string { p.baseExtension = ext } | |
| 70 | p.recursive = v["recursive"]?.bool ?? false | |
| 71 | p.exclude = v["exclude"]?.string | |
| 72 | p.include = words("include") ?? [] | |
| 73 | if let functions = words("publishing-function") { | |
| 74 | let unknown = functions.filter { !PublishProject.functions.contains($0) } | |
| 75 | if !unknown.isEmpty { problems.append("config.toml line \(table.line): unknown publishing-function \(unknown.joined(separator: " "))") } | |
| 76 | p.publishingFunctions = functions.filter(PublishProject.functions.contains) | |
| 77 | } | |
| 78 | p.autoSitemap = v["auto-sitemap"]?.bool ?? false | |
| 79 | if let s = v["sitemap-filename"]?.string { p.sitemapFilename = s } | |
| 80 | p.sitemapTitle = v["sitemap-title"]?.string | |
| 81 | if let s = v["sitemap-style"]?.string { p.sitemapStyle = s } | |
| 82 | if let s = v["sitemap-sort-files"]?.string { p.sitemapSortFiles = s } | |
| 83 | if let s = v["sitemap-sort-folders"]?.string { p.sitemapSortFolders = s } | |
| 84 | p.sitemapIgnoreCase = v["sitemap-ignore-case"]?.bool ?? false | |
| 85 | p.bodyOnly = v["body-only"]?.bool ?? false | |
| 86 | projects.append(p) | |
| 87 | } | |
| 88 | return (projects, problems) | |
| 89 | } | |
| 90 | ||
| 91 | /// Absolute, `~/…`, or relative to `root`. | |
| 92 | static func resolve(_ path: String, root: String?) -> String { | |
| 93 | if path.hasPrefix("/") { return path } | |
| 94 | if path.hasPrefix("~") { return (path as NSString).expandingTildeInPath } | |
| 95 | return ((root ?? NSHomeDirectory()) as NSString).appendingPathComponent(path) | |
| 96 | } | |
| 97 | ||
| 98 | public struct Failure: Error, Equatable, CustomStringConvertible { | |
| 99 | public let description: String | |
| 100 | } | |
| 101 | ||
| 102 | /// `org-publish-expand-projects`: components in place of projects of projects. | |
| 103 | public static func expand(_ chosen: [PublishProject], all: [PublishProject]) throws -> [PublishProject] { | |
| 104 | var rest = chosen | |
| 105 | var out: [PublishProject] = [] | |
| 106 | while !rest.isEmpty { | |
| 107 | let p = rest.removeFirst() | |
| 108 | if p.components.isEmpty { | |
| 109 | if !out.contains(where: { $0.name == p.name }) { out.append(p) } | |
| 110 | continue | |
| 111 | } | |
| 112 | rest = try p.components.map { name in | |
| 113 | guard let c = all.first(where: { $0.name == name }) else { throw Failure(description: "Unknown component \"\(name)\" in project \"\(p.name)\"") } | |
| 114 | return c | |
| 115 | } + rest | |
| 116 | } | |
| 117 | return out | |
| 118 | } | |
| 119 | ||
| 120 | static func directory(_ path: String) -> String { path.hasSuffix("/") ? path : path + "/" } | |
| 121 | ||
| 122 | /// `org-publish-get-base-files`: the project's files, its sitemap and `include`. | |
| 123 | public static func baseFiles(_ p: PublishProject) -> [String] { | |
| 124 | let base = directory(p.baseDirectory) | |
| 125 | let pattern = p.baseExtension == "any" ? "" : "^[^.].*\\.(?:" + EmacsRegex.translate(p.baseExtension) + ")$" | |
| 126 | let regex = try? NSRegularExpression(pattern: pattern) | |
| 127 | func matches(_ name: String) -> Bool { | |
| 128 | regex?.firstMatch(in: name, range: NSRange(location: 0, length: (name as NSString).length)) != nil | |
| 129 | } | |
| 130 | var files: [String] = [] | |
| 131 | let fm = FileManager.default | |
| 132 | func walk(_ dir: String, depth: Int) { | |
| 133 | guard depth <= 100, let names = try? fm.contentsOfDirectory(atPath: dir) else { return } | |
| 134 | for name in names.sorted() { | |
| 135 | let path = dir + name | |
| 136 | var isDirectory: ObjCBool = false | |
| 137 | guard fm.fileExists(atPath: path, isDirectory: &isDirectory) else { continue } | |
| 138 | if isDirectory.boolValue { | |
| 139 | if p.recursive { walk(path + "/", depth: depth + 1) } | |
| 140 | } else if matches(name) { | |
| 141 | files.append(path) | |
| 142 | } | |
| 143 | } | |
| 144 | } | |
| 145 | walk(base, depth: 0) | |
| 146 | if let exclude = p.exclude, let regex = try? NSRegularExpression(pattern: EmacsRegex.translate(exclude)) { | |
| 147 | files.removeAll { file in | |
| 148 | let relative = String(file.dropFirst(base.count)) | |
| 149 | return regex.firstMatch(in: relative, range: NSRange(location: 0, length: (relative as NSString).length)) != nil | |
| 150 | } | |
| 151 | } | |
| 152 | if p.autoSitemap { files.append(base + p.sitemapFilename) } | |
| 153 | files += p.include.map { $0.hasPrefix("/") ? $0 : base + $0 } | |
| 154 | var seen: Set<String> = [] | |
| 155 | return files.filter { seen.insert($0).inserted } | |
| 156 | } | |
| 157 | ||
| 158 | // MARK: - Sitemap | |
| 159 | ||
| 160 | /// `org-publish-find-title`: `#+TITLE`, or the file's base name. | |
| 161 | static func title(_ path: String, read: (String) -> String?) -> String { | |
| 162 | let titles = (read(path) ?? "").matches(of: #/(?mi)^[ \t]*#\+TITLE:[ \t]*(.*?)[ \t]*$/#).map { String($0.1) } | |
| 163 | return titles.isEmpty ? ((path as NSString).lastPathComponent as NSString).deletingPathExtension : titles.joined(separator: " ") | |
| 164 | } | |
| 165 | ||
| 166 | /// `org-publish-find-date`: a timestamp in `#+DATE`, or the modification time. | |
| 167 | static func date(_ path: String, read: (String) -> String?) -> Date { | |
| 168 | if !path.hasSuffix("/"), let text = read(path), | |
| 169 | let line = text.firstMatch(of: #/(?mi)^[ \t]*#\+DATE:[ \t]*(.*?)[ \t]*$/#), | |
| 170 | let m = String(line.1).firstMatch(of: /[<\[][0-9]{4}-[0-9]{2}-[0-9]{2}[^>\]]*[>\]]/), let stamp = Timestamp.parse(m.0) { | |
| 171 | let p = stamp.start | |
| 172 | return Calendar.current.date(from: DateComponents(year: p.year, month: p.month, day: p.day, hour: p.hour ?? 0, minute: p.minute ?? 0)) ?? Date() | |
| 173 | } | |
| 174 | return (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate] as? Date) ?? Date() | |
| 175 | } | |
| 176 | ||
| 177 | /// `org-publish-sitemap` with the default entry format and builder: the sitemap's text. | |
| 178 | public static func sitemap(_ p: PublishProject, read: (String) -> String?) -> String { | |
| 179 | let root = directory(p.baseDirectory) | |
| 180 | let sitemapPath = root + p.sitemapFilename | |
| 181 | var files = baseFiles(p).filter { $0 != sitemapPath } | |
| 182 | if !(p.sitemapStyle == "list" && p.sitemapSortFolders == "ignore") { | |
| 183 | var seen: Set<String> = [] | |
| 184 | let dirs = files.map { ($0 as NSString).deletingLastPathComponent + "/" }.filter { $0 != root && seen.insert($0).inserted } | |
| 185 | files = dirs + files | |
| 186 | } | |
| 187 | if p.sitemapSortFiles != "nil" || p.sitemapSortFolders != "ignore" { | |
| 188 | files = stableSorted(files) { a, b in before(a, b, p, read: read) } | |
| 189 | } | |
| 190 | func entry(_ path: String) -> String { | |
| 191 | let relative = String(path.dropFirst(root.count)) | |
| 192 | if !path.hasSuffix("/") { return "[[file:\(relative)][\(title(path, read: read))]]" } | |
| 193 | return p.sitemapStyle == "tree" ? (String(relative.dropLast()) as NSString).lastPathComponent : relative | |
| 194 | } | |
| 195 | var lines: [String] = [] | |
| 196 | if p.sitemapStyle == "list" { | |
| 197 | lines = files.map { "- " + entry($0) } | |
| 198 | } else { | |
| 199 | let filesOnly = files.filter { !$0.hasSuffix("/") } | |
| 200 | let dirs = files.filter { $0.hasSuffix("/") } | |
| 201 | func subtree(_ dir: String, _ indent: String) { | |
| 202 | for f in filesOnly where (f as NSString).deletingLastPathComponent + "/" == dir { lines.append(indent + "- " + entry(f)) } | |
| 203 | for sub in dirs where (String(sub.dropLast()) as NSString).deletingLastPathComponent + "/" == dir { | |
| 204 | lines.append(indent + "- " + entry(sub)) | |
| 205 | subtree(sub, indent + " ") | |
| 206 | } | |
| 207 | } | |
| 208 | subtree(root, "") | |
| 209 | } | |
| 210 | return "#+TITLE: " + (p.sitemapTitle ?? "Sitemap for project " + p.name) + "\n\n" + lines.joined(separator: "\n") | |
| 211 | } | |
| 212 | ||
| 213 | /// The sort predicate of `org-publish-sitemap`: whether `a` goes before `b`. | |
| 214 | static func before(_ a: String, _ b: String, _ p: PublishProject, read: (String) -> String?) -> Bool { | |
| 215 | var result: Bool? | |
| 216 | switch p.sitemapSortFiles { | |
| 217 | case "alphabetically": | |
| 218 | func key(_ path: String) -> String { | |
| 219 | guard path.hasSuffix(".org") else { return path } | |
| 220 | return (path as NSString).deletingLastPathComponent + "/" + title(path, read: read) | |
| 221 | } | |
| 222 | var (x, y) = (key(a), key(b)) | |
| 223 | if p.sitemapIgnoreCase { (x, y) = (x.lowercased(), y.lowercased()) } | |
| 224 | result = Array(x.unicodeScalars).lexicographicallyPrecedes(Array(y.unicodeScalars)) | |
| 225 | case "chronologically", "anti-chronologically": | |
| 226 | let (x, y) = (date(a, read: read), date(b, read: read)) | |
| 227 | result = p.sitemapSortFiles == "chronologically" ? x < y : y < x | |
| 228 | default: | |
| 229 | result = nil | |
| 230 | } | |
| 231 | if p.sitemapSortFolders == "first" || p.sitemapSortFolders == "last" { | |
| 232 | let (da, db) = (a.hasSuffix("/"), b.hasSuffix("/")) | |
| 233 | if da != db { return da == (p.sitemapSortFolders == "first") } | |
| 234 | } | |
| 235 | return result ?? false | |
| 236 | } | |
| 237 | ||
| 238 | static func stableSorted<T>(_ items: [T], by before: (T, T) -> Bool) -> [T] { | |
| 239 | items.enumerated().sorted { x, y in | |
| 240 | if before(x.element, y.element) { return true } | |
| 241 | if before(y.element, x.element) { return false } | |
| 242 | return x.offset < y.offset | |
| 243 | }.map(\.element) | |
| 244 | } | |
| 245 | ||
| 246 | // MARK: - Publishing | |
| 247 | ||
| 248 | public struct Report: Equatable { | |
| 249 | public var published: [String] = [] | |
| 250 | public var skipped: [String] = [] | |
| 251 | } | |
| 252 | ||
| 253 | /// `org-publish-projects`: each project's sitemap, when it has one, then its files, through | |
| 254 | /// its publishing functions. A file whose output is newer than it is skipped unless `force`. | |
| 255 | /// `export` turns an Org file's text into the HTML or Markdown to write. | |
| 256 | public static func publish( | |
| 257 | _ chosen: [PublishProject], all: [PublishProject], force: Bool = false, only: String? = nil, | |
| 258 | read: (String) -> String?, export: (_ function: String, _ text: String, _ path: String, _ bodyOnly: Bool) -> String | |
| 259 | ) throws -> Report { | |
| 260 | var report = Report() | |
| 261 | let fm = FileManager.default | |
| 262 | for p in try expand(chosen, all: all) { | |
| 263 | let base = directory(p.baseDirectory) | |
| 264 | if p.autoSitemap, only == nil { | |
| 265 | let text = sitemap(p, read: read) | |
| 266 | let path = base + p.sitemapFilename | |
| 267 | if (try? String(contentsOfFile: path, encoding: .utf8)) != text { try text.write(toFile: path, atomically: true, encoding: .utf8) } | |
| 268 | } | |
| 269 | for file in baseFiles(p) where only == nil || only == file { | |
| 270 | let relative = String(file.dropFirst(base.count)) | |
| 271 | let outputDirectory = directory(p.publishingDirectory) + ((relative as NSString).deletingLastPathComponent.isEmpty ? "" : (relative as NSString).deletingLastPathComponent + "/") | |
| 272 | for function in p.publishingFunctions { | |
| 273 | let output: String | |
| 274 | if function == "org-publish-attachment" { | |
| 275 | output = outputDirectory + (file as NSString).lastPathComponent | |
| 276 | if directory((file as NSString).deletingLastPathComponent) == outputDirectory { continue } | |
| 277 | } else { | |
| 278 | let ext = function == "org-md-publish-to-md" ? "md" : "html" | |
| 279 | guard let text = read(file) else { throw Failure(description: "Can't read \(file)") } | |
| 280 | output = ExportScope.output(for: URL(fileURLWithPath: outputDirectory + (file as NSString).lastPathComponent), | |
| 281 | name: ExportScope.fileName(text), extension: ext).path | |
| 282 | } | |
| 283 | if !force, upToDate(output, source: file) { | |
| 284 | report.skipped.append(file) | |
| 285 | continue | |
| 286 | } | |
| 287 | try fm.createDirectory(atPath: (output as NSString).deletingLastPathComponent, withIntermediateDirectories: true) | |
| 288 | if function == "org-publish-attachment" { | |
| 289 | if fm.fileExists(atPath: output) { try fm.removeItem(atPath: output) } | |
| 290 | try fm.copyItem(atPath: file, toPath: output) | |
| 291 | } else { | |
| 292 | try export(function, read(file) ?? "", file, p.bodyOnly).write(toFile: output, atomically: true, encoding: .utf8) | |
| 293 | } | |
| 294 | report.published.append(file) | |
| 295 | } | |
| 296 | } | |
| 297 | } | |
| 298 | return report | |
| 299 | } | |
| 300 | ||
| 301 | static func upToDate(_ output: String, source: String) -> Bool { | |
| 302 | let fm = FileManager.default | |
| 303 | guard let out = try? fm.attributesOfItem(atPath: output)[.modificationDate] as? Date, | |
| 304 | let src = try? fm.attributesOfItem(atPath: source)[.modificationDate] as? Date else { return false } | |
| 305 | return out >= src | |
| 306 | } | |
| 307 | ||
| 308 | /// The projects publishing `path`, not counting projects of projects. | |
| 309 | public static func projects(containing path: String, in all: [PublishProject]) -> [PublishProject] { | |
| 310 | all.filter { $0.components.isEmpty && baseFiles($0).contains(path) } | |
| 311 | } | |
| 312 | } | |
Sources/OrgApp/UserConfig.swift +5 −3
| @@ -370,8 +370,9 @@ public enum UserConfig { | ||
| 370 | 370 | if defaults.stringArray(forKey: structureTemplatesKey) != rows { defaults.set(rows, forKey: structureTemplatesKey) } |
| 371 | 371 | continue |
| 372 | 372 | } |
| 373 | // Colors are the theme's to read. | |
| 373 | // Colors are the theme's to read; publishing projects are `Publish`'s. | |
| 374 | 374 | if ThemeSpec.isThemeTable(table.name), table.name != "theme" { continue } |
| 375 | if table.name == "publish", table.isArrayElement { continue } | |
| 375 | 376 | for (key, value) in table.values.sorted(by: { $0.key < $1.key }) { |
| 376 | 377 | if table.name == "theme", !ThemeSpec.typeKeys.contains(key) { continue } |
| 377 | 378 | let name = path(table.name, key) |
| @@ -538,8 +539,9 @@ public enum UserConfig { | ||
| 538 | 539 | var lastInSection: Int? |
| 539 | 540 | for (index, line) in lines.enumerated() { |
| 540 | 541 | let trimmed = line.trimmingCharacters(in: .whitespaces) |
| 541 | if trimmed.hasPrefix("[") && !trimmed.hasPrefix("[[") { | |
| 542 | current = String(trimmed.dropFirst().prefix { $0 != "]" }).trimmingCharacters(in: .whitespaces) | |
| 542 | if trimmed.hasPrefix("[") { | |
| 543 | // An array of tables, such as `[[publish]]`, is no section a setting is in. | |
| 544 | current = trimmed.hasPrefix("[[") ? trimmed : String(trimmed.dropFirst().prefix { $0 != "]" }).trimmingCharacters(in: .whitespaces) | |
| 543 | 545 | if current == section { lastInSection = index } |
| 544 | 546 | continue |
| 545 | 547 | } |
Sources/OrgCore/Keymap/PresetEmacs.swift +12
| @@ -343,6 +343,18 @@ extension KeymapPreset { | ||
| 343 | 343 | [[bind]] |
| 344 | 344 | keys = "C-c C-e c c" |
| 345 | 345 | command = "app.export.icalendar-combined" |
| 346 | [[bind]] | |
| 347 | keys = "C-c C-e P x" | |
| 348 | command = "app.publish" | |
| 349 | [[bind]] | |
| 350 | keys = "C-c C-e P a" | |
| 351 | command = "app.publish.all" | |
| 352 | [[bind]] | |
| 353 | keys = "C-c C-e P f" | |
| 354 | command = "app.publish.current-file" | |
| 355 | [[bind]] | |
| 356 | keys = "C-c C-e P p" | |
| 357 | command = "app.publish.current-project" | |
| 346 | 358 | |
| 347 | 359 | # Org |
| 348 | 360 | [[bind]] |
Sources/OrgEditorAppKit/EditorCommands.swift +4
| @@ -125,6 +125,10 @@ public enum EditorCommands { | ||
| 125 | 125 | EditorCommand(id: "app.export.icalendar", title: "Export to iCalendar", action: .app), |
| 126 | 126 | EditorCommand(id: "app.export.icalendar-agenda", title: "Export Agenda Files to iCalendar", action: .app), |
| 127 | 127 | EditorCommand(id: "app.export.icalendar-combined", title: "Combine Agenda Files into iCalendar", action: .app), |
| 128 | EditorCommand(id: "app.publish", title: "Publish Project…", action: .app), | |
| 129 | EditorCommand(id: "app.publish.all", title: "Publish All Projects", action: .app), | |
| 130 | EditorCommand(id: "app.publish.current-file", title: "Publish Current File", action: .app), | |
| 131 | EditorCommand(id: "app.publish.current-project", title: "Publish Current Project", action: .app), | |
| 128 | 132 | |
| 129 | 133 | movement("forward-char", "Forward Character", "moveForward:"), |
| 130 | 134 | movement("backward-char", "Backward Character", "moveBackward:"), |
Sources/Orgstar/ContentView.swift +45
| @@ -664,6 +664,49 @@ struct ContentView: View { | ||
| 664 | 664 | } |
| 665 | 665 | } |
| 666 | 666 | |
| 667 | /// `org-publish`, `org-publish-all`, `org-publish-current-file` and | |
| 668 | /// `org-publish-current-project`, with the projects in config.toml. | |
| 669 | private func publish(_ id: String) { | |
| 670 | let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? "" | |
| 671 | let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first) | |
| 672 | if let problem = loaded.problems.first { commands.show(problem) } | |
| 673 | guard !loaded.projects.isEmpty else { return commands.show("No [[publish]] projects in config.toml") } | |
| 674 | let read = { (path: String) -> String? in | |
| 675 | session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) | |
| 676 | } | |
| 677 | let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme) | |
| 678 | func run(_ chosen: [PublishProject], only: String? = nil) { | |
| 679 | do { | |
| 680 | let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in | |
| 681 | let settings = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile) | |
| 682 | if function == "org-md-publish-to-md" { return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly) } | |
| 683 | let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension | |
| 684 | return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle) | |
| 685 | } | |
| 686 | commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date")) | |
| 687 | } catch { | |
| 688 | commands.show("\(error)") | |
| 689 | } | |
| 690 | } | |
| 691 | let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? [] | |
| 692 | switch id { | |
| 693 | case "app.publish.all": | |
| 694 | run(loaded.projects) | |
| 695 | case "app.publish.current-file": | |
| 696 | guard let path = session.path, !current.isEmpty else { return commands.show("File is not part of any known project") } | |
| 697 | run([current[0]], only: path) | |
| 698 | case "app.publish.current-project": | |
| 699 | guard !current.isEmpty else { return commands.show("File is not part of any known project") } | |
| 700 | run([current[0]]) | |
| 701 | default: | |
| 702 | let names = loaded.projects.map(\.name) | |
| 703 | commands.ask(Prompt(key: "project", message: "Publish project:", choices: names)) { answer in | |
| 704 | guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return } | |
| 705 | run([project]) | |
| 706 | } | |
| 707 | } | |
| 708 | } | |
| 709 | ||
| 667 | 710 | /// Work a command hands to the platform: tables recalculated in Emacs. |
| 668 | 711 | private func runExternal(_ request: ExternalRequest) { |
| 669 | 712 | switch request { |
| @@ -959,6 +1002,8 @@ struct ContentView: View { | ||
| 959 | 1002 | panel = .export(UUID(), URL(fileURLWithPath: path)) |
| 960 | 1003 | case let id where id.hasPrefix("app.export."): |
| 961 | 1004 | export(String(id.dropFirst("app.export.".count))) |
| 1005 | case let id where id.hasPrefix("app.publish"): | |
| 1006 | publish(id) | |
| 962 | 1007 | default: |
| 963 | 1008 | if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") } |
| 964 | 1009 | } |
Sources/Orgstar/OrgstarApp.swift +5
| @@ -381,6 +381,11 @@ struct OrgstarApp: App { | ||
| 381 | 381 | } |
| 382 | 382 | } |
| 383 | 383 | .disabled(session.path == nil) |
| 384 | Menu("Publish") { | |
| 385 | ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in | |
| 386 | Button(command.title) { commands.run(command.id) } | |
| 387 | } | |
| 388 | } | |
| 384 | 389 | } |
| 385 | 390 | CommandGroup(replacing: .saveItem) { |
| 386 | 391 | Button("Close Buffer") { |
Tests/OrgAppTests/EmacsImportTests.swift +36
| @@ -182,6 +182,42 @@ struct EmacsImportTests { | ||
| 182 | 182 | #expect(s["org-icalendar-combined-agenda-file"] == .string("~/cal/org.ics")) |
| 183 | 183 | } |
| 184 | 184 | |
| 185 | @Test func readsPublishingProjects() async throws { | |
| 186 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)") | |
| 187 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | |
| 188 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 189 | try #""" | |
| 190 | (setq org-publish-project-alist | |
| 191 | `(("notes" :base-directory "~/notes" :base-extension "org" :publishing-directory ,(concat "~/public" "_html") | |
| 192 | :recursive t :publishing-function org-html-publish-to-html :auto-sitemap t :sitemap-style list | |
| 193 | :include ("extra.org") :html-head "<link>") | |
| 194 | ("static" :base-directory "~/notes" :base-extension "css\\|png" :publishing-directory "~/public_html" | |
| 195 | :publishing-function (org-publish-attachment)) | |
| 196 | ("pdf" :base-directory "~/notes" :publishing-directory "~/pdf" :publishing-function org-latex-publish-to-pdf) | |
| 197 | ("site" :components ("notes" "static")))) | |
| 198 | """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8) | |
| 199 | let result = EmacsImport.scan(EmacsImport.files(in: folder)) | |
| 200 | let projects = result.items.compactMap { if case .publish(let name, let toml) = $0.change { (name, toml) } else { nil } } | |
| 201 | #expect(projects.map(\.0) == ["notes", "static", "site"]) | |
| 202 | #expect(projects[0].1 == "[[publish]]\nname = \"notes\"\nbase-directory = \"~/notes\"\nbase-extension = \"org\"\npublishing-directory = \"~/public_html\"\nrecursive = true\npublishing-function = \"org-html-publish-to-html\"\nauto-sitemap = true\nsitemap-style = \"list\"\ninclude = \"extra.org\"\n") | |
| 203 | #expect(projects[1].1.contains("base-extension = \"css\\\\|png\"\n") && projects[1].1.contains("publishing-function = \"org-publish-attachment\"\n")) | |
| 204 | #expect(projects[2].1 == "[[publish]]\nname = \"site\"\ncomponents = \"notes static\"\n") | |
| 205 | #expect(result.unsupported.contains { $0.name == "publishing project \"pdf\"" }) | |
| 206 | #expect(result.unsupported.contains { $0.name == "publishing project \"notes\"" && $0.reason == ":html-head left out" }) | |
| 207 | ||
| 208 | let config = folder.appendingPathComponent("conf") | |
| 209 | try FileManager.default.createDirectory(at: config, withIntermediateDirectories: true) | |
| 210 | try "fill-column = 72\n".write(to: config.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8) | |
| 211 | let summary = await EmacsImport.apply(result.items.filter { if case .publish = $0.change { true } else { false } }, | |
| 212 | defaults: UserDefaults(suiteName: "orgstar-import-\(UUID().uuidString)")!, workspace: nil, directory: config) | |
| 213 | #expect(summary == "Imported 3 publishing projects.") | |
| 214 | let written = try String(contentsOf: config.appendingPathComponent("config.toml"), encoding: .utf8) | |
| 215 | let loaded = await Publish.projects(fromConfig: written, root: nil) | |
| 216 | #expect(loaded.problems.isEmpty && loaded.projects.map(\.name) == ["notes", "static", "site"]) | |
| 217 | #expect(UserConfig.setting(written, section: "", key: "fill-column", to: .integer(80)).hasPrefix("fill-column = 80\n")) | |
| 218 | #expect(!UserConfig.setting(written, section: "theme", key: "font", to: .string("X")).contains("[[publish]]\nname = \"site\"\ncomponents = \"notes static\"\nfont")) | |
| 219 | } | |
| 220 | ||
| 185 | 221 | @Test func readsCaptureTargetsFromVariablesAndForms() throws { |
| 186 | 222 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)") |
| 187 | 223 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
Tests/OrgAppTests/PublishTests.swift added +156
| @@ -0,0 +1,156 @@ | ||
| 1 | import Foundation | |
| 2 | import Testing | |
| 3 | @testable import OrgApp | |
| 4 | import OrgCore | |
| 5 | ||
| 6 | /// `org-publish` against Emacs: sitemaps and the files published. | |
| 7 | struct PublishTests { | |
| 8 | static let files: [(String, String, TimeInterval)] = [ | |
| 9 | ("a.org", "#+TITLE: Zeta page\n#+DATE: <2026-01-05 Mon>\n* H\nText [[file:sub/b.org][b]].\n", 1_780_000_000), | |
| 10 | ("b2.org", "#+TITLE: Alpha\n", 1_780_000_300), | |
| 11 | ("sub/b.org", "#+TITLE: Beta\n#+TITLE: two\n* B\n", 1_780_000_200), | |
| 12 | ("sub/deep/c.org", "no title\n", 1_780_000_100), | |
| 13 | ("other/z.org", "#+TITLE: alpha lower\n", 1_780_000_400), | |
| 14 | ("draft-x.org", "#+TITLE: Draft\n", 1_780_000_500), | |
| 15 | ("style.css", "body{}", 1_780_000_600), | |
| 16 | ("img/logo.png", "png", 1_780_000_700), | |
| 17 | (".hidden.org", "#+TITLE: Hidden\n", 1_780_000_800), | |
| 18 | ] | |
| 19 | ||
| 20 | static func tree(_ folder: URL) throws { | |
| 21 | for (path, text, time) in files { | |
| 22 | let url = folder.appendingPathComponent("src").appendingPathComponent(path) | |
| 23 | try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) | |
| 24 | try text.write(to: url, atomically: true, encoding: .utf8) | |
| 25 | try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: time)], ofItemAtPath: url.path) | |
| 26 | } | |
| 27 | } | |
| 28 | ||
| 29 | /// Projects as config.toml writes them and as Lisp, over `folder`. | |
| 30 | static func projects(_ folder: String) -> (toml: String, lisp: String) { | |
| 31 | let toml = """ | |
| 32 | fill-column = 80 | |
| 33 | ||
| 34 | [[publish]] | |
| 35 | name = "site" | |
| 36 | base-directory = "\(folder)/src" | |
| 37 | publishing-directory = "\(folder)/out" | |
| 38 | recursive = true | |
| 39 | exclude = "^draft-" | |
| 40 | auto-sitemap = true | |
| 41 | sitemap-title = "Site" | |
| 42 | ||
| 43 | [[publish]] | |
| 44 | name = "list" | |
| 45 | base-directory = "\(folder)/src" | |
| 46 | publishing-directory = "\(folder)/out2" | |
| 47 | recursive = true | |
| 48 | auto-sitemap = true | |
| 49 | sitemap-filename = "index.org" | |
| 50 | sitemap-style = "list" | |
| 51 | sitemap-sort-folders = "first" | |
| 52 | ||
| 53 | [[publish]] | |
| 54 | name = "dated" | |
| 55 | base-directory = "\(folder)/src" | |
| 56 | publishing-directory = "\(folder)/out3" | |
| 57 | include = "sub/b.org" | |
| 58 | auto-sitemap = true | |
| 59 | sitemap-filename = "dated.org" | |
| 60 | sitemap-style = "list" | |
| 61 | sitemap-sort-files = "anti-chronologically" | |
| 62 | publishing-function = "org-md-publish-to-md" | |
| 63 | ||
| 64 | [[publish]] | |
| 65 | name = "static" | |
| 66 | base-directory = "\(folder)/src" | |
| 67 | base-extension = "css\\\\|png" | |
| 68 | recursive = true | |
| 69 | publishing-directory = "\(folder)/out" | |
| 70 | publishing-function = "org-publish-attachment" | |
| 71 | ||
| 72 | [[publish]] | |
| 73 | name = "all" | |
| 74 | components = "site list dated static" | |
| 75 | """ | |
| 76 | let lisp = """ | |
| 77 | '(("site" :base-directory "\(folder)/src" :publishing-directory "\(folder)/out" :recursive t :exclude "^draft-" :auto-sitemap t :sitemap-title "Site") | |
| 78 | ("list" :base-directory "\(folder)/src" :publishing-directory "\(folder)/out2" :recursive t :auto-sitemap t :sitemap-filename "index.org" :sitemap-style list :sitemap-sort-folders first) | |
| 79 | ("dated" :base-directory "\(folder)/src" :publishing-directory "\(folder)/out3" :include ("sub/b.org") :auto-sitemap t :sitemap-filename "dated.org" :sitemap-style list :sitemap-sort-files anti-chronologically :publishing-function org-md-publish-to-md) | |
| 80 | ("static" :base-directory "\(folder)/src" :base-extension "css\\\\|png" :recursive t :publishing-directory "\(folder)/out" :publishing-function org-publish-attachment) | |
| 81 | ("all" :components ("site" "list" "dated" "static"))) | |
| 82 | """ | |
| 83 | return (toml, lisp) | |
| 84 | } | |
| 85 | ||
| 86 | static func listing(_ folder: URL) -> [String] { | |
| 87 | let base = folder.path + "/" | |
| 88 | let enumerator = FileManager.default.enumerator(atPath: folder.path) | |
| 89 | var out: [String] = [] | |
| 90 | while let path = enumerator?.nextObject() as? String { | |
| 91 | var isDirectory: ObjCBool = false | |
| 92 | if FileManager.default.fileExists(atPath: base + path, isDirectory: &isDirectory), !isDirectory.boolValue, !path.hasPrefix("ts/") { out.append(path) } | |
| 93 | } | |
| 94 | return out.sorted() | |
| 95 | } | |
| 96 | ||
| 97 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 98 | func publishesLikeOrg() throws { | |
| 99 | let emacsFolder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-e-\(UUID().uuidString)").resolvingSymlinksInPath() | |
| 100 | let ourFolder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-o-\(UUID().uuidString)").resolvingSymlinksInPath() | |
| 101 | defer { | |
| 102 | try? FileManager.default.removeItem(at: emacsFolder) | |
| 103 | try? FileManager.default.removeItem(at: ourFolder) | |
| 104 | } | |
| 105 | try Self.tree(emacsFolder) | |
| 106 | try Self.tree(ourFolder) | |
| 107 | let form = """ | |
| 108 | (progn | |
| 109 | (require 'ox-publish) (require 'ox-md) | |
| 110 | (setq org-publish-timestamp-directory "\(emacsFolder.path)/ts/" | |
| 111 | org-publish-project-alist \(Self.projects(emacsFolder.path).lisp)) | |
| 112 | (org-publish "all" t)) | |
| 113 | """ | |
| 114 | let process = Process() | |
| 115 | process.executableURL = URL(fileURLWithPath: "/usr/bin/env") | |
| 116 | process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form] | |
| 117 | process.standardOutput = FileHandle.nullDevice | |
| 118 | let errors = Pipe() | |
| 119 | process.standardError = errors | |
| 120 | try process.run() | |
| 121 | let log = errors.fileHandleForReading.readDataToEndOfFile() | |
| 122 | process.waitUntilExit() | |
| 123 | #expect(process.terminationStatus == 0, "\(String(decoding: log, as: UTF8.self))") | |
| 124 | ||
| 125 | let loaded = Publish.projects(fromConfig: Self.projects(ourFolder.path).toml, root: nil) | |
| 126 | #expect(loaded.problems.isEmpty, "\(loaded.problems)") | |
| 127 | let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) } | |
| 128 | let all = loaded.projects.first { $0.name == "all" }! | |
| 129 | let report = try Publish.publish([all], all: loaded.projects, force: true, read: read) { function, text, _, _ in function + "\n" + text } | |
| 130 | #expect(!report.published.isEmpty) | |
| 131 | for name in ["sitemap.org", "index.org", "dated.org"] { | |
| 132 | let theirs = try String(contentsOf: emacsFolder.appendingPathComponent("src/" + name), encoding: .utf8) | |
| 133 | let ours = try String(contentsOf: ourFolder.appendingPathComponent("src/" + name), encoding: .utf8) | |
| 134 | #expect(ours == theirs, "\(name)\nours:\n\(ours)\nemacs:\n\(theirs)") | |
| 135 | } | |
| 136 | #expect(Self.listing(ourFolder) == Self.listing(emacsFolder)) | |
| 137 | } | |
| 138 | ||
| 139 | @Test func skipsUpToDateFilesAndFindsProjects() throws { | |
| 140 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-publish-\(UUID().uuidString)").resolvingSymlinksInPath() | |
| 141 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 142 | try Self.tree(folder) | |
| 143 | let loaded = Publish.projects(fromConfig: Self.projects(folder.path).toml, root: nil) | |
| 144 | let site = loaded.projects.first { $0.name == "site" }! | |
| 145 | let read = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) } | |
| 146 | let first = try Publish.publish([site], all: loaded.projects, read: read) { _, text, _, _ in text } | |
| 147 | let second = try Publish.publish([site], all: loaded.projects, read: read) { _, text, _, _ in text } | |
| 148 | #expect(!first.published.isEmpty && second.published.isEmpty && second.skipped.count == first.published.count) | |
| 149 | let a = folder.path + "/src/a.org" | |
| 150 | #expect(Publish.projects(containing: a, in: loaded.projects).map(\.name) == ["site", "list", "dated"]) | |
| 151 | let one = try Publish.publish([site], all: loaded.projects, force: true, only: a, read: read) { _, text, _, _ in text } | |
| 152 | #expect(one.published == [a]) | |
| 153 | #expect(Publish.projects(fromConfig: "[[publish]]\nname = \"x\"\n", root: nil).problems.count == 1) | |
| 154 | #expect(throws: Publish.Failure.self) { try Publish.expand([PublishProject(name: "m")].map { var p = $0; p.components = ["nope"]; return p }, all: []) } | |
| 155 | } | |
| 156 | } | |
docs/manual/guide/03-keys.org +4
| @@ -975,6 +975,10 @@ When a key appears in several rows, it runs the command whose condition holds at | ||
| 975 | 975 | | Export to iCalendar (=app.export.icalendar=) | =C-c C-e c f= | — | — | Exports to an =.ics= calendar (=org-icalendar-export-to-ics=). | |
| 976 | 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 | 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=). | |
| 978 | | Publish Project… (=app.publish=) | =C-c C-e P x= | — | — | Publishes a project from =config.toml= (=org-publish=). | | |
| 979 | | Publish All Projects (=app.publish.all=) | =C-c C-e P a= | — | — | Publishes every project (=org-publish-all=). | | |
| 980 | | Publish Current File (=app.publish.current-file=) | =C-c C-e P f= | — | — | Publishes the current file (=org-publish-current-file=). | | |
| 981 | | Publish Current Project (=app.publish.current-project=) | =C-c C-e P p= | — | — | Publishes the current file's project (=org-publish-current-project=). | | |
| 978 | 982 | |
| 979 | 983 | ** Files, buffers and the app |
| 980 | 984 | |
docs/manual/guide/12-export.org +59
| @@ -261,6 +261,65 @@ Export Agenda Files to iCalendar writes an =.ics= beside each agenda file (see [ | ||
| 261 | 261 | |
| 262 | 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 | 263 | |
| 264 | * Publishing | |
| 265 | ||
| 266 | Publishing (=org-publish=) exports a folder of Org files to a folder of HTML or Markdown files, copies other files beside them, and can write a sitemap. Projects are =[[publish]]= tables in =config.toml=, as =org-publish-project-alist= entries are in Emacs: | |
| 267 | ||
| 268 | #+BEGIN_SRC toml | |
| 269 | [[publish]] | |
| 270 | name = "notes" | |
| 271 | base-directory = "~/notes" | |
| 272 | publishing-directory = "~/public_html" | |
| 273 | recursive = true | |
| 274 | auto-sitemap = true | |
| 275 | sitemap-title = "Notes" | |
| 276 | ||
| 277 | [[publish]] | |
| 278 | name = "static" | |
| 279 | base-directory = "~/notes" | |
| 280 | base-extension = "css\\|png\\|jpg" | |
| 281 | recursive = true | |
| 282 | publishing-directory = "~/public_html" | |
| 283 | publishing-function = "org-publish-attachment" | |
| 284 | ||
| 285 | [[publish]] | |
| 286 | name = "site" | |
| 287 | components = "notes static" | |
| 288 | #+END_SRC | |
| 289 | ||
| 290 | | Key | Value | Default | | |
| 291 | |------------------------+---------------------------------------------------------------------------------------------+-----------------------------| | |
| 292 | | =name= | The project's name | required | | |
| 293 | | =base-directory= | The folder of files to publish: absolute, =~/…=, or relative to the first folder in the sidebar | required | | |
| 294 | | =publishing-directory= | Where the published files go, the same way | required | | |
| 295 | | =base-extension= | The extension of the files to publish, an Emacs regexp such as ="css\\|png"=, or =any= | ="org"= | | |
| 296 | | =recursive= | Files in subfolders too | =false= | | |
| 297 | | =exclude= | An Emacs regexp on the file's path under =base-directory=; matching files are left out | | | |
| 298 | | =include= | More files, relative to =base-directory=, separated by spaces | | | |
| 299 | | =publishing-function= | =org-html-publish-to-html=, =org-md-publish-to-md= or =org-publish-attachment= (copied as they are), several separated by spaces | =org-html-publish-to-html= | | |
| 300 | | =body-only= | The export's body only | =false= | | |
| 301 | | =auto-sitemap= | Write a sitemap into =base-directory= and publish it with the rest | =false= | | |
| 302 | | =sitemap-filename= | The sitemap's name | ="sitemap.org"= | | |
| 303 | | =sitemap-title= | Its =#+TITLE= | ="Sitemap for project NAME"= | | |
| 304 | | =sitemap-style= | =tree= (folders nest) or =list= | ="tree"= | | |
| 305 | | =sitemap-sort-files= | =alphabetically= (by title), =chronologically= or =anti-chronologically= (by =#+DATE=, else the file's date), or =nil= | ="alphabetically"= | | |
| 306 | | =sitemap-sort-folders= | In a =list= sitemap: =ignore= (no folders), =first=, =last= or =nil= (mixed) | ="ignore"= | | |
| 307 | | =sitemap-ignore-case= | Sort titles ignoring case | =false= | | |
| 308 | | =components= | For a project of projects: the projects' names, separated by spaces | | | |
| 309 | ||
| 310 | Files whose names start with a dot are left out. An Org file publishes to the same path under =publishing-directory=, named by =#+EXPORT_FILE_NAME= when it has one, with links to other =.org= files pointing to their =.html=. The sitemap lists each file as a link with its =#+TITLE= (or its name), as Org's default sitemap does. | |
| 311 | ||
| 312 | On the Mac, File ▸ Publish has the commands, which are also in the command palette: | |
| 313 | ||
| 314 | | Command | Emacs preset | What it does | | |
| 315 | |-------------------------+---------------+------------------------------------------------------------| | |
| 316 | | Publish Project… | =C-c C-e P x= | Asks for a project and publishes it (=org-publish=) | | |
| 317 | | Publish All Projects | =C-c C-e P a= | =org-publish-all= | | |
| 318 | | Publish Current File | =C-c C-e P f= | The current file, in the first project that has it (=org-publish-current-file=) | | |
| 319 | | Publish Current Project | =C-c C-e P p= | The first project that has the current file (=org-publish-current-project=) | | |
| 320 | ||
| 321 | A file whose published copy is newer than it is skipped, as Org skips files that haven't changed; delete the copy to publish it again. The message area says how many files were published and how many were up to date. Differences from Org: preparation and completion functions, =:makeindex=, custom sitemap functions and the export options a project can set (=:with-toc=, =:html-head= and the rest) aren't read; set those with =#+OPTIONS= and the other keywords in the files, or a =#+SETUPFILE=. Publishing is on the Mac only. | |
| 322 | ||
| 264 | 323 | * Exporting through Emacs |
| 265 | 324 | |
| 266 | 325 | 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 +6 −1
| @@ -15,7 +15,7 @@ The folder holds these files: | ||
| 15 | 15 | |
| 16 | 16 | | File | What it holds | Written by orgstar | |
| 17 | 17 | |----------------------+------------------------------------------------------------------+---------------------------------------| |
| 18 | | =config.toml= | Every setting of the Settings window, and the theme | Yes, when you change a setting | | |
| 18 | | =config.toml= | Every setting of the Settings window, the theme, and publishing projects | Yes, when you change a setting | | |
| 19 | 19 | | =keymap.toml= | Your key bindings, on top of the preset | Only by Import from Emacs | |
| 20 | 20 | | =capture.toml= | Capture templates | Only by Import from Emacs | |
| 21 | 21 | | =views.toml= | Saved agenda views | No | |
| @@ -315,6 +315,10 @@ py = "src python" | ||
| 315 | 315 | |
| 316 | 316 | Keys are letters, digits, =_= and =-=. Without the table, Org's templates apply. Emacs import adds entries here and so does nothing else in the app; remove one by deleting its line. |
| 317 | 317 | |
| 318 | ** [[publish]] | |
| 319 | ||
| 320 | Publishing projects, one table each, as =org-publish-project-alist= has them. They're read when you publish; see [[file:12-export.org::*Publishing][Publishing]] for the keys. The Settings window leaves them as they are. | |
| 321 | ||
| 318 | 322 | ** [theme] |
| 319 | 323 | |
| 320 | 324 | | Key | Type | Default | Effect | |
| @@ -536,6 +540,7 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, = | ||
| 536 | 540 | | =org-icalendar-use-deadline=, =org-icalendar-use-scheduled= | The list's symbols, separated by spaces | |
| 537 | 541 | | =org-icalendar-include-todo= | =nil=, =t=, =all= or =unblocked=, or a list of keywords separated by spaces | |
| 538 | 542 | | =org-icalendar-combined-agenda-file= | The file name, from a string or a simple form | |
| 543 | | =org-publish-project-alist= | A =[[publish]]= table in =config.toml= per project whose publishing functions are =org-html-publish-to-html=, =org-md-publish-to-md= or =org-publish-attachment=: the directories, =:base-extension=, =:recursive=, =:exclude=, =:include=, =:body-only=, the sitemap properties and =:components=. Other properties are reported as left out | | |
| 539 | 544 | | =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= | |
| 540 | 545 | | =org-log-into-drawer= | A string as given; =t= becomes ="LOGBOOK"=; =nil= becomes =""= | |
| 541 | 546 | | =display-line-numbers-type= | =true= unless =nil=; =relative= and =visual= become absolute numbers | |